这一题开始用的是图的DFS,后来发现边的染色情况会算重><比如样例2里(1,2)染为on,DFS后(4,1)是off,而(1,4)染为off,再DFS(2,1)就会变成on。
后来看正解都是从边入手,如果有点的度数是奇数,ans=0。所以最多有8*6/2=24条边,每个边有两种选择,DFS复杂度是2^24=16777216,不过T=100><加上剪枝应该还OK吧><
首先要判断如果有节点度数是奇数,直接输出0。
DFS逐个给每一组边染色,并记录每个节点offline的边数和online的边数,如果其中一个大于该节点度数的一半,则可以停止继续将未染色的边继续染成这种颜色(on or off),因为这一节点肯定不会满足online==offline了。
#include<iostream>
#include<stdio.h>
#include<cstdio>
#include<stdlib.h>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<stack>
#include<queue>
#include<ctype.h>
#include<map>
#include<time.h>
#include<bitset>
#include<set>
#include<list>
using namespace std;
//hdu 5305
const int maxn=10;
int T;
int n;
int m;
int deg[maxn];
int degon[maxn];
int degoff[maxn];
int ans=0;
pair<int,int>edge[4*maxn];
bool calcolor()
{
for(int i=1;i<=n;i++)
{
if(degon[i]!=degoff[i])
{
return false;
}
}
return true;
}
void dfs(int st)
{
if(st==m)
{
if(calcolor()==true)
{
ans++;
return;
}
}
int x=edge[st].first;
int y=edge[st].second;
if(degon[x]<deg[x]/2&°on[y]<deg[y]/2)//if we make this edge as online relationship
{
degon[x]++;
degon[y]++;
dfs(st+1);
degon[x]--;
degon[y]--;
}
if(degoff[x]<deg[x]/2&°off[y]<deg[y]/2)//if we made this edge as offline relationship
{
degoff[x]++;
degoff[y]++;
dfs(st+1);
degoff[x]--;
degoff[y]--;
}
}
int main()
{
freopen("input.txt","r",stdin);
scanf("%d",&T);
for(int ca=1;ca<=T;ca++)
{
scanf("%d %d",&n,&m);
int x=0;
int y=0;
ans=0;
memset(edge,0,sizeof(edge));
memset(deg,0,sizeof(deg));
memset(degon,0,sizeof(degon));
memset(degoff,0,sizeof(degoff));
for(int i=0;i<m;i++)
{
scanf("%d %d",&x,&y);
edge[i]=make_pair(x,y);
deg[x]++;
deg[y]++;
}
bool flg=true;
for(int i=1;i<=n;i++)
{
if(deg[i]%2!=0)
{
flg=false;
break;
}
}
if(flg==true)
{
dfs(0);
printf("%d\n",ans);
}
else
{
printf("0\n");
}
}
return 0;
}