(HDOJ)Friends-DFS

                                            Friends

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2857    Accepted Submission(s): 1359


 

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≤mn(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 xy 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

 题目分析:

题目大意是m对朋友中,每个人之间可以做online朋友可以做offline朋友,要求每个人的online和offline朋友相等,问有多少种可能的情况。

两个人之间要么online朋友要么offline朋友,就DFS对于每个做online搜一下,对offline搜一下。最后满足情况就记下数,就欧克了。

代码:

#include<iostream>
using namespace std;
struct node {
	int a;
	int b;
};

int T, n, m;
node list[30];			//记有多少对输入
int online[10];			//第i个人的online朋友数 i = 1,2,3...
int offline[10];		//第i个人的offline朋友数
int Friend[10];			//第i个人的总朋友数
int sum = 0;			//计数
void DFS(int t) {
	if (t == m) {
		sum++;
		return;
	}
	//第t对朋友做online朋友,如果该对中的某个人的online朋友超过了他的总朋友的一半就不用搜了。
	online[list[t].a]++;
	online[list[t].b]++;
	if (online[list[t].a] <= Friend[list[t].a] / 2 && online[list[t].b] <= Friend[list[t].b] / 2) {
		DFS(t + 1);
	}
	online[list[t].a]--;
	online[list[t].b]--;
	
	//同上边的意思
	offline[list[t].a]++;
	offline[list[t].b]++;
	if (offline[list[t].a] <= Friend[list[t].a] / 2 && offline[list[t].b] <= Friend[list[t].b] / 2) {
		DFS(t + 1);
	}
	offline[list[t].a]--;
	offline[list[t].b]--;
}

int main() {
	cin >> T;
	while (T--) {
		cin >> n >> m;
		memset(Friend, 0, sizeof(Friend));
		memset(online, 0, sizeof(online));
		memset(offline, 0, sizeof(offline));
		for (int i = 0; i < m; i++) {
			cin >> list[i].a>>list[i].b;
			Friend[list[i].a]++;
			Friend[list[i].b]++;
		}
		DFS(0);
		cout << sum << endl;
		sum = 0;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xiaosi1524/article/details/81428142