hdu 5154 Harry and Magical Computer

时间:2022-03-01 17:27:03

题目连接

http://acm.hdu.edu.cn/showproblem.php?pid=5154

Harry and Magical Computer

Description

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.

Input

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 \leq n \leq 100,1 \leq m \leq 10000$
The next following m lines, each line contains two numbers a b, indicates a dependencies $(a, b). 1 \leq a, b \leq n$

Output

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

YES
NO

先建立一张有向图,再遍历,若有顶点未访问到输出"NO",否则输出"YES"。。。

 #include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<map>
using std::cin;
using std::cout;
using std::endl;
using std::find;
using std::sort;
using std::pair;
using std::vector;
using std::queue;
using std::multimap;
#define pb(e) push_back(e)
#define sz(c) (int)(c).size()
#define mp(a, b) make_pair(a, b)
#define all(c) (c).begin(), (c).end()
#define iter(c) decltype((c).begin())
#define cls(arr,val) memset(arr,val,sizeof(arr))
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define tr(c, i) for (iter(c) i = (c).begin(); i != (c).end(); ++i)
const int N = ;
int n, m, G[N][N];
bool vis[N], flag[N];
typedef unsigned long long ull;
void bfs() {
bool f = false;
queue<int> que;
rep(i, n) {
if (!flag[i]) {
vis[i] = true;
que.push(i);
}
}
while (!que.empty()) {
int p = que.front(); que.pop();
rep(i, n) {
if (G[p][i]) {
if (vis[i]) continue;
que.push(i);
vis[i] = true;
}
}
}
rep(i, n) {
if (!vis[i]) { f = true; break; }
}
puts(f ? "NO" : "YES");
}
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
int a, b;
while (~scanf("%d %d", &n, &m)) {
cls(vis, ), cls(flag, ), cls(G, );
rep(i, m) {
scanf("%d %d", &a, &b);
G[b - ][a - ] = ;
flag[a - ] = ;
}
bfs();
}
return ;
}