首页 > 代码库 > HDU3622-Bomb Game(2-SAT+二分)

HDU3622-Bomb Game(2-SAT+二分)

题目链接


题意:给n对炸弹可以放置的位置(每个位置为一个二维平面上的点),每次放置炸弹是时只能选择这一对中的其中一个点,每个炸弹爆炸的范围半径都一样,控制爆炸的半径使得所有的爆炸范围都不相交(可以相切),求解这个最大半径。

思路:二分答案,其中建图,用2-SAT判断方案是否可行。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;

const int MAXN = 105;
const double eps = 1e-5;

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;

struct Point{
    double x, y;
}p[MAXN][2];

int n;

inline double dis(Point a, Point b) {  
    double dx = a.x - b.x;  
    double dy = a.y - b.y;  
    return sqrt(dx * dx + dy * dy);  
}  

inline bool xj(Point a, Point b, double r) {  
    if (dis(a, b) > 2 * r) 
        return false;  
    return true;  
}  

bool judge(double r) {  
    solver.init(n);  
    for (int i = 0; i < n; i++) {  
        for (int j = i + 1; j < n; j++) {  
            for (int x = 0; x < 2; x++) {  
                for (int y = 0; y < 2; y++) {  
                    if (xj(p[i][x], p[j][y], r))  
                        solver.add_clause(i, x, j, y);  
                }  
            }  
        }  
    }  
    return solver.solve();  
}  

int main() {
    while (scanf("%d", &n) != EOF) {
        for (int i = 0; i < n; i++) 
            for (int j = 0; j < 2; j++) {
                scanf("%lf%lf", &p[i][j].x, &p[i][j].y); 
            }
        double l = 0, r = 1e5;
        while (r - l >= eps) {
            double mid = (l + r) / 2; 
            if (judge(mid)) 
                l = mid;
            else
                r = mid;
        }
        printf("%.2lf\n", l); 
    }
    return 0;
}


HDU3622-Bomb Game(2-SAT+二分)