La3713 Astronauts 2-Sat

題目大意:
有A, B, C三個任務分配給n個宇航員, 其中每個宇航員要被分配一個任務。所有年齡大於平均年齡的宇航員可以選擇A, C兩種任務,其餘人只能選擇B, C兩種任務, 同時這n個宇航員中有m組矛盾, i 和 j 之間矛盾表示 i 與 j 不能參與同一項任務。
問每個宇航員應如何分配任務。
分析:
本題是一個典型的2-Sat類型的題目,宇航員之間的矛盾有兩種情況, 分別表示兩個宇航員屬於同一類型和不屬於同一類型時候的選擇,我們用真來表示選擇A或B, 假來表示選擇C, 那麼當 i 和 j 兩個宇航員屬於同類時, 就說明 i 爲真時 j 必定爲假, 反之亦然。否則,只需要兩者不同爲假即可。
代碼:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 10;

struct Twosat {
    int n;
    vector<int> G[maxn*2];
    bool mark[maxn*2];
    int S[maxn*2], c;

    void init(int n) {
        this->n = n;
        memset(mark, 0, sizeof(mark));
        for(int i=0; i<2*n; i++) G[i].clear();
    }
    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;
    }
    //x = xval or y = yval
    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); // when x != xval , y must = yval;
        G[y^1].push_back(x); // when y != yval , x must = xval;
    }
    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;
    }
}solver;

int n, m, u, v;
bool type[maxn];
int age[maxn], age_sum;

void init() {
    solver.init(n);
    age_sum = 0;
    memset(type, false, sizeof(type));
}
int main() {
#ifndef ONLINE_JUDGE
    freopen("data.txt", "r", stdin);
    freopen("ans.txt", "w", stdout);
#endif
    while(scanf("%d%d", &n, &m) == 2 && n+m) {
        init();
        for(int i=0; i<n; i++) {
            scanf("%d", &age[i]);
            age_sum += age[i];
        }
        for(int i=0; i<n; i++) type[i] = (age[i] * n >= age_sum);

        for(int i=0; i<m; i++) {
            scanf("%d%d", &u, &v); u--, v--;
            if(type[u] == type[v]) 
                solver.add_clause(u, 1, v, 1), solver.add_clause(u, 0, v, 0);
            else 
                solver.add_clause(u, 1, v, 1);
        }
        if(!solver.solve()) printf("No solution.\n");
        else {
            for(int i=0; i<n; i++) {
                if(solver.mark[i*2+1]) 
                    printf("%c\n", type[i] ? 'A' : 'B');
                else 
                    printf("%c\n", 'C');
            }
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章