题解:AT_abc397_g [ABC397G] Maximize Distance
ABC397G 题解
分析
好题,做过类似的,但赛时没有看出来挺可惜的。
考虑什么时候最短路不为
考虑把图分层,如果最短路为
建图流程如下:
- 假设原图有一条边
u \rightarrow v - 对
i \in[1,n-1] 层,加边u_i\rightarrow v_i ,容量为1 - 对
i\in[1,n-2] 层,加边u_i\rightarrow v_{i+1} ,容量为+\infty
下图是对图
Vertex=5 Edge=6
1 -> 2
1 -> 3
1 -> 4
2 -> 5
3 -> 5
4 -> 5
的建图示例(黄色边容量为 1,灰色边容量为无穷大):
简单说明一下正确性,考虑这样的二元组
于是可以二分解决问题。应当注意的是,二分的上界应为
代码
#include "iostream"
#include "cstdio"
#include "queue"
#include "cstring"
using namespace std;
int n,m,k;
const int maxn=1000,maxm=6005,inf=1e9+7;
struct Graph {
int S,T,hd[maxn],t[maxm<<1],nx[maxm<<1],fl[maxm<<1],tt;
int dep[maxn],cur[maxn];
Graph() {tt=1;}
inline void add(int u,int v,int f) {
nx[++tt]=hd[u];t[tt]=v,fl[tt]=f,hd[u]=tt;
}
inline bool bfs() {
memset(dep,0,sizeof dep);
memcpy(cur,hd,sizeof hd);
queue<int> q; dep[S]=1; q.push(S);
while(!q.empty()) {
int u=q.front(); q.pop();
for(int i=hd[u];i;i=nx[i]) {
if(dep[t[i]]||!fl[i]) continue;
dep[t[i]]=dep[u]+1;
if(t[i]==T) return 1;
q.push(t[i]);
}
}
return dep[T];
}
int dfs(int u,int f) {
if(u==T||!f) return f;
int x=0,y=f;
for(int &i=cur[u];i;i=nx[i]) {
if(dep[t[i]]!=dep[u]+1||!fl[i]) continue;
int res=dfs(t[i],min(y,fl[i]));
fl[i]-=res; fl[i^1]+=res;
x+=res; y-=res;
if(!y) break;
}
if(x==f) dep[u]=-1;
return x;
}
inline int dinic() {
int res=0;
while(bfs()) res+=dfs(S,inf);
return res;
}
}G,_G;
inline bool chk(int b) {
G=_G; G.T=b*n;
if(!b||G.dinic()<=k) return 1;
return 0;
}
int main() {
ios::sync_with_stdio(0);
cin>>n>>m>>k;
for(int i=1;i<=m;++i) {
int u,v; cin>>u>>v;
for(int j=0;j<n;++j) {
G.add(u+j*n,v+j*n,1);
G.add(v+j*n,u+j*n,0);
if(j!=n-1) {
G.add(u+j*n,v+(j+1)*n,inf);
G.add(v+(j+1)*n,u+j*n,0);
}
}
}
G.S=1; G.T=n; _G=G; G.bfs();
int l=0,r=G.dep[n]-1,ans=0;
while(l<=r) {
int mid=l+r>>1;
if(chk(mid)) {
ans=mid,l=mid+1;
} else r=mid-1;
}
cout<<ans;
return 0;
}
附上 AC 记录。
The end.