poj 3207 Ikki's Story IV - Panda's Trick(2-SAT)

題目連接:http://poj.org/problem?id=3207ios

思路分析:該問題給出N個點,並給出M條鏈接這些點的線,須要判斷是否這些線不會相交;this

(1)假設兩條線A的端點按照圓圈的順時針方向依次爲A0,A1,同理線B爲B0, B1,則能夠知道當 A0 < B0 < A1 < B1 或者 B0 < A0 < B1 < A1時線A與B若是同時在內側或者外側,則線A與B一定相交;spa

(2)將M條線視爲圖中的M個布爾變量,每條線或者在內側或者在外側,若是線段A與B在同一側並定相交,則能夠獲得等價式:線A在內側—>線B在外側,線A在外側—>線B在內側,線B在內側—>線A在外側,線B在外側—>線A在內側;code

 

代碼以下:blog

#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
using namespace std;

const int MAX_N = 5000 + 10;
int e[MAX_N][MAX_N];

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

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

    void AddClause(int x, int y)
    {
        int a = 2 * x;
        int b = 2 * y;
        G[a].push_back(b ^ 1);
        G[a ^ 1].push_back(b);
        G[b].push_back(a ^ 1);
        G[b ^ 1].push_back(a);
    }

    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;
    }

    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;
    }
};

inline bool Judge(int x, int y)
{
    if ((e[x][0] < e[y][0]) && (e[y][0] < e[x][1])
        && (e[x][1] < e[y][1]))
        return true;
    if ((e[y][0] < e[x][0]) && (e[x][0] < e[y][1])
        && (e[y][1] < e[x][1]))
        return true;
    return false;
}

inline void Swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

TwoSAT sat;

int main()
{
    int n, m;

    while (scanf("%d %d", &n, &m) != EOF)
    {
        memset(e, 0, sizeof(e));
        sat.Init(m);
        for (int i = 0; i < m; ++i)
        {
            scanf("%d %d", &e[i][0], &e[i][1]);
            if (e[i][0] > e[i][1])
                Swap(e[i][0], e[i][1]);
        }
        for (int i = 0; i < m; ++i)
        {
            for (int j = i + 1; j < m; ++j)
            {
                if (Judge(i, j))
                    sat.AddClause(i, j);
            }
        }
        bool ok = sat.Solve();
        if (ok)
            printf("panda is telling the truth...\n");
        else
            printf("the evil panda is lying again\n");
    }
    return 0;
}
相關文章
相關標籤/搜索