您的位置:首页 > Web前端

POJ - 3905 Perfect Election(2-SAT)

2015-09-09 20:38 302 查看
题目大意:题意挺好理解的

解题思路:就按照题意来建边就可以了

[code]#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int MAXNODE = 2010;

vector<int> G[MAXNODE];
bool mark[MAXNODE * 2];
int Stack[MAXNODE * 2];
int n, m, top;

void AddClause(int x, int xval, int y, int yval) {
    x = x * 2 + xval;
    y = y * 2 + yval;
    G[x].push_back(y);
}

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

    char s1[15], s2[15];
    char sign1, sign2;
    int x, valx, y, valy;
    for (int i = 0; i < m; i++) {
        scanf("%s%s", s1, s2);
        sscanf(s1, "%c%d", &sign1, &x);
        sscanf(s2, "%c%d", &sign2, &y);
        valx = (sign1 == '+' ? 1 : 0);
        valy = (sign2 == '+' ? 1 : 0);
        AddClause(x, valx ^ 1, y, valy);
        AddClause(y, valy ^ 1, x, valx);
    }
}

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

void solve() {
    for (int i = 2; i < 2 * n; i += 2) {
        if (!mark[i] && !mark[i^1]) {
            top = 0;
            if (!dfs(i)) {
                while (top) mark[Stack[top--]] = false;
                if (!dfs(i ^ 1)) {
                    printf("0\n");
                    return ;
                }
            }
        }

    }
    printf("1\n");
}

int main() {
    while (scanf("%d%d", &n, &m) != EOF) {
        init();
        solve();
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: