[51nod1299]监狱逃离
到现在还是不会写系列,直接贴题解了。
http://www.51nod.com/question/index.html#!questionId=1157
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 #define ll long long 7 #define ui unsigned int 8 using namespace std; 9 const int maxn=100233; 10 struct zs{int too,pre;}e[maxn<<1];int tot,last[maxn]; 11 int zt[maxn],deg[maxn]; 12 int i,j,k,n,m,ans; 13 bool gg[maxn],GG; 14 15 int ra,fh;char rx; 16 inline int read(){ 17 rx=getchar(),ra=0,fh=1; 18 while((rx<'0'||rx>'9')&&rx!='-')rx=getchar(); 19 if(rx=='-')fh=-1,rx=getchar(); 20 while(rx>='0'&&rx<='9')ra*=10,ra+=rx-48,rx=getchar();return ra*fh; 21 } 22 inline void insert(int a,int b){ 23 deg[a]++,deg[b]++; 24 e[++tot].too=b,e[tot].pre=last[a],last[a]=tot, 25 e[++tot].too=a,e[tot].pre=last[b],last[b]=tot; 26 } 27 void dfs(int x,int fa){ 28 zt[x]=1; 29 int num[3]={0,0,0}; 30 for(int i=last[x];i;i=e[i].pre)if(e[i].too!=fa) 31 dfs(e[i].too,x),num[zt[e[i].too]]++; 32 if(gg[x]&°[x]==1)GG=1; 33 if(gg[x])zt[x]=2,ans+=num[1]; 34 else if(num[1]&&num[2])zt[x]=0,ans++; 35 else if(num[1]||num[2])zt[x]=num[1]?1:2; 36 else if(num[0])zt[x]=0; 37 // printf("x:%d zt:%d\n",x,zt[x]); 38 } 39 int main(){ 40 n=read()+1,m=read(); 41 for(i=1;i<n;i++)insert(read()+1,read()+1); 42 for(i=1;i<=m;i++)gg[read()+1]=1; 43 for(i=n;i;i--)if(deg[i]==1){dfs(i,0),ans+=zt[i]==2;break;} 44 printf("%d\n",!GG?ans:-1); 45 }