题意: 一个n个城市m条边的有向图,有c个人要从起点走到终点,每个人走到终点的花费为该人所走路径上经过人最多的边的人数平方,求所有人到达终点花费总和的最小值
题解: 因为花费是平方,每个人最优的走法一定是将人数按路径平均下来。最终所有人的花费总和其实就是每一条能到达终点的路径上的最大人数平方和。从起点到终点的路径数量用容量为1的边跑最大流可以得到。
然后就按照最优分法,将人数c平均分为路径数量份,每份有c/maxflow人,这其实就是每条路径的最大人数,要注意的是当除不尽的时候,余数作为1加到任意几条路径上,那么这几条路径的最大人数都+1。于是,若整除每条路径通过最多t个人,非整除路径通过最多t+1个人,其实就是路径数量 × 通过人数 × 最大人数 × 最大人数 就是结果。其中通过人数就是最大人数。路径数量其实就分为两类,一类带余数的t+1个人的路,有c%maxflow条,另一种即t个人的路,即maxflow -(c%maxflow)条
最后注意虽然是裸的最大流题目,但是数据卡裸的dinic,需要使用当前弧优化才能不超时。当前弧优化即在分层图计算流量时记录了每个节点遍历到那条边的位置。保证每条边只会遍历到一次。
#include<bits/stdc++.h>///普通的最大流题目,但是数据卡当前弧优化
#define LL long long
#define M(a,b) memset(a,b,sizeof a)
#define pb(x) push_back(x)
using namespace std;
const int maxn=508;
const int inf=0x3f3f3f3f;
struct edge
{
int to,nxt,val;
edge() {}
edge(int a,int b,int c)
{
to=a;
val=b;
nxt=c;
}
} mp[maxn*maxn];
int head[maxn],dep[maxn],cnt;
int n,m,c;
void addedge(int from,int to,int val)
{
mp[cnt]=edge(to,val,head[from]);
head[from]=cnt++;
mp[cnt]=edge(from,0,head[to]);
head[to]=cnt++;
}
bool bfs(int st,int ed)
{
memset(dep,-1,sizeof dep);
queue<int>q;
while(!q.empty())q.pop();
dep[st]=0;
q.push(st);
while(!q.empty())
{
int tmp=q.front();
q.pop();
if(tmp==ed) return true;
for(int i=head[tmp]; i!=-1; i=mp[i].nxt)
{
int &to=mp[i].to,flow=mp[i].val;
if(dep[to]==-1&&flow)
{
dep[to]=dep[tmp]+1;
q.push(to);
if(to==ed)return true;
}
}
}
return false;
}
int cur[maxn];///当前弧优化数组
int dfs(int s,int t,int flow)
{
if(s==t||flow==0)return flow;///当前弧优化
int pre=0;
for(int &i=cur[s]; i!=-1; i=mp[i].nxt)///每次dfs的时候记录遍历优化到那条边了
{///如果再次遍历这个点的时候就可以直接取拜访那条边
int &to=mp[i].to,val=mp[i].val;
if(dep[s]+1==dep[to]&&val)
{
int tmp=min(flow-pre,val);
int sub=dfs(to,t,tmp);
mp[i].val-=sub;
mp[i^1].val+=sub;
pre+=sub;
if(pre==flow)return pre;
}
}
return pre;
}
int dinic(int st,int ed)
{
int ans=0;
while(bfs(st,ed))
{
for(int i=1;i<=n;i++)cur[i]=head[i];///清空当前弧
ans+=dfs(st,ed,inf);
}
return ans;
}
int main()
{
int from,to,val,st,ed;
while(scanf("%d%d%d%d%d",&n,&m,&st,&ed,&c),n||m||st||ed||c)
{
M(head,-1);
cnt=0;
for(int i=1; i<=m; i++)
{
scanf("%d%d",&from,&to);
addedge(from,to,1);
}
int sum=dinic(st,ed);
LL ans=0;
LL tmp=c/sum;
LL mod=c%sum;
ans+=mod*(tmp+1)*(tmp+1)*(tmp+1)+(sum-mod)*tmp*tmp*tmp;
printf("%lld\n",ans);
}
}