【模板】最大流
luoguTST:129ms
CODE:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<queue> 5 #define inf 2147483647 6 #define ms(a,b) memset(a,b,sizeof a) 7 #define rep(i,a,n) for(int i = a;i <= n;i++) 8 #define per(i,n,a) for(int i = n;i >= a;i--) 9 using namespace std; 10 typedef long long ll; 11 int read() { 12 int as = 0,fu = 1; 13 char c = getchar(); 14 while(c < '0' || c > '9') { 15 if(c == '-') fu = -1; 16 c = getchar(); 17 } 18 while(c >= '0' && c <= '9') { 19 as = as * 10 + c - '0'; 20 c = getchar(); 21 } 22 return as * fu; 23 } 24 const int N = 200005; 25 //head 26 int n,m,s,t; 27 int head[N],cst[N],nxt[N],mo[N],cnt = -1,ans; 28 int cur[N]; 29 inline void add(int x,int y,int w) { 30 mo[++cnt] = y; 31 cst[cnt] = w; 32 nxt[cnt] = head[x]; 33 head[x] = cnt; 34 return; 35 } 36 37 int dep[N]; 38 inline int dfs(int x,int lim) { 39 if(x == t || !lim) return lim; 40 int ret = 0; 41 for(int& i = cur[x]; i != -1; i = nxt[i]) { 42 int sn = mo[i]; 43 if(dep[sn] == dep[x] + 1 && cst[i]) { 44 int dis = dfs(sn,min(lim,cst[i])); 45 if(dis) { 46 cst[i] -= dis; 47 cst[i^1] += dis; 48 ret += dis,lim -= dis; 49 if(!lim) break; 50 } 51 } 52 } 53 return ret; 54 } 55 56 queue <int> q; 57 inline bool bfs() { 58 while(!q.empty()) q.pop(); 59 ms(dep,0); 60 dep[s] = 1; 61 q.push(s); 62 while(!q.empty()) { 63 int x = q.front(); 64 q.pop(); 65 for(int i = head[x]; i != -1; i = nxt[i]) { 66 if(cst[i] && !dep[mo[i]]) { 67 dep[mo[i]] = dep[x] + 1; 68 q.push(mo[i]); 69 } 70 } 71 } 72 return dep[t]; 73 } 74 75 inline void init() { 76 n = read(); 77 m = read(); 78 s = read(); 79 t = read(); 80 ms(head,-1); 81 ms(nxt,-1); 82 rep(i,1,m) { 83 int x = read(); 84 int y = read(); 85 int w = read(); 86 add(x,y,w),add(y,x,0); 87 } 88 } 89 90 int main() { 91 init(); 92 while(bfs()) { 93 rep(i,1,n) cur[i] = head[i]; 94 ans += dfs(s,inf); 95 } 96 printf("%d\n",ans); 97 return 0; 98 }
> 别忘了 总有人在等着你

浙公网安备 33010602011771号