赞
踩
题目链接:codeforces.com/problemset/problem/527/E
题意:给出一个无向联通图,把无向边变成有向边,并添加最少的有向边使得所有结点入度出度都是偶数
思路:最终构造出来的图是一个欧拉回路,对于一张无向图,当其所有点度数为偶数时存在欧拉回路,如果回路边数为偶数则一定能构造出来,所以对于一开始度数是奇数的点依次添加无向边使它们度数为偶数,然后对于这张无向图,任选起点跑欧拉回路,构造类似a - > b <- c -> d...的路径,如果跑出的路径为奇数任选一点添加自环即可,注意要将之前访问过的边拆掉以防超时
- #include <cstdio>
- #include <cstring>
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <utility>
- #include <cmath>
- #include <queue>
- #include <set>
- #include <map>
- #include <climits>
- #include <functional>
- #include <deque>
- #include <ctime>
-
- #define lson l, mid, rt << 1
- #define rson mid + 1, r, rt << 1 | 1
- #pragma comment(linker, "/STACK:102400000,102400000")
-
- using namespace std;
-
- const int maxn = 500100;
- const int inf = 0x3f3f3f3f;
-
- int head[maxn], cnt;
-
- int deg[maxn], vis[maxn];
- vector <int> ans;
-
- struct edge
- {
- int from, to, nxt;
- } e[maxn];
-
- void init()
- {
- cnt = 0;
- memset(head, -1, sizeof(head));
- memset(deg, 0, sizeof(deg));
- memset(vis, 0, sizeof(vis));
- }
-
- void add(int u, int v)
- {
- e[cnt].from = u;
- e[cnt].to = v;
- e[cnt].nxt = head[u];
- head[u] = cnt++;
- }
-
- void dfs(int u)
- {
- for (int &i = head[u]; ~i; i = e[i].nxt)
- {
- if (vis[i / 2]) continue;
- vis[i / 2] = 1;
- int v = e[i].to;
- int tmp = i;
- dfs(v);
- ans.push_back(tmp);
- }
- }
-
- int main()
- {
- int n, m;
- while (~scanf("%d%d", &n, &m))
- {
- init();
- while (m--)
- {
- int u, v;
- scanf("%d%d", &u, &v);
- add(u, v);
- add(v, u);
- deg[u]++, deg[v]++;
- }
-
- int p = -1;
- for (int i = 1; i <= n; i++)
- {
- if (deg[i] & 1)
- {
- if (p == -1)
- p = i;
- else
- {
- add(i, p);
- add(p, i);
- deg[i]++, deg[p]++;
- p = -1;
- }
- }
- }
- if ((cnt / 2) & 1) add(n, n); //加自环
-
- ans.clear();
- dfs(1);
- cout << ans.size() << endl;
- for (int i = 0; i < ans.size(); i++)
- {
- if (i & 1)
- printf("%d %d\n", e[ans[i]].from, e[ans[i]].to);
- else
- printf("%d %d\n", e[ans[i]].to, e[ans[i]].from);
- }
- }
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。