HDU - 5154 Harry and Magical Computer 拓扑排序

Training 8 - A题

In reward of being yearly outstanding magic student, Harry gets a magical computer. When the computer begins to deal with a process, it will work until the ending of the processes. One day the computer got n processes to deal with. We number the processes from 1 to n. However there are some dependencies between some processes. When there exists a dependencies (a, b), it means process b must be finished before process a. By knowing all the m dependencies, Harry wants to know if the computer can finish all the n processes.


There are several test cases, you should process to the end of file.

For each test case, there are two numbers n m on the first line, indicates the number processes and the number of dependencies. 1≤n≤100,1≤m≤100001≤n≤100,1≤m≤10000

The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b). 1≤a,b≤n1≤a,b≤n


Output one line for each test case.

If the computer can finish all the process print “YES” (Without quotes).

Else print “NO” (Without quotes).

Sample Input

3 2
3 1
2 1
3 3
3 2
2 1
1 3

Sample Output


#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
#include <set>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 100 + 200;
const int M = 10000 + 200;

int head[N], ver[M], nex[M];
int deg[N];//入度
int tot, cnt;
int n, m;

void add(int x, int y)
	ver[tot] = y;
	nex[tot] = head[x];
	head[x] = tot;

bool topsort()
	queue<int> q;
	for (int i = 1; i <= n; i++)
		if (deg[i] == 0)
	while (q.size())
		int x = q.front();
		for (int i = head[x]; i; i = nex[i])
			int y = ver[i];
			if (--deg[y] == 0)
	if (cnt < n)
		return 1;//有环
	return 0;

int main()
	while (scanf("%d%d", &n, &m) != EOF)
		memset(head, 0, sizeof(head));
		memset(ver, 0, sizeof(ver));
		memset(nex, 0, sizeof(nex));
		memset(deg, 0, sizeof(deg));
		tot = cnt = 0;
		for (int i = 1; i <= m; i++)
			int a, b;
			scanf("%d%d", &a, &b);
			add(a, b);
		int ans = topsort();
		if (ans == 0)
	return 0;


发布了48 篇原创文章 · 获赞 0 · 访问量 807


©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客