Counting Cliques
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2922 Accepted Submission(s): 1059
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条边的无向图,从图中找个有S个顶点的连通图,求能够找到的数目。
思路:一开始的想法是通过dfs直接找到所有的恰好S个顶点的子图,然后把顶点排序,用set判重,不过一直超内存Orz,然后看了题解发现只要构造一个有向图,dfs搜索的时候就不会让所有的顶点重复啦。也就是
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int N,M,S,maze[110][110],cnt,ans,head[1110];
struct Edge{
int to,next;
}edge[1110];
void add(int u, int v){
edge[cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt ++;
}
void dfs(int rt, int cur, int a[]){
if(cur >= S){
ans ++;
return ;
}
for(int i = head[rt]; i != -1; i = edge[i].next){
int u = edge[i].to;
bool flag = true;
for(int j = 0; j < cur; j ++){
if(!maze[u][a[j]]){
flag = false; break;
}
}
if(flag){
a[cur] = u;
dfs(u,cur+1,a);
}
}
}
int main(){
int t;
scanf("%d",&t);
while(t --){
scanf("%d%d%d",&N,&M,&S);
cnt = 0;
memset(maze,0,sizeof(maze));
memset(head,-1,sizeof(head));
for(int i = 1; i <= M; i ++){
int u,v;
scanf("%d%d",&u,&v);
if(u < v) swap(u,v);
maze[u][v] = maze[v][u] = 1;
add(u,v);//人为构造一个有向图
}
int a[15];
ans = 0;
for(int i = 1; i <= N; i ++){
a[0] = i;
dfs(i,1,a);
}
printf("%d\n",ans);
}
return 0;
}