HDU5952 Counting Cliques (dfs)

来源:互联网 发布:vmware fusion 知乎 编辑:程序博客网 时间:2024/05/27 00:31

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
34 3 21 22 33 45 9 31 31 41 52 32 42 53 43 54 56 15 41 21 31 41 51 62 32 42 52 63 43 53 64 54 65 6
 

Sample Output
3715
 

Source
2016ACM/ICPC亚洲区沈阳站-重现赛(感谢东北大学)


题意:有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;}

原创粉丝点击