您的位置:首页 > 其它

hdu 5305 Friends (dfs)

2015-08-13 11:11 399 查看
题目地址
http://acm.hdu.edu.cn/showproblem.php?pid=5305


Friends

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 1626    Accepted Submission(s): 817


Problem 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

 

思路

一开始没有想到是用DFS,模拟了半天全WA了。。不过在n=1时我清楚为什么输出为2就A了。。

AC代码

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cstring>
using namespace std;
int sum[10],on[10],off[10],ans,m;
struct edge
{
int u,v;
};
edge p[100000];
void dfs(int now)
{
if(now==m+1){
ans++;
return;
}
int u=p[now].u;
int v=p[now].v;
if(on[u]&&on[v])
{
on[u]--;
on[v]--;
dfs(now+1);
on[u]++;
on[v]++;
}
if(off[u]&&off[v])
{
off[u]--;
off[v]--;
dfs(now+1);
off[u]++;
off[v]++;
}
return;
}
int main()
{
int tot,f;
int n;
scanf("%d",&tot);
while(tot--){
ans=0;
memset(sum,0,sizeof(sum));
memset(on,0,sizeof(on));
memset(off,0,sizeof(off));
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++){
scanf("%d%d",&p[i].u,&p[i].v);
sum[p[i].u]++;
sum[p[i].v]++;
}
bool f=false;
for(int i=1;i<=n;i++){
on[i]=sum[i]/2;
off[i]=sum[i]/2;
if(sum[i]&1)
{
f=true;
break;
}
}
if(f){
printf("0\n");
continue;
}
dfs(1);
printf("%d\n",ans);

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDU DFS 六校