Counting Cliques
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 184 Accepted Submission(s): 56
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
建图思路参考:http://blog.csdn.net/yuanjunlai141/article/details/52972715
总是TLE,然后看了看上面的博客中建图的方法,好巧妙!之所以可以从小的节点指向大的节点是因为,最后要找的是一个无向完全图,在无向完全图中肯定可以找到一条从小节点依次走到到大节点的有向路:比如1->2->3这样的路,边的双向信息用另一个数组存一下就行了
这样就减少了大量不必要的计算,而且不会重复,因为你在一个无向完全图里只可能找到一个,v1 < v2 < v3 ... < vx
这样的偏序关系的路,不可能再出现例如v2 < v1 < v3 < ... < vx这种路,因为这么多点大小的偏序关系是唯一的,确定了一次,以后都不会重复了,连标记去重都不用,真巧妙!
改了改建图方式就过了……还要感谢涛哥给的整体思路……弱代码实现的时候俩BUG也是卡醉了,还是差点火候……
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#include <set>
using namespace std;
typedef long long ll;
int T, n, m, t, ans;
vector<int> G[105];
bool vis[105], book[105][105];
int p[15];
void dfs(int s, int cnt) {
bool ck = false;
for (int i = 0; i < cnt; i++) {
if (!book[s][p[i]]) {
ck = true;
break;
}
}
if (!ck)
{
p[cnt] = s;
if (cnt + 1 == t) {
ans++;
return;
}
}
else
{
return;
}
for (int i = 0; i < G[s].size(); i++) {
if (!vis[G[s][i]]) {
vis[G[s][i]] = true;
dfs(G[s][i], cnt + 1);
vis[G[s][i]] = false;
}
}
}
int main()
{
cin >> T;
while (T--) {
scanf("%d%d%d", &n, &m, &t);
for (int i = 0; i < 104; i++) {
G[i].clear();
}
memset(book, false, sizeof(book));
for (int i = 1; i <= m; i++) {
int u, v;
scanf("%d%d", &u, &v);
if (u > v)
swap(u, v);
G[u].push_back(v);
book[u][v] = book[v][u] = true;
}
memset(vis, false, sizeof(vis));
ans = 0;
for (int i = 1; i <= n; i++) {
vis[i] = true;
dfs(i, 0);
vis[i] = false;
}
printf("%d\n", ans);
}
return 0;
}