P3007 [USACO11JAN] The Continental Cowngress G
P3007 [USACO11JAN] The Continental Cowngress G
思路:2-SAT模板,经典的或条件,那么直接建图即可,对于可行解,我们直接枚举每个方案支持和反对,然后染色判断即可。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define all(u) u.begin(), u.end()
#define endl '\n'
#define debug(x) cout<<#x<<":"<<x<<endl;
typedef pair<int, int> PII;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 1e5 + 10, M = 105;
const int mod = 1e9 + 7;
const int cases = 0;
vector<int> e[N];
stack<int> stk;
int dfn[N],low[N],tot;
int instk[N],scc[N],siz[N],cnt;
int n,m,st[N];
void tarjan(int u){
dfn[u]=low[u]=++tot;
stk.push(u);instk[u]=1;
for(auto v:e[u]){
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}else if(instk[v]) low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u]){
int v;cnt++;
do{
v=stk.top();
stk.pop();
instk[v]=0;
scc[v]=cnt;
siz[cnt]++;
}while(v!=u);
}
}
void dfs(int u){
st[u]=1;
for(auto v:e[u]){
if(!st[v]) dfs(v);
}
}
bool check(int u){
memset(st,0,sizeof st);
dfs(u);
for(int i=0;i<n;i++){
if(st[i<<1]&&st[i<<1|1]) return false;
}
return true;
}
void Showball(){
cin>>n>>m;
while(m--){
int u,v;
char uu,vv;
cin>>u>>uu>>v>>vv;
u--,v--;
e[(u<<1)+!(uu=='N')].pb((v<<1)+(vv=='N'));
e[(v<<1)+!(vv=='N')].pb((u<<1)+(uu=='N'));
}
for(int i=0;i<2*n;i++){
if(!dfn[i]) tarjan(i);
}
string ans="";
for(int i=0;i<n;i++){
bool Y=check(i<<1),N=check(i<<1|1);
if(!Y&&!N) return cout<<"IMPOSSIBLE\n",void();
if(Y&&N) ans+="?";
else if(!Y&&N) ans+="N";
else ans+="Y";
}
cout<<ans<<endl;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int T=1;
if(cases) cin>>T;
while(T--)
Showball();
return 0;
}