题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1997
大意:给一个哈密顿回路以及其他边,问是否图中任意两条无重合顶点的边不相交。
对于两条边,要么连外面要么连里面。然后就可以2-sat啦。(当边数大于点数*3时肯定不合法)
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct sef { int ne,en; }h[1000050];
int tot,first[2030];
int T,n,m,ex[10020],ey[10050],pos[2004];
int sum,Be[2030];
int stk[2030],top,low[2030],dfn[2030],tim;
bool vis[2030];
inline bool Judge(int x,int y)
{
return (y-x==1||y-x==n-1);
}
inline bool Cr(int i,int j)
{
return (ex[i]<ex[j]&&ex[j]<ey[i]&&ey[i]<ey[j]);
}
inline void setl(int x,int y)
{
h[++tot].ne=first[x]; h[tot].en=y;
first[x]=tot;
h[++tot].ne=first[y]; h[tot].en=x;
first[y]=tot;
}
void Dfs(int x)
{
vis[x]=1;
stk[++top]=x;
low[x]=dfn[x]=++tim;
int y;
for (int i=first[x];y=h[i].en,i;i=h[i].ne)
if (!dfn[y]) {
Dfs(y);
low[x]=min(low[x],low[y]);
} else if (vis[y]) low[x]=min(low[x],dfn[y]);
if (low[x]==dfn[x]) {
++sum;
while (stk[top]!=x) {
Be[stk[top]]=sum;
vis[stk[top]]=0;
--top;
}
Be[x]=sum; vis[x]=0;
--top;
}
}
int main()
{
scanf("%d",&T);
while (T--) {
scanf("%d%d",&n,&m);
for (int i=1;i<=m;++i) scanf("%d%d",&ex[i],&ey[i]);
int x;
for (int i=1;i<=n;++i) {
scanf("%d",&x); pos[x]=i;
}
if (m>n*3) { printf("NO\n"); continue; }
tot=0; memset(first,0,sizeof(first));
for (int i=1;i<=m;++i) {
ex[i]=pos[ex[i]]; ey[i]=pos[ey[i]];
if (ex[i]>ey[i]) swap(ex[i],ey[i]);
if (!Judge(ex[i],ey[i])) {
for (int j=1;j<i;++j)
if (!Judge(ex[j],ey[j])) {
if (Cr(i,j)||Cr(j,i)) {
setl(i*2-1,j*2);
setl(i*2,j*2-1);
}
}
}
}
tim=top=sum=0; memset(dfn,0,sizeof(dfn));
for (int i=1;i<=m*2;++i)
if (!dfn[i]) Dfs(i);
bool boo=false;
for (int i=1;i<=m;++i)
if (Be[i*2-1]==Be[i*2]) { boo=true; break; }
if (boo) printf("NO\n");
else printf("YES\n");
}
}