P1714] [Week4 islands | |
|
Problem Description
N-islands on the lake, numbered from 1 ~ n. Now to make the bridge connecting the island on the lake. Bridge two-way traffic.
Input Format
Input of the first line has two integers n, m.
Followed by m rows, each row in order of time is a query.
Each line q represents an integer of inquiry content:
if q = 1, then the next number is two islands a, b (a ≠ b) ;
if q = 2, then the next number is an island c.
Output Format
For each query, the answer in sequence as the respective output line:
Q =. 1 applies: If a, b to each other up, output Yes; if a, b is not reachable to each other, the output No, and built in between a, b a bridge.
when q = 2: Output an integer x, it can reach starting from the islands c x (excluding itself c).
Sample input
5 9
1 2 3
1 3 2
2 1
2 2
1 4 5
1 2 4
1 2 5
2 4
2 5
Sample Output
No
Yes
0
1
No
No
Yes
3
3
prompt
To 100% of the data, 2≤n≤10,000, 1≤m≤30,000.
// #include<bits/stdc++.h> using namespace std; #define maxnn 30100 int f[maxnn],cnt[maxnn]; int q; int n,m; int gf(int v) { return f[v]==v? v: f[v]=gf(f[v]); } void merge(int x,int y) { int fx=gf(x); int fy=gf(y); if(fx!=fy) { f[fx]=fy; cnt[fy]+=cnt[fx]; } } int main() { cin>>n>>m; int x,y; for(int i=1;i<=n;i++) f[i]=i,cnt[i]=1; for(int i=1;i<=m;i++) { cin>>q; if(q==1) { cin>>x>>y; if(gf(x)==gf(y)) cout<<"Yes"<<endl; else cout<<"No"<<endl; if(!(gf(x)==gf(y))) merge(x,y); } else { cin>>x; cout<<cnt[gf(x)]-1<<endl; } } }