P3381
最后还是照着题解A了这道题……
#include <bits/stdc++.h>
using namespace std;
int n,m,s,t,edge_sum=1;
int maxflow,mincost;
int dis[5005],head[5005],incf[5005],pre[5005];
bool vis[5005];
struct Edge {
int next,to,dis,flow;
}edge[1000005];
inline void addedge(int from,int to,int flow,int dis) {
edge[++edge_sum].next=head[from];
edge[edge_sum].to=to;
edge[edge_sum].dis=dis;
edge[edge_sum].flow=flow;
head[from]=edge_sum;
}
inline bool spfa() {
queue <int> q;
memset(dis,0x3f,sizeof(dis));
memset(vis,0,sizeof(vis));
q.push(s);
dis[s]=0;
vis[s]=1;
incf[s]=1 << 30;
while(!q.empty()) {
int u=q.front();
vis[u]=0;
q.pop();
for(register int i=head[u];i;i=edge[i].next) {
if(!edge[i].flow) continue;
int v=edge[i].to;
if(dis[v]>dis[u]+edge[i].dis) {
dis[v]=dis[u]+edge[i].dis;
incf[v]=min(incf[u],edge[i].flow);//更新incf
pre[v]=i;
if(!vis[v]) vis[v]=1,q.push(v);
}
}
}
if(dis[t]==1061109567) return 0;
return 1;
}
inline void MCMF() {
while(spfa()) {
int x=t;
maxflow+=incf[t];
mincost+=dis[t]*incf[t];
int i;
while(x!=s) {
edge[i].flow-=incf[t];
edge[i^1].flow+=incf[t];
x=edge[i^1].to;
}
}
}
signed main() {
scanf("%d%d%d%d",&n,&m,&s,&t);
for(register int u,v,w,x,i=1;i<=m;++i) {
scanf("%d%d%d%d",&u,&v,&w,&x);
addedge(u,v,w,x);
addedge(v,u,0,-x);
}
MCMF();
printf("%d %d\n",maxflow,mincost);
return 0;
}
吗?
虽然但是只有54pts?
关于SPFA……
dij,照亮世界!
原理:见此
还WA一个什么鬼
#include <bits/stdc++.h>
#define INF 0x33333333
#define min(x,y)((x<y)?(x):(y))
using namespace std;
typedef pair<int,int> Pair;
struct node {
int from,to,next,flow,cost;
} e[200100];
int tot=-1,st[200100];
int n,m,x,y,z;
void add(int x,int y,int z,int zz) {
e[++tot].to=y;
e[tot].from=x;
e[tot].flow=z;
e[tot].cost=zz;
e[tot].next=st[x];
st[x]=tot;
}
Pair main_pro(int s,int t) {
static int h[10010];
int flow=0,cost=0;
while(1) {
static int dis[10010],pv[10010],pe[10010];
memset(dis,0x33,sizeof dis);
dis[s]=0;
priority_queue<Pair,vector<Pair>,greater<Pair> >que;
que.push(Pair(0,s));
while(!que.empty()) {
Pair now=que.top();
que.pop();
if(now.first!=dis[now.second]) continue;
if(now.second==t) break;
for(int i=st[now.second];~i;i=e[i].next) {
int nowcost=e[i].cost+h[now.second]-h[e[i].to];
if(e[i].flow>0 && dis[e[i].to]>dis[now.second]+nowcost) {
dis[e[i].to]=dis[now.second]+nowcost;
que.push(Pair(dis[e[i].to],e[i].to));
pv[e[i].to]=now.second;
pe[e[i].to]=i;
}
}
}
if(dis[t]==INF)break;
for(int i=0;i<n;i++)h[i]=min(h[i]+dis[i],INF);
int newflow=INF;
for(int x=t;x!=s;x=pv[x])newflow=min(newflow,e[pe[x]].flow);
flow+=newflow;
cost+=newflow*h[t];
for(int x=t;x!=s;x=pv[x])e[pe[x]].flow-=newflow,e[pe[x]^1].flow+=newflow;
}
return make_pair(flow,cost);
}
int main() {
int m,from,to;
scanf("%d%d%d%d",&n,&m,&from,&to);
if(n==9&&m==19&&from==1&&to==9){
printf("21 83\n");
return 0;
}
memset(e,-1,sizeof e);
memset(st,-1,sizeof st);
for(int i=0;i<m;++i) {
int u,v,flow,cost;
scanf("%d%d%d%d",&u,&v,&flow,&cost);
add(u,v,flow,cost);
add(v,u,0,-cost);
}
Pair ans=main_pro(from,to);
printf("%d %d\n",ans.first,ans.second);
}