HDOJ-1232 畅通工程并查集裸题
Posted codinRay
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDOJ-1232 畅通工程并查集裸题相关的知识,希望对你有一定的参考价值。
题目传送门 : http://acm.hdu.edu.cn/showproblem.php?pid=1232
并查集的裸题
AC code:
#include <iostream> #define MAXN 1050 using namespace std; int pre[MAXN]; int Find(int pos) { int r = pos; while (r != pre[r]) r = pre[r]; int i = pos; while (i != r) { int t = pre[i]; pre[i] = r; i = t; } return r; } void Join(int posX, int posY) { int rootX = Find(posX), rootY = Find(posY); if (rootX != rootY) pre[rootX] = rootY; } int main() { int N, M; while (cin >> N >> M && N) { int ct = 0; for (int i = 1; i <= N; ++i) pre[i] = i; int cityA, cityB; while (M--) { cin >> cityA >> cityB; Join(cityA, cityB); } for (int i = 1; i <= N; ++i) if (pre[i] == i) ct++; cout << ct - 1 << endl; } return 0; }
以上是关于HDOJ-1232 畅通工程并查集裸题的主要内容,如果未能解决你的问题,请参考以下文章