Counting Cliques

A clique is a complete graph, in which there is an edge between every pair of the vertices. Given a graph with N vertices and M edges, your task is to count the number of cliques with a specific size S in the graph.
Input
The first line is the number of test cases. For each test case, the first line contains 3 integers N,M and S (N ≤ 100,M ≤ 1000,2 ≤ S ≤ 10), each of the following M lines contains 2 integers u and v (1 ≤ u < v ≤ N), which means there is an edge between vertices u and v. It is guaranteed that the maximum degree of the vertices is no larger than 20.
Output
For each test case, output the number of cliques with size S in the graph.
Sample Input
3
4 3 2
1 2
2 3
3 4
5 9 3
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
6 15 4
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
Sample Output
3
7
15
思路:构建vst[][]矩阵以便于查询各个点之间的关系。vector建图减少查询此点所能到达的点的时间 。
dfs递归进行搜索只要限制下一个进入集合的点比当前的点大就无需考虑搜索重复。(刚开始一直TLE,到最后才发现归零的时候忘记到最大的那个节点了,好菜)

#include"cstdio"
#include"cmath"
#include"cstring"
#include"iostream"
#include"algorithm"
#include"vector"
#include"bits/stdc++.h"
using namespace std;
#define Maxn 1105
vector<int>vec[Maxn];
long long s[Maxn];
long long vst[Maxn][Maxn];
long long N,M,S;
long long sum;
bool check(int a,int b)
{
	for(int i=1;i<=b;i++)
		if(vst[a][s[i]]!=1)
			return false;	
	return true;
}
void dfs(int x,int y)
{
	if(y==S)
	{
		sum++;
		return;
	}
	int len=vec[x].size();
	for(int i=0;i<len;i++)
	{
		if(vec[x][i]<x)//判断是否大于他,小于就直接不用考虑,节省时间复杂度
		{
			continue;
		}
		if(check(vec[x][i],y))
		{
			s[y+1]=vec[x][i];
			dfs(vec[x][i],y+1);
		}
	}
}
int main()
{
	long long T;
	cin>>T; 
	while(T--)
	{	
		cin>>N>>M>>S;
		for(int i=1;i<=N;i++)
		{
            vec[i].clear();
            for(int j=1;j<=M;j++)
            {
            	vst[i][j]=0;
			}
		}
		for(int i=0;i<M;i++)
		{
			long long a,b;
			cin>>a>>b;
			vst[a][b]=vst[b][a]=1;
			vec[a].push_back(b);
			vec[b].push_back(a);
		}
		sum=0;
		for(int i=1;i<=N;i++)
		{
			s[1]=i;
			dfs(i,1);
		}
		printf("%lld\n",sum);
	}
	return 0;
}
发布了76 篇原创文章 · 获赞 1 · 访问量 2763

猜你喜欢

转载自blog.csdn.net/weixin_44824383/article/details/104345702