C. Restructuring Company ###K
题目链接:https://codeforces.com/edu/course/2/lesson/7/2/practice/contest/289391/problem/C
题意:n个人,有三种操作,一是x和y合并成同一组人, 二是x x+1~ y 合并成同一组人,三是查询2个人是否同一组,开始各为一组
思路:主要是考虑操作2如何进行,可以开多一个nxt[] 数组 nxt[i]记录的是 第i个人之后的第一个不同组的人
最多每个人 扫一遍之后就不会再需要更新了
1 #include <bits/stdc++.h> 2 #define double long double 3 #define lb long double 4 #define ll long long 5 #define pi pair<int,int> 6 #define fi first 7 #define sc second 8 #define pb push_back 9 using namespace std; 10 const int maxn=2e5+10; 11 12 int f[maxn],nxt[maxn]; 13 14 int find1(int x) 15 { 16 if(x==f[x]) return x; 17 return f[x]=find1(f[x]); 18 } 19 20 21 int main() 22 { 23 ios::sync_with_stdio(0); 24 cin.tie(0); 25 int n,q; 26 cin>>n>>q; 27 for(int i=1;i<=n;i++) f[i]=i,nxt[i]=i+1; 28 while(q--) 29 { 30 int t,x,y; 31 cin>>t>>x>>y; 32 if(t==1) 33 { 34 f[find1(x)]=find1(y); 35 } 36 else if(t==2) 37 { 38 int t1=find1(x); 39 for(int i=x,j;i<=y;i=j) 40 { 41 int t2=find1(i); 42 f[t2]=t1; 43 j=nxt[i]; 44 nxt[i]=nxt[y]; 45 } 46 } 47 else 48 { 49 if(find1(x)==find1(y)) cout<<"YES"<<'\n'; 50 else cout<<"NO"<<'\n'; 51 } 52 } 53 54 55 }

浙公网安备 33010602011771号