题目:https://www.luogu.com.cn/problem/P3381
AC代码:
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef long long ll;
const int N = 10010,M = 500050;
const ll inf = ll(1e18);
struct edge{
int next,to;
ll w,c;
}edges[M];
int head[N],cur[N],vis[N],inq[N];
int cnt = 1;
ll dist[N];
int n,m,s,t;
void add(int u,int v,ll w,ll c){
edges[++cnt].next = head[u];
edges[cnt].to = v;
edges[cnt].w = w;
edges[cnt].c = c;
head[u] = cnt;
}
bool SPFA(){
fill(dist,dist+(n+1),inf);
dist[s] = 0;
queue<int> q;
q.push(s);
while(!q.empty()){
int u = q.front();
q.pop();
inq[u] = 0;
for(int i = head[u]; i;i = edges[i].next){
int to = edges[i].to;
ll w = edges[i].w;
if(w > 0 && dist[to] > dist[u] + edges[i].c){
dist[to] = dist[u] + edges[i].c;
if(!inq[to]){
inq[to] = 1;
q.push(to);
}
}
}
}
return dist[t] != inf;
}
ll dfs(int p = s, ll flow = inf){
if(p == t) return flow;
ll rmn = flow;
vis[p] = 1;
for(int& i = cur[p]; i && rmn; i = edges[i].next){
int to = edges[i].to;
ll w = edges[i].w;
if(w > 0 && !vis[to] && dist[to] == dist[p] + edges[i].c){
ll f = dfs(to,min(rmn,w));
rmn -= f;
edges[i].w -= f;
edges[i^1].w += f;
}
}
vis[p] = 0;
return flow - rmn;
}
pair<ll, ll> dinic(){
pair<ll,ll> ans(0,0);
while(SPFA()){
memcpy(cur,head,sizeof(head));//弧优化
ll flow = dfs();
ans.first += flow;
ans.second += dist[t] * flow;
}
return ans;
}
int main(){
ios_base::sync_with_stdio(false);
cin >> n >> m >> s >> t;
int u,v;
ll w,c;
for(int i = 1;i<=m;i++){
cin >> u >> v >> w >> c;
add(u,v,w,c);
add(v,u,0,-c);
}
pair<ll,ll> ans = dinic();
cout << ans.first << " " << ans.second << endl;
return 0;
}