Astronauts UVALive - 3713(2-SAT)

大白书例题

#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#define rap(a, n) for(int i=a; i<=n; i++)
#define MOD 2018
#define LL long long
#define ULL unsigned long long
#define Pair pair<int, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define _  ios_base::sync_with_stdio(0),cin.tie(0)
//freopen("1.txt", "r", stdin);
using namespace std; 
const int maxn = 100005;
 
struct TwoSAT {
    int n;
    vector<int> G[maxn*2];
    bool mark[maxn*2];
    int S[maxn*2], c;
 
    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 < n*2; i++) 
            G[i].clear();
        memset(mark, 0, sizeof(mark));
    }
    
    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 < n*2; 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 n, m, total_age, age[maxn];
 
int is_young(int x) {
    return age[x] * n < total_age;
}
 
int main() {
    while(scanf("%d%d", &n, &m) == 2 && n) {
        total_age = 0;
        for(int i = 0; i < n; i++) { 
            scanf("%d", &age[i]); 
            total_age += age[i]; 
        }
 
        solver.init(n);
        for(int i = 0; i < m; i++) {
            int a, b;
            scanf("%d%d", &a, &b); 
            a--; 
            b--;
            if(a == b) continue;
            solver.add_clause(a, 1, b, 1);   //不能同时为真
            if(is_young(a) == is_young(b)) 
                solver.add_clause(a, 0, b, 0);   //不能同时为假
        }
 
        if(!solver.solve()) printf("No solution.\n");
        else {
            for(int i = 0; i < n; i++)
                if(solver.mark[i*2]) printf("C\n");   //设的是选c为真  因为年龄小和年龄大的c是相同的  a和b不好直接判断 所以只要c被标记了 那么就是选了c
                else if(is_young(i)) printf("B\n");    //如果没选c  那就判断是不是年龄小的  
                else printf("A\n"); 
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/WTSRUVF/p/9365395.html