HDU 5154_Harry and Magical Computer

来源:互联网 发布:淘宝售后退款多久到账 编辑:程序博客网 时间:2024/06/08 11:20
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1676    Accepted Submission(s): 656


Problem 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. 1n100,1m10000
The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b). 1a,bn
 

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 23 12 13 33 22 11 3
 

Sample Output
YESNO

这道题的意思是判断给出的数值里面有没有环,有的话输出NO,没有输出YES。

其实一开始是想到用二维数组来弄的,后来果断爆内存了,再后来想到了用一维数组来代替二维数组,一开始初始化数组的时候让数组的值等于它的下标,然后再输入数值,不断更新一维数组,如果遇到一开始更新时的那个值,就说明输入的数组里面有环,输出NO,否则输出YES。


#include<iostream>#include<string.h>#include<stdio.h>using namespace std;int num[10010];int flag=0;int find(int a,int b){if(num[b]==a)  return 1;if(num[b]==b)  return 0;find(a,num[b]);}int main(){int n,m;while(scanf("%d %d",&n,&m)!=EOF){flag=0;for(int i=1;i<=n;i++)  num[i]=i;int ans,nut;for(int i=1;i<=m;i++){scanf("%d %d",&ans,&nut);if(find(ans,nut))  flag=1;else  num[ans]=nut;}if(flag==1)  printf("NO\n");else  printf("YES\n");}return 0;}




0 0
原创粉丝点击