hdu5952 Counting Cliques DFS

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


發佈了198 篇原創文章 · 獲贊 8 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章