HDU 5305 Friends dfs
Friends
题目连接:
http://acm.hdu.edu.cn/showproblem.php?pid=5305
Description
There are n people and m pairs of friends. For every pair of friends, they can choose to become online friends (communicating using online applications) or offline friends (mostly using face-to-face communication). However, everyone in these n people wants to have the same number of online and offline friends (i.e. If one person has x onine friends, he or she must have x offline friends too, but different people can have different number of online or offline friends). Please determine how many ways there are to satisfy their requirements.
Input
The first line of the input is a single integer T (T=100), indicating the number of testcases.
For each testcase, the first line contains two integers n (1≤n≤8) and m (0≤m≤n(n−1)2), indicating the number of people and the number of pairs of friends, respectively. Each of the next m lines contains two numbers x and y, which mean x and y are friends. It is guaranteed that x≠y and every friend relationship will appear at most once.
Output
For each testcase, print one number indicating the answer.
Sample Input
2
3 3
1 2
2 3
3 1
4 4
1 2
2 3
3 4
4 1
Sample Output
0
2
Hint
题意
给你一个图,n点m边,你现在边分为两种,叫做“线上朋友”和“线下朋友”
现在对于每个人要求线上朋友和线下朋友一样多
问你有多少种方案。
题解:
数据范围太小了,直接暴力dfs就好了……
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 115;
int n,m,ans,l[maxn],r[maxn];
vector<int>E[maxn];
int cnt1[maxn],cnt2[maxn],cnt[maxn];
void init()
{
for(int i=0;i<maxn;i++)E[i].clear();
memset(cnt,0,sizeof(cnt));
memset(cnt1,0,sizeof(cnt1));
memset(cnt2,0,sizeof(cnt2));
ans=0;
}
void dfs(int x)
{
if(x==m)
{
int flag = 0;
for(int i=1;i<=n;i++)
{
if(cnt1[i]!=cnt2[i])
{
flag=1;
break;
}
}
if(!flag)ans++;
return;
}
if(cnt1[l[x]]<cnt[l[x]]/2&&cnt1[r[x]]<cnt[r[x]]/2)
{
cnt1[l[x]]++;
cnt1[r[x]]++;
dfs(x+1);
cnt1[l[x]]--;
cnt1[r[x]]--;
}
if(cnt2[l[x]]<cnt[l[x]]/2&&cnt2[r[x]]<cnt[r[x]]/2)
{
cnt2[l[x]]++;
cnt2[r[x]]++;
dfs(x+1);
cnt2[l[x]]--;
cnt2[r[x]]--;
}
}
void solve()
{
init();
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
int x,y;scanf("%d%d",&x,&y);
E[x].push_back(y);
E[y].push_back(x);
l[i]=x,r[i]=y;
cnt[x]++,cnt[y]++;
}
for(int i=1;i<=n;i++)
{
if(E[i].size()%2==1)
{
cout<<"0"<<endl;
return;
}
}
dfs(0);
cout<<ans<<endl;
}
int main()
{
int t;scanf("%d",&t);
while(t--)solve();
return 0;
}