P17014 [GESP202606 七级] 染色
题目
传送门
思路
我们模拟样例可以发现如果图里面的环里有奇数个点,那么我们至少要3个颜色,否则就要2个颜色。
如果判断环是否是奇数?
在每次输入边时,我们连接u,v,这样子,我们就可以得到若干个连通块,我们只要遍历每个点,看他是否是根节点,并且包含的结点数量为奇数我们就输出3,否则就是输出2。
代码
有注释
#include<bits/stdc++.h>
using namespace std;
int n;
int f[100005],s[100005];
int find(int x){//查询函数
return f[x]==x?f[x]=x:f[x]=find(f[x]);//f[x]=find(f[x]);
}
int main(){
int t;
cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++){
f[i]=i;//初始化
s[i]=1;
}
for(int i=1;i<=n;i++){
int x,y;
cin>>x>>y;
x=find(x),y=find(y);//找根
if(x==y)continue;//一样就算了
s[x]+=s[y];//加上子有的结点数量
f[y]=x;//合并
}
bool f=0;
for(int i=1;i<=n;i++){
if(find(i)==i&&s[i]%2==1){
f=1;//寻找有奇数个结点的环
break;
}
}
if(f==0)cout<<2;
else cout<<3;
cout<<'\n';
}
return 0;
}
无注释
#include<bits/stdc++.h>
using namespace std;
int n;
int f[100005],s[100005];
int find(int x){
return f[x]==x?f[x]=x:f[x]=find(f[x]);//f[x]=find(f[x]);
}
int main(){
int t;
cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++){
f[i]=i;
s[i]=1;
}
for(int i=1;i<=n;i++){
int x,y;
cin>>x>>y;
x=find(x),y=find(y);
if(x==y)continue;
s[x]+=s[y];
f[y]=x;
}
bool f=0;
for(int i=1;i<=n;i++){
if(find(i)==i&&s[i]%2==1){
f=1;
break;
}
}
if(f==0)cout<<2;
else cout<<3;
cout<<'\n';
}
return 0;
}

浙公网安备 33010602011771号