Alice lives in the country where people like to make friends. The friendship is bidirectional and if any two person have no less than k friends in common, they will become friends in several days. Currently, there are totally n people in the country, and m friendship among them. Assume that any new friendship is made only when they have sufficient friends in common mentioned above, you are to tell how many new friendship are made after a sufficiently long time.
Input
There are multiple test cases.
The first lien of the input contains an integer T (about 100) indicating the number of test cases. Then T cases follow. For each case, the first line contains three integers n, m, k (1 ≤ n ≤ 100, 0 ≤ m ≤ n×(n-1)/2, 0 ≤ k ≤ n, there will be no duplicated friendship) followed by m lines showing the current friendship. The ith friendship contains two integers ui, vi (0 ≤ ui, vi < n, ui ≠ vi) indicating there is friendship between person ui and vi.
Note: The edges in test data are generated randomly.
Output
For each case, print one line containing the answer.
Sample Input
3
4 4 2
0 1
0 2
1 3
2 3
5 5 2
0 1
1 2
2 3
3 4
4 0
5 6 2
0 1
1 2
2 3
3 4
4 0
2 0
Sample Output
2
0
4
思路:枚举每一个点是否同时是两个人的朋友。如果两个人相同的朋友数不小于k个,那么他们两个也是朋友,同时让他们建立朋友关系。接下来继续寻找是否有新的朋友关系建立,直到最后遍历所有的点后都不能再建立朋友关系时退出
代码:
#include
#include
int vis[110][110];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(vis,0,sizeof(vis));
int n,m,k,u,v;
scanf("%d%d%d",&n,&m,&k);
for(int i=0; iscanf("%d%d",&u,&v);
vis[u][v]=vis[v][u]=1;
}
int ans=0,flag=1;
while(flag)
{
flag=0;
for(int i=0; ifor(int j=i+1; jif(!vis[i][j])
{
int cnt=0;
for(int l=0; l//枚举每一个点
{
if(vis[i][l]&&vis[j][l])
++cnt;
}
if(cnt>=k)
{
flag=1;
++ans;
vis[i][j]=vis[j][i]=1;
}
}
}
}
printf("%d\n",ans);
}
return 0;
}
ps:比赛时我用的是二维数组vector,re[x].size()代表x有多少个朋友,如果两个人是朋友,就让他们互相加入数组中。然而在加入vector的时候,可能会出现重复加入的情况,这种情况没有考虑到所以就wrong了。。。。
我修改后的代码:
#include
#include
#include
#include
#include
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define maxn 100+10
int n,m,k;
int vis[maxn][maxn];
vector<int>re[maxn];
int judge(int x,int y)
{
set<int>s;//set去除了重复的元素
for(int i=0; ifor(int i=0; iint num=re[x].size()+re[y].size();
if(num-s.size()>=k)
return 1;
return 0;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
mem(vis,0);
scanf("%d%d%d",&n,&m,&k);
for(int i=0; i<=100; i++)
vis[i][i]=1,re[i].clear();
int u,v;
for(int i=0; iscanf("%d%d",&u,&v);
re[u].push_back(v);
re[v].push_back(u);
vis[u][v]=vis[v][u]=1;
}
int ans=0;
int flog=1;
while(flog)
{
flog=0;
for(int i=0; ifor(int j=i+1; jif(!vis[i][j])
{
if(judge(i,j))
{
flog=1;
re[i].push_back(j);
re[j].push_back(i);
vis[i][j]=vis[j][i]=1;
ans++;
}
}
}
}
}
printf("%d\n",ans);
}
return 0;
}