您的位置:首页 > 运维架构

HDOJ 5348 MZL's endless loop

2015-08-07 20:19 344 查看


MZL's endless loop

Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)

Total Submission(s): 2043    Accepted Submission(s): 442
Special Judge


Problem Description

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.

 

Input

The first line of the input is a single integer T,
indicating the number of testcases.

For each test case, the first line contains two integers n and m.

And the next m lines,
each line contains two integers ui and vi,
which describe an edge of the graph.
T≤100, 1≤n≤105, 1≤m≤3∗105, ∑n≤2∗105, ∑m≤7∗105.

 

Output

For each test case, if there is no solution, print a single line with −1,
otherwise output m lines,.

In ith
line contains a integer 1 or 0, 1 for
direct the ith
edge to ui→vi, 0 for ui←vi.

 

Sample Input

2
3 3
1 2
2 3
3 1
7 6
1 2
1 3
1 4
1 5
1 6
1 7

 

Sample Output

1
1
1
0
1
0
1
0
1

 

Source

2015 Multi-University Training Contest 5

 

Recommend

wange2014

#include <cstdio>
#include <cstring>

const int N = 1e5 + 10;
int degree
;
int targ
[2];
int head
;
bool vis
;
int edge_cnt, found;

struct node{
int v, next, dict;
}edge[N * 6];

void Init() {
memset(head, -1, sizeof(head));
memset(vis, false, sizeof(vis));
memset(targ, 0, sizeof(targ));
memset(degree, 0, sizeof(degree));
edge_cnt = 0;
}

void add_edge(int u, int v) {
node tmp = {v, head[u], -1};
head[u] = edge_cnt;
edge[edge_cnt++] = tmp;
}

void dfs(int u, int dict) {
if (vis[u] == true) {
found = u;
return ;
}
vis[u] = true;
while (~head[u]) {
int lct = head[u];
node tmp = edge[lct];
head[u] = tmp.next;
int v = tmp.v;

if (edge[lct].dict != -1 || (u != v && targ[v][dict ^ 1] > targ[v][dict]))
continue;

edge[lct].dict = dict;
edge[lct ^ 1].dict = dict ^ 1;

targ[u][dict]++;
targ[v][dict ^ 1]++;

dfs(v, dict);

if (found != -1) {
if (found == u) {
found = -1;
continue;
}
else {
vis[u] = false;
break;
}
}

break;
}
vis[u] = false;
}

int main() {
int T;

scanf("%d", &T);

while (T--) {
Init();
int n, m;
int u, v;

scanf("%d%d", &n, &m);

for (int i = 0; i < m; ++i) {
scanf("%d%d", &u, &v);
degree[u]++;
degree[v]++;
add_edge(u, v);
add_edge(v, u);
}

for (int i = 1; i <= n; ++i) {
while (targ[i][0] + targ[i][1] < degree[i]) {
found = -1;
if (targ[i][0] <= targ[i][1])
dfs(i, 0);
else
dfs(i, 1);
}
}

for (int i = 0; i < edge_cnt; i += 2)
printf("%d\n", edge[i].dict);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: