Ural2089:Experienced coach(二分图匹配)

Misha trains several ACM teams at the university. He is an experienced coach, and he does not underestimate the meaning of friendly and collaborative atmosphere during training sessions. It used to be that way, but one of the teams happened to win contests a little bit more often than others, and hence became slightly too big for their boots. That does not contribute to positive spirit which is essential for successful training. But Misha knows what to do!
Representatives of  k teams participate in Misha’s training sessions, each team has three members. Alas, teams rarely attend en masse, but at least one member per team is always present, of course. During the next training session Misha is going to split everyone into  n pairs, so that each pair will include representatives of different teams. Players will play a mini-contest against each other in each pair.
A situation when no two mini-contests are won by representatives of one team is the one that suits Misha’s goals best. He may be somewhat cunning when selecting winner in each pair in order to achieve such situation. Find out whether Misha will succeed.

Input

The first line contains two numbers —  n and  k (1 ≤  n ≤ 105, 2 ≤  k ≤ 105).  n lines follow.  i-th of these contains two numbers  x iy i (1 ≤  x iy i ≤  kx i ≠  y i) — the numbers of teams, whose representatives are in pair number  i.
It is guaranteed that each team is represented in no less than one and no more than three pairs.

Output

If Misha is to succeed, output  Yes in the first line. In each of the following  n lines output one number — the number of team that is to win in the corresponding pair. If there are several answers, output any.
If Misha is to fail, output  No in the only line.

Samples

input output
3 4
1 2
2 3
1 4
Yes
2
3
4
6 4
1 2
1 3
1 4
2 3
2 4
3 4
No
Problem Author: Alexander Ipatov, prepared by Egor Shchelkonogov

题意:有K个队伍,N次比赛。问如果教练来决定每次比赛谁赢谁输,是否可以找到一种方案,使得每支队伍最多赢一场。

思路:每一次比赛对两支队伍匹配连边,如果匹配次数等于N,则可行。

#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=400010;
int Laxt[maxn],Next[maxn],To[maxn],cnt,N,M,T;
int linker[maxn],vis[maxn];
void add(int u,int v){
    Next[++cnt]=Laxt[u];
    Laxt[u]=cnt;
    To[cnt]=v;
}
bool find(int u){
    for(int i=Laxt[u];i;i=Next[i]){
        int v=To[i];
        if(vis[v]!=T){
            vis[v]=T;
            if(!linker[v]||find(linker[v])){
                linker[v]=u; return true;
            }
        }
    }
    return false;
}
int main()
{
    int u,v,i,ans=0;
    scanf("%d%d",&N,&M);
    for(int i=1;i<=N;i++){
       scanf("%d%d",&u,&v);
       add(u,i); add(v,i);
    }
    for(i=1;i<=M;i++){
        T=i; if(find(i)) ans++;
    }
    if(ans<N) printf("No\n");
    else {
       printf("Yes\n");
       for(i=1;i<=N;i++) printf("%d\n",linker[i]); 
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hua-dong/p/8862422.html