poj2749
题意
有 n 个农场,2个中转站,每个农场只能连接到一个中转站,2个农场可能不愿意连接到同一中转站,也可能只愿意连接到同一中转站,给出农场和中转站的坐标,求使得任意两个农场通过中转站连接的距离最大值最小,如果存在农场无法连接输出-1。
分析
对于农场 x, y 如果不愿意连接到同一中转站有 x xor y = 1,只愿意连接到同一中转站有 x xor y = 0,二分最大距离,对于两个农场通过中转站连接的距离大于这个距离的话则有 x and y = 0 【对立】 (本题的对立关系是 只能连接到一个中转站,那么对立的一方只能连接到另一个中转站了。
code
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int INF = 1e9;
const int MAXN = 3e3 + 5;
int vis[MAXN], flag[MAXN];
vector<int> G[MAXN], rG[MAXN];
vector<int> vs;
int n, m;
void addedge(int x, int y)
{
G[x].push_back(y);
rG[y].push_back(x);
}
void dfs(int u)
{
vis[u] = 1;
for(int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if(!vis[v]) dfs(v);
}
vs.push_back(u);
}
void rdfs(int u, int k)
{
vis[u] = 1; flag[u] = k;
for(int i = 0; i < rG[u].size(); i++)
{
int v = rG[u][i];
if(!vis[v]) rdfs(v, k);
}
}
int scc()
{
vs.clear();
memset(vis, 0, sizeof vis);
for(int i = 0; i < n; i++)
if(!vis[i]) dfs(i);
memset(vis, 0, sizeof vis);
int k = 0;
for(int i = vs.size() - 1; i >= 0; i--)
if(!vis[vs[i]]) rdfs(vs[i], k++);
return k;
}
bool judge()
{
int N = n;
n = 2 * n;
scc();
n /= 2;
for(int i = 0; i < n; i++)
if(flag[i] == flag[i + N]) return false;
return true;
}
int A, B, sx1, sy1, sx2, sy2;
int hate1[MAXN], hate2[MAXN];
int like1[MAXN], like2[MAXN];
int px[MAXN], py[MAXN];
void solve()
{
int l = 0, r = 4000000, mid;
int DIST = abs(sx1 - sx2) + abs(sy1 - sy2);
while(l < r)
{
mid = (l + r) / 2;
for(int i = 0; i < 2 * n; i++)
{
G[i].clear(); rG[i].clear();
}
for(int i = 0; i < A; i++) // x xor y = 1
{
addedge(hate1[i], hate2[i] + n);
addedge(hate1[i] + n, hate2[i]);
addedge(hate2[i], hate1[i] + n);
addedge(hate2[i] + n, hate1[i]);
}
for(int i = 0; i < B; i++) // x xor y = 0
{
addedge(like1[i], like2[i]);
addedge(like1[i] + n, like2[i] + n);
addedge(like2[i], like1[i]);
addedge(like2[i] + n, like1[i] + n);
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < i; j++)
{
// 连接到同一中转站
if(abs(px[i] - sx1) + abs(py[i] - sy1) + abs(px[j] - sx1) + abs(py[j] - sy1) > mid)
{
addedge(i, j + n); addedge(j, i + n);
}
if(abs(px[i] - sx2) + abs(py[i] - sy2) + abs(px[j] - sx2) + abs(py[j] - sy2) > mid)
{
addedge(i + n, j); addedge(j + n, i);
}
// 连接到不同中转站
if(abs(px[i] - sx1) + abs(py[i] - sy1) + abs(px[j] - sx2) + abs(py[j] - sy2) + DIST > mid)
{
addedge(i, j); addedge(j + n, i + n);
}
if(abs(px[j] - sx1) + abs(py[j] - sy1) + abs(px[i] - sx2) + abs(py[i] - sy2) + DIST > mid)
{
addedge(j, i); addedge(i + n, j + n);
}
}
}
if(!judge()) l = mid + 1;
else r = mid;
}
if(l == 0 || l == 4000000) puts("-1");
else printf("%d
", l);
}
int main()
{
while(~scanf("%d%d%d", &n, &A, &B))
{
scanf("%d%d%d%d", &sx1, &sy1, &sx2, &sy2);
for(int i = 0; i < n; i++) scanf("%d%d", &px[i], &py[i]);
for(int i = 0; i < A; i++)
{
scanf("%d%d", &hate1[i], &hate2[i]);
hate1[i]--; hate2[i]--;
}
for(int i = 0; i < B; i++)
{
scanf("%d%d", &like1[i], &like2[i]);
like1[i]--; like2[i]--;
}
solve();
}
return 0;
}