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 151 152 153 154 155 156 157 158 159 160 161
|
#include<cstring> #include<cstdio> #include<queue>
using namespace std;
const int N=5e3+100; const int M=1e6+100; const int inf=0x3f3f3f3f;
int tot; int head[N]; struct edge{ int y; int f,w; int next; }e[M];
struct node{ int x,w; bool operator <(const node &s)const{ return w > s.w; } };
int cnt[N]; int tmp[N]; int vis[N];
int pre[N]; int dis[N]; int flo[N];
int n,m; int s,t;
inline int max(int a,int b){return a>b?a:b;} inline int min(int a,int b){return a<b?a:b;} inline int ops(int x){return x^1;}
inline void init(){ tot=0; memset(head,-1,sizeof(head)); return ; }
inline void add(int x,int y,int f,int w){ e[tot].y=y; e[tot].f=f; e[tot].w=w; e[tot].next=head[x]; head[x]=tot++; }
inline void make(int x,int y,int f,int w){ add(x,y,f,w); add(y,x,0,-w); return ; }
inline void spfa(int start,int to){ memset(tmp,0x3f,sizeof(tmp)); queue<int>q; q.push(start); tmp[start]=0; while(!q.empty()){ int x=q.front(); q.pop(); vis[x]=0; for(int i=head[x];~i;i=e[i].next){ int y=e[i].y; int f=e[i].f; int w=e[i].w; if(!f)continue; if(tmp[x]+w<tmp[y]){ tmp[y]=tmp[x]+w; if(!vis[y]){ vis[y]=1; q.push(y); } } } } return ; }
inline bool dij(int start,int to){ priority_queue<node>q; for(int i=1;i<=n;i++){ dis[i]=inf; flo[i]=0; vis[i]=0; } dis[start]=0; flo[start]=inf; q.push(node{start,dis[start]}); while(!q.empty()){ int x=q.top().x; q.pop(); if(vis[x])continue; vis[x]=1; for(int i=head[x];~i;i=e[i].next){ int y=e[i].y; int f=e[i].f; int w=e[i].w+tmp[x]-tmp[y]; if(!f)continue; if(dis[y]>dis[x]+w){ flo[y]=min(flo[x],f); dis[y]=dis[x]+w; pre[y]=i; q.push(node{y,dis[y]}); } } } return flo[to]>0; }
inline void EK(int start,int to,int &flow,int &cost){ flow=0; cost=0; while(dij(start,to)){ int t=flo[to]; flow+=t; cost+=t*(dis[to]-tmp[start]+tmp[to]); for(int i=to;i!=start;i=e[ops(pre[i])].y){ e[pre[i]].f-=t; e[ops(pre[i])].f+=t; } for(int i=1;i<=n;i++){ if(dis[i]<inf){ tmp[i]+=dis[i]; } } } return ; }
int main(){ init(); scanf("%d%d%d%d",&n,&m,&s,&t); for(int i=1;i<=m;i++){ int x,y,f,w; scanf("%d%d%d%d",&x,&y,&f,&w); make(x,y,f,w); } spfa(s,t); int flow=0; int cost=0; EK(s,t,flow,cost); printf("%d %d\n",flow,cost); return 0; }
|