題意:一個二分圖,兩邊各1e3個點,1e5條邊。求最小染色種類(染色邊)方案使得同一個點相連的邊沒有相同染色。
思路:
- 二分圖沒有奇環
- 1000個點n*m的時間剛好夠
- 考慮匈牙利算法,我們每次更新一條邊,然後強行配偶,被綠的那個點再去找新歡。那我們染邊也一樣,因爲沒有奇環。我們每次找兩個點所能連出的最小染色序號,然後強行配偶選擇一個最小序號,被綠的那個點再去新點匹配新的最小序號找新歡,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<<'\n';
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<<'\n';
}*/
}
/*for1(i,m) {
int u = a[i].first,v = a[i].second;
for1(j,ans) cerr<<color[u][j]<<' ';
cerr<<'\n';
}*/
/*
for1(i,m) {
int u = a[i].first,v = a[i].second;
for1(j,ans) cerr<<color[v][j]<<' ';
cerr<<'\n';
}*/
for1(i,aa){
int x = 1000+i;
for1(j,ans) if(color[x][j]) res[pos[x][color[x][j]]] = j;
}
cout << ans <<'\n';
forn(i,m) cout <<res[i]<<' ';
return 0;
}