As we all kown, MZL hates the endless loop deeply, and he commands you to solve this problem to end the loop.
You are given an undirected graph with n vertexs and m edges. Please direct all the edges so that for every vertex in the graph the inequation |out degree − in degree|≤1 is satisified.
The graph you are given maybe contains self loops or multiple edges.
1 #include <iostream>
2 #include <cstdio>
3 #include <cmath>
4 #include <cstring>
5 #include <algorithm>
6 #include <vector>
7 using namespace std;
8 #define MAXN 100010
9 #define MAXM 300010
10 int t, n, m;
11 int targ[MAXN][2];
12 int degree[MAXN], ans[MAXM << 1];
13 int head[MAXN], edge_cnt;
14 struct node {
15 int v, next;
16 } edge[MAXM << 1];
17 void init() {
18 memset(head, -1, sizeof head);
19 memset(degree, 0, sizeof degree);
20 memset(targ, 0, sizeof targ);
21 memset(ans, -1, sizeof ans);
22 edge_cnt = 0;
23 }
24 void add_edge(int u, int v) {
25 edge[edge_cnt].v = v;
26 edge[edge_cnt].next = head[u];
27 head[u] = edge_cnt++;
28 }
29 void DFS(int u, int col) {
30 for(int i = head[u]; ~i; i = edge[i].next) {
31 if(ans[i] != -1) {
32 head[u] = edge[i].next;//拆边
33 continue;
34 }
35 int v = edge[i].v;
36 if(u != v && targ[v][col ^ 1] > targ[v][col]) continue;
37 ans[i] = col;
38 ans[i ^ 1] = col ^ 1;
39 head[u] = edge[i].next;
40 targ[u][col]++;
41 targ[v][col ^ 1]++;
42 DFS(v, col);
43 break;
44 }
45 }
46 int main() {
47 scanf("%d", &t);
48 while(t--) {
49 scanf("%d%d", &n, &m);
50 init();
51 int a, b;
52 for(int i = 1; i <= m; i++) {
53 scanf("%d%d", &a, &b);
54 add_edge(a, b);
55 add_edge(b, a);
56 degree[a]++; degree[b]++;
57 }
58 for(int i = 1; i <= n; i++) {
59 while(targ[i][0] + targ[i][1] < degree[i]) {
60 if(targ[i][0] < targ[i][1]) DFS(i, 0);
61 else DFS(i, 1);
62 }
63 }
64 for(int i = 0; i < edge_cnt; i += 2) {
65 printf("%d\n", ans[i]);
66 }
67 }
68 return 0;
69 }