2-SAT模板

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL maxn = 2000000 + 100;
const LL maxm = 10000000 + 100;
LL age[maxn],a[maxn][2],vis[maxn];
LL he[maxn],ver[maxm],ne[maxm],tot,n;
LL dfn[maxn],low[maxn],c[maxn],st[maxn],top,tim,color;
vector bcc[maxn];
void add( LL x,LL y ){
ver[++tot] = y;
ne[tot] = he[x];
he[x] = tot;
}
void tarjan( LL x ){
st[top++] = x;
dfn[x] = low[x] = ++tim;
for( LL cure = he[x]; cure; cure = ne[cure] ){
LL y = ver[cure];
if( !dfn[y] ){
tarjan(y);
low[x] = min( low[x],low[y] );
}else if( !c[y] ){
low[x] = min( low[x],dfn[y] );
}
}
if( low[x] == dfn[x] ){
LL cur;
color++;
do{
cur = st[–top];
c[cur] = color;
bcc[color].push_back( cur );
}while( cur != x );
}
}
struct sat{
void init(){
for( LL i = 0; i < 2n;i ++ ){
he[i] = 0;
dfn[i] = 0;
c[i] = 0;
bcc[i].clear();
}
tim = top = color = 0;
tot = 1;
}
void add_clause( LL x,LL p,LL y,LL q ){
add( x+pn,y+(q^(LL)1)n );
add( y+qn,x+(p ^(LL)1 )*n );
}
bool solve(){
for( LL i = 0; i < 2 * n;i++ ){
if( dfn[i] ) continue;
tarjan(i);
}
for( LL i = 0; i < n;i ++ ){
if( c[i] == c[i+n] ) return false;
}
return true;
}
void print(){
for( LL i = 0; i < n;i ++ ){
if( c[i] < c[i+n] ){
printf("%c\n", a[i][0] ? ‘A’ : ‘B’ );
}else {
printf(“C\n”);
}
}
}
}solver;

int main()
{
//freopen( “123.txt”,“r”,stdin );
LL m,sum,av,x,y;
while( 2 == scanf("%lld%lld",&n,&m) && n && m ){
solver.init();
for( LL i = 0; i < n;i ++ ){
a[i][0] = a[i][1] = 0;
}
sum = 0;
for( LL i = 0; i < n; i ++ ){
scanf("%lld",&age[i]);
sum += age[i];
}
if( (sum % n) == 0 ){
av = sum / n;
}else{
av = sum / n + 1;
}
for( LL i = 0; i < n; i ++ ){
if( age[i] >= av ){
a[i][0] = 1;
}else{
a[i][1] = 1;
}
}
for( LL i = 0; i < m;i ++ ){
scanf("%lld%lld",&x,&y );
x–;y–;
if( x == y ) continue;
solver.add_clause( x,1,y,1 );
if( a[x][0] && a[y][0] ){
solver.add_clause( x,0,y,0 );
}else if( a[x][1] && a[y][1] ){
solver.add_clause( x,0,y,0 );
}
}
if( solver.solve() ){
solver.print();
}else {
printf(“No solution.\n”);
}
}
return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值