拓扑排序模板

拓扑排序是对ADG(有向无环图进行线性排序)

模板:

二维数组模拟链表

#include<cstdio>

#include<cstring>

#include<algorithm>

#include<queue>

using namespace std;

int indegree[100];

queue<int> q;

int n,m;

bool map[100][100];

int a[100];

int topo(int n)

{

    int cnt = 1;

    while(!q.empty())

        q.pop();

    for(int i = 1; i <= n ; i++)

        if(indegree[i] == 0)

            q.push(i);

    int u;

    while(!q.empty()){

        u = q.front();

        a[cnt++] = u;

        q.pop();

        for(int i = 1; i <= n ; i++){

            if(map[u][i]){

                indegree[i] --;

                if(indegree[i] == 0)

                    q.push(i);

            }

        }

        if(cnt == n){

            for(int i = 1 ; i <= n ; i++)

                printf(" %d",a[i]);

        }

        else printf("The network has a cycle");

    }

}

int main()

{

    int u,v;

    while(~scanf("%d%d",&n,&m)){

        memset(indegree,0,sizeof(indegree));

        memset(map,0,sizeof(map));

        for(int i = 0 ; i < m ; i++){

            scanf("%d%d",&u,&v);

            if(!map[u][v])

                indegree[v]++;

                map[u][v] = 1;

        }

               topo(n);

    }

    return 0;

}

  

邻接表实现

#include<cstring>

#include<algorithm>

#include<queue>

#include<vector>

using namespace std;

const int M = 100005;

int a[M];

int indegree[M];

int n,m,u,v;

vector<int> G[M];

void topo()

{

    memset(indegree,0,sizeof(indegree));

    memset(a,0,sizeof(a));

    for(int i = 1; i <= n ; i++){

        for(int j = 0 ; j <= G[i].size(); j++){

            indegree[G[i][j]]++;

        }

    }

    queue<int> q;

    while(!q.empty())

        q.pop();

    int cnt = 1;

    for(int i = 1;i <= n ; i++){

        if(!indegree[i])

            q.push(i);

    }

    while(!q.empty()){

        int u = q.front();

        q.pop();

        a[cnt++] = u;

        for(int i = 0 ; i <G[u].size(); i++){

            int v = G[u][i];

            indegree[v]--;

            if(!indegree[v])

                q.push(v);

        }

    }

    if(cnt == n){

        for(int i = 1; i < cnt; i++)

            printf(" %d", a[i]);

        printf("%d\n",a[cnt]);

    }

    else printf("This is a cycle\n");

}

int main()

{

    while(~scanf("%d%d",&n,&m)){

     for(int i = 1; i <= n ; i++)

      G[i].clear();

        for(int i = 1; i <= m ; i++){

            scanf("%d%d",&u,&v);

            G[u].push_back(v);

        } 

        topo();

    }

    return 0;

}

  

  

你可能感兴趣的:(排序)