学习到的一种全新的做法,每次输入一个路径时将他们的最老祖先找到并记录,最后做出来代码短的吃惊。
// Problem#: 19852
// Submission#: 4951325
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
using namespace std;
int set[100001];
int findSet(int p);
int main() {
int p, q;
for (int i = 0; i < 100002; i++) {set[i] = i;}
while(cin >> p >> q) {
if (findSet(p) != findSet(q)) {
cout << p << ' ' << q << endl;
set[findSet(p)] = set[findSet(q)];
}
}
return 0;
}
int findSet(int p) {return p == set[p]?p:(set[p] = findSet(set[p]));}