HDU 1815 Building roads

时间:2021-03-15 23:48:17

二分答案 + 2-SAT验证

POJ 稳过,HDU C++ 超时,G++ 550ms左右AC

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std; const int maxn=+;
int N,A,B;
int left,right,mid;
int s1x,s1y,s2x,s2y;
struct point
{
int x,y;
int p_s1;
int p_s2;
}p[maxn];
int Hx[maxn],Hy[maxn];
int Lx[maxn],Ly[maxn]; stack<int>S;
vector<int>G[maxn];
vector<int>FG[maxn];
int Belong[maxn];
int flag[maxn];
int Block; int dis1,dis2,dis3; void init()
{
for(int i=;i<maxn;i++) G[i].clear();
for(int i=;i<maxn;i++) FG[i].clear();
memset(Belong,,sizeof Belong);
memset(flag,,sizeof flag);
while(!S.empty()) S.pop();
Block=;
} void addEgde(int x,int y)
{
G[x].push_back(y);
FG[y].push_back(x);
} int Dis(int x1,int y1,int x2,int y2)
{
return abs(x1-x2)+abs(y1-y2);
} void read()
{
scanf("%d%d%d%d",&s1x,&s1y,&s2x,&s2y);
for(int i=;i<N;i++)
scanf("%d%d",&p[i].x,&p[i].y);
for(int i=;i<=A;i++)
{
scanf("%d%d",&Hx[i],&Hy[i]);
Hx[i]--;Hy[i]--;
}
for(int i=;i<=B;i++)
{
scanf("%d%d",&Lx[i],&Ly[i]);
Lx[i]--;Ly[i]--;
}
} void dfs1(int now)
{
flag[now]=;
for(int i=;i<G[now].size();i++)
if(!flag[G[now][i]])
dfs1(G[now][i]);
S.push(now);
} void dfs2(int now)
{
Belong[now]=Block;
for(int i=;i<FG[now].size();i++)
if(!Belong[FG[now][i]])
dfs2(FG[now][i]);
} bool judge()
{
for(int i=;i<*N;i++) if(!flag[i]) dfs1(i);
while(!S.empty())
{
int Top=S.top(); S.pop();
if(!Belong[Top])
{
Block++;
dfs2(Top);
}
}
for(int i=;i<N;i++)
if(Belong[*i]==Belong[*i+])
return ;
return ;
} void solve()
{
left=;right=;
int ans=-;
while(left<=right)
{
mid=(left+right)/;
init(); for(int i=;i<N;i++){
for(int j=i+;j<N;j++)
{
int pi_s1=p[i].p_s1;
int pi_s2=p[i].p_s2;
int pj_s1=p[j].p_s1;
int pj_s2=p[j].p_s2;
int s1_s2=Dis(s1x,s1y,s2x,s2y); if(pi_s1+pj_s1>mid) {
addEgde(*i,*j+);
addEgde(*j,*i+);
} if(pi_s2+pj_s2>mid) {
addEgde(*i+,*j);
addEgde(*j+,*i);
} if(pi_s1+s1_s2+pj_s2>mid) {
addEgde(*i,*j);
addEgde(*j+,*i+);
} if(pi_s2+s1_s2+pj_s1>mid) {
addEgde(*i+,*j+);
addEgde(*j,*i);
}
} } for(int i=;i<=A;i++)
{
addEgde(*Hx[i],*Hy[i]+);
addEgde(*Hy[i]+,*Hx[i]);
addEgde(*Hx[i]+,*Hy[i]);
addEgde(*Hy[i],*Hx[i]+);
}
for(int i=;i<=B;i++)
{
addEgde(*Lx[i],*Ly[i]);
addEgde(*Ly[i],*Lx[i]);
addEgde(*Lx[i]+,*Ly[i]+);
addEgde(*Ly[i]+,*Lx[i]+);
}
if(judge()) ans=mid,right=mid-;
else left=mid+;
}
printf("%d\n",ans);
}
int main()
{
while(~scanf("%d%d%d",&N,&A,&B))
{
read();
for(int i=;i<N;i++)
{
p[i].p_s1=Dis(p[i].x,p[i].y,s1x,s1y);
p[i].p_s2=Dis(p[i].x,p[i].y,s2x,s2y);
}
solve();
}
return ;
}