N - Is It A Tree? POJ - 1308

xiaoxiao2021-02-28  87

题目大意:

       跟小希的迷宫差不多,其实这个题的代码我用小希的代码加了一个判断条件就AC了。

解题思路:

       看到别人的易错情况:

1、0 0 yes

2、1 1 0 0 no

3、1 2 1 2 0 0 no 

4、1 2 2 3 4 5 0 0 no (多个根结点)

5、1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 0 0  no(环?一个结点指向祖先)

6、1 2 2 1 0 0 no

参考代码:

#include <iostream> #include <vector> #include <map> #include <string> #include <queue> #include <stack> #include <set> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> using namespace std; const int INF=0x3f3f3f3f; const int SIZE=1e5+10; set<int> st; ///这个是为了两两查找的时候方便一点 int id[SIZE]; int sz[SIZE]; int count; int find(int x) ///找跟根结点 { while(x!=id[x]) { id[x]=id[id[x]]; x=id[x]; } return x; } int un(int p,int q) { int pr=find(p); int qr=find(q); if(pr==qr) return -1; if(sz[pr]<=sz[qr]) { sz[qr]+=sz[pr];id[pr]=qr; } else { sz[pr]+=sz[qr];id[qr]=pr; } } void clear() { for(int i=1;i<=SIZE;i++) { id[i]=i;sz[i]=1; } st.clear(); } int main() { int p,q; int temp,flag; int cas=1; while(cin>>p>>q) { flag=0; clear(); if(p==-1&&q==-1) break; if(p==0&&q==0) {cout<<"Case "<<cas<<" is a tree.\n";cas++;continue;}///特判0 0的情况 if(p==q) flag=1; *************小希的迷宫增加的唯一判断 st.insert(p); st.insert(q); un(p,q); int mark=p; while(cin>>p>>q) { if(p==0&&q==0) break; if(p==q) flag=1; //*******小希的迷宫增加的唯一判断 if(!flag) temp=un(p,q); if(temp==-1) flag=1; st.insert(p);st.insert(q); } count=st.size(); if(sz[find(mark)]<count) flag=1; if(flag==1) cout<<"Case "<<cas<<" is not a tree.\n"; else cout<<"Case "<<cas<<" is a tree.\n"; cas++; } return 0; }

转载请注明原文地址: https://www.6miu.com/read-97285.html

最新回复(0)