[swustoj 856] Huge Tree
Huge Tree(0856)
问题描述
There are N trees in a forest. At first, each tree contains only one node as its root. And each node is marked with a number.
You're asked to do the following two operations:
A X Y, you need to link X's root to Y as a direct child. If X and Y have already been in the same tree, ignore this operation.
B X, you need to output the maximum mark in the chain from X to its root (inclusively).
输入
The first line contains an integer T, indicating the number of followed cases. (1 <= T <= 20)
For each case, the first line contains two integers N and M, indicating the number of trees at beginning, and the number of operations follows, respectively. (1 <= N, M <= 100,000)
And the following line contains N integers, which are the marks of the N trees. (0 <= Mark <= 100,000)
And the rest lines contain the operations, in format A X Y, or B X, (0 <= X, Y < N).
输出
For each 'B X' operation, output the maximum mark.
样例输入
1
5 5
5 4 2 9 1
A 1 2
A 0 4
B 4
A 1 0
B 1
样例输出
1
5
简单并查集、
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define N 100010 int n,m; int val[N]; int mx[N]; int f[N]; void init() { for(int i=1;i<=n;i++){ f[i]=i; mx[i]=val[i]; } } int Find(int x) { if(x==f[x]) return x; int t=f[x]; f[x]=Find(t); mx[x]=max(mx[x],mx[t]); return f[x]; } void UN(int x,int y) { x=Find(x); //y=Find(y); if(x==y) return; f[x]=y; } int main() { int T; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&val[i]); init(); while(m--){ char op; int a,b; scanf(" %c",&op); if(op=='A'){ scanf("%d%d",&a,&b); a++; b++; UN(a,b); } else{ scanf("%d",&a); a++; Find(a); printf("%d\n",mx[a]); } } } return 0; }