2015 Multi-University Training Contest 5 F(MZL's endless loop)

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
题意:将一个无向图构造出一个有向图,要求每个点的入度和出度之差绝对值不超过1。

思路:来自:https://blog.csdn.net/k183000860/article/details/47312943

       如果对于某个点u,它的入度in[u]>=出度out[u],那么就正向搜索,我们找一个与u相连且不等于u的点v,假设点v的in[v]<out[v],那么刚好符合条件,我们就将u,v这条边置为1,使得out[u]++,in[v]++时间复杂度为O(n+m),要达到这个效率,我们用链式向前星来存储边,然后用head[u]=edge[i].next来删除已经访问过的边。但这道题目我不太知道怎么去证明无论如何都不会没有解,即都不会输出-1。

总之,找到奇度数的结点出发,奇度数结点结束,(一定有偶数个奇结点),相当于把此图分为若干欧拉图,毕竟欧拉图一定满足每个点的入度和出度之差绝对值不超过1。

代码:

const int maxn=1000005;
struct node
{
    int to;
    int cost;
    int next;
}G[maxn];
int head[maxn],cnt;
int n,m,sign,deg[maxn];
void add(int u,int v)
{
    G[cnt].to=v;
    G[cnt].cost=0;
    G[cnt].next=head[u];
    head[u]=cnt++;
}
void dfs(int s)
{
    if(sign) return ;
    for(int i=head[s];i!=-1;i=G[i].next)
    {
        if(sign) return ;
        int temp=G[i].to;
        int flag=(G[i].cost^G[i^1].cost);//给边已经走过
        if(flag) continue;
        head[s]=G[i].next;//
        G[i].cost=1;
        if(deg[temp])
        {
            deg[temp]=0;
            sign=1;
            return ;
        }
        if(!sign)
        dfs(temp);
    }
    return ;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        cnt=0;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        deg[i]=0,head[i]=-1;
        for(int i=1;i<=m;i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            add(u,v);
            add(v,u);
            deg[u]^=1;
            deg[v]^=1;
        }
        for(int i=1;i<=n;i++)
        {
            if(deg[i])
            {
                sign=0;
                deg[i]=0;
                dfs(i);
            }
        }
        sign=0;
        for(int i=1;i<=n;i++)
        {
            if(head[i]!=-1)//该点连的边有没标完的
            {
                dfs(i);
            }
        }
        for(int i=0;i<cnt;i+=2)
        {
            cout<<G[i].cost<<endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/snayf/article/details/81321558