Friends
- Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
- Total Submission(s): 3 Accepted Submission(s): 3
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.
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.
For each testcase, print one number indicating the answer.
2
3 3
1 2
2 3
3 1
4 4
1 2
2 3
3 4
4 1
0
2
题意:有n个人和m个联系,有两种关系,线上,线下。要求每个人的线下朋友和线上朋友一样。这就是一个带权的无向图,要求出度等于入度,题目点数要求较少,用DFS暴力求解,如果直接暴力,会超时。所以要去除一些条件,如一个点的度一定要是偶数。还有的就是在DFS的时候如果点的出度或者入度超过了总度数的一半,就不再继续往下搜。
#include<bits/stdc++.h>
using namespace std;
int b[35][2];
int note[35];//总度数
int x[35]; //出度
int y[35];//入度
int co,n,m;
void dfs(int step)
{
if(step==m+1)
{
for(int i=1; i<=n; i++)
{
if(x[i]!=y[i])
{
return;
}
}
co++;
return;
}
int u=b[step][0];
int v=b[step][1];
if(x[u]+1<=note[u]/2&&x[v]+1<=note[v]/2) //出度为总度数的一半的情况下,第step条边为0时
{
x[u]++;
x[v]++;
dfs(step+1);
x[u]--;
x[v]--;
}
if(y[u]+1<=note[u]/2&&y[v]+1<=note[v]/2)//入度为总度数的一半的情况下,第step条边为1时
{
y[u]++;
y[v]++;
dfs(step+1);
y[u]--;
y[v]--;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(note,0,sizeof(note));
memset(x,0,sizeof(x));
memset(y,0,sizeof(y));
memset(b,0,sizeof(b));
scanf("%d %d",&n,&m);
for(int i=1; i<=m; i++)
{
scanf("%d %d",&b[i][0],&b[i][1]);
int u=b[i][0];
int v=b[i][1];
note[u]++;
note[v]++;
}
int jg=1;
for(int i=1; i<=n; i++)
{
if(note[i]%2!=0)
{
jg=0;
break;
}
}
co=0;
if(jg==1)
{
dfs(1);
}
printf("%d\n",co);
}
}