loj 1156(二分+最大流)

时间:2021-07-02 17:16:20

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=26870

思路:由于溢出问题,wa了半天,还以为构图错了呢,查了半天!一看到最大最小问题,就应该想到二分,二分最大距离,然后建图跑最大流验证。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define MAXN 222
#define MAXM 222222
#define inf 1<<30
#define FILL(a,b) memset(a,b,sizeof(a)) struct Edge{
int v,cap,next;
}edge[MAXM]; int n,D,vs,vt,NV,NE;
int head[MAXN]; void Insert(int u,int v,int cap)
{
edge[NE].v=v;
edge[NE].cap=cap;
edge[NE].next=head[u];
head[u]=NE++; edge[NE].v=u;
edge[NE].cap=;
edge[NE].next=head[v];
head[v]=NE++;
} int level[MAXN],gap[MAXN];
void bfs(int vt)
{
FILL(level,-);
FILL(gap,);
queue<int>que;
que.push(vt);
level[vt]=;
gap[]++;
while(!que.empty()){
int u=que.front();
que.pop();
for(int i=head[u];i!=-;i=edge[i].next){
int v=edge[i].v;
if(level[v]!=-)continue;
level[v]=level[u]+;
gap[level[v]]++;
que.push(v);
}
}
} int pre[MAXN],cur[MAXN];
int SAP(int vs,int vt)
{
bfs(vt);
memcpy(cur,head,sizeof(head));
int u=pre[vs]=vs,aug=inf,maxflow=;
gap[]=NV;
while(level[vs]<NV){
bool flag=false;
for(int &i=cur[u];i!=-;i=edge[i].next){
int v=edge[i].v;
if(edge[i].cap>&&level[u]==level[v]+){
flag=true;
aug=min(aug,edge[i].cap);
pre[v]=u;
u=v;
if(v==vt){
maxflow+=aug;
for(u=pre[u];v!=vs;v=u,u=pre[u]){
edge[cur[u]].cap-=aug;
edge[cur[u]^].cap+=aug;
}
aug=inf;
}
break;
}
}
if(flag)continue;
int minlevel=NV;
for(int i=head[u];i!=-;i=edge[i].next){
int v=edge[i].v;
if(edge[i].cap>&&level[v]<minlevel){
minlevel=level[v];
cur[u]=i;
}
}
if(--gap[level[u]]==)break;
level[u]=minlevel+;
gap[level[u]]++;
u=pre[u];
}
return maxflow;
} struct Node{
int d;
char flag;
}node[MAXN]; void Build(int limit)
{
NE=;
vs=,vt=*n+,NV=vt+;
FILL(head,-);
for(int i=;i<=n;i++){
if(node[i].flag=='B')Insert(i,i+n,);
else if(node[i].flag=='S')Insert(i,i+n,);
}
for(int i=;i<=n;i++){
for(int j=i+;j<=n;j++){
if(node[j].d-node[i].d<=limit){
Insert(i+n,j,);
}
}
}
for(int i=;i<=n;i++){
if(node[i].d<=limit)Insert(vs,i,);
if(D-node[i].d<=limit)Insert(i+n,vt,);
}
if(D<=limit)Insert(vs,vt,);
} int main()
{
int _case,t=;
char str[];
scanf("%d",&_case);
while(_case--){
scanf("%d%d",&n,&D);
for(int i=;i<=n;i++){
scanf("%s",str);
sscanf(str,"%c-%d",&node[i].flag,&node[i].d);
}
int low=,high=D,mid,ans;
while(low<=high){
mid=(low+high)>>;
Build(mid);
if(SAP(vs,vt)>=){
ans=mid;
high=mid-;
}else
low=mid+;
}
printf("Case %d: %d\n",t++,ans);
}
return ;
}