图论拓扑排序

#include<iostream>
#include<string>
#include<cmath>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<queue>
#include<stack>
#include<sstream>
#include<cstdio>
#define INF 0x3f3f3f3f
const int maxn = 1e6 + 5;
const double PI = acos(-1.0);
typedef long long ll;
using namespace std;

int T, n, m, u, v, num;
int InDeg[maxn];
vector<int> vec[maxn];
queue<int>q;

bool topsort() {
    while (!q.empty())  q.pop();
    num = 0;
    for (int i = 1; i <= n; i++) if (!InDeg[i]) q.push(i);
    while (!q.empty()) {
        int now = q.front();
        q.pop();
        num++;
        for (int i = 0; i < vec[now].size(); i++) {
            if (--InDeg[vec[now][i]] == 0) q.push(vec[now][i]);    //入度为零,进入队列
            
        }
    }
    if (n == num)    return true;
    return false;
}

int main() {
    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &n, &m);   //n个点,m条边
        while (m--) {
            scanf("%d%d", &u, &v);
            vec[u].push_back(v);       //临接表存储
            InDeg[v]++;
        }
        if (topsort()) printf("Correct");
        else printf("Wrong");
    }
    return 0;
}

  可以用DFS求出DAG的拓扑排序,如果排序失败,说明该图存在有向环,不是DAG

  UVA 10305 给任务排序

  

John有n个任务要做,每个任务在做之前要先做特定的一些任务。

输入第一行包含两个整数n和m,其中1<=n<=100。 n表示任务数,而m表示有m条任务之间的关系。 接下来有m行,每行包含两个整数i和j,表示任务i要在j之前做。

当读入两个0(i=0,j=0)时,输入结束。

输出包含q行,每行输出一条可行的安排方案。

  

#include<iostream>
#include<string>
#include<cmath>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<queue>
#include<stack>
#include<sstream>
#include<cstdio>
#define INF 0x3f3f3f3f
const int maxn = 105;
const double PI = acos(-1.0);
typedef long long ll;
using namespace std;

int T, n, m, u, v, num;
int InDeg[maxn];
int topo[maxn];
vector<int> vec[maxn];
queue<int>q;
int cnt;

bool topsort() {
    while (!q.empty())  q.pop();
    num = 0;
    for (int i = 1; i <= n; i++) if (!InDeg[i])  q.push(i), topo[cnt++] = i;
    while (!q.empty()) {
        int now = q.front();
        q.pop();
        num++;
        for (int i = 0; i < vec[now].size(); i++) {
            if (--InDeg[vec[now][i]] == 0) q.push(vec[now][i]), topo[cnt++] = vec[now][i];    //入度为零,进入队列

        }
    }
    if (n == num)  return true;
    return false;
}

int main() {
    while (scanf("%d%d", &n, &m)!=EOF) { //n个点,m条边
        if (n == m && n == 0) break;
        cnt = 0;
        while (m--) {
              scanf("%d%d", &u, &v);
              vec[u].push_back(v);       //临接表存储
              InDeg[v]++;
         }
         if (topsort()) {
             printf("%d", topo[0]);
             for (int i = 1; i < cnt; i++) printf(" %d", topo[i]);
        }
        else printf("Wrong");
         printf("\n");
        }
    return 0;
}
View Code

  

原文地址:https://www.cnblogs.com/hznumqf/p/12309351.html