hihoCoder_1174 拓扑排序
传送门
Problem Description
我们都知道大学的课程是可以自己选择的,每一个学期可以自由选择打算学习的课程。唯一限制我们选课是一些课程之间的顺序关系:有的难度很大的课程可能会有一些前置课程的要求。比如课程A是课程B的前置课程,则要求先学习完A课程,才可以选择B课程。大学的教务收集了所有课程的顺序关系,但由于系统故障,可能有一些信息出现了错误。现在小Ho把信息都告诉你,请你帮小Ho判断一下这些信息是否有误。错误的信息主要是指出现了”课程A是课程B的前置课程,同时课程B也是课程A的前置课程”这样的情况。当然”课程A是课程B的前置课程,课程B是课程C的前置课程,课程C是课程A的前置课程”这类也是错误的。
Input
第1行:1个整数T,表示数据的组数T(1 <= T <= 5)
接下来T组数据按照以下格式:
第1行:2个整数,N,M。N表示课程总数量,课程编号为1..N。M表示顺序关系的数量。1 <= N <= 100,000. 1 <= M <= 500,000
第2..M+1行:每行2个整数,A,B。表示课程A是课程B的前置课程。
Output
第1..T行:每行1个字符串,若该组信息无误,输出"Correct",若该组信息有误,输出"Wrong"。
Sample Input
2
2 2
1 2
2 1
3 2
1 2
1 3
Sample Output
Wrong
Correct
Solution
拓扑排序问题。
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
int T, n, m;
const int maxn = 100005;
vector<int> vec[maxn];
int InDeg[maxn];
queue<int> q;
bool topsort() {
//清空队列
while (!q.empty())
q.pop();
int num = 0;
//入度为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 (num == n)return true;
return false;
}
int main() {
cin >> T;
while (T--) {
cin >> n >> m;
for (int i = 1; i < n; i++) vec[i].clear();
memset(InDeg, 0, sizeof(InDeg));
int x, y;
//记录初始数据
for (int i = 0; i < m; i++) {
cin >> x >> y;
vec[x].push_back(y);
InDeg[y]++;
}
if (topsort()) puts("Correct");
else puts("Wrong");
}
return 0;
}