HDU 1232

来源:互联网 发布:故宫 淘宝 彩妆 编辑:程序博客网 时间:2024/06/05 11:42

题目大意:中文题

解题思路:最基础的并查集,注意一点,虽然路径优化了,但pre[i]不一定就是最上级,所以最后查找还得用find函数。该博客详尽的多http://blog.csdn.net/dellaserss/article/details/7724401/

ac代码:

#include <iostream>#include <set>using namespace std;int n, m, t1, t2, pre[1005];set <int>se;int find(int x){int r=x, temp;while (r != pre[r])r = pre[r];while (r != x){temp = pre[x];pre[x] = r;x = temp;}return r;}void join(int x, int y){int fx=find(x), fy=find(y);if (fx != fy)pre[fx] = fy;}int main(){while (scanf("%d", &n)!=EOF && n){scanf("%d", &m);for (int i=1; i<=n; i++)pre[i] = i;for (int i=0; i<m; i++){scanf("%d%d", &t1, &t2);join(t1, t2);}for (int i=1; i<=n; i++)se.insert(find(i));printf("%d\n", se.size()-1);se.clear();}return 0;}
原创粉丝点击