标签:dfs tchar algorithm stack 信息 传递 get getc ack
P2661 信息传递
dfs求最小环,要加时间戳,记录这个点是哪一次被dfs到的。]
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<algorithm> 5 #include<cmath> 6 #include<ctime> 7 #include<set> 8 #include<map> 9 #include<stack> 10 #include<cstring> 11 #define inf 2147483647 12 #define For(i,a,b) for(register int i=a;i<=b;i++) 13 #define p(a) putchar(a) 14 #define g() getchar() 15 //by war 16 //2017.11.5 17 using namespace std; 18 int n; 19 bool vis[200010]; 20 int x; 21 int ans; 22 int d[200010]; 23 int t[200010]; 24 struct node 25 { 26 int n; 27 node *next; 28 }*e[200010]; 29 void in(int &x) 30 { 31 int y=1; 32 char c=g();x=0; 33 while(c<‘0‘||c>‘9‘) 34 { 35 if(c==‘-‘) 36 y=-1; 37 c=g(); 38 } 39 while(c<=‘9‘&&c>=‘0‘)x=(x<<1)+(x<<3)+c-‘0‘,c=g(); 40 x*=y; 41 } 42 void o(int x) 43 { 44 if(x<0) 45 { 46 p(‘-‘); 47 x=-x; 48 } 49 if(x>9)o(x/10); 50 p(x%10+‘0‘); 51 } 52 53 void push(int x,int y) 54 { 55 node *p; 56 p=new node(); 57 p->n=y; 58 if(e[x]==NULL) 59 e[x]=p; 60 else 61 { 62 p->next=e[x]->next; 63 e[x]->next=p; 64 } 65 } 66 67 void dfs(int now,int dis,int Time) 68 { 69 d[now]=dis; 70 vis[now]=true; 71 t[now]=Time; 72 for(node *i=e[now];i!=NULL;i=i->next) 73 if(vis[i->n]) 74 { 75 if(t[now]==t[i->n]) 76 ans=min(ans,d[now]-d[i->n]+1); 77 } 78 else 79 dfs(i->n,dis+1,Time); 80 } 81 82 int main() 83 { 84 in(n); 85 For(i,1,n) 86 { 87 in(x); 88 push(i,x); 89 } 90 ans=inf; 91 For(i,1,n) 92 { 93 if(!vis[i]) 94 { 95 t[i]=i; 96 dfs(i,0,i); 97 } 98 } 99 o(ans); 100 return 0; 101 }
标签:dfs tchar algorithm stack 信息 传递 get getc ack
原文地址:http://www.cnblogs.com/war1111/p/7791478.html