2016年11月10日 星期四

TIOJ 1833 - Problem B 陽炎眩亂

http://tioj.infor.org/problems/1833

還是很普通的disjoint-set



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<bits/stdc++.h>
using namespace std;
int n,m;
int djs[100005];

int F(int a){
    if(djs[a]==a)return a;
    else return djs[a] = F(djs[a]);
}
void U(int a,int b){
    a=F(a);
    b=F(b);
    djs[b]=a;
}
void P(){
    cout<<"djs:";for(int i=1;i<=n;i++)cout<<djs[i]<<" ";cout<<endl;
}
int main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)djs[i]=i;
    while(m--){
        string s;
        cin>>s;
        if(s[0]=='M'){
            int a,b;
            cin>>a>>b;
            U(a,b);
            // P();
        }
        else{
            int k;
            cin>>k;
            cout<<F(k)<<'\n';
        }
    }
}

沒有留言:

張貼留言