码迷,mamicode.com
首页 > 其他好文 > 详细

[swustoj 856] Huge Tree

时间:2015-05-16 16:12:37      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

 

[swustoj 856] Huge Tree

标签:

原文地址:http://www.cnblogs.com/hate13/p/4507943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!