Counting Cliques
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 622 Accepted Submission(s): 235
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
题意:n个点,m条边(n<=100,m<=1000),每个点最大度数为20度的简单图。问图中有多少个点数为s(s<=10)的完全图。
解法:完全图的性质是图中每一对不同顶点之间恰好只有一条边的简单图,可以知道完全图中每一个点要与图中其他所有点相连。s为10,每个点最大度数为20,那么我们就可以枚举每一个点,在它连着的所有点中找s-1个点出来与当前点构成一个大小为s的图,再判断这个图是不是完全图进行计数就行了。因为有重复计数,答案要除s。
这样做的最高复杂度是C(9,20)*100*(判断完全图)。C(9,20)为17W。判断算100的话,就1e9了,反正杭电会T,不过据说沈阳现场能过。
然后就需要剪枝,我当时想到了优化判断完全图,在添加进一个点时,判断这个点是否与之前每个点都相连,如果不相连,当前这种状态以及后续构成的状态都不可能是完全图,就不需要再继续搜下去。这样优化了一个常数,但是并没有什么用,还是T。
最后考虑了一下,可以不可把重复计数这个过程去掉,就自然想到枚举了一个点之后,把这个点删掉,以后包含这个点的情况都不再考虑进去。这样就避免了重复计数的问题。然后再交就过了。
CODE
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 105;
int n,m,s,ans;
int G[N][N]; ///邻接表存图
int sz[25]; ///邻接表size
int a[25]; ///dfs过程中存判断完全图的点
int mp[N][N]; ///邻接矩阵方便判断点之间的关系
void Init() ///初始化
{
ans = 0;
memset(mp,0,sizeof mp);
memset(sz,0,sizeof sz);
}
void add(int u,int v) ///加边
{
G[u][++sz[u]] = v; ///模拟邻接表加边
mp[u][v] = 1; ///邻接矩阵加边
}
int chk(int dep) ///只需要判断一个点是否与前面几个点有边
{
for(int i = 1;i < dep;i++)
if(!mp[a[dep]][a[i]]) return 0;
return 1;
}
void dfs(int u,int id,int dep)
{
if(dep == s){
ans += chk(dep-1);
return;
}
if(!chk(dep-1)) return; ///dfs中判断
for(int i = id+1;i <= sz[u];i++){
if(sz[G[u][i]] == 0) continue;
a[dep] = G[u][i];
dfs(u,i,dep+1);
}
}
void solve()
{
for(int i = 1;i <= n;i++){ ///枚举点
dfs(i,0,1);
sz[i] = 0; ///sz赋值为0就相当于删除操作了
}
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--){
Init();
scanf("%d%d%d",&n,&m,&s);
for(int i = 1;i <= m;i++){
int u,v;
scanf("%d%d",&u,&v);
add(u,v);
add(v,u);
}
solve();
printf("%d\n",ans);
}
return 0;
}