问题描述:
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.
问题分析:
问题的大意是有n个人其中m对朋友。朋友分为网络朋友和现实朋友,问给定m对朋友关系,要求每个人网络朋友的显示朋友数量相等的情况下,求出有多少中朋友关系。
这题的解题思路也很明确直接用dfs。我的dfs方法是遍历每一个人和其他人的朋友关系,从第一个人开始遍历,遍历到n满足条件就加1。dfs(x,y)表示当前第x个人与第y个人的关系。
AC代码:
/*
author:Manson
date:8.20.2018
theme:
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 50;
int used[N];
int g[N][N];
int on[N],off[N];
int n,m,ans;
//x表示遍历的点,而y表示与遍历的点连接的点
void dfs(int x,int y){
//遍历满足条件,成功结束
if(x > n){
ans++;
}
//一个点所有相邻的点遍历结束
else if(y > n){
//不满足时直接退出
if(on[x] != off[x]){
return;
}
dfs(x+1,x+2);
}
else{
//如果是相连接的点
if(g[x][y]){
on[x]++;
on[y]++;
dfs(x,y+1);
on[x]--;
on[y]--;
off[x]++;
off[y]++;
dfs(x,y+1);
off[x]--;
off[y]--;
}
else{
dfs(x,y+1);
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin>>t;
while(t--){
cin>>n>>m;
memset(g,0,sizeof(g));
memset(on,0,sizeof(on));
memset(off,0,sizeof(off));
for(int i = 0;i < m;i++){
int x,y;
cin>>x>>y;
g[x][y] = 1;
g[y][x] = 1;
}
if(m % 2 == 1){
cout<<0<<endl;
continue;
}
ans = 0;
dfs(1,2);
cout<<ans<<endl;
}
return 0;
}