la3713

2-sat。。。求解2-sat方案直接每个变量枚举就行了,lrj的代码很靠谱。。。

#include<bits/stdc++.h>
using namespace std;
const int N = 300010;
struct edge {
    int nxt, to;
} e[N << 4];
int n, m, x, cnt, top;
bool mark[N];
int head[N], u[N], v[N], age[N], st[N];
void Init()
{
    cnt = 1; top = x = 0;
    memset(head, 0, sizeof(head)); 
    memset(mark, false, sizeof(mark));
}
void link(int u, int v)
{
    e[++cnt].nxt = head[u];
    head[u] = cnt;
    e[cnt].to = v;
}
bool dfs(int u)
{
    if(mark[u ^ 1]) return false;
    if(mark[u]) return true;
    mark[u] = true; st[++top] = u;
    for(int i = head[u]; i; i = e[i].nxt) if(!dfs(e[i].to)) return false;
    return true;
}
bool solve()
{
    for(int i = 2; i <= 2 * n + 1; i += 2) if(!mark[i] && !mark[i + 1]) 
    {
        top = 0;
        if(!dfs(i)) 
        {
            while(top) mark[st[top--]] = false;
            if(!dfs(i + 1)) return false;
        }
    }
    return true;
}
int main()
{
    while(scanf("%d%d", &n, &m))
    {
        if(n == 0 && m == 0) break;
        Init();
        for(int i = 1; i <= n; ++i) scanf("%d", &age[i]), x += age[i];
        for(int i = 1; i <= m; ++i)
        {
            int u1, v1, u2, v2; scanf("%d%d", &u[i], &v[i]);
            u1 = u[i] << 1; u2 = u1 + 1; v1 = v[i] << 1; v2 = v1 + 1;
            if(age[u[i]] * n >= x)
            {
                if(age[v[i]] * n >= x) link(u2, v1), link(v1, u2), link(u1, v2), link(v2, u1);
                if(age[v[i]] * n < x) link(u1, v2), link(v1, u2);
            }
            else 
            {
                if(age[v[i]] * n >= x) link(u1, v2), link(v1, u2);
                if(age[v[i]] * n < x) link(u1, v2), link(v2, u1), link(u2, v1), link(v1, u2);
            }
        }
        if(!solve()) { puts("No solution."); continue; }
        for(int i = 1; i <= n; ++i) 
        {
            if(mark[i * 2]) puts("C");
            else if(age[i] * n >= x) puts("A");
            else puts("B"); 
        }        
    }
    return 0;
}
View Code

 

posted @ 2017-05-16 22:17  19992147  阅读(103)  评论(0编辑  收藏  举报