模型的解决方法看论文《利用对称性解决2-SAT问题》
HDU1814 :难度1.5
HDU1824: 难度 2
HDU1815: 难度3
HDU1816:
对于每两个人,二选一
HDU1814
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
using namespace std;
#define R 1//red 为ok
#define B 2//black 访问过但不ok
#define W 0//white 待染色
const int maxn = 16005;
vector<int>G[maxn];
int cnt,col[maxn],ans[maxn],n,m;
bool dfs(int u)
{
if (col[u] == B) return false;
if (col[u] == R) return true;
col[u] = R;col[u^1] = B;ans[cnt++]=u;
for(int i=0;i<G[u].size();i++)
if (!dfs(G[u][i])) return false;
return true;
}
bool _solve()
{
int i, j;
memset(col,0,sizeof(col));
for (i=0; i<n; i++){
if (col[i]) continue;
cnt=0;
if (!_dfs(i)){
for (j=0;j<cnt;j++){
col[ans[j]]=W;
col[ans[j]^1]=W;
}
if (!dfs(i^1)) return false;
}
}
return true;
}
int main()
{
int i,a,b;
while (~scanf("%d %d",&n, &m)){
n <<= 1;//加倍
for(i=0;i<=n;i++) G[i].clear();
while (m--){
scanf("%d %d",&a, &b);
a--;b--;
G[a].push_back(b^1);
G[b].push_back(a^1);
}
if (_solve()){
for (i=0; i<n; i++)
if(col[i] == R)
printf("%d
",i+1);
}
else printf("NIE
");
}
return 0;
}
对于每个人留或者不留,二选一
HDU1824
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
using namespace std;
#define R 1
#define B 2
#define W 0
const int maxn = 80000;
vector<int>G[maxn];
int cnt,col[maxn],ans[maxn],n,m;
bool _dfs(int u)
{
if (col[u] == B) return false;
if (col[u] == R) return true;
col[u] = R;col[u^1] = B;ans[cnt++]=u;
for(int i=0;i<G[u].size();i++)
if (!_dfs(G[u][i])) return false;
return true;
}
bool _solve()
{
int i, j;
memset(col,0,sizeof(col));
for (i=0; i<n*6; i++){
if (col[i]) continue;
cnt=0;
if (!_dfs(i)){
for (j=0;j<cnt;j++){
col[ans[j]]=W;
col[ans[j]^1]=W;
}
if (!_dfs(i^1)) return false;
}
}
return true;
}
int main()
{
int i,a,b,c;
while (~scanf("%d %d",&n, &m)){
for(i=0;i<n*6;i++) G[i].clear();
for(i=1;i<=n;i++){
scanf("%d%d%d",&a,&b,&c);
a*=2;b*=2;c*=2;
G[a^1].push_back(b);
G[a^1].push_back(c);
G[b^1].push_back(a);
G[c^1].push_back(a);
}
for(i=1;i<=m;i++){
scanf("%d%d",&a,&b);
a*=2;b*=2;
G[a].push_back(b^1);
G[b].push_back(a^1);
}
if (_solve()) printf("yes
");
else printf("no
");
}
return 0;
}