Counting Cliques
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
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
这道题题意:一个n个点,m条边的无向图中,求n个点的完全子图的数量。
解题思路:只需要暴力搜索每一个点,将可能成为s元完全子图的点(这个点相连的所有点)也加入,同时更新这个完全子图中的点数和那些点,搜索到完全子图中点数为s返回。 但是需要注意:
看题意有100个点,点很少,暴搜一遍吧,但是有可能出现重复而超时,怎么做,用一个数组记录已经存在的团的大小,数组是一个由小到大的数组,即前点要进入团时,判断该节点是否比团内所有点大,这样就避免了重复,判断大小时只需要判断进最后一个点是否比当前点小就行了所以建图是可以按照 小的点指向大的点得方式建图,这样会少很多不必要的搜索操作。
// main.cpp
// temp2
//
// Created by Sly on 2017/3/2.
// Copyright © 2017年 Sly. All rights reserved.
//
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <vector>
#define MAXN 105
using namespace std;
int N,M,S;
int ans;
int edg[MAXN][MAXN];
vector<int>G[MAXN];
void Dfs(int index,int *temp,int size)
{
if(size==S)
{
ans++;
return;
}
int i,j;
for(i=0;i<G[index].size();i++)
{
int v=G[index][i];
bool vis=true;
for(j=1;j<=size;j++)
{
if(!edg[v][temp[j]]){
vis=false;
break;
}
}
if(vis)
{
size++;
temp[size]=v;
Dfs(v,temp,size);
temp[size]=0;
size--;
}
}
}
int main()
{
int i,T;
scanf("%d",&T);
while(T--)
{
ans=0;
memset(edg,0,sizeof(edg));
for(i=1;i<=100;i++)G[i].clear();
scanf("%d%d%d",&N,&M,&S);
for(i=0;i<M;i++)
{
int a,b;
scanf("%d %d",&a,&b);
edg[a][b]=edg[b][a]=1;
if(a>b)swap(a, b);
G[a].push_back(b); //建立一个小节点指向大节点的图
}
for(i=1;i<=N;i++)
{
int temp[MAXN];
memset(temp,0,sizeof(temp));
temp[1]=i;
Dfs(i,temp,1);
}
printf("%d\n",ans);
}
return 0;
}