cf 600f Educational Codeforces Round 2 F Edge coloring of bipartite graph 匈牙利板子理解

题意:一个二分图,两边各1e3个点,1e5条边。求最小染色种类(染色边)方案使得同一个点相连的边没有相同染色。
思路:

  1. 二分图没有奇环
  2. 1000个点n*m的时间刚好够
  3. 考虑匈牙利算法,我们每次更新一条边,然后强行配偶,被绿的那个点再去找新欢。那我们染边也一样,因为没有奇环。我们每次找两个点所能连出的最小染色序号,然后强行配偶选择一个最小序号,被绿的那个点再去新点匹配新的最小序号找新欢,0 1 0 1 0 1 0 1因为没有奇环,所以一定不会出错。
    代码:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define forn(i,n) for(int i=0;i<n;i++)
#define for1(i,n) for(int i=1;i<=n;i++)
#define IO ios::sync_with_stdio(false);cin.tie(0)
const int maxn = 2e3+5;
const int maxm = 1e5+5;
int res[maxm],color[maxn][maxn],pos[maxn][maxn],tot = 1;
vector<pair<int,int> >a(maxm);
void dfs(int u,int v,int now,int pre){
    if(now==pre) {
        color[u][now] = v,color[v][now] = u;
        return;
    }
    int vv = color[v][now];
    color[u][now] = v,color[v][now] = u;
    if(!vv) color[v][pre] = 0;
    else dfs(v,vv,pre,now);
}
int main(){
    IO;
    int aa,bb,m;cin>>aa>>bb>>m;
    forn(i,m){
        int u,v;cin>>u>>v;
        u+=1000;
        a[i] = {u,v};
        pos[u][v] = i;
    }   
    int ans = 0;
    forn(i,m){
        int cnt1 = 1,cnt2 = 1,u = a[i].first,v = a[i].second;
        while(color[u][cnt1]) cnt1++;
        while(color[v][cnt2]) cnt2++;
        ans =  max({ans,cnt1,cnt2});
        //cerr<<"@!#!@#@!#    "<<u<<' '<<v<<' '<<cnt1<<' '<<cnt2<<'
';
        dfs(u,v,cnt1,cnt2);
        /*for1(j,m) {
            int u = a[j].first,v = a[j].second;
            for1(k,ans) cerr<<color[v][k]<<' ';
            cerr<<'
';
        }*/
    }
    /*for1(i,m) {
        int u = a[i].first,v = a[i].second;
        for1(j,ans) cerr<<color[u][j]<<' ';
        cerr<<'
';
    }*/
    /*
    for1(i,m) {
        int u = a[i].first,v = a[i].second;
        for1(j,ans) cerr<<color[v][j]<<' ';
        cerr<<'
';
    }*/
    for1(i,aa){
        int x = 1000+i;
        for1(j,ans) if(color[x][j]) res[pos[x][color[x][j]]] = j;
    }
    cout << ans <<'
';
    forn(i,m) cout <<res[i]<<' ';
    return 0;
}
原文地址:https://www.cnblogs.com/AlexPanda/p/12520287.html