【題解】CF742E (二分圖+構造)
給定的條件就是一個二分圖的模型,但是有一些不同。不同就不同在可以出現相鄰兩個點顏色相同的情況。
構造常用方法之一是按奇偶分類,就是儘管不同奇偶性的塊之間會產生影響,但是我們先不管這些限制。
這道題裏,假若奇偶塊之內都能滿足題目的限制,那麼奇偶塊之間也滿足限制了。因爲限制是不能存在三個聯繫相等,然而我們已經保證塊內每兩個不相等。
- 男女朋友連邊。
- \(2i\)和\(2i-1\)連邊。
然後跑二分圖染色,考慮是否存在無解,這個圖顯然有染色方案,因爲所有聯通塊個數爲偶數
//@winlere
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define ERR(s) cerr<<(#s)<<"="<<(s)<<endl;
#define getchar() (__c==__ed?(__ed=__buf+fread(__c=__buf,1,19260817,stdin),*__c++):*__c++)
using namespace std; typedef long long ll; char __buf[19260817],*__c=__buf,*__ed=__buf;
inline int qr(){
register int ret=0,f=0;
register char c=getchar();
while(!isdigit(c))f|=c==45,c=getchar();
while(isdigit(c)) ret=ret*10+c-48,c=getchar();
return f?-ret:ret;
}
const int maxn=2e5+5;
vector<int> e[maxn];
inline void add(const int&fr,const int&to){e[fr].push_back(to); e[to].push_back(fr);}
pair<int,int> P[maxn>>1];
int n,w[maxn];
queue<int> q;
inline void bfs(const int&s){
q.push(s);
if(w[s-1]) w[s]=w[s-1]^1;
else w[s]=2;
while(q.size()){
int now=q.front();
q.pop();
for(auto t:e[now])
if(!w[t]) w[t]=w[now]^1,q.push(t);
}
}
int main(){
n=qr();
for(int t=1;t<=n;++t) P[t].first=qr(),P[t].second=qr(),add(P[t].first,P[t].second);
for(int t=1;t<=n+n;t+=2) add(t,t+1);
for(int t=1;t<=n+n;++t) if(!w[t]) bfs(t);
for(int t=1;t<=n;++t)
printf("%d %d\n",w[P[t].first]-1,w[P[t].second]-1);
return 0;
}
後話:博主最開始看錯題了(英語太菜),把題幹裏的some solution scheme
看作some solution schemes
,加上沒看樣例和輸出格式。以爲要計數,想了很久不會做。有沒有人會做這題的計數版本?就是問有多少種合法方案。