Harry and Magical Computer
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1942 Accepted Submission(s): 761
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. 1≤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≤n
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≤10000
The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b). 1≤a,b≤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).
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
题意:一个电脑会工作到所有工作结束,但是工作会先后顺序,n个工作,m种关系,问能不能将所有工作都完成。
思路:拓扑排序判断是否存在负环,直接写就好了
ac代码:
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stack>
#include<set>
#include<queue>
#include<vector>
#include<iostream>
#include<algorithm>
#define MAXN 1010000
#define LL long long
#define ll __int64
#define INF 0xfffffff
#define mem(x) memset(x,0,sizeof(x))
#define PI acos(-1.0)
using namespace std;
int gcd(int a,int b){return b?gcd(b,a%b):a;}
LL powmod(LL a,LL b,LL MOD){LL ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}
//head
int pri[110][110];
int v[110];
int main()
{
int n,m;
int i,j;
while(scanf("%d%d",&n,&m)!=EOF)
{
mem(v);mem(pri);
for(i=0;i<m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
if(!pri[b][a])
{
pri[b][a]=1;
v[a]++;
}
}
int cnt=0;
for(i=0;i<n;i++)
{
int k=-1;
for(j=1;j<=n;j++)
{
if(v[j]==0)
{
k=j;
break;
}
}
if(k==-1)
break;
v[k]=-1;
cnt++;
for(j=1;j<=n;j++)
{
if(pri[k][j])
{
pri[k][j]=0;
v[j]--;
}
}
}
if(cnt==n)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}