题意:N对夫妇举行婚礼,对立相坐于矩形桌两边,其中夫妇必须一边只能一人,其中有M对情妇,要求新郎那边不能有情妇,输出新娘这边的情况。
2-sat。 其中建图要注意新郎一定会在。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#define INF 6010
#define inf 0x0f0f0f0f
using namespace std;
vector <int> vec[INF], node[INF];
int Dfn[INF], Low[INF], Stack[INF], Blo[INF], Block, Cnt, Now, Match[INF], Ind[INF];
bool Instack[INF]; int vis[INF];
int n,m;
int init(){
Cnt=0;
Block=0;
Now=0;
for(int i=0;i<2*n;i++){
vec[i].clear();
node[i].clear();
}
memset(Ind,0,sizeof Ind);
memset(Dfn,0,sizeof Dfn);
memset(Low,0,sizeof Low);
memset(Blo,0,sizeof Blo);
}
void _addedge(int i, int j) { vec[i].push_back(j); };
void Tarjan(int n)
{
int i, j, siz=vec[n].size();
Low[n]=Dfn[n]=++Cnt, Instack[Stack[++Now]=n]=true;
for (i=0; i<siz; i++)
if (Dfn[j=vec[n][i]]==0)
Tarjan(j), Low[n]=min(Low[n], Low[j]);
else if (Instack[j]) Low[n]=min(Low[n], Low[j]);
if (Dfn[n]==Low[n] && ++Block)
do Blo[i=Stack[Now--]]=Block, Instack[i]=false;
while (i!=n);
}
void Top_sort(int n)
{
queue <int> q; int i, j, t, siz;
memset(vis, 0xff, sizeof(vis));
for (i=0; i<n; i++)
Match[Blo[i]]=Blo[i+n], Match[Blo[i+n]]=Blo[i];
for (i=0; i<n*2; i++)
for (j=0, siz=vec[i].size(); j<siz; j++)
if (Blo[i]!=Blo[t=vec[i][j]])
node[Blo[t]].push_back(Blo[i]), Ind[Blo[i]]++;
for (i=1; i<=Block; i++)
if (Ind[i]==0) q.push(i);
while (!q.empty()) {
if (i=q.front(), q.pop(), vis[i]==-1)
vis[i]=1, vis[Match[i]]=0;
for (j=0, siz=node[i].size(); j<siz; j++)
if (--Ind[t=node[i][j]]==0)
q.push(t);
}
}
int X, Y, Z1,Z2;
int main()
{
//freopen("1.txt", "r", stdin);
int a,b;
char sa,sb;
int i,j;
while(~scanf("%d%d",&n,&m)){
if(n==0 && m==0) break;
init();
for(i=0;i<m;i++){
scanf("%d%c%d%c",&a,&sa,&b,&sb);
if(sa=='w' && sb=='h'){
_addedge(a,b);
_addedge(b+n,a+n);
}
if(sa=='w' && sb=='w'){
_addedge(a,b+n);
_addedge(b,a+n);
}
if(sa=='h' && sb=='w'){
_addedge(a+n,b+n);
_addedge(b,a);
}
if(sa=='h' && sb=='h'){
_addedge(a+n,b);
_addedge(b+n,a);
}
}
_addedge(0,n);
for (i=0; i<=2*n-1; i++)
if (Dfn[i]==0) Tarjan(i);
int f=0;
for (i=0; i<n; i++)
if (Blo[i]==Blo[i+n]){
f=1;
break;
}
if(!f){
Top_sort(n);
for (i=1; i<n; i++)
if (vis[Blo[i]]==1) printf("%dh%c",i, i==n-1?'\n':' ');
else printf("%dw%c",i, i==n-1?'\n':' ');
}
if(f) printf("bad luck\n");
}
return 0;
}
/*
10 6
3h 7h
5w 3w
7h 6w
8w 3w
7h 3w
2w 5h
0 0
*/