首页 > 代码库 > POJ 2438 解题报告
POJ 2438 解题报告
分析:
2*n个小朋友,每个最多有n-1个"敌人",显然是存在哈密顿回路的.
预处理边,然后找哈密顿回路.
code
#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <vector>using namespace std;#define pb push_back#define sz(a) (int)(a).size()const int INF = 500;bool edge[INF][INF];typedef vector<int> vi;vi ans;//求哈密顿回路O(n^2)void Hamilton (vi& ans, bool edge[INF][INF], int n) { int s = 1, tol = 2, t, i, j; bool vis[INF] = {0}; for (i = 1; i <= n; i++) if (edge[s][i]) break; t = i; vis[s] = vis[t] = 1; ans.pb (s); ans.pb (t); while (1) { //头尾拓展 while (1) { for (i = 1; i <= n; i++) { if (edge[t][i] && !vis[i]) { vis[i] = 1; t = i; ans.pb (i); break; } } if (i > n) break; } reverse (ans.begin(), ans.end() ); swap (s, t); while (1) { for (i = 1; i <= n; i++) { if (edge[t][i] && !vis[i]) { vis[i] = 1; t = i; ans.pb (i); break; } } if (i > n) break; } //如果S和T不相连 if (!edge[s][t]) { for (i = 1; i < sz (ans) - 2; i++) if (edge[ans[i]][t] && edge[ans[i + 1]][s]) break; reverse (ans.begin() + i + 1, ans.end() ); t = * (ans.end() - 1); } tol = sz (ans); if (tol == n) return; //如果还有点未加入ans for (j = 1; j <= n; j++) { if (vis[j]) continue; //找到与这个点相连的点 for (i = 1; i < tol - 1; i++) if (edge[ans[i]][j]) break; if (edge[ans[i]][j]) break; } s = ans[i - 1], t = j; reverse (ans.begin(), ans.begin() + i ); reverse (ans.begin() + i, ans.end() ); ans.pb (j), vis[j] = 1; }}int n, m;int main() { while (~scanf ("%d %d", &n, &m) ) { if (n == 0 && m == 0) return 0; memset (edge, 1, sizeof edge); for (int i = 1; i <= 2 * n; i++) edge[i][i] = 0; int x, y; for (int i = 1; i <= m; i++) { scanf ("%d %d", &x, &y); edge[y][x] = edge[x][y] = 0; } ans.clear(); Hamilton (ans, edge, n << 1); printf ("%d", ans[0]); for (int i = 1; i < sz (ans); i++) printf (" %d", ans[i]); putchar (10); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。