Cod sursa(job #1338256)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 9 februarie 2015 22:00:21
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

void topologicalSort(vector<int> adjList[], int N);

int main()
{
    int N, M, X, Y, i;
    ifstream f("sortaret.in");
    f >> N >> M;
    vector<int> adjList[N + 1];

    for (i = 1; i <= N; i++)
        adjList[i].push_back(0);

    for (i = 1; i <= M; i++)
    {
        f >> X >> Y;
        adjList[Y][0]++;
        adjList[X].push_back(Y);
    }
    f.close();

    topologicalSort(adjList, N);

    return 0;
}

void topologicalSort(vector<int> adjList[], int N)
{
    queue<int> q;
    int i;
    for (i = 1; i <= N; i++)
        if (adjList[i][0] == 0)
            q.push(i);

    ofstream g("sortaret.out");
    int current, node;
    while (!q.empty())
    {
        current = q.front();
        g << current << " ";
        q.pop();
        for (i = 1; i < adjList[current].size(); i++)
        {
            node = adjList[current][i];
            adjList[node][0]--;
            if (adjList[node][0] == 0)
                q.push(node);
        }
    }
    g.close();
}