求dalao看看,感觉O(n)算法神奇的挂了

P2661 [NOIP2015 提高组] 信息传递

```cpp // Chlience 's code #include <bits/stdc++.h> using namespace std; int num[200010],p[200010],fa[200010];//x=0->没有环 x=1->是环 x=2->后面有环 bool vis[200010],flag; int total=0,h,ans=200010; int read() { int ans=0,flag=1; char ch=getchar(); while((ch>'9' || ch<'0') && ch!='-') ch=getchar(); if(ch=='-') flag=-1,ch=getchar(); while(ch>='0' && ch<='9') ans=ans*10+ch-'0',ch=getchar(); return ans*flag; } void search(int x) { if(p[x]==1) { return ; } if(vis[x]) { p[x]=1; h=x; return ; } vis[x]=1; search(fa[x]); p[x]=1; if(flag) { return ; }else if(h!=0) { total++; if(x==h) { flag=1; return ; } } } int main() { int n=read(); for(int i=1;i<=n;i++) fa[i]=read(); for(int i=1;i<=n;i++) { // memset(vis,0,sizeof(vis)); 你已经判断过了, 不必清0 vis过的肯定不会再次访问了 total=0,flag=0,h=0; search(i); if(total!=0) ans=min(ans,total); } printf("%d",ans); return 0; } ```
by yxr811740686 @ 2017-10-30 00:11:16


刚刚交了一遍, 32ms过...
by yxr811740686 @ 2017-10-30 00:12:31


尴尬
by Chlience @ 2017-10-30 10:50:53


|