AtCoder Regular Contest 065 D - Connectivity ###K ###K ###K //K
题目链接:https://atcoder.jp/contests/arc065/tasks/arc065_b
题意:给定 城市由公路连接和铁路连接 问每个城市 既有公路连接又有铁路连接的城市有几个,(包括自己)
思路:是否连通 很容易想到两个 并查集 把铁路和公路的都分号集合
然后就是考虑如何一次遍历 全部处理出来,考虑用map pair 维护, 要使得又有铁路连接又有公路连接 只需要 每个i 的 f1[i] f2[i] 就能代表一个独立的集合
这个集合里面的是 既有i号铁路也有i号公路连接的 集合 每个这样的集合++即可
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 #define ull unsigned long long 5 #define pb push_back 6 const int maxn=2e5+10; 7 const int mod=998244353; 8 int f1[maxn]; 9 int f2[maxn]; 10 11 int find1(int x) 12 { 13 if(f1[x]==x) 14 return x; 15 return f1[x]=find1(f1[x]); 16 } 17 int find2(int x) 18 { 19 if(f2[x]==x) 20 return x; 21 return f2[x]=find2(f2[x]); 22 } 23 24 void add1(int x,int y) 25 { 26 int t1=find1(x),t2=find1(y); 27 f1[t1]=t2; 28 } 29 void add2(int x,int y) 30 { 31 int t1=find2(x),t2=find2(y); 32 f2[t1]=t2; 33 } 34 35 int main() 36 { 37 ios::sync_with_stdio(false); 38 cin.tie(0); 39 int n,k,l; 40 cin>>n>>k>>l; 41 for(int i=1;i<maxn;i++) 42 f1[i]=f2[i]=i; 43 while(k--) 44 { 45 int p,q; 46 cin>>p>>q; 47 add1(p,q); 48 } 49 while(l--) 50 { 51 int r,s; 52 cin>>r>>s; 53 add2(r,s); 54 } 55 map<pair<int,int>,int>mp; 56 for(int i=1;i<=n;i++) 57 { 58 mp[{find1(i),find2(i)}]++; 59 } 60 for(int i=1;i<=n;i++) 61 { 62 cout<<mp[{f1[i],f2[i]}]<<" "; 63 } 64 65 66 }

浙公网安备 33010602011771号