传送门
一看题目里两个约束条件:很显然最小费用最大流啊。
于是开始搞:
拆点xi,yi,表示入点和出点;
由于每个点只能到达一次,xi向yi连边,容量为1,费用为0;其中1和n除外,因为可以经过多次。
然后按照题目描述的建图,从起点的yi(出点)向终点的xi(入点)连边,每条边的长度即为费用。注意这里的边的容量也应该为1,因为有可能从1直接到n 233
从超级源向x1连边,从yn向超级汇连边,容量都为INF,费用为0。
#include
#include
#include
#include
using namespace std;
const int max_n=205;
const int max_N=max_n*2+2;
const int max_m=2e4+5;
const int max_M=max_n*3+max_m;
const int max_e=max_M*2;
const int INF=2e9;
int n,m,N,x,y,z,maxflow,mincost;
int tot,point[max_N],next[max_e],v[max_e],c[max_e],remain[max_e];
int dis[max_N],last[max_N];
bool vis[max_N];
queue <int> q;
inline void addedge(int x,int y,int z,int cap){
++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=z; remain[tot]=cap;
++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x; c[tot]=-z; remain[tot]=0;
}
inline int addflow(int s,int t){
int now=t,ans=INF;
while (now!=s){
ans=min(ans,remain[last[now]]);
now=v[last[now]^1];
}
now=t;
while (now!=s){
remain[last[now]]-=ans;
remain[last[now]^1]+=ans;
now=v[last[now]^1];
}
return ans;
}
inline bool bfs(int s,int t){
memset(dis,0x7f,sizeof(dis));
memset(vis,0,sizeof(vis));
dis[s]=0;
vis[s]=true;
while (!q.empty()) q.pop();
q.push(s);
while (!q.empty()){
int now=q.front(); q.pop();
vis[now]=false;
for (int i=point[now];i!=-1;i=next[i])
if (dis[v[i]]>dis[now]+c[i]&&remain[i]){
dis[v[i]]=dis[now]+c[i];
last[v[i]]=i;
if (!vis[v[i]]){
vis[v[i]]=true;
q.push(v[i]);
}
}
}
if (dis[t]>INF) return false;
int flow=addflow(s,t);
maxflow+=flow;
mincost+=dis[t]*flow;
return true;
}
inline void major(int s,int t){
maxflow=0; mincost=0;
while (bfs(s,t));
}
int main(){
tot=-1;
memset(point,-1,sizeof(point));
memset(next,-1,sizeof(next));
scanf("%d%d",&n,&m);
N=n*2+2;
addedge(1,2,0,INF);
addedge(N-1,N,0,INF);
addedge(1+1,1+n+1,0,INF);
addedge(1+n,1+n+n,0,INF);
for (int i=2;i1+i,1+n+i,0,1);
for (int i=1;i<=m;++i){
scanf("%d%d%d",&x,&y,&z);
addedge(1+n+x,1+y,z,1);
}
major(1,N);
printf("%d %d\n",maxflow,mincost);
}
边的容量也是1!!!坑爹啊!!!
不过考虑一下以后这样的情况怎么避免出错。