題意:直白的2-sat,但是這個是要輸出最小的字典序,那麼我們只能選擇暴力。
思路:我的暴力的想法是,枚舉每對元素,先優先取靠前的那個,把它所有連了邊的都取了然後打tag,如果它不會產生矛盾,那麼繼續,如果有,那麼先把所有的tag取消,再判斷a+1有沒有矛盾,如果a+1也有矛盾,那這組數據就已經gg了。我已經是個蠢到取消tag也要用dfs的人了,看了別人的暴力...基本都是用棧保留然後取消tag,我試了一下,我的兩波dfs要跑2s.....而用棧處理.只需要1s不到。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 8e3 + 50, maxe = 2e5;
struct node
{
int to,next;
node(int a,int b){to = a; next = b;}
node(){}
}edge[maxe];
int h[maxn<<1];
int n,m,edgenum,snum=0;
int vis[maxn],col[maxn],ans[maxn],S[maxn];
void add(int f,int t)
{
edge[edgenum] = node(t,h[f]);
h[f] = edgenum++;
}
int flag = 0;
bool dfs(int u,int root)
{
if(col[u^1] != -1) return 0;
if(col[u] != -1) return 1;
col[u] = root;
for(int i = h[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if(dfs(v,root) == 0) return 0;
}
return true;
}
void clean(int u)
{
col[u] = -1;
for(int i = h[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if(col[v] != -1)
clean(v);
}
}
int main()
{
int a,b;
while(~scanf("%d%d",&n,&m))
{
edgenum = snum = 0;
for(int i = 0; i < n*2 ; i++) h[i] = -1,col[i] = -1;
for(int i = 0; i < m ; i++)
{
scanf("%d%d",&a,&b); a--,b--;
add(a,b^1); add(b,a^1);
}
int mark = 0;
int num = 0;
for(int i = 0; i < n*2 ; i += 2)
{
if(col[i] == -1 && col[i+1] == -1)
{
if(dfs(i,i)) continue;
else
{
clean(i);
if(dfs(i+1,i+1)) continue;
else {mark = 1;break;}
}
}
}
if(mark) {printf("NIE\n");}
else
{
for(int i = 0; i < n*2; i++)
if(col[i]!=-1)printf("%d\n",i+1);
}
}
return 0;
}