標籤:
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. 題目大致就是說對一個有向圖判斷是否有環。BC 25 的A題,這場比賽很幸運的爆零了,我覺得是因為A題不停的寫錯導致整個人都亂了,看來以後要注意,如果第一個題就亂了的話要注意調整,不能影響之後的發揮。 這個題目的題解是用的floyd寫的,我使用dfs寫的,貌似複雜度低一點。 代碼如下:
#include<iostream>#include<cstdio>#include<cstring>using namespace std;bool vis[105];bool rem[105];int n,m;int first[105];int next[10005];int bs[10005],be[10005];bool dfs(int x){ int t=first[x]; while(t) { if(rem[be[t]]) //這裡要注意先判斷。 return 0; if(vis[be[t]]==0) { vis[be[t]]=1; rem[be[t]]=1; if(dfs(be[t])==0) return 0; rem[be[t]]=0; } t=next[t]; //不然會無限迴圈。 } return 1;}bool getans(){ for(int i=1;i<=n;++i) if(vis[i]==0) { memset(rem,0,sizeof(rem)); //這裡要注意清零。 rem[i]=1; vis[i]=1; if(dfs(i)==0) return 0; } return 1;}int main(){ int a,b; int temp; while(~scanf("%d %d",&n,&m)) { memset(vis,0,sizeof(vis)); memset(first,0,sizeof(first)); memset(next,0,sizeof(next)); for(int i=1;i<=m;++i) { scanf("%d %d",&a,&b); bs[i]=b; be[i]=a; temp=first[b]; first[b]=i; next[i]=temp; } if(getans()) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0;}
View Code
(簡單) HDU 5154 Harry and Magical Computer,圖論。