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
题意:给你一张图,求子图的个数,该子图满足 其定点数为 s, 且是完全图。
思路:暴力 dfs , 用邻接表存边的时候,存顶点号小 到 顶点号大 的边(用于暴力遍历,这样能够保证计算的时候不会计算出重复的子图), 然后一个邻接矩阵 存双向边(用于判断). 然后有一个 a 数组,其中 a[0] 表示子图的顶点数量, 其后存放的是满足条件的子图的顶点号。
AC代码:
#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define INT(t) int t; scanf("%d",&t)
#define LLI(t) LL t; scanf("%I64d",&t)
using namespace std;
const int maxn = 110;
int mp[maxn][maxn];
int head[maxn];
int a[25];
struct xx{
int v,nex;
xx(){}
xx(int v,int nex):
v(v),nex(nex){}
}edge[maxn*10];
int cnt,ans;
int n,m,s;
void dfs(int x){
if(a[0] == s){
++ ans;
return ;
}
for(int i = head[x];i != -1;i = edge[i].nex){
int flag = 0;
int v = edge[i].v;
for(int j = 1;j <= a[0];j ++)
if(!mp[v][a[j]]){
flag = 1;
break;
}
if(flag == 0){
a[0] ++;
a[a[0]] = v;
dfs(v);
a[0] --;
}
}
}
int main()
{
int t; scanf("%d",&t);
while(t --){
scanf("%d%d%d",&n,&m,&s);
clr(mp,0);
cnt = 0; ans = 0;
clr(head,-1);
int u,v;
rep(i,0,m){
scanf("%d%d",&u,&v);
if(u > v) swap(u,v);
edge[cnt] = xx(v,head[u]); /// 建 u 到 v
head[u] = cnt ++;
mp[u][v] = mp[v][u] = 1;
}
for(int i = 1;i <= n;i ++){
a[0] = 1;
a[1] = i;
dfs(i);
}
printf("%d\n",ans);
}
return 0;
}