hdu5952 Counting Cliques DFS

19 篇文章 0 订阅

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值