uvaLive 3713

题目链接

#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define N 200010
#define INF 0x3f3f3f3f

struct TwoSAT{
    int n, c;
    vector<int> G[N];
    bool mark[N];
    int S[N];

    bool dfs(int x) {
        if (mark[x ^ 1]) return false;
        if (mark[x]) return true;
        mark[x] = true;
        S[c++] = x;
        for (int i = 0; i < G[x].size(); i++)
            if (!dfs(G[x][i])) return false;
        return true;
    }

    void init(int n) {
        this->n = n;
        for (int i = 0; i < 2 * n; i++)
            G[i].clear();
        memset(mark, 0, sizeof(mark));
    }

    //x == xval or y == yval
     //这里的值是x为真或者y为真,若想两条件不同时成立,可以传递进非x和非y,即x^1 y^1
    void add_clause(int x, int xval, int y, int yval) {
        x = x * 2 + xval;
        y = y * 2 + yval;
        G[x^1].push_back(y);
        G[y^1].push_back(x);
    }

    bool solve() {
        for (int i = 0; i < 2 * n; i += 2) {
            if (!mark[i] && !mark[i + 1]) {
                c = 0;
                if (!dfs(i)) {
                    while (c > 0) mark[S[--c]] = false;
                    if (!dfs(i + 1)) return false;
                }
            }
        }
        return true;
    }
};

TwoSAT solver;
int age[N], ave, n, m;

void solve()
{
    if(!solver.solve())
        printf("No solution.\n");
    else
    {
        for(int i = 0; i < n; i++)
            if(age[i] >= ave)
                printf("%c\n", !solver.mark[i * 2] ? 'A' : 'C');
            else
                printf("%c\n", !solver.mark[i * 2] ? 'B' : 'C');
    }
}

int main()
{
    while(~scanf("%d%d", &n, &m) && n + m)
    {
        solver.init(n);
        ave = 0;
        for(int i = 0; i < n; i++) {
                scanf("%d", age + i);
                ave += age[i];
        }
        ave = (ave + n - 1) / n;
        int u, v;
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d", &u, &v);
            u--, v--;
            if((age[u] >= ave && age[v] >= ave) || (age[u] < ave && age[v] < ave))
            {
                solver.add_clause(u, 1, v, 1);
                solver.add_clause(u, 0, v, 0);
            }
            else
            {
                solver.add_clause(u, 1, v, 1);
            }
        }
        solve();
    }
    return 0;
}


你可能感兴趣的:(ACM)