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|\leq 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 $u_i$ and $v_i$, which describe an edge of the graph. $T\leq 100$, $1\leq n\leq 10^5$, $1\leq m\leq 3*10^5$, $\sum n\leq 2*10^5$, $\sum m\leq 7*10^5$.
Output
For each test case, if there is no solution, print a single line with $-1$, otherwise output $m$ lines,. In $i$th line contains a integer $1$ or $0$, $1$ for direct the $i$th edge to $u_i\rightarrow v_i$, $0$ for $u_i\leftarrow v_i$.
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
题意:
给一个无向图,给每一个边加一个方向,使无向图变成有向图。写出任意一种方案
分析:
爆搜然后删边
代码:
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e6+10;
const int MAXM = 1e6+10;
int n, m;
int x, y;
//
struct Edge
{
int to, next;
int index;
bool flag;
}edge[MAXM];
int head[MAXM], tot;
int sum_du[MAXN];
int du[MAXN][2];
int ans[MAXM];
void addedge(int u, int v, int index)
{
edge[tot].to = v;
edge[tot].flag = false;
edge[tot].index = index;
edge[tot].next = head[u];
head[u] = tot++;
}
void init()
{
tot = 0;
memset(head, -1, sizeof(head));
memset(du, 0, sizeof(du));
memset(sum_du,0,sizeof(sum_du));
memset(ans,-1,sizeof(ans));
}
void dfs(int u,int ok)
{
for (int i = head[u]; i != -1; i = edge[i].next)
{
if (edge[i].flag)
{
head[u] = edge[i].next;
continue;
}
int v = edge[i].to;
if (u != v && du[v][ok^1] > du[v][ok])
continue;
edge[i].flag = true;
edge[i ^ 1].flag = true;
if (i % 2 == 1)
ans[i / 2] = ok ;
else
ans[i / 2] = ok^1;
du[u][ok]++;
du[v][ok ^ 1]++;
head[u] = edge[i].next;
dfs(v,ok);
break;
}
}
int main()
{
int t;
scanf("%d",&t);
while (t--)
{
scanf("%d %d",&n,&m);
init();
for (int i = 0; i < m; i++)
{
scanf("%d%d",&x,&y);
addedge(x, y, i);
addedge(y, x, i);
sum_du[x]++;
sum_du[y]++;
}
for (int i = 1; i <= n; i++)
{
while (du[i][0] + du[i][1] < sum_du[i])
{
if (du[i][0] <= du[i][1])
dfs(i, 0);
else
dfs(i, 1);
}
}
for (int i = 0; i < m; i++)
printf("%d\n",ans[i]);
}
return 0;
}