1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
|
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std;
typedef long long ll;
namespace cflow{
const int maxn=5005,maxm=50005; const ll inf=0x3f3f3f3f3f3f3f3f;
int n,s,t;
inline int oth(int x){ return ((x-1)^1)+1; }
struct edge{ int u,v; ll w,c; int nxt; edge(){} edge(int u_,int v_,ll w_,ll c_,int nxt_) { u=u_,v=v_,w=w_,c=c_,nxt=nxt_; } }e[2*maxm]; int fst[maxn],tp=0;
void addedge(int u,int v,ll w,ll c){ e[++tp]=edge(u,v,w,c,fst[u]); fst[u]=tp; } void addflow(int u,int v,ll w,ll c){ addedge(u,v,w,c); addedge(v,u,0,-c); }
ll dis[maxn],h[maxn],mxw[maxn];int cnt[maxn],frm[maxn],fre[maxn]; bool vis[maxn];
void spfa(){ static queue<int> q; while(!q.empty()){ q.pop(); }
memset(dis,0x3f,sizeof(dis)); memset(cnt,0,sizeof(cnt)); memset(vis,0,sizeof(vis));
dis[s]=0;vis[s]=1;q.push(s);cnt[s]++; while(!q.empty()){ int u=q.front();q.pop();vis[u]=0; if(cnt[u]>n+1){ break; } for(int i=fst[u];i!=0;i=e[i].nxt){ int v=e[i].v; ll c=e[i].c; if(e[i].w==0){ continue; } if(dis[v]>dis[u]+c){ dis[v]=dis[u]+c; if(!vis[v]){ vis[v]=1;q.push(v);cnt[v]++; } } } } }
void clear(){ memset(cflow::fst,0,sizeof(cflow::fst));cflow::tp=0; } void init(int n_,int s_,int t_){ n=n_,s=s_,t=t_; }
struct pr{ ll dis;int u;pr(){}pr(int u_,ll dis_){u=u_,dis=dis_;} }; bool operator<(pr a,pr b){ return (a.dis!=b.dis)?(a.dis>b.dis):(a.u>b.u); }
bool dijkstra(){ static priority_queue<pr> q; while(!q.empty()){ q.pop(); } memset(dis,0x3f,sizeof(dis)); dis[s]=0;mxw[s]=inf;q.push(pr(s,0)); while(!q.empty()){ int u=q.top().u;q.pop(); for(int i=fst[u];i!=0;i=e[i].nxt){ int v=e[i].v; ll c=e[i].c+h[u]-h[v],w=e[i].w; if(w && (dis[v]>dis[u]+c)){ dis[v]=dis[u]+c; mxw[v]=min(mxw[u],w); frm[v]=u; fre[v]=i; q.push(pr(v,dis[v])); } } } return dis[t]!=inf; }
ll mincost,maxflow;
void MCMF(){
spfa(); memcpy(h,dis,sizeof(h));
mincost=maxflow=0; while(dijkstra()){ ll flow=mxw[t]; maxflow+=flow; mincost+=flow*(dis[t]-h[s]+h[t]); for(int i=t;i!=s;i=frm[i]){ e[fre[i]].w-=flow; e[oth(fre[i])].w+=flow; } for(int i=1;i<=n;i++){ h[i]+=dis[i]; } } } }
int n,m,s,t;
int main(){ scanf("%d%d%d%d",&n,&m,&s,&t); cflow::n=n; cflow::s=s; cflow::t=t; for(int i=1;i<=m;i++){ int u,v;ll w,c; scanf("%d%d%lld%lld",&u,&v,&w,&c); if(c<0){ cflow::addflow(v,u,w,-c); }else{ cflow::addflow(u,v,w,c); } }
cflow::MCMF();
printf("%lld %lld\n",cflow::maxflow,cflow::mincost);
return 0;
}
|