poj1419Graph Coloring(一般图最大独立集或着最大团)
2016-06-23 13:30
465 查看
一般图的最大独立集和最大团是等效的。图G = (V, E),其补图G’。G的最大独立集等价于G’的最大团。度娘
一般的做法就是搜索。
一般的做法就是搜索。
// 最大独立集做法 vector<vector<int> > G; int n, m; int color[123]; vector<int> rec; int maxnum; void dfs(int u,int _count) { if (_count > maxnum) {//更新答案 maxnum = _count; rec.clear(); for (int i = 1;i <= n;++i) { if (color[i]) rec.push_back(i); } } if (u == n + 1) return ; //用于判断是否可以染成黑色 bool ok = true; for (int i = 0;i < G[u].size();++i) { if (color[G[u][i]]) ok = false; } if (ok) {//u节点可以染成黑色 color[u] = 1; dfs(u + 1, _count + 1); color[u] = 0; } dfs(u + 1, _count);//u染成白色->跳过 } int main(int argc, const char * argv[]) { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); // clock_t _ = clock(); int t, u, v; cin >> t; while(t--) { scanf("%d%d", &n, &m); G.clear(); G.resize(n + 2); while(m--) { scanf("%d%d", &u, &v); G[u].push_back(v); G[v].push_back(u); } memset(color, 0,sizeof color); maxnum = 0; dfs(1, 0); printf("%d\n", maxnum); for (int i = 0;i < rec.size();++i) printf("%d%c", rec[i], i == maxnum - 1?'\n':' '); } // printf("\nTime cost: %.2fs\n", 1.0 * (clock() - _) / CLOCKS_PER_SEC); return 0; } //最大团做法 int mp[123][123]; int rec[123]; int tmp[123]; int cnt, ans; int n, m; void dfs(int u) { if (u == n + 1) { if (cnt > ans) ans = cnt; memcpy(rec, tmp, sizeof tmp); return ; } //判断u是否可以划入到这个团中去 bool ok = true; for (int i = 1;i < u;++i) { if (tmp[i] && mp[i][u]) { ok = false; break; } } if (ok) { tmp[u] = 1;cnt++; dfs(u + 1); tmp[u] = 0;cnt--; } //跳过u节点后判断下可行性 if (n + cnt - u > ans) dfs(u + 1); } int main(int argc, const char * argv[]) { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); // clock_t _ = clock(); int t; cin >> t; while(t--) { scanf("%d%d", &n, &m); memset(mp, 0,sizeof mp); memset(tmp, 0,sizeof tmp); int u, v; for (int i = 1;i <= m;++i) { scanf("%d%d", &u, &v); mp[u][v] = mp[v][u] = 1; } cnt = ans = 0; dfs(1); printf("%d\n", ans); bool first = true; for (int i = 1;i <= n;++i) { if (rec[i]) { if (first) printf("%d", i); else printf(" %d", i); first = false; } } printf("\n"); } // printf("\nTime cost: %.2fs\n", 1.0 * (clock() - _) / CLOCKS_PER_SEC); return 0; }
相关文章推荐
- 分布式算法 3 最大独立集
- POJ 1419 : Graph Coloring - 最大团(裸)
- 【日常学习】【二分图匹配】【匈牙利算法】codevs4265 大智的妹子们题解
- ACM俱乐部 3919 旅游景点 【最大团】
- HDU 3829 Cat VS Dog(最大独立集|二分图最大匹配)
- 【HDU5556 2015合肥赛区E】【最大团or二分图匹配】Land of Farms 不同编号不相邻条件下的最大农场数
- UVA 11159 Factors and Multiples (最大独立集)
- HDU 4619 Warm up 2(贪心、并查集 | 二分图最大独立集)
- UVALive 4288 Cat vs. Dog
- 二分图的概念和几种用法
- 最大团算法(Maximum Clique)
- 二分图最大匹配总结(匈牙利算法)
- 极大团和最大团
- POJ 3692 最大团
- HDU - 5952 暴力dfs
- ZOJ - 1492 dfs剪枝求最大团
- HDU1530 Maximum Clique & ZOJ 1492 Maximum Clique
- PAT 1021. Safe Fruit (35)
- 51Nod-1524-可除图的最大团
- BZOJ1040 骑士