标签:span style name max cond 有一个 const ini size
与无向图那题一样,但是需要多考虑一个点是树入度为0的点只有一个,因此边的前后顺序有了作用,这是和之前题的唯一区别。
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 #include <set> 5 #include <map> 6 using namespace std; 7 const int maxn=1e5+5; 8 9 int x; 10 int f[maxn]; 11 int find(int x){ 12 if(x!=f[x]){ 13 f[x]=find(f[x]); 14 } 15 return f[x]; 16 } 17 void init(){ 18 for(int i=0;i<=100000;i++) 19 f[i]=i; 20 } 21 map<int,int>M; 22 set<int> S; 23 int main(){ 24 int a,b;int flag=1; 25 std::ios::sync_with_stdio(false); 26 init(); 27 int cas=1; 28 while(cin>>a>>b){ 29 if(a==-1&&b==-1) break; 30 if(a==0&&b==0) 31 { 32 //cout <<"flag="<<flag<<endl; 33 //cout <<"S.ize"<<S.size()<<endl; 34 if(flag==0) 35 { 36 cout <<"Case "<<cas++<<" is not a tree.\n"; 37 flag=1; 38 } 39 else 40 { 41 //cout <<"in"; 42 int sign;set<int>::iterator it=S.begin(); 43 if(!S.empty()) sign=find(*it),it++; 44 for(;it!=S.end();it++){ 45 if(find(*it)!=sign) flag=0; 46 //cout <<"in"; 47 } 48 49 if(flag) 50 { 51 int num=0; 52 map<int,int>:: iterator iter=M.begin(); 53 //cout <<M.size()<<endl; 54 for(;iter!=M.end();iter++){ 55 //cout <<iter->first<<" "<<iter->second<<endl; 56 if(iter->second==0) num++; 57 } 58 if(num>1) cout <<"Case "<<cas++<<" is not a tree.\n"; 59 else cout <<"Case "<<cas++<<" is a tree.\n"; 60 } 61 else cout <<"Case "<<cas++<<" is not a tree.\n"; 62 } 63 //cout <<"in"; 64 flag=1; 65 S.clear(); 66 M.clear(); 67 init(); 68 } 69 else 70 { 71 S.insert(a);S.insert(b); 72 M[b]=1;if(!M.count(a)) M[a]=0; 73 int fa=find(a); 74 int fb=find(b); 75 //cout <<"root"<<fa<<" "<<fb<<endl; 76 if(fa==fb) 77 { 78 flag=0; 79 }else 80 { 81 f[fb]=fa; 82 } 83 } 84 } 85 86 return 0; 87 }
标签:span style name max cond 有一个 const ini size
原文地址:https://www.cnblogs.com/Msmw/p/11266575.html