NC252835. Dream Team
描述
输入描述
The first line contains two integers , representing there are students and pairs of students directly familiar with each other.For the following lines, each line contains two integers , representing are directly familiar with each other.
输出描述
A single integer, represents the minimum sum of anxiety level of all students.
示例1
输入:
3 5 1 2 1 3 4 5 4 6 7 8
输出:
4
C++(clang++ 11.0.1) 解法, 执行用时: 216ms, 内存消耗: 23928K, 提交时间: 2023-06-08 08:46:04
#include <iostream> using namespace std; int n,m,x,y,a,b,f[3000006],num[3000006]; int fnd(int x){ return f[x]==x?x:f[x]=fnd(f[x]); } int main() { cin>>n>>m; n*=3; for(int i=1;i<=n;i++) f[i]=i; for(int i=1;i<=m;i++){ cin>>x>>y; int fx=fnd(x),fy=fnd(y); if(fx!=fy) f[fx]=fy; } for(int i=1;i<=n;i++) num[fnd(i)]++; for(int i=1;i<=n;i++){ if(f[i]==i){ if(num[i]%3==2) a++; else if(num[i]%3==1) b++; } } if(a>=b) cout<<b*4+(a-b)/3*8; else cout<<(a+b)*2; return 0; }
C++(g++ 7.5.0) 解法, 执行用时: 135ms, 内存消耗: 26912K, 提交时间: 2023-07-09 21:43:08
#include <iostream> using namespace std; int n,m,x,y,a,b,f[3000001],d[3000001],i; int fnd(int a){ return f[a]==a?a:f[a]=fnd(f[a]); } int main() { cin>>n>>m; n*=3; for(;i<n;i++) f[i]=i,d[i]=1; for(i=0;i<m;i++){ scanf("%d%d",&x,&y); x=fnd(x),y=fnd(y); if(x!=y) f[x]=y,d[y]+=d[x]; } for(i=0;i<n;i++){ if(f[i]==i){ if(d[i]%3==2) a++; if(d[i]%3==1) b++; } } cout<<(a>b?b*4+(a-b)/3*8:(a+b)*2); return 0; }