您的位置:首页 > 其它

HDOJ5305 Friends(dfs)

2015-08-29 18:19 204 查看


Friends

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

Total Submission(s): 1797 Accepted Submission(s): 903



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




n个人中有m对朋友关系,问你有多少种方案可以使得online friends 和 offline friends数量相同。

朋友关系数是奇数时没有方法满足题意,而后每个人进行dfs。

AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
bool map[10][10];
int deg[10], c1[10], c2[10];
int n, m, cnt, ans;
struct node
{
	/* data */
	int u, v;
}e[100005];
void dfs(int x)
{
	if(x == m + 1) {
		ans++;
		return ;
	}
	int v = e[x].v, u = e[x].u;
	if(c1[u] && c1[v]) {
		c1[u]--;
		c1[v]--;
		dfs(x + 1);
		c1[u]++;
		c1[v]++;
	}
	if(c2[u] && c2[v]) {
		c2[u]--;
		c2[v]--;
		dfs(x + 1);
		c2[u]++;
		c2[v]++;
	}
	return ;
}
int main(int argc, char const *argv[])
{
	int t;
	scanf("%d", &t);
	while(t--) {
		scanf("%d%d", &n, &m);
		cnt = 0;
		ans = 0;
		memset(deg, 0, sizeof(deg));
		memset(e, 0, sizeof(e));
		memset(c1, 0, sizeof(c1));
		memset(c2, 0, sizeof(c2));
		for(int i = 1; i <= m; ++i) {
			scanf("%d%d", &e[i].u, &e[i].v);
			deg[e[i].u]++;
			deg[e[i].v]++;
		}
		bool flag = false;
		for(int i = 1; i <= n; ++i) {
			c1[i] = c2[i] = deg[i] / 2;
			if(deg[i] & 1) {
				flag = true;
				break;
			}
		}
		if(flag) {
			printf("0\n");
			continue;
		}
		dfs(1);
		printf("%d\n", ans);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: