题目连接:
HDU 1272
这个主要是 图的判连通 和 判不存在环 即可。也属于水题。第一次使用了递归压缩路径,纪念一下。
这个主要是 图的判连通 和 判不存在环 即可。也属于水题。第一次使用了递归压缩路径,纪念一下。
// HDU 1272 小希的迷宫 并查集 判连通+判环
//测试数据:
//1 2 2 3 4 5 0 0
//0 0
//6 8 5 3 5 2 6 4 5 6 0 0
//8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0
//3 8 6 8 6 4 5 3 5 6 5 2 0 0
//1 2 2 3 3 4 4 5 5 6 6 1 0 0
//1 2 1 2 0 0
//-1 -1
#include <cstdio>
#include <iostream>
#include <cstring>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int MAXP = 100005;
bool flag;
int father[MAXP];
void init(){
memset(father,-1,sizeof(father));
flag = true;
}
int find(int a){
if (father[a] <= 0) return a;
return father[a] = find(father[a]);
}
void combination(int ra,int rb){
father[rb] = ra; //father[rb]一定为 0 或 -1
if ( father[ra] < 0 )
father[ra] = 0; // 只有-1有资格变成0
}
bool is_connected(){
int s=0;
for (int i =1; i < MAXP; i++)
if (father[i]==0)
s++;
if (s>1)return false;
else return true;
}
int main()
{
// freopen("in.txt","r",stdin);
while(1){
int a,b,l=0;
init();
while(scanf("%d%d",&a,&b)&&a!=-1){
if (a<=0 && b<=0){
if (l==0)
flag = true;
break;
}else{
int ra = find(a);
int rb = find(b);
if (ra == rb){ // they have same ancestor
flag = false;
}else{
combination(ra,rb);
}
}l++;
}
if (a==-1)break;
if (flag && is_connected()){
cout << "Yes" << endl;
}else{
cout << "No" << endl;
}
}
return 0;
}