AcWing 4415. 点的赋值

给定一个 n 个点 m 条边的无向无权图。

点的编号为 1∼n。

图中不含重边和自环。

现在,请你给图中的每个点进行赋值,要求:

每个点的权值只能是 1 或 2 或 3。
对于图中的每一条边,其两端点的权值之和都必须是奇数。
请问,共有多少种不同的赋值方法。

由于结果可能很大,你只需要输出对 998244353 取模后的结果。

输入格式
第一行包含整数 T,表示共有 T 组测试数据。

每组数据第一行包含两个整数 n,m。

接下来 m 行,每行包含两个整数 u,v,表示点 u 和点 v 之间存在一条边。

输出格式
一个整数,表示不同赋值方法的数量对 998244353 取模后的结果。

数据范围
前三个测试点满足 1≤T≤6,∑i=1Tm≤50。
所有测试点满足 1≤T≤3×105,1≤n≤3×105,0≤m≤3×105,1≤u,v≤n,∑i=1Tn≤3×105,∑i=1Tm≤3×105。

输入样例:
2
2 1
1 2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
输出样例:
4
0

进行二分图染色,黑色的数量为cnt1,白色为cnt2,因为奇数有两种选择,所以每个连通块的方案数为2^cnt1 + 2^cnt2

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 3e5+10,mod = 998244353;
int color[N];
int cnt1=0,cnt2=0;
vector<int> v[N];
bool work(int now,int clr){
if(clr==1) cnt1++;
else cnt2++;
for(int y:v[now]){
if(color[y]==clr) return false;
if(!color[y]){
color[y]=3-clr;
if(!work(y,3-clr)) return false;
}
}
return true;
}
int qpow2(int x){
LL base=2,ans=1;
while(x){
if(x&1){
ans=ans*base%mod;
}
base=base*base%mod;
x>>=1;
}
return ans%mod;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t,n,m,x,y;
cin>>t;
while(t--){
cin>>n>>m;
for(int i=1;i<=n;i++) v[i].clear(),color[i]=0;
for(int i=1;i<=m;i++){
cin>>x>>y;
v[x].push_back(y);
v[y].push_back(x);
}
bool flag=true;
LL tot=1;
for(int i=1;i<=n;i++){
cnt1=0,cnt2=0;
if(color[i]) continue;
color[i]=1;
if(!work(i,1)){
flag=false;
break;
}
//cout<<cnt1<<" "<<cnt2<<endl;
tot=tot*(qpow2(cnt1)+qpow2(cnt2))%mod;
}
if(!flag) cout<<0<<endl;
else cout<<tot<<endl;
}
}

本文作者:xhy666

本文链接:https://www.cnblogs.com/xhy666/p/16224503.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   xhy666  阅读(30)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起