Counting Cliques
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1243 Accepted Submission(s): 479
Problem Description
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
Source
暴力即可,判断所有的点,如果该点的度数小于s-1,那肯定不行。否则对该点进行dfs,判断与该点连接的所有点中,存在多少个满足条件的情况,对一个点dfs后,可以做如下的减枝操作:把所有与改点相连的边删掉,这样可以加快速度。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<string.h>
using namespace std;
vector<int>V[105];
int deg[105];
int road[105][105];
int n,m,s;
int stack[105];
int h;
int ans;
void dfs(int now,int di)
{
if(h==s)
{
ans++;
return;
}
if(di>V[now].size()||V[now].size()-di<(s-h)) return;
int f=1;
for(int i=0;i<h;i++)
{
if(road[V[now][di]][stack[i]]==0)
{
f=0;
break;
}
}
if(f==1)
{
stack[h++]=V[now][di];
dfs(now,di+1);
h--;
}
dfs(now,di+1);
}
int main()
{
int cas;
scanf("%d",&cas);
while(cas--)
{
for(int i=0;i<105;i++)
{
V[i].clear();
}
ans=0;
memset(deg,0,sizeof(deg));
memset(road,0,sizeof(road));
scanf("%d%d%d",&n,&m,&s);
int u,v;
for(int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
V[u].push_back(v);
V[v].push_back(u);
road[u][v]=1;
road[v][u]=1;
deg[u]++;
deg[v]++;
}
for(int i=1;i<=n;i++)
{
if(deg[i]<s-1)
continue;
h=0;
stack[h++]=i;
dfs(i,0);
for(int j=1;j<=n;j++)
{
if(road[i][j])
{
road[i][j]=road[j][i]=0;
deg[j]--;
}
}
}
cout<<ans<<endl;
}
return 0;
}