Cod sursa(job #2968906)

Utilizator liviu_gheorghe1234Liviu Gheorghe liviu_gheorghe1234 Data 22 ianuarie 2023 12:53:55
Problema Sortare topologica Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <bits/stdc++.h>
using namespace std;

vector<vector<pair<int, int>>> adjList;

int N, M;

ifstream fin("sortaret.in");

ofstream fout("sortaret.out");

vector<bool> visited;

vector<int> recursionStack = vector<int>();

bool cyclic = true;

void topsort(int nod)
{

    if (find(recursionStack.begin(), recursionStack.end(), nod) != recursionStack.end())
    {
        cout << "GRAF CICLIC, nodul a mai fost gasit: " << nod;

        cyclic = true;
        exit(0);
    }
    else
    {
        recursionStack.push_back(nod);
    }

    visited[nod] = true;

    for (int i = 0; i < adjList[nod].size(); i++)
    {

        if (!visited[adjList[nod][i].first])
        {
            topsort(adjList[nod][i].first);
        }
    }

    cout << nod << " | ";
    fout << nod << " ";
}

void citireGrafTastatura()
{
    // Se citeste numarul de noduri si nr de muchii, dupa care se citesc muchiile

    cin >> N >> M;

    int x, y, c;

    adjList = vector<vector<pair<int, int>>>(N + 1, vector<pair<int, int>>());

    // Se citesc muchiile, fiecare avand un cost asociat
    for (int i = 1; i <= M; i++)
    {
        cin >> x >> y;
        // adjList[x].push_back(make_pair(y, c));
        adjList[y].push_back(make_pair(x, 0));
    }
}

void citireGrafFisier()
{
    // Se citeste numarul de noduri si nr de muchii, dupa care se citesc muchiile

    fin >> N >> M;

    int x, y, c;

    adjList = vector<vector<pair<int, int>>>(N + 1, vector<pair<int, int>>());

    // Se citesc muchiile, fiecare avand un cost asociat
    for (int i = 1; i <= M; i++)
    {
        fin >> x >> y;
        // adjList[x].push_back(make_pair(y, 0));
        adjList[y].push_back(make_pair(x, 0));
    }
}

void afisareGraf()
{

    for (int i = 0; i < N; i++)
    {
        cout << i << ": ";
        for (int j = 0; j < adjList[i].size(); j++)
        {
            printf("(nod = %d, cost=%d) ", adjList[i][j].first, adjList[i][j].second);
        }
        cout << "\n";
    }
}

int main()
{

    citireGrafFisier();

    // afisareGraf();

    visited = vector<bool>(N + 1, false);

    for (int i = 1; i <= N; i++)
    {
        if (!visited[i])
        {
            topsort(i);
        }
    }

    return 0;
}