并查集应用
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <queue> #include <algorithm> #include <vector> #include <cstring> #include <stack> #include <cctype> #include <utility> #include <map> #include <string> #include <climits> #include <set> #include <string> #include <sstream> #include <utility> #include <ctime> using std::priority_queue; using std::vector; using std::swap; using std::stack; using std::sort; using std::max; using std::min; using std::pair; using std::map; using std::string; using std::cin; using std::cout; using std::set; using std::queue; using std::string; using std::istringstream; using std::make_pair; using std::getline; using std::greater; using std::endl; const int MAXN(20010); struct FIND_SET { int fa[MAXN], dist[MAXN]; void init(int n) { for(int i = 1; i <= n; ++i) { fa[i] = i; dist[i] = 0; } } int find(int sour) { if(sour != fa[sour]) { int tf = find(fa[sour]); dist[sour] += dist[fa[sour]]; fa[sour] = tf; return tf; } else return sour; } void Union(int sour1, int sour2) { fa[sour1] = sour2; dist[sour1] = abs(sour1-sour2)%1000; } int query(int sour) { find(sour); return dist[sour]; } }; FIND_SET fs; char str[5]; int main() { int T, N; scanf("%d", &T); while(T--) { scanf("%d", &N); fs.init(N); int op1, op2; while(scanf("%s", str), str[0] != 'O') { if(str[0] == 'E') { scanf("%d", &op1); printf("%d\n", fs.query(op1)); } else { scanf("%d%d", &op1, &op2); fs.Union(op1, op2); } } } return 0; }