Friends
題目描述:
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:
Sample Output:
題目大意:
給出了T個測試樣例子,給了n個人,m對朋友,他要求每一個人都擁有同等數量的在線朋友與離線朋友,要求在m對朋友來分配,有多少種方式,意思就是說這裏有m對朋友,但他們沒有標明是在線還是離線,所以由你來標明,分配即可。
思路分析:
這道題首先要看每個人擁有多少個朋友,如果該朋友數量是奇數,說明無法同等分配,如果是偶數才能繼續分配,這裏有個很簡單的思路把,就是朋友的數量是固定的,但分配朋友對的數量的時候,在線朋友對多一個,離線朋友對就少一個,那麼依次爲條件DFS,看是否所有朋友對數量,能否等於m就即可,就多出一種方法。
AC代碼:
用時:15ms
#include<cstdio>
#include<iostream>
#include<string.h>
using namespace std;
int num[10000];//記錄該人有多少朋友
int Leave[10000];//在線人數
int rise[10000];//離線人數
int sum,flag;//flag用於標記,sum用於方法
int m,n;
struct
{
int n1,n2;
}Lemon[10000];//標記朋友對數量
void LemonDFS(int num1)
{
if(num1 == m+1)//如果剛好等於朋友對數量,說明滿足條件
{
sum++;
return;
}
//記錄朋友對的關係
int LF= Lemon[num1].n1;
int RF= Lemon[num1].n2;
if(rise[LF] && rise[RF])//在線人數分配
{
rise[LF]--;
rise[RF]--;
LemonDFS(num1+1);
rise[LF]++;
rise[RF]++;
}
if(Leave[LF] && Leave[RF])//離線人數分配
{
Leave[LF]--;
Leave[RF]--;
LemonDFS(num1+1);
Leave[LF]++;
Leave[RF]++;
}
return;
}
int main()
{
int T;
cin >> T;
while(T--)
{
memset(Lemon,0,sizeof(Lemon));
memset(Leave,0,sizeof(Leave));
memset(rise,0,sizeof(rise));
memset(num,0,sizeof(num));
//刷新4個數組的數據
sum=0;//記錄 方法數量
cin >> n >> m;//輸入人數量與朋友數量
for(int i=1;i<=m;i++)//開始標明第幾號人有多少個朋友
{
cin >> Lemon[i].n1 >> Lemon[i].n2;
num[Lemon[i].n1]++;
num[Lemon[i].n2]++;
}
flag=0;//標記是否有方法
for(int i=1;i<=n;i++)
{
rise[i]=Leave[i]=num[i]/2;//如果朋友對是偶數才能同等分配,如果是奇數
//不滿足條件,退出循環。
if(num[i]%2!=0)
{
flag=1;
break;
}
}
if(flag)//無方法的時候
{
printf("0\n");
}
else//有方法的時候就 DFS分配
{
LemonDFS(1);
printf("%d\n",sum);
}
}
}