题目链接:https://vjudge.net/problem/UVA-1146
题意:有n架飞机需要登陆。每架飞机可以选择“早着陆”和“晚着陆”两种方式,且必须选择一种。第i架飞机早着陆时间为Ei,晚着陆时间为Li,不得在其他时间着陆。求:在把所有飞机按照实际着陆时间从早到晚排好序的情况下,相邻两个着陆时间间隔的最小值最大是多少。
思路:最大化最小值,可以用二分来求解。则可以把问题转化为,任意两个着陆时间差不小于P。用布尔变量Xi表示一个飞机着陆的情况(早着陆为0,晚着陆为1),然后枚举所有的着陆时间,若存在两个时间差小于P,则给相应的变量值连边。即把问题转化成了2-SAT问题。
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 2000 + 10;
struct TwoSAT {
int n;
vector<int> G[maxn*2];
bool mark[maxn*2];
int S[maxn*2], c;
bool dfs(int u) {
if(mark[u^1]) return false;
if(mark[u]) return true;
mark[u] = true;
S[c++] = u;
for(int i = 0; i < G[u].size(); i++)
if(!dfs(G[u][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, T[maxn][2];
bool test(int diff) {
solver.init(n);
for(int i = 0; i < n; i++) for(int a = 0; a < 2; a++)
for(int j = i+1; j < n; j++) for(int b = 0; b < 2; b++)
if(abs(T[i][a] - T[j][b]) < diff) solver.add_clause(i, a^1, j, b^1);
return solver.solve();
}
int main() {
while(scanf("%d", &n) == 1) {
int L = 0, R = 0;
for(int i = 0; i < n; i++) for(int a = 0; a < 2; a++) {
scanf("%d", &T[i][a]);
R = max(R, T[i][a]);
}
int ans = 0;
while(L <= R) {
int mid = (L + R) >> 1;
if(test(mid)) {
ans = mid;
L = mid + 1;
}
else R = mid - 1;
}
printf("%d\n", ans);
}
return 0;
}