http://acm.hdu.edu.cn/showproblem.php?pid=1272
小希的迷宫 使用并查集求解。
- //小希的迷宫
- //*****并查集*****
- #include<stdio.h>
- #define N 100001
- int parent[N];
- int height[N];
- int get_parent(int v)
- {
- while (parent[v] != v)
- {
- v = parent[v];
- }
- return v;
- }
- void main()
- {
- int u, v;
- int i;
- int temp1, temp2;
- int flag, count;
- while (scanf("%d%d", &u, &v) != EOF && !(u == -1 && v == -1))
- {
- if (u == 0 && u == 0)
- {
- printf("Yes\n");
- continue;
- }
- for (i = 1; i < N; i++)
- {
- parent[i] = i;
- height[i] = 1;
- }
- flag = 0;
- if (u == v)
- flag = 1;
- else
- {
- parent[v] = u;
- height[u]++;
- }
- while (scanf("%d%d", &u, &v) != EOF && !(u == 0 && v == 0))
- {
- temp1 = get_parent(u);
- temp2 = get_parent(v);
- if (temp1 == temp2 || flag == 1)
- flag = 1;
- else
- {
- if (height[temp1] > height[temp2])
- parent[temp2] = temp1;
- else
- {
- if (height[temp1] == height[temp2])
- {
- parent[temp2] = temp1;
- height[temp1]++;
- }
- else
- parent[temp1] = temp2;
- }
- }
- }
- count = 0;
- for (i = 1; i < N; i++)
- {
- if (i == parent[i] && height[i] != 1)
- count++;
- }
- if (count <= 1 && flag == 0)
- printf("Yes\n");
- else
- printf("No\n");
- }
- }