题目描述
算法1 2-sat算法,思路分分钟,写代码20分钟,然而各种细节调了一下午
C++ 代码
#include<cstring>
#include<cmath>
#include<cstdio>
using namespace std;
#define a first
#define b second
typedef pair<int, int> PII;
const int N = 210, M = 10010;
PII edges[M];
int st[2 * M]; // is in loop
//tarjan
int dfn[M * 2], low[M * 2], ts, stk[M * 2], top, ins[M * 2];
int id[M * 2], cnt;
int h[M * 2], e[2000010], ne[2000010], idx;
int mp[N];
int n, m;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
bool is_cross(int i, int j)//check if two edges cross
{
int ia = mp[edges[i].a], ib = mp[edges[i].b];
if(ia > ib) swap(ia, ib);
int ja = mp[edges[j].a], jb = mp[edges[j].b];
if(ja > jb) swap(ja, jb);
if(ia < ja && ib < jb && ib > ja) return true;
if(ja < ia && jb < ib && jb > ia) return true;
return false;
}
void tarjan(int u)
{
dfn[u] = low[u] = ++ ts;
stk[++ top ] = u, ins[u] = true;
for(int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if(!dfn[j])
{
tarjan(j);
low[u] = min(low[u], low[j]);
}
else if(ins[j]) low[u] = min(dfn[j], low[u]);
}
if(dfn[u] == low[u])
{
++ cnt;
int k;
do{
k = stk[top --];
ins[k] = false;
id[k] = cnt;
}while(k != u);
}
}
int main()
{
int t;
scanf("%d", &t);
while(t --)
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
memset(st, 0, sizeof st);
memset(mp, 0, sizeof mp);
memset(dfn, 0, sizeof dfn);
memset(low, 0, sizeof low);
memset(id, 0, sizeof id);
ts = 0, cnt = 0;
idx = 0;
for(int i = 1; i <= m; ++ i)
{
int a, b;
scanf("%d%d", &a, &b);
edges[i] = {a, b};
}
for(int i = 1; i <= n; ++ i)
{
int x;
scanf("%d", &x);
mp[x] = i;
}
if(m > (n * 3 - 6))
{
puts("NO");
continue;
}
for(int i = 1; i <= m; ++ i)
{
int a = edges[i].a, b = edges[i].b;
if((abs(mp[a] - mp[b]) == 1) || (abs(mp[a] - mp[b]) == n - 1))
st[i] = true, st[i + m] = true;
}
//for(int i = 1; i <= m; ++ i)
// printf("%d %d %d %d\n", i, edges[i].a, edges[i].b, st[i]);
for(int i = 1; i <= m; ++ i)
if(st[i]) continue;
else
for(int j = 1; j < i; ++ j)
if(st[j]) continue;
else if(is_cross(i, j))
{
//printf("%d %d\n", i, j);
add(i, j + m), add(j, i + m);
add(i + m, j), add(j + m, i);
}
for(int i = 1; i <= 2 * m; ++ i)
if(!st[i] && !dfn[i])
tarjan(i);
bool tag = true;
//for(int i = 1; i <= 2 * m; ++ i)
// printf("%d ", id[i]);
for(int i = 1; i <= m; ++ i)
if(!st[i] && id[i] == id[i + m])
{
tag = false;
break;
}
if(tag) printf("YES\n");
else printf("NO\n");
}
return 0;
}