name
stringlengths
2
88
description
stringlengths
31
8.62k
public_tests
dict
private_tests
dict
solution_type
stringclasses
2 values
programming_language
stringclasses
5 values
solution
stringlengths
1
983k
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#define _USE_MATH_DEFINES #include <iostream> #include <fstream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <string> #include <vector> #include <utility> #include <complex> #include <set> #include <map> #include <queue> #include <stack> #include <deque> #include <tuple> #include <bitset> #include <algorithm> #include <random> using namespace std; typedef long double ld; typedef long long ll; typedef vector<int> vint; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<double, double> pdd; typedef complex<ld> compd; #define rep(i,n) for(int i=0;i<n;i++) #define srep(i,a,n) for(int i=a;i<n;i++) #define REP(i,n) for(int i=0;i<=n;i++) #define SREP(i,a,n) for(int i=a;i<=n;i++) #define rrep(i,n) for(int i=n-1;i>=0;i--) #define RREP(i,n) for(int i=n;i>=0;i--) #define all(a) (a).begin(),(a).end() #define mp(a,b) make_pair(a,b) #define mt make_tuple #define pb push_back #define fst first #define scn second #define bicnt(x) __buildin__popcount(x) #define gcd(a,b) __gcd__(a,b) #define debug(x) cout<<"debug: "<<x<<endl #define DEBUG 0 const ll inf = (ll)1e9; const ll mod = 1e9 + 7; const ld eps = 1e-9; const int dx[] = { 0,1,0,-1 }; const int dy[] = { 1,0,-1,0 }; struct edge { int to, cap, cost, rev; edge(int to_, int cap_, int cost_, int rev_) { to = to_; cap = cap_; cost = cost_; rev = rev_; } }; int n; vector<edge> e[1010]; int h[1010]; int dist[1010]; int prevv[1010], preve[1010]; void add_edge(int s, int t, int cap, int cost) { e[s].push_back(edge(t, cap, cost, e[t].size())); e[t].push_back(edge(s, 0, -cost, e[s].size() - 1)); } int min_cost_flow(int s, int t, int f) { int ret = 0; REP(i, n) h[i] = 0; while (f > 0) { priority_queue<pii> pq; pq.push(mp(0, -s)); REP(i, n) dist[i] = inf; dist[s] = 0; while (!pq.empty()) { auto it = pq.top(); pq.pop(); int v = -it.second, cost = -it.first; if (dist[v] < cost) continue; rep(i, e[v].size()) { edge* to = &e[v][i]; if (to->cap > 0 && dist[to->to] > dist[v] + to->cost + h[v] - h[to->to]) { dist[to->to] = dist[v] + to->cost + h[v] - h[to->to]; prevv[to->to] = v; preve[to->to] = i; pq.push(mp(-dist[to->to], -to->to)); } } } if (dist[t] == inf) return -1; rep(i, n) h[i] += dist[i]; int d = f; for (int i = t; i != s; i = prevv[i]) { d = min(d, e[prevv[i]][preve[i]].cap); } f -= d; ret += d*h[t]; for (int i = t; i != s; i = prevv[i]) { edge* to = &e[prevv[i]][preve[i]]; to->cap -= d; e[i][to->rev].cap += d; } } return ret; } int main() { int e, f; cin >> n >> e >> f; rep(i, e) { int s, t, c, d; cin >> s >> t >> c >> d; add_edge(s, t, c, d); } cout << min_cost_flow(0, n - 1, f) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <cstdio> #include <algorithm> #include <vector> #include <queue> using namespace std; using Weight=long long; static const Weight INF=1LL<<57; template <class T> using gp_queue=priority_queue<T, deque<T>, less<T>>; struct Arc { // accessible to the reverse edge size_t src, dst; Weight capacity, cost, flow; size_t rev; Arc() {} Arc(size_t src, size_t dst, Weight capacity, Weight cost=0): src(src), dst(dst), capacity(capacity), cost(cost), flow(0), rev(-1) {} Weight residue() const { return capacity - flow; } }; bool operator<(const Arc &e, const Arc &f) { if (e.cost != f.cost) { return e.cost > f.cost; } else if (e.capacity != f.capacity) { return e.capacity > f.capacity; } else { return e.src!=f.src? e.src<f.src : e.dst<f.dst; } } using Arcs=vector<Arc>; using Node=vector<Arc>; using FlowNetwork=vector<Node>; void connect(FlowNetwork &g, size_t s, size_t d, Weight c=1, Weight k=0) { g[s].push_back(Arc(s, d, c, k)); g[d].push_back(Arc(d, s, 0, -k)); g[s].back().rev = g[d].size()-1; g[d].back().rev = g[s].size()-1; } void join(FlowNetwork &g, size_t s, size_t d, Weight c=1, Weight k=0) { g[s].push_back(Arc(s, d, c, k)); g[d].push_back(Arc(d, s, c, k)); g[s].back().rev = g[d].size()-1; g[d].back().rev = g[s].size()-1; } pair<Weight, Weight> mincost_flow( FlowNetwork &g, size_t s, size_t t, Weight F=INF ) { size_t V=g.size(); vector<Arc *> prev(V, NULL); pair<Weight, Weight> total; // <cost, flow> while (F > total.second) { vector<Weight> d(V, INF); d[s]=0; for (size_t i=0; i<V; ++i) { for (size_t v=0; v<V; ++v) { if (d[v] == INF) continue; for (Arc &e: g[v]) { if (e.capacity <= 0) continue; if (d[e.dst] > d[e.src] + e.cost) { d[e.dst] = d[e.src] + e.cost; prev[e.dst] = &e; } } } } if (d[t] == INF) { total.first = -1; return total; } Weight f=F-total.second; for (Arc *e=prev[t]; e!=NULL; e=prev[e->src]) f = min(f, e->capacity); total.second += f; total.first += f * d[t]; for (Arc *e=prev[t]; e!=NULL; e=prev[e->src]) { e->capacity -= f; g[e->dst][e->rev].capacity += f; } } return total; } int main() { size_t V, E; Weight F; scanf("%zu %zu %lld", &V, &E, &F); FlowNetwork g(V); for (size_t i=0; i<E; ++i) { size_t u, v; Weight c, d; scanf("%zu %zu %lld %lld", &u, &v, &c, &d); connect(g, u, v, c, d); } printf("%lld\n", mincost_flow(g, 0, V-1, F).first); return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> P; constexpr int IINF = INT_MAX; struct edge{ int to, cap, cost, rev; }; int V, E, F; vector<vector<edge> > G; vector<int> h, dist, prevv, preve; void add_edge(int from, int to, int cap, int cost){ G[from].push_back((edge){to, cap, cost, int(G[to].size())}); G[to].push_back((edge){from, 0, -cost, int(G[from].size())-1}); } // 最小費用流 int min_cost_flow(int s, int t, int f){ h.resize(G.size()); dist.resize(G.size()); prevv.resize(G.size()); preve.resize(G.size()); int res = 0; fill(h.begin(), h.end(), 0); while(f > 0){ priority_queue<P, vector<P>, greater<P> > que; fill(dist.begin(), dist.end(), IINF); dist[s] = 0; que.push({0,s}); while(!que.empty()){ P p = que.top(); que.pop(); int v = p.second; if(dist[v] < p.first) continue; for(int i=0;i<int(G[v].size());i++){ auto &e = G[v][i]; if(e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]){ dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push({dist[e.to], e.to}); } } } if(dist[t] == IINF){ return -1; } for(int v=0; v<G.size(); v++) h[v] += dist[v]; int d = f; for(int v=t; v!=s; v=prevv[v]){ d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d*h[t]; for(int v=t; v!=s; v=prevv[v]){ auto &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main() { cin >> V >> E >> F; G.resize(V); for(int i=0;i<E;i++){ int u, v, c, d; cin >> u >> v >> c >> d; add_edge(u, v, c, d); } cout << min_cost_flow(0, V-1, F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.PriorityQueue; import java.util.TreeMap; public class Main { static ContestScanner in;static Writer out;public static void main(String[] args) {try{in=new ContestScanner();out=new Writer();Main solve=new Main();solve.solve(); in.close();out.flush();out.close();}catch(IOException e){e.printStackTrace();}} static void dump(int[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();} static void dump(int[]a,int n){for(int i=0;i<a.length;i++)out.printf("%"+n+"d ",a[i]);out.println();} static void dump(long[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();} static void dump(char[]a){for(int i=0;i<a.length;i++)out.print(a[i]);out.println();} static long pow(long a,int n){long r=1;while(n>0){if((n&1)==1)r*=a;a*=a;n>>=1;}return r;} static String itob(int a,int l){return String.format("%"+l+"s",Integer.toBinaryString(a)).replace(' ','0');} static void sort(int[]a){m_sort(a,0,a.length,new int[a.length]);} static void sort(int[]a,int l){m_sort(a,0,l,new int[l]);} static void sort(int[]a,int l,int[]buf){m_sort(a,0,l,buf);} static void sort(int[]a,int s,int l,int[]buf){m_sort(a,s,l,buf);} static void m_sort(int[]a,int s,int sz,int[]b) {if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;} m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz; while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];} while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i]; } /* qsort(3.5s)<<msort(9.5s)<<<shuffle+qsort(17s)<Arrays.sort(Integer)(20s) */ static void sort(long[]a){m_sort(a,0,a.length,new long[a.length]);} static void sort(long[]a,int l){m_sort(a,0,l,new long[l]);} static void sort(long[]a,int l,long[]buf){m_sort(a,0,l,buf);} static void sort(long[]a,int s,int l,long[]buf){m_sort(a,s,l,buf);} static void m_sort(long[]a,int s,int sz,long[]b) {if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;} m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz; while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];} while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];} static void swap(long[] a,int i,int j){final long t=a[i];a[i]=a[j];a[j]=t;} static void swap(int[] a,int i,int j){final int t=a[i];a[i]=a[j];a[j]=t;} static int binarySearchSmallerMax(int[]a,int v)// get maximum index which a[idx]<=v {int l=-1,r=a.length-1,s=0;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;} static int binarySearchSmallerMax(int[]a,int v,int l,int r) {int s=-1;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;} @SuppressWarnings("unchecked") static List<Integer>[]createGraph(int n) {List<Integer>[]g=new List[n];for(int i=0;i<n;i++)g[i]=new ArrayList<>();return g;} void solve() throws NumberFormatException, IOException{ final int n = in.nextInt(); final int m = in.nextInt(); int f = in.nextInt(); MinCostFlow mf = new MinCostFlow(n, f); for(int i=0; i<m; i++){ int from = in.nextInt(); int to = in.nextInt(); int cap = in.nextInt(); int cost = in.nextInt(); mf.edge(from, to, cap, cost); } int res = mf.flow(0, n-1); if(mf.f>0) res = -1; System.out.println(res); } } class MinCostFlow{ final int n; int f; List<Edge>[] node; @SuppressWarnings("unchecked") public MinCostFlow(int n, int f) { this.n = n; this.f = f; node = new List[n]; for(int i=0; i<n; i++) node[i] = new ArrayList<>(); } void edge(int from, int to, int cap, int cost){ Edge e = new Edge(to, cap, cost); Edge r = new Edge(from, 0, -cost); e.rev = r; r.rev = e; node[from].add(e); node[to].add(r); } int flow(int s, int t){ int[] h = new int[n]; int[] dist = new int[n]; int[] preV = new int[n]; int[] preE = new int[n]; final int inf = Integer.MAX_VALUE; PriorityQueue<Pos> qu = new PriorityQueue<>(); int res = 0; while(f>0){ Arrays.fill(dist, inf); dist[s] = 0; qu.clear(); qu.add(new Pos(s, 0)); while(!qu.isEmpty()){ Pos p = qu.poll(); if(dist[p.v]<p.d) continue; final int sz = node[p.v].size(); for(int i=0; i<sz; i++){ Edge e = node[p.v].get(i); final int nd = e.cost+p.d + h[p.v]-h[e.to]; if(e.cap>0 && nd < dist[e.to]){ preV[e.to] = p.v; preE[e.to] = i; dist[e.to] = nd; qu.add(new Pos(e.to, nd)); } } } if(dist[t]==inf) break; for(int i=0; i<n; i++) h[i] += dist[i]; int minf = f; for(int i=t; i!=s; i=preV[i]){ minf = Math.min(minf, node[preV[i]].get(preE[i]).cap); } f -= minf; res += minf*h[t]; for(int i=t; i!=s; i=preV[i]){ node[preV[i]].get(preE[i]).cap -= minf; node[preV[i]].get(preE[i]).rev.cap += minf; } } return res; } } class Pos implements Comparable<Pos>{ int v, d; public Pos(int v, int d) { this.v = v; this.d = d; } @Override public int compareTo(Pos o) { return d-o.d; } } class Edge{ int to, cap, cost; Edge rev; Edge(int t, int c, int co){ to = t; cap = c; cost = co; } void rev(Edge r){ rev = r; } } @SuppressWarnings("serial") class MultiSet<T> extends HashMap<T, Integer>{ @Override public Integer get(Object key){return containsKey(key)?super.get(key):0;} public void add(T key,int v){put(key,get(key)+v);} public void add(T key){put(key,get(key)+1);} public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);} public MultiSet<T> merge(MultiSet<T> set) {MultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;} for(Entry<T,Integer>e:s.entrySet())l.add(e.getKey(),e.getValue());return l;} } @SuppressWarnings("serial") class OrderedMultiSet<T> extends TreeMap<T, Integer>{ @Override public Integer get(Object key){return containsKey(key)?super.get(key):0;} public void add(T key,int v){put(key,get(key)+v);} public void add(T key){put(key,get(key)+1);} public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);} public OrderedMultiSet<T> merge(OrderedMultiSet<T> set) {OrderedMultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;} while(!s.isEmpty()){l.add(s.firstEntry().getKey(),s.pollFirstEntry().getValue());}return l;} } class Pair implements Comparable<Pair>{ int a,b;final int hash;Pair(int a,int b){this.a=a;this.b=b;hash=(a<<16|a>>16)^b;} public boolean equals(Object obj){Pair o=(Pair)(obj);return a==o.a&&b==o.b;} public int hashCode(){return hash;} public int compareTo(Pair o){if(a!=o.a)return a<o.a?-1:1;else if(b!=o.b)return b<o.b?-1:1;return 0;} } class Timer{ long time;public void set(){time=System.currentTimeMillis();} public long stop(){return time=System.currentTimeMillis()-time;} public void print(){System.out.println("Time: "+(System.currentTimeMillis()-time)+"ms");} @Override public String toString(){return"Time: "+time+"ms";} } class Writer extends PrintWriter{ public Writer(String filename)throws IOException {super(new BufferedWriter(new FileWriter(filename)));} public Writer()throws IOException{super(System.out);} } class ContestScanner implements Closeable{ private BufferedReader in;private int c=-2; public ContestScanner()throws IOException {in=new BufferedReader(new InputStreamReader(System.in));} public ContestScanner(String filename)throws IOException {in=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));} public String nextToken()throws IOException { StringBuilder sb=new StringBuilder(); while((c=in.read())!=-1&&Character.isWhitespace(c)); while(c!=-1&&!Character.isWhitespace(c)){sb.append((char)c);c=in.read();} return sb.toString(); } public String readLine()throws IOException{ StringBuilder sb=new StringBuilder();if(c==-2)c=in.read(); while(c!=-1&&c!='\n'&&c!='\r'){sb.append((char)c);c=in.read();} return sb.toString(); } public long nextLong()throws IOException,NumberFormatException {return Long.parseLong(nextToken());} public int nextInt()throws NumberFormatException,IOException {return(int)nextLong();} public double nextDouble()throws NumberFormatException,IOException {return Double.parseDouble(nextToken());} public void close() throws IOException {in.close();} }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
java
import java.awt.geom.Point2D; import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { Scanner sc = new Scanner(System.in); public static void main(String[] args){ new Main(); } public Main(){ // new A().doIt(); new GRL_6().doIt(); } class GRL_6{ void doIt(){ int n = sc.nextInt(); int e = sc.nextInt(); int max = sc.nextInt(); MCF m = new MCF(n); for(int i = 0;i < e;i++){ int from = sc.nextInt(); int to = sc.nextInt(); int cap = sc.nextInt(); int cost = sc.nextInt(); m.addEdge(from, to, cap, cost); } System.out.println(m.minCostFlow(0, n-1, max)); } class MCF{ int INF=1<<24; ArrayList<ArrayList<Edge>> G; class Edge { int to, cap, cost; int rev; public Edge(int to, int cap, int cost, int rev) { this.to = to;this.cap = cap;this.cost = cost; this.rev = rev; } } MCF(int v){ G= new ArrayList<ArrayList<Edge>>(); for(int i=0;i<v;i++){ G.add(new ArrayList<Edge>()); } } private void addEdge(int from, int to, int cap, int cost){ G.get(from).add(new Edge(to, cap, cost, G.get(to).size())); G.get(to).add(new Edge(from, 0, -cost, G.get(from).size() - 1)); } private int minCostFlow(int s, int t, int f) { int V = G.size(); int [] dist = new int[V], prevv = new int[V], preve = new int[V]; int res=0; while(f > 0){ Arrays.fill(dist, INF); dist[s] = 0; boolean update = true; while(update) { update = false; for(int v = 0; v < V; v++){ if(dist[v] == INF) continue; for(int i = 0 ; i < G.get(v).size(); i++){ Edge e = G.get(v).get(i); if(e.cap > 0 && dist[e.to]> dist[v] + e.cost ){ dist[e.to] = dist[v] + e.cost; prevv[e.to] = v; preve[e.to] = i; update = true; } } } } if(dist[t] == INF) return -1; int d= f; for(int v=t;v!= s; v = prevv[v]){ d= Math.min(d, G.get(prevv[v]).get(preve[v]).cap); } f -= d; res += d * dist[t]; for(int v = t; v!= s; v = prevv[v]){ Edge e =G.get(prevv[v]).get(preve[v]); e.cap -= d; G.get(v).get(e.rev).cap += d; } } return res; } } } class A{ BigInteger sum[] = new BigInteger[501]; BigInteger bit[] = new BigInteger[501]; void doIt(){ sum[1] = new BigInteger("1"); bit[1] = new BigInteger("1"); for(int i = 2;i < 501;i++){ bit[i] = bit[i-1].multiply(new BigInteger("2")); sum[i] = sum[i-1].add(bit[i]); } while(true){ String str = sc.next(); if(str.equals("0"))break; BigInteger num = new BigInteger(str); int length = num.toString(2).length() + 1; ArrayList<Par> array = new ArrayList<Par>(); array.add(new Par(bit[length],1,length-1)); System.out.println(bit[length - 1]+" "+sum[length - 1]); System.out.println(array.get(0).num+" "+array.get(0).cnt+" "+array.get(0).length); } } class Par{ BigInteger num; int cnt,length; public Par(BigInteger num,int cnt,int length){ this.num = num; this.cnt = cnt; this.length = length; } } } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Vector; public class Main { static final int INF = 10000000; /** * @param args * @throws IOException */ @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] tmpArray = br.readLine().split(" "); int v = Integer.parseInt(tmpArray[0]); int e = Integer.parseInt(tmpArray[1]); int f = Integer.parseInt(tmpArray[2]); V = v; G = new Vector[V]; for(int i = 0; i < G.length; i++){ G[i] = new Vector<Edge>(); } dist = new int[V]; prevv = new int[V]; preve = new int[V]; h = new int[V]; for(int i = 0; i < e; i++){ tmpArray = br.readLine().split(" "); int from = Integer.parseInt(tmpArray[0]); int to = Integer.parseInt(tmpArray[1]); int c = Integer.parseInt(tmpArray[2]); int d = Integer.parseInt(tmpArray[3]); addEdge(from, to, c, d); } int result = minCostFlow(0, V - 1, f); System.out.println(result); } static int V; static Vector<Edge> G[]; static int dist[]; static int prevv[]; static int preve[]; static int h[]; static void addEdge(int from, int to, int cap, int cost){ G[from].add(new Edge(to, cap, cost, G[to].size())); G[to].add(new Edge(from, 0, -cost, G[from].size() - 1)); } static int minCostFlow(int s, int t, int f){ int res = 0; Arrays.fill(h, 0); while(f > 0){ //dijkstra PriorityQueue<Dist> que = new PriorityQueue<Dist>(); Arrays.fill(dist, INF); dist[s] = 0; que.add(new Dist(0, s)); while(!que.isEmpty()){ Dist p = que.remove(); int v = p.v; if(dist[v] < p.dist){ continue; } for(int i = 0; i < G[v].size() ;i++){ Edge e = G[v].get(i); if(e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]){ dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.add(new Dist(dist[e.to], e.to)); } } } if(dist[t] == INF){ return -1; } for(int v=0; v < V; v++){ h[v] += dist[v]; } //s-t間経路に沿って目一杯流す int d = f; for(int v = t; v != s; v = prevv[v]){ d = Math.min(d, G[prevv[v]].get(preve[v]).cap); } f -= d; res += d * h[t]; for(int v = t; v != s; v = prevv[v]){ Edge e = G[prevv[v]].get(preve[v]); e.cap -= d; G[v].get(e.rev).cap += d; } } return res; } } class Edge { int to, cap, cost, rev; Edge(int to, int cap, int cost, int rev){ this.to = to; this.cap = cap; this.cost = cost; this.rev = rev; } } class Dist implements Comparable<Dist>{ int dist; int v; Dist(int dist, int v){ this.dist = dist; this.v = v; } //近い順に並べる @Override public int compareTo(Dist d) { return this.dist - d.dist; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <bits/stdc++.h> #define pb push_back using namespace std; const int INF=0x3f3f3f3f; const int maxn=105; struct Edge { int from,to,cap,flow,cost; Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w) {} }; int n,m,tf; vector<Edge>edges; vector<int>G[maxn]; bool inq[maxn]; int d[maxn]; int a[maxn]; int p[maxn]; inline void addedge (int u,int v,int c,int w) { edges.pb(Edge(u,v,c,0,w)); edges.pb(Edge(v,u,0,0,-w)); int id=edges.size()-2; G[u].pb(id); G[v].pb(id+1); } inline bool spfa (int s,int t,int& flow,int& cost) { for (int i=0;i<n;i++) d[i]=INF; d[s]=0; inq[s]=1; a[s]=max(0,tf-flow); queue<int>q; q.push(s); while (q.size()) { int u=q.front(); q.pop(); inq[u]=0; for (int id:G[u]) { Edge& e=edges[id]; if (e.cap>e.flow && d[e.to]>d[u]+e.cost) { d[e.to]=d[u]+e.cost; p[e.to]=id; a[e.to]=min(a[u],e.cap-e.flow); if (!inq[e.to]) {inq[e.to]=1;q.push(e.to);} } } } if (d[t]==INF) return 0; flow+=a[t]; cost+=d[t]*a[t]; // cout<<flow<<' '<<cost<<'\n'; for (int u=t;u!=s;u=edges[p[u]].from) { edges[p[u]].flow+=a[t]; edges[p[u]^1].flow-=a[t]; } return 1; } inline int mcmf (int s,int t) { int flow=0 , cost=0; while (spfa(s,t,flow,cost) && flow<tf); if (flow<tf) return -1; else return cost; } int main() { cin>>n>>m>>tf; for (int i=0;i<m;i++) { int u,v,c,w; cin>>u>>v>>c>>w; addedge(u,v,c,w); } cout<<mcmf(0,n-1)<<'\n'; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <bits/stdc++.h> using namespace std; struct PrimalDual{ const int INF = 1<<28; typedef pair<int,int> P; struct edge{ int to,cap,cost,rev; edge(){} edge(int to,int cap,int cost,int rev):to(to),cap(cap),cost(cost),rev(rev){} }; int n; vector<vector<edge> > G; vector<int> h,dist,prevv,preve; PrimalDual(){} PrimalDual(int sz):n(sz),G(sz),h(sz),dist(sz),prevv(sz),preve(sz){} void add_edge(int from,int to,int cap,int cost){ G[from].push_back(edge(to,cap,cost,G[to].size())); G[to].push_back(edge(from,0,-cost,G[from].size()-1)); } int flow(int s,int t,int f){ int res=0; fill(h.begin(),h.end(),0); while(f>0){ priority_queue<P,vector<P>,greater<P> > que; fill(dist.begin(),dist.end(),INF); dist[s]=0; que.push(P(0,s)); while(!que.empty()){ P p=que.top();que.pop(); int v=p.second; if(dist[v]<p.first) continue; for(int i=0;i<(int)G[v].size();i++){ edge &e=G[v][i]; if(e.cap>0&&dist[e.to]>dist[v]+e.cost+h[v]-h[e.to]){ dist[e.to]=dist[v]+e.cost+h[v]-h[e.to]; prevv[e.to]=v; preve[e.to]=i; que.push(P(dist[e.to],e.to)); } } } if(dist[t]==INF) return -1; for(int v=0;v<n;v++) h[v]+=dist[v]; int d=f; for(int v=t;v!=s;v=prevv[v]){ d=min(d,G[prevv[v]][preve[v]].cap); } f-=d; res+=d*h[t]; for(int v=t;v!=s;v=prevv[v]){ edge &e=G[prevv[v]][preve[v]]; e.cap-=d; G[v][e.rev].cap+=d; } } return res; } }; int main(){ int v,e,f; cin>>v>>e>>f; PrimalDual pd(v); for(int i=0;i<e;i++){ int u,v,c,d; cin>>u>>v>>c>>d; pd.add_edge(u,v,c,d); } cout<<pd.flow(0,v-1,f)<<endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include<iostream> using namespace std; //Minimum Cost Flow O(FE log V) #include<algorithm> #include<utility> #include<vector> #include<queue> #include<limits> template<typename T> struct MCF{ vector<vector<pair<pair<int,int>,pair<int,T> > > >G; vector<T>h,d; vector<int>pv,pe; MCF(int n_=0):G(n_),h(n_,0),d(n_),pv(n_),pe(n_){} void add_edge(int from,int to,int cap,T cost) { G[from].push_back(make_pair( make_pair(to,G[to].size()),make_pair(cap,cost) )); G[to].push_back(make_pair( make_pair(from,G[from].size()-1),make_pair(0,-cost) )); } T min_cost_flow(int s,int t,int f)//ans or -1 { T ret=0; while(f>0) { priority_queue<pair<T,int>,vector<pair<T,int> >,greater<pair<T,int> > >P; fill(d.begin(),d.end(),numeric_limits<T>::max()); d[s]=0; P.push(make_pair(0,s)); while(!P.empty()) { pair<T,int>p=P.top();P.pop(); if(d[p.second]<p.first)continue; for(int i=0;i<G[p.second].size();i++) { pair<pair<int,int>,pair<int,T> >&e=G[p.second][i]; if(e.second.first>0&& d[e.first.first]>d[p.second]+e.second.second+h[p.second]-h[e.first.first]) { d[e.first.first]=d[p.second]+e.second.second+h[p.second]-h[e.first.first]; pv[e.first.first]=p.second; pe[e.first.first]=i; P.push(make_pair(d[e.first.first],e.first.first)); } } } if(d[t]==numeric_limits<T>::max())return -1; for(int u=0;u<G.size();u++)h[u]+=d[u]; int d=f; for(int u=t;u!=s;u=pv[u])d=min(d,G[pv[u]][pe[u]].second.first); f-=d; ret+=d*h[t]; for(int u=t;u!=s;u=pv[u]) { G[pv[u]][pe[u]].second.first-=d; G[u][G[pv[u]][pe[u]].first.second].second.first+=d; } } return ret; } }; int main() { int N,E,F; cin>>N>>E>>F; MCF<int>mf(N); for(int i=0;i<E;i++) { int u,v,c,d;cin>>u>>v>>c>>d; mf.add_edge(u,v,c,d); } cout<<mf.min_cost_flow(0,N-1,F)<<endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <bits/stdc++.h> using namespace std; #define int long long //O(F*V^2) class MinimumCostFlow { private: struct edge { int to, cap, cost, rev; }; const int INF = 1e18; int V; vector<vector<edge>> G; vector<int> h, dist; vector<int> prevv, preve; void add_edge(int from, int to, int cap, int cost) { G[from].push_back({to, cap, cost, (int)G[to].size()}); G[to].push_back({from, 0LL, -cost, (int)G[from].size() - 1LL}); } int min_cost_flow(int s, int t, int f) { int res = 0; fill(h.begin(), h.end(), 0LL); while (f > 0) { using P = pair<int, int>; priority_queue<P, vector<P>, greater<P>> que; fill(dist.begin(), dist.end(), INF); dist[s] = 0; que.push(P(0, s)); while (!que.empty()) { P p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(P{dist[e.to], e.to}); } } } if (dist[t] == INF) { return -1; } for (int v = 0; v < V; v++) { h[v] += dist[v]; } int d = f; for (int v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } public: MinimumCostFlow(int N) : V(N), G(N, vector<edge>()), h(N), dist(N), prevv(N), preve(N) {} void addEdge(int from, int to, int cap, int cost) { return add_edge(from, to, cap, cost); } int minCostFlow(int s, int t, int f) { return min_cost_flow(s, t, f); } }; signed main() { int V, E, F; cin >> V >> E >> F; MinimumCostFlow mcf(V); for (int i = 0; i < E; i++) { int u, v, c, d; cin >> u >> v >> c >> d; mcf.addEdge(u, v, c, d); } cout << mcf.minCostFlow(0, V - 1, F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i,n) REP(i,0,n) #define REP(i,s,e) for(int i=(s); i<(int)(e); i++) #define repr(i, n) REPR(i, n, 0) #define REPR(i, s, e) for(int i=(int)(s-1); i>=(int)(e); i--) #define pb push_back #define all(r) r.begin(),r.end() #define rall(r) r.rbegin(),r.rend() #define fi first #define se second typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int INF = 1e9; const ll MOD = 1e9 + 7; double EPS = 1e-8; // ????°??????¨??? O(F |E| |V|) struct MinCostFlow { typedef pair<int, int> P; // first -> minDist, second -> v struct Edge { int to, cap, cost, rev; }; const int V; vector<vector<Edge>> G; vector<int> dist, prevv, preve; MinCostFlow(int v) : V(v), G(v), dist(v), prevv(v), preve(v){} void add_edge(int from, int to, int cap, int cost) { G[from].push_back({to, cap, cost, (int)G[to].size()}); G[to].push_back({from, 0, -cost, (int)G[from].size()-1}); } // minCostFlow s -> t // noexist flow return -1 int min_cost_flow(int s, int t, int f) { int res = 0; while(f > 0) { for(int i = 0; i < V; ++i) dist[i] = INF; dist[s] = 0; bool update = true; while(update) { update = false; for(int v = 0; v < V; ++v) { if(dist[v] == INF) continue; for(int i = 0; i < G[v].size(); ++i) { Edge& e = G[v][i]; if(e.cap > 0 && dist[e.to] > dist[v] + e.cost) { dist[e.to] = dist[v] + e.cost; prevv[e.to] = v; preve[e.to] = i; update = true; } } } } if(dist[t] == INF) return -1; int d = f; for(int v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * dist[t]; for(int v = t; v != s; v = prevv[v]) { Edge& e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } }; int main(){ int V, E, F; cin >> V >> E >> F; MinCostFlow f(V); rep(i, E) { int a, b, c, d; cin >> a >> b >> c >> d; f.add_edge(a, b, c, d); } cout << f.min_cost_flow(0, V-1, F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B&lang=jp #include <iostream> #include <map> #include <queue> #include <vector> #include <algorithm> using namespace std; typedef pair<int, int>P; class MCF{ public: class edge{ public: int to, cap, cost, rev; edge(){}; edge(int _to, int _cap, int _cost, int _rev){ to = _to; cap = _cap; cost = _cost; rev = _rev; } }; vector<vector<edge> >G; vector<int>h; vector<int>dist; vector<int>prevv; vector<int>preve; MCF(int n){ G.resize(n); preve.resize(n, 0); prevv.resize(n, 0); } void addEdge(int from, int to, int cap, int cost){ G[from].push_back(edge(to, cap, cost, G[to].size())); G[to].push_back(edge(from, 0, -cost, G[from].size() - 1)); } int flow(int s, int t, int f){ int res = 0; h.clear(); h.resize(G.size(), 0); while (f > 0){ priority_queue<P, vector<P>, greater<P> >que; dist.clear(); dist.resize(G.size(), 1145141919); dist[s] = 0; que.push(P(0, s)); while (!que.empty()){ P p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first)continue; for (int i = 0; i < G[v].size(); i++){ edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]){ dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(P(dist[e.to], e.to)); } } } if (dist[t] == 1145141919){ return -1; } for (int v = 0; v < G.size(); v++)h[v] += dist[v]; int d = f; for (int v = t; v != s; v = prevv[v]){ d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d*h[t]; for (int v = t; v != s; v = prevv[v]){ edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } }; int main(){ int V, E, F; cin >> V >> E >> F; MCF mcf(V); for (int i = 0; i < E; i++){ int from, to, cap, cost; cin >> from >> to >> cap >> cost; mcf.addEdge(from, to, cap, cost); } cout << mcf.flow(0, V - 1, F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
python3
from heapq import heappush, heappop import collections class MinCostFlowDijkstra: def __init__(self, N): self.N = N self.edges = collections.defaultdict(list) def add(self, fro, to, cap, cost, directed=True): # edge[fro]: to, cap, cost, rev(逆辺) if directed: self.edges[fro].append([to, cap, cost, len(self.edges[to])]) self.edges[to].append([fro, 0, -cost, len(self.edges[fro]) - 1]) else: # TODO: must be Verified self.edges[fro].append([to, cap, cost, len(self.edges[to])]) self.edges[to].append([fro, 0, -cost, len(self.edges[fro]) - 1]) self.edges[to].append([fro, cap, cost, len(self.edges[fro])]) self.edges[fro].append([to, 0, -cost, len(self.edges[to]) - 1]) def minCostFlow(self, start, goal, flow): res = 0 potential = collections.defaultdict(int) prevVertex = collections.defaultdict(int) prevEdge = collections.defaultdict(int) while flow > 0: dist = collections.defaultdict(lambda: float('inf')) dist[start] = 0 que = [] heappush(que, (0, start)) while que: k, v = heappop(que) if dist[v] < k: continue for i, (to, cap, cost, _) in enumerate(self.edges[v]): if cap > 0 and dist[to] > dist[v] + cost + potential[v] - potential[to]: dist[to] = dist[v] + cost + potential[v] - potential[to] prevVertex[to] = v prevEdge[to] = i heappush(que, (dist[to], to)) if dist[goal] == float('inf'): return -1 for i in range(self.N): potential[i] += dist[i] d = flow v = goal while v != start: d = min(d, self.edges[prevVertex[v]][prevEdge[v]][1]) v = prevVertex[v] flow -= d res += d * potential[goal] v = goal while v != start: e = self.edges[prevVertex[v]][prevEdge[v]] e[1] -= d self.edges[v][e[3]][1] += d v = prevVertex[v] #print(d, flow, prevVertex, prevEdge) return res V, E, F = map(int, input().split()) graph = MinCostFlowDijkstra(V) for _ in range(E): u, v, c, d = map(int, input().split()) graph.add(u, v, c, d) print(graph.minCostFlow(0, V-1, F))
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <bits/stdc++.h> #define _overload(_1,_2,_3,name,...) name #define _rep(i,n) _range(i,0,n) #define _range(i,a,b) for(int i=int(a);i<int(b);++i) #define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__) #define _rrep(i,n) _rrange(i,n,0) #define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i) #define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__) #define _all(arg) begin(arg),end(arg) #define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg)) #define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary) #define clr(a,b) memset((a),(b),sizeof(a)) #define bit(n) (1LL<<(n)) #define popcount(n) (__builtin_popcountll(n)) using namespace std; template<class T>bool chmax(T &a, const T &b) { return (a < b) ? (a = b, 1) : 0;} template<class T>bool chmin(T &a, const T &b) { return (b < a) ? (a = b, 1) : 0;} using ll = long long; using R = long double; const R EPS = 1e-9; // [-1000,1000]->EPS=1e-8 [-10000,10000]->EPS=1e-7 inline int sgn(const R& r) {return (r > EPS) - (r < -EPS);} inline R sq(R x) {return sqrt(max<R>(x, 0.0));} const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1}; // Problem Specific Parameter: //Appropriately Changed using W = ll; using edge = struct {int to, rev; W cap, flow, cost;}; using G = vector<vector<edge>>; //Appropriately Changed void add_edge(G &graph, int from, int to, W cap, W cost) { graph[from].push_back({to, int(graph[to].size()) , cap , 0 , cost}); graph[to].push_back({from, int(graph[from].size()) - 1, 0 , 0, -cost}); } // Description: ??°??????????????????????°??????¨??? // TimeComplexity: $ \mathcal{O}(FEV) $ // Verifyed: AOJ GRL_6_B W primal_dual(G &graph, int s, int t, int f) { const W inf = 1LL << 50; W res = 0; while (f) { int n = graph.size(), update; vector<W> dist(n, inf); vector<int> pv(n, 0), pe(n, 0); dist[s] = 0; rep(loop, n) { update = false; rep(v, n)rep(i, graph[v].size()) { edge &e = graph[v][i]; if (e.cap > e.flow and chmin(dist[e.to], dist[v] + e.cost)) { pv[e.to] = v, pe[e.to] = i; update = true; } } if (!update) break; } if (dist[t] == inf) return -1; W d = f; for (int v = t; v != s; v = pv[v]) chmin(d, graph[pv[v]][pe[v]].cap - graph[pv[v]][pe[v]].flow); f -= d, res += d * dist[t]; for (int v = t; v != s; v = pv[v]) { edge &e = graph[pv[v]][pe[v]]; e.flow += d; graph[v][e.rev].flow -= d; } } return res; } int main(void) { int v, e, f; cin >> v >> e >> f; G graph(v); rep(i, e) { int a, b, c, d; cin >> a >> b >> c >> d; add_edge(graph, a, b, c, d); } cout << primal_dual(graph, 0, v - 1, f) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include<bits/stdc++.h> #define fi first #define se second typedef long long ll; using namespace std; //BEGIN CUT HERE //Min_cost_flow class Min_cost_flow{ public: explicit Min_cost_flow(int n):vertex(static_cast<unsigned int>(n+10)){ G.resize(vertex); prev_e.resize(vertex); prev_v.resize(vertex); } void add_edge(int from,int to,ll cap,ll cost){ G[from].push_back((edge){to, cap, cost, static_cast<int>(G[to].size())}); G[to].push_back((edge){from, 0, -cost, static_cast<int>(G[from].size() - 1)}); } ll flow(int s,int t,ll f){ ll res=0; h.clear(); h.resize(vertex,0); while(f>0){ vector<ll> dist; dist.resize(vertex); dist=dijkstra(s); if(dist[t]==INF)return -1; for(int i=0;i<vertex;i++)h[i]+=dist[i]; ll d=f; for(int i=t;i!=s;i=prev_v[i]){ d=min(d,G[prev_v[i]][prev_e[i]].cap); } f-=d; res+=d*h[t]; for(int i=t;i!=s;i=prev_v[i]){ edge &e=G[prev_v[i]][prev_e[i]]; e.cap-=d; G[i][e.rev].cap+=d; } } return res; } private: struct edge{ int to; ll cap; ll cost; int rev; }; unsigned int vertex; ll INF=(ll)1e16; vector<vector<edge> > G; vector<ll> h; vector<int> prev_v,prev_e; vector<ll> dijkstra(int start){ vector<ll> dist(vertex,INF); dist[start]=0; priority_queue<pair<ll,int> > q; q.push({0,start}); while(!q.empty()){ int now=q.top().se; ll now_cost=-q.top().fi; q.pop(); if(now_cost>dist[now])continue; for(int i=0;i<(int)G[now].size();i++){ edge &e=G[now][i]; if(e.cap>0 && dist[e.to]>dist[now]+e.cost+h[now]-h[e.to]){ dist[e.to]=dist[now]+e.cost+h[now]-h[e.to]; prev_v[e.to]=now; prev_e[e.to]=i; q.push({-dist[e.to],e.to}); } } } return dist; } }; int main(){ int v,e,f;cin>>v>>e>>f; Min_cost_flow m(v); for(int i=0;i<e;i++){ int from,to,cap,cost; cin>>from>>to>>cap>>cost; m.add_edge(from,to,cap,cost); } cout<<m.flow(0,v-1,f)<<endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
python3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools import time,random sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 mod2 = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def pe(s): return print(str(s), file=sys.stderr) def JA(a, sep): return sep.join(map(str, a)) def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a) class Edge(): def __init__(self,t,f,r,ca,co): self.to = t self.fron = f self.rev = r self.cap = ca self.cost = co class MinCostFlow(): size = 0 graph = [] def __init__(self, s): self.size = s self.graph = [[] for _ in range(s)] def add_edge(self, f, t, ca, co): self.graph[f].append(Edge(t, f, len(self.graph[t]), ca, co)) self.graph[t].append(Edge(f, t, len(self.graph[f])-1, 0, -co)) def min_path(self, s, t): dist = [inf] * self.size route = [None] * self.size que = collections.deque() inq = [False] * self.size dist[s] = 0 que.append(s) inq[s] = True while que: u = que.popleft() inq[u] = False for e in self.graph[u]: if e.cap == 0: continue v = e.to if dist[v] > dist[u] + e.cost: dist[v] = dist[u] + e.cost route[v] = e if not inq[v]: que.append(v) inq[v] = True if dist[t] == inf: return inf, 0 flow = inf v = t while v != s: e = route[v] if flow > e.cap: flow = e.cap v = e.fron c = 0 v = t while v != s: e = route[v] e.cap -= flow self.graph[e.to][e.rev].cap += flow c += e.cost * flow v = e.fron return dist[t], flow def calc_min_cost_flow(self, s, t, flow): total_cost = 0 while flow > 0: c,f = self.min_path(s, t) if f == 0: return inf f = min(flow, f) total_cost += c * f flow -= f return total_cost def main(): n,m,f = LI() uvcd = [LI() for _ in range(m)] mf = MinCostFlow(n) for u,v,c,d in uvcd: mf.add_edge(u,v,c,d) r = mf.calc_min_cost_flow(0, n-1, f) if r == inf: return -1 return r # start = time.time() print(main()) # pe(time.time() - start)
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <bits/stdc++.h> static const int MAX=100; static const int INFTY=(1<<30); class edge{ public: int target, cap, cost, rev; edge(int target = 0, int cap =0, int cost = 0, int rev =0) : target(target), cap(cap), cost(cost), rev(rev) {} }; int V; std::vector<edge> G[MAX]; int h[MAX], dist[MAX], prevv[MAX], preve[MAX]; void add_edge(const int &source, const int &target, const int &cap, const int &cost) { G[source].push_back(edge(target, cap, cost, G[target].size())); G[target].push_back(edge(source, 0, -cost, G[source].size()-1)); } int min_cost_flow(int s, int t, int f) { int res = 0; std::fill(h, h+V, 0); while(f > 0) { std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int> >, std::greater<std::pair<int, int> > > pq; std::fill(dist, dist + V, INFTY); dist[s] = 0; pq.push({0, s}); while (!pq.empty()) { std::pair<int, int> p = pq.top(); pq.pop(); int current = p.second; if (dist[current] < p.first) continue; for (int i = 0; i < G[current].size(); i++) { edge &e = G[current][i]; if (e.cap > 0 && dist[e.target] > dist[current] + e.cost + h[current] - h[e.target]) { dist[e.target] = dist[current] + e.cost + h[current] - h[e.target]; prevv[e.target] = current; preve[e.target] = i; pq.push({dist[e.target], e.target}); } } } if (dist[t] == INFTY) return -1; for (int v = 0; v < V; v++) h[v] += dist[v]; int d = f; for (int v = t; v != s; v = prevv[v]) { d = std::min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * h[t]; for (int v = t; v!=s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main() { int E, f, source, target, cap, cost; std::scanf("%d %d %d", &V, &E, &f); for (int i = 0; i < E; i++) { std::scanf("%d %d %d %d", &source, &target, &cap, &cost); add_edge(source, target, cap, cost); } std::printf("%d\n", min_cost_flow(0, V-1, f)); return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <iostream> #include <fstream> #include <string> #include <vector> #include <queue> #include <stack> #include <map> #include <algorithm> #include <sstream> #include <cmath> #include <set> #include <iomanip> #include <deque> #include <stdio.h> using namespace std; #define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++) #define RREP(i,n) for(int (i)=(int)(n)-1;i>=0;i--) #define REMOVE(Itr,n) (Itr).erase(remove((Itr).begin(),(Itr).end(),n),(Itr).end()) typedef long long ll; template<class T> struct MinCostFlow { struct Edge { int to, rev; T cap, cost; Edge () {} Edge (int _to, T _cap, T _cost, int _rev) : to(_to), cap(_cap), cost(_cost), rev(_rev) {} }; const T INF = numeric_limits<T>::max() / 2; int N; vector< vector<Edge> > G; vector<T> h; vector<T> dist; vector<int> prevv, preve; MinCostFlow (int n) : N(n), G(n), h(n), dist(n), prevv(n), preve(n) {} void add_edge(int from, int to, T cap, T cost) { G[from].push_back(Edge(to,cap,cost,G[to].size())); G[to].push_back(Edge(from,0,-cost,G[from].size()-1)); } T get_min(int s, int t, T f) { T ret = 0; for (int i=0; i<N; i++) h[i] = 0; while (f > 0) { priority_queue< pair<T,int>, vector< pair<T,int> >, greater< pair<T,int> > > que; for (int i=0; i<N; i++) dist[i] = INF; dist[s] = 0; que.push(make_pair(0,s)); while (que.size() != 0) { pair<int,int> p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; for (int i=0; i<G[v].size(); i++) { Edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(make_pair(dist[e.to], e.to)); } } } if (dist[t] == INF) { return -1; } for (int v=0; v<N; v++) h[v] += dist[v]; int d = f; for (int v=t; v!=s; v=prevv[v]) { d = min(d,G[prevv[v]][preve[v]].cap); } f -= d; ret += d * h[t]; for (int v=t; v!=s; v=prevv[v]) { Edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return ret; } }; int main() { int V,E,F; cin >> V >> E >> F; MinCostFlow<int> inst(110); REP(i,E) { int a,b,c,d; cin >> a >> b >> c >> d; inst.add_edge(a,b,c,d); } cout << inst.get_min(0,V-1,F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <cassert> #include <iostream> #include <vector> #include <queue> #include <utility> #include <tuple> #include <limits> using namespace std; struct MinCostFlowGraph { private: using ll = long long; struct edge { int to; ll cap, cost; int r_idx; edge(int t, ll cap, ll cost, int r) : to(t), cap(cap), cost(cost), r_idx(r) {} }; vector<vector<edge>> G; int sz; public: MinCostFlowGraph(int n) : G(n), sz(n) {} void add_edge(int from, int to, ll cap, ll cost){ int i = G[to].size(), i_ = G[from].size(); G[from].emplace_back(to,cap,cost,i); G[to].emplace_back(from,0,-cost,i_); } ll min_cost_flow(int from, int to, ll f){ ll ans = 0; while(f > 0){ const ll INF = numeric_limits<ll>::max(); vector<ll> dist(sz,INF); dist[from] = 0; vector<ll> potential(sz); vector<int> prev_v(sz,-1); vector<int> prev_e(sz,-1); priority_queue<pair<ll,int>> pq; pq.emplace(0,from); while(pq.size()){ // auto [d, v] = pq.top(); ll d, v; tie(d,v) = pq.top(); d *= -1; pq.pop(); if(dist[v] < d) continue; for(size_t i = 0; i < G[v].size(); ++i){ const auto& e = G[v][i]; if(e.cap == 0) continue; int v_ = e.to; ll d_ = d + e.cost + potential[v] - potential[v_]; if(dist[v_] <= d_) continue; dist[v_] = d_; prev_v[v_] = v; prev_e[v_] = i; pq.emplace(-d_,e.to); } } if(dist[to] >= INF) return -1; for(int i = 0; i < sz; ++i) potential[i] += dist[i]; int v = to; ll flow = f; while(v != from){ int v_ = prev_v[v]; flow = min(flow,G[v_][prev_e[v]].cap); v = v_; } v = to; while(v != from){ int v_ = prev_v[v]; auto& e = G[v_][prev_e[v]]; e.cap -= flow; ans += flow*e.cost; G[v][e.r_idx].cap += flow; v = v_; } f -= flow; } return ans; } }; int main(){ int n, m, f; cin >> n >> m >> f; MinCostFlowGraph G(n); for(int i = 0; i < m; ++i){ long long u, v, c, d; cin >> u >> v >> c >> d; G.add_edge(u,v,c,d); } cout << G.min_cost_flow(0,n-1,f) << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
CORRECT
cpp
#include <bits/stdc++.h> using namespace std; template<typename T, T INF> class MinCostFlow{ public: //辺を表す構造体(行き先、容量、コスト、逆辺) struct edge{ int to,cap; T cost; int rev; edge(); edge(int to,int cap,T cost,int rev):to(to),cap(cap),cost(cost),rev(rev){} }; int V; //頂点数 vector<vector<edge> > G; //グラフの隣接リスト表現 vector<T> dist; //最短距離 vector<int> prevv,preve; //直前の頂点と辺 MinCostFlow():V(-1){} MinCostFlow(int V):V(V), G(V), dist(V), prevv(V), preve(V){}; // fromからtoへ向かう容量cap、コストcostの辺をグラフに追加する。 void add_edge(int from,int to,int cap ,T cost){ assert(from>=0 && to >= 0); assert(from<V && to<V); G[from].push_back((edge){to,cap,cost,(int)G[to].size()}); G[to].push_back((edge){from,0,-cost,(int)G[from].size()-1}); } //sからtへの流量fの最小費用流を求める //流せない場合-1を返す T flow(int s, int t, int f){ T res = 0; while(f>0){ //ベルマンフォード法により,s-t間最短路を求める fill(dist.begin(),dist.end(),INF); dist[s] = 0; bool update = true; while(update){ update = false; for(int v=0; v<V ;v++){ if(dist[v]==INF) continue; for(int i=0; i<(int)G[v].size(); i++){ edge &e = G[v][i]; if(e.cap > 0 && dist[e.to] > dist[v] + e.cost) { if(abs(dist[e.to] - dist[v] - e.cost) < 1e-8) continue; //double演算用 dist[e.to] = dist[v] + e.cost; prevv[e.to] = v; preve[e.to] = i; update = true; } } } } if(dist[t]==INF) return -1; //これ以上流せない。 //s−t間短路に沿って目一杯流す int d = f; for(int v=t; v!=s; v=prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap); f -= d; res += d * dist[t]; for(int v=t; v!=s; v=prevv[v]){ edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } }; int main(){ int V, E, F; cin>>V>>E>>F; MinCostFlow<long long, 1LL<<55> f(V); for(int i=0;i<E;i++){ int u, v, c, d; cin>>u>>v>>c>>d; f.add_edge(u, v, c, d); } int ans = f.flow(0, V-1, F); cout<<ans<<endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
UNKNOWN
import std.stdio, std.array, std.string, std.conv, std.algorithm; import std.typecons, std.range, std.random, std.math, std.container; import std.numeric, std.bigint, core.bitop; void main() { auto s = readln.split.map!(to!int); auto V = s[0]; auto E = s[1]; auto F = s[2]; auto mcf = new MinCostFlow(V); foreach (_; 0..E) { s = readln.split.map!(to!int); mcf.add_edge(s[0], s[1], s[2], s[3]); } mcf.run(0, V-1, F).writeln; } class MinCostFlow { alias Tuple!(int, "to", int, "cap", int, "cost", int, "rev") Edge; immutable int INF = 1 << 29; int V; Edge[][] G; int[] h; int[] dist; int[] prevv; int[] preve; this(int v) { V = v; G = new Edge[][](v); h = new int[](v); dist = new int[](v); prevv = new int[](v); preve = new int[](v); } void add_edge(int from, int to, int cap, int cost) { G[from] ~= Edge(to, cap, cost, G[to].length.to!int); G[to] ~= Edge(from, cap, cost, G[from].length.to!int - 1); } int run(int s, int t, int f) { // source, sink, flow int res = 0; h.fill(0); while (f > 0) { auto pq = new BinaryHeap!(Array!(Tuple!(int, int)), "a[0] < b[0]"); dist.fill(INF); dist[s] = 0; pq.insert(tuple(0, s)); while (!pq.empty) { auto p = pq.front; pq.removeFront; int v = p[1]; if (dist[v] < p[0]) continue; foreach (i; 0..G[v].length.to!int) { auto e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; pq.insert(tuple(dist[e.to], e.to)); } } } if (dist[t] == INF) { return -1; } foreach (v; 0..V) { h[v] += dist[v]; } int d = f; for (int v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { G[prevv[v]][preve[v]].cap -= d; G[v][G[prevv[v]][preve[v]].rev].cap += d; } } return res; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct edge { i64 from; i64 to; i64 cap; i64 cost; i64 rev; }; i64 INF = 1e18; i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g, std::vector<i64> b) { i64 ans = 0; i64 U = *std::max_element(begin(b), end(b)); i64 delta = (1 << ((int)(std::log2(U)) + 1)); int n = g.size(); std::vector<i64> e = b; std::vector<i64> p(n, 0); for (int i = 0; i < n; i++) { if (b[i] > 0) p[i] = 1e8; } int zero = 0; for (auto x : e) { if (x == 0) zero++; } for (; delta > 0; delta >>= 1) { if (zero == n) break; for (int s = 0; s < n; s++) { if (!(e[s] >= delta)) continue; std::vector<std::size_t> pv(n, -1); std::vector<std::size_t> pe(n, -1); std::vector<i64> dist(n, INF); using P = std::pair<i64, i64>; std::priority_queue<P, std::vector<P>, std::greater<P>> que; dist[s] = 0; que.push({dist[s], s}); while (!que.empty()) { int v = que.top().second; i64 d = que.top().first; que.pop(); if (dist[v] < d) continue; for (std::size_t i = 0; i < g[v].size(); i++) { const auto& e = g[v][i]; std::size_t u = e.to; if (e.cap == 0) { continue; } i64 ccc = e.cost + p[v] - p[u]; assert(ccc >= 0); if (dist[u] > dist[v] + ccc) { dist[u] = dist[v] + ccc; pv[u] = v; pe[u] = i; que.push({dist[u], u}); } } } for (int i = 0; i < n; i++) { if (pv[i] != -1) p[i] += dist[i] - p[s]; } p[s] += dist[s] - p[s]; int t = 0; for (; t < n; t++) { if (!(e[s] >= delta)) break; if (e[t] <= -delta && pv[t] != -1) { std::size_t u = t; for (; pv[u] != -1; u = pv[u]) { ans += delta * g[pv[u]][pe[u]].cost; g[pv[u]][pe[u]].cap -= delta; g[u][g[pv[u]][pe[u]].rev].cap += delta; } e[u] -= delta; e[t] += delta; if (e[u] == 0) zero++; if (e[t] == 0) zero++; } } } } for (int i = 0; i < n; i++) { } if (zero == n) return ans; else return -1e18; } int main() { i64 N, M, F; cin >> N >> M >> F; vector<vector<edge>> g(N + M); vector<i64> e(N + M, 0); int s = 0; int t = N - 1; e[s + M] = F; e[t + M] = -F; for (int i = 0; i < M; i++) { i64 a, b, c, d; cin >> a >> b >> c >> d; e[i] = c; e[a + M] -= c; g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()}); g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1}); g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()}); g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1}); } i64 ans = capacity_scaling_bflow(g, e); if (ans == -1e18) { cout << -1 << endl; } else { cout << ans << endl; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct edge { i64 from; i64 to; i64 cap; i64 cost; i64 rev; }; i64 INF = 1e8; i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g, std::vector<i64> b) { i64 ans = 0; i64 U = *std::max_element(begin(b), end(b)); i64 delta = (1 << ((int)(std::log2(U)) + 1)); int n = g.size(); std::vector<i64> e = b; std::vector<i64> p(n, 0); int zero = 0; for (auto x : e) { if (x == 0) zero++; } for (; delta > 0; delta >>= 1) { if (zero == n) break; while (true) { std::vector<std::size_t> pv(n, -1); std::vector<std::size_t> pe(n, -1); std::vector<std::size_t> start(n, -1); std::vector<i64> dist(n, INF); using P = std::pair<i64, i64>; std::priority_queue<P, std::vector<P>, std::greater<P>> que; bool t_exist = false; for (int s = 0; s < n; s++) { if (e[s] >= delta) { dist[s] = 0; start[s] = s; que.push({dist[s], s}); } if (e[s] <= -delta) t_exist = true; } if (que.empty()) break; if (!t_exist) break; while (!que.empty()) { int v = que.top().second; i64 d = que.top().first; que.pop(); if (dist[v] < d) continue; for (std::size_t i = 0; i < g[v].size(); i++) { const auto& e = g[v][i]; std::size_t u = e.to; if (e.cap == 0) continue; assert(e.cost + p[v] - p[u] >= 0); if (dist[u] > dist[v] + e.cost + p[v] - p[u]) { dist[u] = dist[v] + e.cost + p[v] - p[u]; pv[u] = v; pe[u] = i; start[u] = start[v]; que.push({dist[u], u}); } } } for (int i = 0; i < n; i++) { p[i] += dist[i]; } bool sended = false; for (int t = 0; t < n; t++) { if (e[t] <= -delta && pv[t] != -1 && e[start[t]] >= delta) { sended = true; std::size_t u = t; for (; pv[u] != -1; u = pv[u]) { ans += delta * g[pv[u]][pe[u]].cost; g[pv[u]][pe[u]].cap -= delta; g[u][g[pv[u]][pe[u]].rev].cap += delta; } e[u] -= delta; e[t] += delta; if (e[u] == 0) zero++; if (e[t] == 0) zero++; } } if (!sended) { break; } } } if (zero == n) return ans; else return -1e18; } int main() { i64 N, M, F; cin >> N >> M >> F; vector<vector<edge>> g(N + M); vector<i64> e(N + M, 0); int s = 0; int t = N - 1; e[s + M] = F; e[t + M] = -F; for (int i = 0; i < M; i++) { i64 a, b, c, d; cin >> a >> b >> c >> d; e[i] = c; e[a + M] -= c; g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()}); g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1}); g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()}); g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1}); } i64 ans = capacity_scaling_bflow(g, e); if (ans == -1e18) { cout << -1 << endl; } else { cout << ans << endl; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct edge { i64 from; i64 to; i64 cap; i64 cost; i64 rev; }; i64 INF = 1e8; i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g, std::vector<i64> b) { i64 ans = 0; i64 U = *std::max_element(begin(b), end(b)); i64 delta = (1 << ((int)(std::log2(U)) + 1)); int n = g.size(); std::vector<i64> e = b; std::vector<i64> p(n, 0); int zero = 0; for (auto x : e) { if (x == 0) zero++; } for (; delta > 0; delta >>= 1) { if (zero == n) break; for (int s = 0; s < n; s++) { if (!(e[s] >= delta)) continue; std::vector<std::size_t> pv(n, -1); std::vector<std::size_t> pe(n, -1); std::vector<i64> dist(n, 1e18); using P = std::pair<i64, i64>; std::priority_queue<P, std::vector<P>, std::greater<P>> que; dist[s] = 0; que.push({dist[s], s}); while (!que.empty()) { int v = que.top().second; i64 d = que.top().first; que.pop(); if (dist[v] < d) continue; for (std::size_t i = 0; i < g[v].size(); i++) { const auto& e = g[v][i]; std::size_t u = e.to; i64 ccc = e.cost + p[v] - p[u]; if (e.cap == 0) ccc = INF; assert(ccc >= 0); if (dist[u] > dist[v] + ccc) { dist[u] = dist[v] + ccc; pv[u] = v; pe[u] = i; que.push({dist[u], u}); } } } for (int i = 0; i < n; i++) { p[i] += dist[i]; } int t = 0; for (; t < n; t++) { if (!(e[s] >= delta)) break; if (e[t] <= -delta && pv[t] != -1 && dist[t] < INF) { std::size_t u = t; for (; pv[u] != -1; u = pv[u]) { ans += delta * g[pv[u]][pe[u]].cost; g[pv[u]][pe[u]].cap -= delta; g[u][g[pv[u]][pe[u]].rev].cap += delta; } e[u] -= delta; e[t] += delta; if (e[u] == 0) zero++; if (e[t] == 0) zero++; } } } } if (zero == n) return ans; else return -1e18; } int main() { i64 N, M, F; cin >> N >> M >> F; vector<vector<edge>> g(N + M); vector<i64> e(N + M, 0); int s = 0; int t = N - 1; e[s + M] = F; e[t + M] = -F; for (int i = 0; i < M; i++) { i64 a, b, c, d; cin >> a >> b >> c >> d; e[i] = c; e[a + M] -= c; g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()}); g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1}); g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()}); g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1}); } i64 ans = capacity_scaling_bflow(g, e); if (ans == -1e18) { cout << -1 << endl; } else { cout << ans << endl; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
UNKNOWN
class PQueue attr_accessor :node def initialize @node = [] end def insert(num) i = @node.size @node[i] = num down_heap(i) end def extract ret = @node[0] if @node.size > 1 @node[0] = @node.pop() up_heap(0) else @node = [] end return ret end def delete(node) i = @node.index(node) break until i if i == @node.size - 1 @node.pop else @node[i] = @node.pop copy = @node.clone down_heap(i) if copy == @node up_heap(i) end end end def modify(old, new) delete(old) insert(new) end def up_heap(i) h = @node.size largest = i l = 2 * i + 1 largest = l if l < h && @node[l] > @node[largest] r = 2 * i + 2 largest = r if r < h && @node[r] > @node[largest] while largest != i @node[i], @node[largest] = @node[largest], @node[i] i = largest l = 2 * i + 1 largest = l if l < h && @node[l] > @node[largest] r = 2 * i + 2 largest = r if r < h && @node[r] > @node[largest] end end def down_heap(i) p = (i+1)/2-1 while i > 0 && @node[p] < @node[i] @node[i], @node[p] = @node[p], @node[i] i = p p = (i+1)/2-1 end end end INF = 1.0 / 0.0 class Node attr_accessor :i, :c, :prev, :d, :pot, :ans def initialize(i) @i = i @c = {} @ans = {} @prev = nil @d = INF @pot = 0 end def <(other) if self.d > other.d return true else return false end end def >(other) if self.d < other.d return true else return false end end end nv, ne, f = gets.split.map(&:to_i) g = Array.new(nv){|i| Node.new(i)} ne.times{|i| u, v, c, d = gets.split.map(&:to_i) g[u].c[v] = [c, d] g[u].ans[v] = [0,d] } loop do nv.times{|i| g[i].d = INF g[i].prev = nil } g[0].d = 0 q = PQueue.new nv.times{|i| q.insert(g[i]) } while q.node.size > 0 u = q.extract u.c.each{|v, val| alt = u.d + val[1] if g[v].d > alt q.delete(g[v]) g[v].d = alt g[v].prev = u.i q.insert(g[v]) end } end # p g max = f c = nv-1 path = [c] while c != 0 p = g[c].prev if p == nil puts "-1" exit end path.unshift(p) max = g[p].c[c][0] if max > g[p].c[c][0] c = p end # p path # p max if max < f then #make potential path.each{|i| g[i].pot -= g[i].d } (path.size-1).times{|i| u = path[i] v = path[i+1] g[u].ans[v][0] += max } # p g f -= max else (path.size-1).times{|i| u = path[i] v = path[i+1] g[u].ans[v][0] += f } break end #make sub-network (path.size-1).times{|i| u = path[i] v = path[i+1] g[v].c[u] ||= [0, -g[u].c[v][1]] g[v].c[u][0] += max g[u].c[v][0] -= max if g[u].c[v][0] == 0 g[u].c.delete(v) end } #make modified sub-network g.size.times{|i| g[i].c.each{|j, val| # p "#{g[i].c[j][1]} #{g[i].pot} #{g[j].pot}" g[i].c[j][1] -= g[i].pot - g[j].pot } } # g.size.times{|i| # p g[i] # } end sum = 0 nv.times{|i| g[i].ans.each{|k,v| sum += v[0]*v[1] } } puts sum
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
python3
from heapq import heappop, heappush def trace(source, edge_trace): v = source for i in edge_trace: e = edges[v][i] yield e v = e[1] def min_cost_flow(source, sink, required_flow): res = 0 while required_flow: visited = set() queue = [(0, source, tuple())] while queue: total_cost, v, edge_memo = heappop(queue) if v in visited: continue elif v == sink: dist = total_cost edge_trace = edge_memo break for i, (remain, target, cost, _) in enumerate(edges[v]): if remain and target not in visited: heappush(queue, (total_cost + cost, target, edge_memo + (i,))) else: return -1 aug = min(required_flow, min(e[0] for e in trace(source, edge_trace))) required_flow -= aug res += aug * dist for e in trace(source, edge_trace): remain, target, cost, idx = e e[0] -= aug edges[target][idx][0] += aug return res n, m, f = map(int, input().split()) edges = [[] for _ in range(n)] for _ in range(m): s, t, c, d = map(int, input().split()) es, et = edges[s], edges[t] ls, lt = len(es), len(et) es.append([c, t, d, lt]) et.append([0, s, d, ls]) print(min_cost_flow(0, n - 1, f))
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
UNKNOWN
#include <bits/stdc++.h> struct node { int id; int cap; int cost; struct node *next; }; struct node **list; int **flow, *delta, *dist, *prev; int *heap, *heap_index, heapsize; void Insert(int, int, int, int); void downheap(int); void upheap(int); void PQ_init(int); int PQ_remove(void); void PQ_update(int); int Maxflow(int, int, int); int main(void) { int i, v, e, f, s, t, c, d, mincost = 0; scanf("%d %d %d", &v, &e, &f); list = (struct node **)malloc(sizeof(struct node *) * v); flow = (int **)malloc(sizeof(int *) * v); delta = (int *)malloc(sizeof(int) * v); dist = (int *)malloc(sizeof(int) * v); prev = (int *)malloc(sizeof(int) * v); for (i = 0; i < v; i++) { list[i] = NULL; flow[i] = (int *)calloc(v, sizeof(int)); } for (i = 0; i < e; i++) { scanf("%d %d %d %d", &s, &t, &c, &d); Insert(s, t, c, d); } while (f > 0 && Maxflow(0, v - 1, v)) { int n = v - 1; f -= delta[v - 1]; if (f < 0) delta[v - 1] += f; do { flow[prev[n]][n] += delta[v - 1]; flow[n][prev[n]] -= delta[v - 1]; n = prev[n]; } while (n); } if (f <= 0) { for (i = 0; i < v; i++) { struct node *n; for (n = list[i]; n != NULL; n = n->next) { mincost += flow[i][n->id] * n->cost; } } printf("%d\n", mincost); } else printf("-1\n"); for (i = 0; i < v; i++) { free(list[i]); free(flow[i]); } free(list); free(flow); free(delta); free(dist); free(prev); } void Insert(int a, int b, int cap, int cost) { struct node *p = (struct node *)malloc(sizeof(struct node)); p->id = b; p->cap = cap; p->cost = cost; p->next = list[a]; list[a] = p; p = (struct node *)malloc(sizeof(struct node)); p->id = a; p->cap = 0; p->cost = 0; p->next = list[b]; list[b] = p; } void downheap(int k) { int j, v = heap[k]; while (k < heapsize / 2) { j = 2 * k + 1; if (j < heapsize - 1 && dist[heap[j]] > dist[heap[j + 1]]) j++; if (dist[v] <= dist[heap[j]]) break; heap[k] = heap[j]; heap_index[heap[j]] = k; k = j; } heap[k] = v; heap_index[v] = k; } void upheap(int j) { int k, v = heap[j]; while (j > 0) { k = (j + 1) / 2 - 1; if (dist[v] >= dist[heap[k]]) break; heap[j] = heap[k]; heap_index[heap[k]] = j; j = k; } heap[j] = v; heap_index[v] = j; } void PQ_init(int size) { int i; heapsize = size; heap = (int *)malloc(sizeof(int) * size); heap_index = (int *)malloc(sizeof(int) * size); for (i = 0; i < size; i++) { heap[i] = i; heap_index[i] = i; } for (i = heapsize / 2 - 1; i >= 0; i--) downheap(i); } int PQ_remove(void) { int v = heap[0]; heap[0] = heap[heapsize - 1]; heap_index[heap[heapsize - 1]] = 0; heapsize--; downheap(0); return v; } void PQ_update(int v) { upheap(heap_index[v]); } int Maxflow(int s, int t, int size) { struct node *n; int i; for (i = 0; i < size; i++) { delta[i] = INT_MAX; dist[i] = INT_MAX; prev[i] = -1; } dist[s] = 0; PQ_init(size); while (heapsize) { i = PQ_remove(); if (i == t) break; if (dist[i] == INT_MAX) break; for (n = list[i]; n != NULL; n = n->next) { int v = n->id; if (flow[i][v] < n->cap && dist[i] != INT_MAX) { int newlen = dist[i] + n->cost; if (newlen < dist[v]) { dist[v] = newlen; prev[v] = i; delta[v] = ((delta[i]) < (n->cap - flow[i][v]) ? (delta[i]) : (n->cap - flow[i][v])); PQ_update(v); } } } } free(heap); free(heap_index); return dist[t] != INT_MAX; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
// warm heart, wagging tail,and a smile just for you! // ███████████ // ███╬╬╬╬╬╬╬╬╬╬███ // ███╬╬╬╬╬╬╬██╬╬╬╬╬╬███ // ███████████ ██╬╬╬╬╬████╬╬████╬╬╬╬╬██ // █████████╬╬╬╬╬████████████╬╬╬╬╬██╬╬╬╬╬╬███╬╬╬╬╬██ // ████████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████████╬╬╬╬╬╬██╬╬╬╬╬╬╬██ // ████╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████████╬╬╬╬╬╬╬╬╬╬╬██ // ███╬╬╬█╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬███╬╬╬╬╬╬╬█████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬████████╬╬╬╬╬██ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬╬╬╬╬╬███ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬██ // ████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████╬╬╬╬╬████ // █████████████╬╬╬╬╬╬╬╬██╬╬╬╬╬████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬██████ // ████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬██████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██████╬╬╬╬╬╬╬███████████╬╬╬╬╬╬╬╬██╬╬╬██╬╬╬██ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████╬╬╬╬╬╬╬╬╬╬╬█╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬██ // ██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬▓▓▓▓▓▓╬╬╬████╬╬████╬╬╬╬╬╬╬▓▓▓▓▓▓▓▓▓█╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬███ // ██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██████▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓▓▓▓▓▓▓█╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬█████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██ // ██████████████ ████╬╬╬╬╬╬███████████████████████████╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████ // ███████ █████ ███████████████████ #include "bits/stdc++.h" using namespace std; #define MOD 1000000007 #define INF 1LL<<60 #define fs first #define sc second #define pb push_back #define int long long #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define RFOR(i,a,b) for(int i = (b-1);i>=a;i--) #define REP(i,n) FOR(i,0,n) #define RREP(i,n) RFOR(i,0,n) #define ITR(itr,mp) for(auto itr = (mp).begin(); itr != (mp).end(); ++itr) #define RITR(itr,mp) for(auto itr = (mp).rbegin(); itr != (mp).rend(); ++itr) #define range(i,a,b) (a)<=(i) && (i)<(b) #define debug(x) cout << #x << " = " << (x) << endl; typedef pair<int,int> P; struct edge{int to,cap,cost,rev;}; const int MAX_V = 3e5; int V; vector<edge> G[MAX_V]; vector<int> h,dist,prevv(MAX_V),preve(MAX_V); void add_edge(int from, int to, int cap, int cost){ G[from].pb((edge){to,cap,cost,G[to].size()}); G[to].pb((edge){from,0,-cost,G[from].size()-1}); } int min_cost_flow(int s, int t, int f){ int res = 0; h.assign(V,0); while(f > 0){ priority_queue<P,vector<P>,greater<P>> que; dist.assign(V,INF); dist[s] = 0; que.push(P(0,s)); while(!que.empty()){ P p = que.top(); que.pop(); int v = p.sc; if(dist[v] < p.fs) continue; REP(i,G[v].size()){ edge &e = G[v][i]; if(e.cap > 0 && dist[e.to] > dist[v]+e.cost+h[v]-h[e.to]){ dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(P(dist[e.to],e.to)); } } } if(dist[t] == INF) return -1; REP(v,V) h[v] += dist[v]; int d = f; for(int v = t; v != s; v = prevv[v]) d = min(d,G[prevv[v]][preve[v]].cap); f -= d; res += d*h[t]; for(int v = t; v != s; v = prevv[v]){ edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } // Vを頂点数で更新する!! signed main(){ ios::sync_with_stdio(false); cin.tie(0); int v,e,f; cin >> v >> e >> f; V = v; REP(_,e){ int s,t,cap,dist; cin >> s >> t >> cap >> dist; add_edge(s,t,cap,dist); } cout << min_cost_flow(0,v-1,f) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using Int = int64_t; using UInt = uint64_t; using C = std::complex<double>; template <typename T> using RQ = std::priority_queue<T, std::vector<T>, std::greater<T>>; int main() { Int v, e, f; std::cin >> v >> e >> f; std::vector<Int> ss(e + 1), ts(e + 1), cs(e + 1), fs(e + 1), bs(e + 1); for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { Int a, b, c, d; std::cin >> a >> b >> c >> d; ss[i] = a, ts[i] = b, cs[i] = d, fs[i] = 0, bs[i] = c; } std::vector<std::vector<Int>> es(v); for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { Int s = ss[i], t = ts[i]; es[s].emplace_back(i); es[t].emplace_back(-i); } Int res = 0; Int source = 0, sink = v - 1; while (f > 0) { RQ<std::pair<Int, Int>> q; q.emplace(0, source); std::vector<Int> ps(v, -1), xs(v, -1), ys(v), hs(v); xs[source] = 0; ys[source] = f; while (not q.empty()) { Int d, s; std::tie(d, s) = q.top(); q.pop(); if (not(d == xs[s])) continue; ; for (Int i : es[s]) { Int k = std::abs(i); Int t = i > 0 ? ts[k] : ss[k]; Int tf = i > 0 ? bs[k] : fs[k]; if (not(tf > 0)) continue; ; Int nd = d + cs[k] + hs[s] - hs[t]; if (not(xs[t] == -1 or xs[t] > nd)) continue; ; xs[t] = nd; ps[t] = i; ys[t] = std::min(ys[s], tf); q.emplace(nd, t); } } Int tf = ys[sink]; if (false) fprintf(stderr, "tf = %ld\n", tf); f -= tf; if (f > 0 and tf == 0) { res = -1; break; } for (Int i = 0; i < (Int)(v); ++i) hs[i] += xs[i]; for (Int i = sink, k = ps[i]; i != source; i = k > 0 ? ss[k] : ts[k], k = ps[i]) { Int ak = std::abs(k); if (false) fprintf(stderr, "i=%ld, k=%ld\n", i, k); if (k > 0) { res += tf * cs[ak]; fs[ak] += tf; bs[ak] -= tf; } else { res -= tf * cs[ak]; fs[ak] -= tf; bs[ak] += tf; } } if (f == 0) break; for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { if (false) fprintf(stderr, "%ld -> %ld : cost=%ld : ->=%ld : <-=%ld\n", ss[i], ts[i], cs[i], fs[i], bs[i]); } } printf("%ld\n", res); }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; struct edge { int to, cap, cost, rev; }; static const int MAX_V = 10000; int V; vector<edge> G[MAX_V]; int dist[MAX_V]; int prevv[MAX_V], preve[MAX_V]; void addEdge(int from, int to, int cap, int cost) { G[from].push_back((edge{to, cap, cost, (int)G[to].size()})); G[to].push_back((edge{from, 0, -cost, (int)G[from].size() - 1})); } int minCostFlow(int s, int t, int f) { int res = 0; while (f > 0) { fill(dist, dist + V, (long long)(2 * 1e9)); dist[s] = 0; bool update = true; while (update) { update = false; for (int v = (0); v < (int)(V); v++) { if (dist[v] == (long long)(2 * 1e9)) continue; for (int i = (0); i < (int)(G[v].size()); i++) { edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost) { dist[e.to] = dist[v] + e.cost; prevv[e.to] = v; preve[e.to] = i; update = true; } } } } if (dist[t] == (long long)(2 * 1e9)) { return -1; } int d = f; for (int v = 0; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * dist[t]; for (int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main() { int v, e, f; cin >> v >> e >> f; V = v; for (int i = (0); i < (int)(e); i++) { int u, v, c, d; cin >> u >> v >> c >> d; addEdge(u, v, c, d); } cout << minCostFlow(0, v - 1, f) << endl; END: return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using Int = int64_t; using UInt = uint64_t; using C = std::complex<double>; template <typename T> using RQ = std::priority_queue<T, std::vector<T>, std::greater<T>>; int main() { Int v, e, f; std::cin >> v >> e >> f; std::vector<Int> ss(e + 1), ts(e + 1), cs(e + 1), fs(e + 1), bs(e + 1); for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { Int a, b, c, d; std::cin >> a >> b >> c >> d; ss[i] = a, ts[i] = b, cs[i] = d, fs[i] = 0, bs[i] = c; } std::vector<std::vector<Int>> es(v); for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { Int s = ss[i], t = ts[i]; es[s].emplace_back(i); es[t].emplace_back(-i); } Int res = 0; Int source = 0, sink = v - 1; while (f > 0) { RQ<std::pair<Int, Int>> q; q.emplace(0, source); std::vector<Int> ps(v, -1), xs(v, -1), ys(v); ys[source] = (Int)1 << 53; while (not q.empty()) { Int d, s; std::tie(d, s) = q.top(); q.pop(); for (Int i : es[s]) { Int k = std::abs(i); Int t = i > 0 ? ts[k] : ss[k]; Int tf = i > 0 ? bs[k] : fs[k]; if (not(tf > 0)) continue; ; if (not(xs[t] == -1 or xs[t] > xs[s] + cs[k])) continue; ; xs[t] = xs[s] + cs[k]; ps[t] = i; ys[t] = std::min(ys[s], tf); q.emplace(xs[s] + cs[k], t); } } Int tf = ys[sink]; if (false) fprintf(stderr, "tf = %ld\n", tf); f -= tf; if (f > 0 and tf == 0) { res = -1; break; } for (Int i = sink, k = ps[i]; i != source; i = k > 0 ? ss[k] : ts[k], k = ps[i]) { Int ak = std::abs(k); res += tf * cs[ak]; if (k > 0) { fs[ak] += tf; bs[ak] -= tf; } else { fs[ak] -= tf; bs[ak] += tf; } } if (f == 0) break; for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { if (false) fprintf(stderr, "%ld -> %ld : cost=%ld : ->=%ld : <-=%ld\n", ss[i], ts[i], cs[i], fs[i], bs[i]); } } printf("%ld\n", res); }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <stdexcept> #include <cmath> #include <utility> #include <queue> #include <limits> #include <iostream> #include <vector> #include <cstddef> #include <type_traits> namespace loquat { using vertex_t = size_t; } namespace loquat { namespace edge_param { struct to_ { vertex_t to; explicit to_(vertex_t t = 0) : to(t) { } }; template <typename T> struct weight_ { using weight_type = T; weight_type weight; explicit weight_(const weight_type& w = weight_type()) : weight(w) { } }; template <typename T> using weight = weight_<T>; template <typename T> struct capacity_ { using capacity_type = T; capacity_type capacity; explicit capacity_(const capacity_type& c = capacity_type()) : capacity(c) { } }; template <typename T> using capacity = capacity_<T>; } namespace detail { template <typename T, typename... Params> struct edge_param_wrapper : public T, edge_param_wrapper<Params...> { template <typename U, typename... Args> explicit edge_param_wrapper(U&& x, Args&&... args) : T(std::forward<U>(x)) , edge_param_wrapper<Params...>(std::forward<Args>(args)...) { } }; template <typename T> struct edge_param_wrapper<T> : public T { template <typename U> explicit edge_param_wrapper(U&& x) : T(std::forward<U>(x)) { } }; } template <typename... Params> struct edge : public detail::edge_param_wrapper<edge_param::to_, Params...> { template <typename... Args> explicit edge(Args&&... args) : detail::edge_param_wrapper<edge_param::to_, Params...>( std::forward<Args>(args)...) { } }; } namespace loquat { template <typename EdgeType> struct has_weight { private: template <typename U> static std::true_type check_type(typename U::weight_type *); template <typename U> static auto check_member(const U& x) public: static const bool value = decltype(check_type<EdgeType>(nullptr))::value && decltype(check_member(std::declval<EdgeType>()))::value; }; } namespace loquat { template <typename EdgeType> class adjacency_list { public: using edge_type = EdgeType; using edge_list = std::vector<edge_type>; private: std::vector<std::vector<EdgeType>> m_edges; public: explicit adjacency_list(size_t n) : m_edges(n) { } size_t size() const { return m_edges.size(); } const edge_list& operator[](vertex_t u) const { return m_edges[u]; } edge_list& operator[](vertex_t u){ return m_edges[u]; } template <typename... Args> void add_edge(vertex_t from, Args&&... args){ m_edges[from].emplace_back(std::forward<Args>(args)...); } void add_edge(vertex_t from, const edge_type& e){ m_edges[from].emplace_back(e); } }; } namespace loquat { namespace detail { template <typename EdgeType> auto negate_weight(EdgeType& e) -> typename std::enable_if<has_weight<EdgeType>::value, void>::type { e.weight = -e.weight; } } template <typename EdgeType> struct residual_edge : public EdgeType { using base_type = EdgeType; size_t rev; residual_edge(const base_type& e, size_t rev) : base_type(e) , rev(rev) { } }; template <typename EdgeType> adjacency_list<residual_edge<EdgeType>> make_residual(const adjacency_list<EdgeType>& graph){ using edge_type = EdgeType; using residual_type = residual_edge<edge_type>; using capacity_type = typename edge_type::capacity_type; const size_t n = graph.size(); adjacency_list<residual_type> result(n); for(vertex_t u = 0; u < n; ++u){ for(const auto& e : graph[u]){ result.add_edge(u, residual_type(e, 0)); } } for(vertex_t u = 0; u < n; ++u){ const size_t m = graph[u].size(); for(size_t i = 0; i < m; ++i){ auto e = graph[u][i]; const auto v = e.to; e.to = u; e.capacity = capacity_type(); detail::negate_weight(e); result[u][i].rev = result[v].size(); result.add_edge(v, residual_type(e, i)); } } return result; } } namespace loquat { template <typename EdgeType, typename Predicate> adjacency_list<EdgeType> filter( const adjacency_list<EdgeType>& graph, Predicate pred) { const size_t n = graph.size(); adjacency_list<EdgeType> result(n); for(vertex_t u = 0; u < n; ++u){ for(const auto& e : graph[u]){ if(pred(u, e)){ result.add_edge(u, e); } } } return result; } } namespace loquat { template <typename T> constexpr inline auto positive_infinity() noexcept -> typename std::enable_if<std::is_integral<T>::value, T>::type { return std::numeric_limits<T>::max(); } template <typename T> constexpr inline auto is_positive_infinity(T x) noexcept -> typename std::enable_if<std::is_integral<T>::value, bool>::type { return x == std::numeric_limits<T>::max(); } } namespace loquat { class no_solution_error : public std::runtime_error { public: explicit no_solution_error(const char *what) : std::runtime_error(what) { } }; } namespace loquat { template <typename EdgeType> std::vector<typename EdgeType::weight_type> sssp_bellman_ford(vertex_t source, const adjacency_list<EdgeType>& graph){ using weight_type = typename EdgeType::weight_type; const auto inf = positive_infinity<weight_type>(); const auto n = graph.size(); std::vector<weight_type> result(n, inf); result[source] = weight_type(); bool finished = false; for(size_t iter = 0; !finished && iter < n; ++iter){ finished = true; for(loquat::vertex_t u = 0; u < n; ++u){ if(loquat::is_positive_infinity(result[u])){ continue; } for(const auto& e : graph[u]){ const auto v = e.to; if(result[u] + e.weight < result[v]){ result[v] = result[u] + e.weight; finished = false; } } } } if(!finished){ throw no_solution_error("graph has a negative cycle"); } return result; } } namespace loquat { template <typename EdgeType> typename EdgeType::weight_type mincostflow_primal_dual( typename EdgeType::capacity_type flow, vertex_t source, vertex_t sink, adjacency_list<EdgeType>& graph) { using edge_type = EdgeType; using weight_type = typename edge_type::weight_type; const auto inf = positive_infinity<weight_type>(); const auto n = graph.size(); const auto predicate = [](vertex_t, const edge_type& e) -> bool { return e.capacity > 0; }; auto h = sssp_bellman_ford(source, filter(graph, predicate)); std::vector<vertex_t> prev_vertex(n); std::vector<size_t> prev_edge(n); weight_type result = 0; while(flow > 0){ using pair_type = std::pair<weight_type, vertex_t>; std::priority_queue< pair_type, std::vector<pair_type>, std::greater<pair_type>> pq; std::vector<weight_type> d(n, inf); pq.emplace(0, source); d[source] = weight_type(); while(!pq.empty()){ const auto p = pq.top(); pq.pop(); const auto u = p.second; if(d[u] < p.first){ continue; } for(size_t i = 0; i < graph[u].size(); ++i){ const auto& e = graph[u][i]; if(e.capacity <= 0){ continue; } const auto v = e.to; const auto t = d[u] + e.weight + h[u] - h[v]; if(d[v] <= t){ continue; } d[v] = t; prev_vertex[v] = u; prev_edge[v] = i; pq.emplace(t, v); } } if(is_positive_infinity(d[sink])){ throw no_solution_error("there are no enough capacities to flow"); } for(size_t i = 0; i < n; ++i){ h[i] += d[i]; } weight_type f = flow; for(vertex_t v = sink; v != source; v = prev_vertex[v]){ const auto u = prev_vertex[v]; f = std::min(f, graph[u][prev_edge[v]].capacity); } flow -= f; result += f * h[sink]; for(vertex_t v = sink; v != source; v = prev_vertex[v]){ const auto u = prev_vertex[v]; auto& e = graph[u][prev_edge[v]]; e.capacity -= f; graph[v][e.rev].capacity += f; } } return result; } } using namespace std; using edge = loquat::edge< loquat::edge_param::weight<int>, loquat::edge_param::capacity<int>>; int main(){ ios_base::sync_with_stdio(false); int n, m, f; cin >> n >> m >> f; loquat::adjacency_list<edge> g(n); for(int i = 0; i < m; ++i){ int a, b, c, d; cin >> a >> b >> c >> d; g.add_edge(a, b, d, c); } const int source = 0, sink = n - 1; auto residual = loquat::make_residual(g); cout << loquat::mincostflow_primal_dual(f, source, sink, residual) << std::endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
python3
from heapq import heappop, heappush def trace(source, edge_trace): v = source for i in edge_trace: e = edges[v][i] yield e v = e[1] def min_cost_flow(source, sink, required_flow): res = 0 while required_flow: dist = [-1] * n queue = [(0, source, tuple())] edge_trace = None while queue: total_cost, v, edge_memo = heappop(queue) if dist[v] != -1: continue dist[v] = total_cost if v == sink: edge_trace = edge_memo break for i, (remain, target, cost, _) in enumerate(edges[v]): if remain and dist[target] == -1: heappush(queue, (total_cost + cost, target, edge_memo + (i,))) if dist[sink] == -1: return -1 aug = min(required_flow, min(e[0] for e in trace(source, edge_trace))) required_flow -= aug res += aug * dist[sink] for e in trace(source, edge_trace): remain, target, cost, idx = e e[0] -= aug edges[target][idx][0] += aug return res n, m, f = map(int, input().split()) edges = [[] for _ in range(n)] for _ in range(m): s, t, c, d = map(int, input().split()) es, et = edges[s], edges[t] ls, lt = len(es), len(et) es.append([c, t, d, lt]) et.append([0, s, d, ls]) print(min_cost_flow(0, n - 1, f))
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using ll = long long; using ld = long double; template <class T, class S> void cmin(T &a, const S &b) { if (a > b) a = b; } template <class T, class S> void cmax(T &a, const S &b) { if (a < b) a = b; } ll dx[] = {0, 0, 1, -1}; ll dy[] = {1, -1, 0, 0}; ll W, H; bool inrange(ll x, ll y) { return (0 <= x && x < W) && (0 <= y && y < H); } using namespace std; using Flow = ll; using Cost = ll; struct Edge { ll s, to, rev, cost, source, sink; Flow cap; Edge(ll _s, ll _to) : s(_s), to(_to) { ; } Edge(ll _s, ll _to, ll _c) : s(_s), to(_to), cost(_c) { ; } Edge(ll _s, ll _to, Flow f, ll _rev) : s(_s), to(_to), cap(f), rev(_rev) { ; } Edge(ll _s, ll _to, Flow f, ll _rev, ll _c) : s(_s), to(_to), cost(_c), cap(f), rev(_rev) { ; } }; class MCF { public: using pair<ll, ll> = pair<ll, ll>; using ve = vector<Edge>; using vve = vector<ve>; ll n; vve G; vector<ll> h, dist, prev, pree; MCF(ll size) { n = size; G = vve(n); h = dist = prev = pree = vector<ll>(n); } void add_edge(ll s, ll t, Flow ca, ll co) { Edge e = Edge(t, ca, co, (ll)G[t].size()); G[s].push_back(e); Edge ee = Edge(s, 0, -co, (ll)G[s].size() - 1); G[t].push_back(ee); } ll mcf(ll s, ll t, Flow f) { ll out = 0; h = vector<ll>(n); while (f > 0) { priority_queue<pair<ll, ll>, vector<pair<ll, ll>>> q; dist = vector<ll>(n, 1e9); dist[s] = 0; q.push(pair<ll, ll>(0, s)); while (!q.empty()) { pair<ll, ll> p = q.top(); q.pop(); ll v = p.second; if (dist[v] < -p.first) continue; for (ll i = 0; i < G[t].size(); i++) { Edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prev[e.to] = v; pree[e.to] = i; q.push(pair<ll, ll>(-dist[e.to], e.to)); } } } if (dist[t] == 1e9) return -1; for (ll i = 0; i < n; i++) h[i] += dist[i]; ll d = f; for (ll v = t; v != s; v = prev[v]) d = min(d, G[prev[v]][pree[v]].cap); f -= d; out += d * h[t]; for (ll v = t; v != s; v = prev[v]) { Edge &e = G[prev[v]][pree[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return out; } }; signed main() { ll v, e, f; cin >> v >> e >> f; MCF hoge(v); for (ll i = 0; i < e; i++) { ll a, b, c, d; cin >> a >> b >> c >> d; hoge.add_edge(a, b, c, d); } cout << hoge.mcf(0, --v, f) << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct edge { i64 from; i64 to; i64 cap; i64 cost; i64 rev; }; i64 INF = 1e18; i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g, std::vector<i64> b) { i64 ans = 0; i64 U = *std::max_element(begin(b), end(b)); i64 delta = (1 << ((int)(std::log2(U)) + 1)); int n = g.size(); std::vector<i64> e = b; std::vector<i64> p(n, 0); int zero = 0; for (auto x : e) { if (x == 0) zero++; } for (; delta > 0; delta >>= 1) { if (zero == n) break; for (int s = 0; s < n; s++) { if (!(e[s] >= delta)) continue; std::vector<std::size_t> pv(n, -1); std::vector<std::size_t> pe(n, -1); std::vector<i64> dist(n, INF); using P = std::pair<i64, i64>; std::priority_queue<P, std::vector<P>, std::greater<P>> que; dist[s] = 0; que.push({dist[s], s}); while (!que.empty()) { int v = que.top().second; i64 d = que.top().first; que.pop(); if (dist[v] < d) continue; for (std::size_t i = 0; i < g[v].size(); i++) { const auto& e = g[v][i]; std::size_t u = e.to; if (e.cap == 0) continue; assert(e.cost + p[v] - p[u] >= 0); if (dist[u] > dist[v] + e.cost + p[v] - p[u]) { dist[u] = dist[v] + e.cost + p[v] - p[u]; pv[u] = v; pe[u] = i; que.push({dist[u], u}); } } } for (int i = 0; i < n; i++) { if (pv[i] != -1) p[i] += dist[i]; } int t = 0; for (; t < n; t++) { if (!(e[s] >= delta)) break; if (e[t] <= -delta && pv[t] != -1) { std::size_t u = t; for (; pv[u] != -1; u = pv[u]) { ans += delta * g[pv[u]][pe[u]].cost; g[pv[u]][pe[u]].cap -= delta; g[u][g[pv[u]][pe[u]].rev].cap += delta; } e[u] -= delta; e[t] += delta; if (e[u] == 0) zero++; if (e[t] == 0) zero++; } } } } if (zero == n) return ans; else return -1e18; } int main() { i64 N, M, F; cin >> N >> M >> F; vector<vector<edge>> g(N + M); vector<i64> e(N + M, 0); int s = 0; int t = N - 1; e[s + M] = F; e[t + M] = -F; for (int i = 0; i < M; i++) { i64 a, b, c, d; cin >> a >> b >> c >> d; e[i] = c; e[a + M] -= c; g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()}); g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1}); g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()}); g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1}); } i64 ans = capacity_scaling_bflow(g, e); if (ans == -1e18) { cout << -1 << endl; } else { cout << ans << endl; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <iostream> #include <vector> using namespace std; constexpr int INF = 1e9; struct Edge { int to, cap, rev, weight; Edge(int t, int c, int r, int w) : to(t), cap(c), rev(r), weight(w){} }; using Edges = vector<Edge>; using Graph = vector<Edges>; class Flow { public: Flow(int v){ mGraph.resize(v); mUsed.assign(v,false); mVert = v; } void add_edge(int from, int to, int cap, int weight = 1){ mGraph[from].emplace_back(to,cap,mGraph[to].size(), weight); // directed mGraph[to].emplace_back(from,0,mGraph[from].size()-1, weight); } // use after add all edges int bipartite_matching(int x, int y){ int start = max(x,y)*2; int end = max(x,y)*2 + 1 ; for(int i = 0; i < x; ++i) add_edge(start, i, 1); for(int i = 0; i < y; ++i) add_edge(i+x, end, 1); return max_flow(start,end); } // verify : GRL_7_A // ford-fulkerson int dfs(int v, int t, int f){ if(v==t) return f; mUsed[v] = true; for(auto &e : mGraph[v]){ if(!mUsed[e.to] && e.cap > 0){ int d = dfs(e.to,t,min(f,e.cap)); if(d > 0){ e.cap -= d; mGraph[e.to][e.rev].cap += d; return d; } } } return 0; } int max_flow(int s,int t){ int flow = 0; while(true){ mUsed.assign(mVert,false); int f = dfs(s,t,INF); if(f==0) break; flow += f; } return flow; } // verify : GRL_6_A // min_cost_flow int min_cost_flow(int s, int t, int f){ int res = 0; vector<int> prevv(mVert); vector<int> preve(mVert); while(f > 0){ // bellman_ford vector<int> dst(mVert,INF); dst[s] = 0; for(int i = 0; i < mVert; ++i){ if(dst[i] == INF) continue; for(int j = 0; j < mGraph[i].size(); ++j){ auto e = mGraph[i][j]; if(e.cap > 0 && dst[e.to] > dst[i]+e.weight){ dst[e.to] = dst[i] + e.weight; prevv[e.to] = i; preve[e.to] = j; } } } if(dst[t] == INF) return -1; // 経路を後ろから辿り、流せる最大容量を確定 int d = f; for(int i = t; i != s; i = prevv[i]){ d = min(d, mGraph[prevv[i]][preve[i]].cap); } f -= d; res += d * dst[t]; // 流す for(int i = t; i != s; i = prevv[i]){ Edge &e = mGraph[prevv[i]][preve[i]]; e.cap -= d; mGraph[i][e.rev].cap += d; } } return res; } private: Graph mGraph; vector<bool> mUsed; int mVert; }; int main(){ int V,E,F,u,v,c,d; cin >> V >> E >> F; Flow f(V); for(int i=0; i < E; ++i){ cin >> u >> v >> c >> d; f.add_edge(u,v,c,d); } cout << f.min_cost_flow(0,V-1,F) << '\n'; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; static const int MAX_V = 110; static const int INF = (1 << 30); struct edge { int to, cap, cost, rev; }; int V; vector<edge> G[MAX_V]; int h[MAX_V], dist[MAX_V], prevv[MAX_V], preve[MAX_V]; void add_edge(int from, int to, int cap, int cost) { G[from].push_back((edge){to, cap, cost, (int)G[to].size()}); G[to].push_back((edge){from, 0, -cost, (int)G[from].size() - 1}); } int min_cost_flow(int s, int t, int f) { int res = 0; fill(h, h + V, 0); while (f > 0) { priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > que; fill(dist, dist + V, INF); dist[s] = 0; que.push(pair<int, int>(0, s)); while (!que.empty()) { pair<int, int> p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; for (int i = 0; i < G[v].size(); ++i) { edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(pair<int, int>(dist[e.to], e.to)); } } } if (dist[t] == INF) return -1; for (int v = 0; v < V; ++v) h[v] += dist[v]; int d = f; for (int v = t; v < s; v = prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap); f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main(int argc, char const *argv[]) { int E, F; cin >> V >> E >> F; for (int i = 0; i < E; ++i) { int s, t, c, d; cin >> s >> t >> c >> d; add_edge(s, t, c, d); } cout << min_cost_flow(0, V - 1, F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
UNKNOWN
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MinimumCostFlow { class Edge : IComparable { internal int from, to, cap, cost; public Edge(int from, int to) { this.from = from; this.to = to; } public Edge(int u, int v, int c, int d) { from = u; to = v; cap = c; cost = d; } public int CompareTo(object obj) { Edge e = obj as Edge; return e.cost - cost; } } class MinimumCostFlow { readonly int n, INFTY = int.MaxValue / 2; Dictionary<int, List<Edge>> G; public MinimumCostFlow(int V) { n = V; G = new Dictionary<int, List<Edge>>(); for (int i = 0; i < n; i++) G.Add(i, new List<Edge>()); } public void AddEdge(int from, int to, int cap, int cost) { G[from].Add(new Edge(from, to, cap, cost)); G[to].Add(new Edge(to, from, 0, -cost)); } public int Solve(int s, int t, int F) { int[,] capacity = new int[n, n]; int[,] cost = new int[n, n]; int[,] flow = new int[n, n]; for (int i = 0; i < n; i++) { foreach (var e in G[i]) { int u = e.from; int v = e.to; capacity[u, v] = e.cap; cost[u, v] = e.cost; } } int ret = 0; int[] h = new int[n]; while (F > 0) { int[] d = Enumerable.Repeat(INFTY, n).ToArray(); int[] p = Enumerable.Repeat(-1, n).ToArray(); d[s] = 0; PriorityQueue<Edge> que = new PriorityQueue<Edge>(); ???// "e < f" <=> "e.cost > f.cost" que.Enqueue(new Edge(-2, s)); while (que.Count > 0) { Edge e = que.Dequeue(); if (p[e.to] != -1) continue; p[e.to] = e.from; foreach (var u in G[e.to]) { if (capacity[u.from, u.to] - flow[u.from, u.to] > 0) { if (d[u.to] > d[u.from] + cost[u.from, u.to] + h[u.from] - h[u.to]) { d[u.to] = d[u.from] + cost[u.from, u.to] + h[u.from] - h[u.to]; que.Enqueue(new Edge(u.from, u.to, 0, d[u.to])); } } } } if (p[t] == -1) return -1; int f = F; for (int u = t; u != s; u = p[u]) { f = Math.Min(f, capacity[p[u], u] - flow[p[u], u]); } for (int u = t; u != s; u = p[u]) { ret += f * cost[p[u], u]; flow[p[u], u] += f; flow[u, p[u]] -= f; } F -= f; for (int u = 0; u < n; u++) h[u] += d[u]; } return ret; } } class PriorityQueue<T> where T : IComparable { List<T> heap; int size; public PriorityQueue() { heap = new List<T>(); } public void Enqueue(T x) { heap.Add(x); int i = size++; while (i > 0) { int p = (i - 1) / 2; if (Compare(heap[p], x) <= 0) break; heap[i] = heap[p]; i = p; } heap[i] = x; } public T Dequeue() { T ret = heap[0]; T x = heap[--size]; int i = 0; while (i * 2 + 1 < size) { int a = i * 2 + 1; int b = i * 2 + 2; if (b < size && Compare(heap[b], heap[a]) < 0) a = b; if (Compare(heap[a], x) >= 0) break; heap[i] = heap[a]; i = a; } heap[i] = x; heap.RemoveAt(size); return ret; } public int Count { get { return size; } } private int Compare(T x, T y) { return y.CompareTo(x); } } class Program { static void Main(string[] args) { string[] input = Console.ReadLine().Split(' '); int V = int.Parse(input[0]); int E = int.Parse(input[1]); int F = int.Parse(input[2]); MinimumCostFlow MCF = new MinimumCostFlow(V); for (int i = 0; i < E; i++) { input = Console.ReadLine().Split(' '); int u = int.Parse(input[0]); int v = int.Parse(input[1]); int c = int.Parse(input[2]); int d = int.Parse(input[3]); MCF.AddEdge(u, v, c, d); } Console.WriteLine(MCF.Solve(0, V - 1, F)); } } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const int maxN = 1100; bool mark[maxN]; int parentEdge[maxN], dis[maxN]; int n, k, m, st, fn, F, remFlow; struct edge { int u, v, weight, cap; }; vector<int> g[maxN]; edge e[maxN * maxN]; int curID = 0; edge make_edge(int u, int v, int w, int cap) { edge e; e.u = u; e.v = v; e.weight = w; e.cap = cap; return e; } void input() { cin >> n >> m >> F; for (int i = 1; i <= m; i++) { int k1, k2, w, cap; cin >> k1 >> k2; k1++; k2++; cin >> cap >> w; e[curID] = make_edge(k1, k2, w, cap); g[k1].push_back(curID++); } } int extract_min() { int ret = 0; for (int i = 1; i <= n; i++) if (!mark[i] && dis[i] < dis[ret]) ret = i; return ret; } void update(int v) { mark[v] = true; for (auto ID : g[v]) if (dis[e[ID].v] > dis[v] + e[ID].weight && e[ID].cap > 0) { parentEdge[e[ID].v] = ID; dis[e[ID].v] = dis[v] + e[ID].weight; } } pair<int, int> dijkstra(int v = st) { int pushed = remFlow; int cost = 0; fill(dis, dis + n + 1, INT_MAX / 2); memset(mark, 0, (n + 10) * sizeof(mark[0])); memset(parentEdge, -1, (n + 10) * sizeof(parentEdge[0])); dis[v] = 0; while (int v = extract_min()) { update(v); } if (!mark[fn]) return {0, 0}; v = fn; while (parentEdge[v] != -1) { pushed = min(pushed, e[parentEdge[v]].cap); v = e[parentEdge[v]].u; } v = fn; while (parentEdge[v] != -1) { cost += pushed * e[parentEdge[v]].weight; e[parentEdge[v]].cap -= pushed; e[parentEdge[v] ^ 1].cap += pushed; v = e[parentEdge[v]].u; } return {pushed, cost}; } int MinCostMaxFlow() { int flow = 0, cost = 0; remFlow = F; while (true) { auto ans = dijkstra(); if (ans.first == 0) break; flow += ans.first; remFlow -= ans.first; cost += ans.second; } return cost; } void show() { for (int i = 0; i < curID; i++) { auto ed = e[i]; cout << i << " " << ed.u << " " << ed.v << " " << ed.cap << " " << ed.weight << endl; } } int main() { input(); st = 1; fn = n; int cost = MinCostMaxFlow(); if (remFlow > 0) cout << -1 << endl; else cout << cost << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; namespace MCF { const int MAXN = 120; const int MAXM = 2100; int to[MAXM]; int next[MAXM]; int first[MAXN]; int c[MAXM]; long long w[MAXM]; long long pot[MAXN]; int rev[MAXM]; long long ijk[MAXN]; int v[MAXN]; long long toc; int tof; int n; int m; void init(int _n) { n = _n; for (int i = 0; i < n; i++) first[i] = -1; } void ae(int a, int b, int cap, int wei) { next[m] = first[a]; to[m] = b; first[a] = m; c[m] = cap; w[m] = wei; m++; next[m] = first[b]; to[m] = a; first[b] = m; c[m] = 0; w[m] = -wei; m++; } int solve(int s, int t, int flo) { toc = tof = 0; while (tof < flo) { for (int i = 0; i < n; i++) ijk[i] = 9999999999999LL; for (int i = 0; i < n; i++) v[i] = 0; priority_queue<pair<int, int> > Q; ijk[s] = 0; Q.push(make_pair(0, s)); while (Q.size()) { int cost = -Q.top().first; int at = Q.top().second; Q.pop(); if (v[at]) continue; v[at] = 1; for (int i = first[at]; ~i; i = next[i]) { int x = to[i]; if (v[x] || ijk[x] <= ijk[at] + w[i] + pot[x] - pot[at]) continue; if (c[i] == 0) continue; ijk[x] = ijk[at] + w[i] + pot[x] - pot[at]; rev[x] = i; Q.push(make_pair(-ijk[x], x)); } } int flow = flo - tof; if (!v[t]) return 0; int at = t; while (at != s) { flow = min(flow, c[rev[at]]); at = to[rev[at] ^ 1]; } at = t; tof += flow; toc += flow * (ijk[t] + pot[s] - pot[t]); at = t; while (at != s) { c[rev[at]] -= flow; c[rev[at] ^ 1] += flow; at = to[rev[at] ^ 1]; } for (int i = 0; i < n; i++) pot[i] += ijk[i]; } return 1; } } // namespace MCF int main() { int a, b, c; scanf("%d%d%d", &a, &b, &c); MCF::init(a); for (int i = 0; i < b; i++) { int p, q, r, s; scanf("%d%d%d%d", &p, &q, &r, &s); MCF::ae(p, q, r, s); } int res = MCF::solve(0, a - 1, c); if (!res) printf("-1\n"); else printf("%lld\n", MCF::toc); }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template <class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return 1; } return 0; } template <class A, size_t N, class T> void Fill(A (&a)[N], const T &v) { fill((T *)a, (T *)(a + N), v); } const int INF = 1 << 29; struct Edge { int src, dst; int weight, cap; int rev; Edge(int src, int dst, int weight = 0, int cap = 0, int rev = -1) : src(src), dst(dst), weight(weight), cap(cap), rev(rev) {} }; struct Node : public vector<Edge> {}; bool operator<(const Edge &a, const Edge &b) { return a.weight < b.weight; } bool operator>(const Edge &a, const Edge &b) { return b < a; } void add_edge(vector<Node> &G, int src, int dst, int cap, int cost) { G[src].push_back(Edge(src, dst, cost, cap, G[dst].size())); G[dst].push_back(Edge(dst, src, -cost, 0, G[src].size() - 1)); } int min_cost_flow(vector<Node> &G, int s, int t, int f) { int res = 0; int V = G.size(); vector<int> h(V, 0); vector<int> prevv(V); vector<int> preve(V); if (s == t) return 0; bool start = true; while (f > 0) { vector<int> dist(V, INF); if (start) { bool update = true; dist[s] = 0; while (update) { update = false; for (int v = 0; v < (V); v++) { if (dist[v] == INF) continue; for (int i = 0; i < (G[v].size()); i++) { Edge &e = G[v][i]; if (e.cap > 0 && dist[e.dst] > dist[v] + e.weight) { dist[e.dst] = dist[v] + e.weight; prevv[e.dst] = v; preve[e.dst] = i; update = true; } } } } start = 0; } else { priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > que; dist[s] = 0; que.push(pair<int, int>(0, s)); while (!que.empty()) { pair<int, int> p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; for (int i = 0; i < (int)G[v].size(); i++) { Edge &e = G[v][i]; if (e.cap > 0 && dist[e.dst] > dist[v] + e.weight + h[v] - h[e.dst]) { dist[e.dst] = dist[v] + e.weight + h[v] - h[e.dst]; prevv[e.dst] = v; preve[e.dst] = i; que.push(pair<int, int>(dist[e.dst], e.dst)); } } } } if (dist[t] == INF) { return -1; } for (int v = 0; v < V; v++) h[v] += dist[v]; int d = f; for (int v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { Edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main() { int V, E, F; cin >> V >> E >> F; vector<Node> g(V + 1); for (int i = 0; i < (E); i++) { int u, v, c, d; cin >> u >> v >> c >> d; add_edge(g, u, v, c, d); } auto ans = min_cost_flow(g, 0, V - 1, F); cout << ans << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<map> #include<set> #include<utility> #include<cmath> #include<cstring> #include<queue> #include<cstdio> #include<sstream> #define loop(i,a,b) for(int i=a;i<b;i++) #define rep(i,a) loop(i,0,a) #define pb push_back #define mp make_pair #define all(in) in.begin(),in.end() const double PI=acos(-1); const double EPS=1e-10; const int inf=1e9; using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pii; struct edge{ int to,cap,cost,rev; }; typedef vector<edge> ve; typedef vector<ve> vve; class MCF{ //Minimum Cost Flow public: int n; vve G; vi h,dist,prev,pree; MCF(int size){ n=size; G=vve(n); h=dist=prev=pree=vi(n); } void add_edge(int s,int t,int ca,int co){ edge e={t,ca,co,G[t].size()}; G[s].pb(e); edge ee={s,0,-co,G[s].size()-1}; G[t].pb(ee); } int mcf(int s,int t,int f){ int out=0; h=vi(n); while(f>0){ priority_queue<pii,vector<pii> >q; dist=vi(n,inf); dist[s]=0; q.push(pii(0,s)); while(!q.empty()){ pii p=q.top();q.pop(); int v=p.second; if(dist[v]<-p.first)continue; rep(i,G[v].size()){ edge &e=G[v][i]; if(e.cap>0&&dist[e.to]>dist[v]+e.cost+h[v]-h[e.to]){ dist[e.to]=dist[v]+e.cost+h[v]-h[e.to]; prev[e.to]=v; pree[e.to]=i; // cout<<" "<<dist[e.to]<<endl; q.push(pii(-dist[e.to],e.to)); } } } // rep(i,n)dist[i]*=-1; // rep(i,n)cout<<dist[i]<<endl; if(dist[t]==inf)return -1; rep(i,n)h[i]+=dist[i]; int d=f; for(int v=t;v!=s;v=prev[v])d=min(d,G[prev[v]][pree[v]].cap); f-=d; out+=d*h[t]; for(int v=t;v!=s;v=prev[v]){ edge &e=G[prev[v]][pree[v]]; e.cap-=d; G[v][e.rev].cap+=d; } // cout<<f<<endl; } return out; } }; int main(){ int n,m,f; cin>>n>>m>>f; MCF mcf(n); while(m--){ int a,b,c,d; cin>>a>>b>>c>>d; mcf.add_edge(a,b,c,d); } cout<<mcf.mcf(0,n-1,f); }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct edge { i64 from; i64 to; i64 cap; i64 cost; i64 rev; }; i64 INF = 1e8; i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g, std::vector<i64> b) { i64 ans = 0; i64 U = *std::max_element(begin(b), end(b)); i64 delta = (1 << ((int)(std::log2(U)) + 1)); int n = g.size(); std::vector<i64> e = b; std::vector<i64> p(n, 0); int zero = 0; for (auto x : e) { if (x == 0) zero++; } for (; delta > 0; delta >>= 1) { if (zero == n) break; for (int s = 0; s < n; s++) { if (!(e[s] >= delta)) continue; std::vector<std::size_t> pv(n, -1); std::vector<std::size_t> pe(n, -1); std::vector<i64> dist(n, 1e18); using P = std::pair<i64, i64>; std::priority_queue<P, std::vector<P>, std::greater<P>> que; dist[s] = 0; que.push({dist[s], s}); while (!que.empty()) { int v = que.top().second; i64 d = que.top().first; que.pop(); if (dist[v] < d) continue; for (std::size_t i = 0; i < g[v].size(); i++) { const auto& e = g[v][i]; std::size_t u = e.to; i64 ccc = e.cost + p[v] - p[u]; if (e.cap == 0) ccc = INF; assert(ccc >= 0); if (dist[u] > dist[v] + ccc) { dist[u] = dist[v] + ccc; pv[u] = v; pe[u] = i; que.push({dist[u], u}); } } } for (int i = 0; i < n; i++) { p[i] += dist[i]; } int t = 0; for (; t < n; t++) { if (!(e[s] >= delta)) break; if (e[t] <= -delta && pv[t] != -1) { std::size_t u = t; for (; pv[u] != -1; u = pv[u]) { ans += delta * g[pv[u]][pe[u]].cost; g[pv[u]][pe[u]].cap -= delta; g[u][g[pv[u]][pe[u]].rev].cap += delta; } e[u] -= delta; e[t] += delta; if (e[u] == 0) zero++; if (e[t] == 0) zero++; } } } } if (zero == n) return ans; else return -1e18; } int main() { i64 N, M, F; cin >> N >> M >> F; vector<vector<edge>> g(N + M); vector<i64> e(N + M, 0); int s = 0; int t = N - 1; e[s + M] = F; e[t + M] = -F; for (int i = 0; i < M; i++) { i64 a, b, c, d; cin >> a >> b >> c >> d; e[i] = c; e[a + M] -= c; g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()}); g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1}); g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()}); g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1}); } i64 ans = capacity_scaling_bflow(g, e); if (ans == -1e18) { cout << -1 << endl; } else { cout << ans << endl; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
java
import java.io.*; import java.util.*; public class Main implements Runnable{ private ArrayList<ArrayList<Integer>> graph; private Edge[] edges; public static void main(String[] args) throws Exception { new Thread(null, new Main(), "bridge", 16 * 1024 * 1024).start(); } @Override public void run() { try { solve(); } catch (Exception e) { e.printStackTrace(); } } private void solve() throws Exception{ FastScanner scanner = new FastScanner(System.in); int V = scanner.nextInt(); int E = scanner.nextInt(); int F = scanner.nextInt(); graph = new ArrayList<>(V); edges = new Edge[E * 2]; for(int i = 0; i < V; ++i){ graph.add(new ArrayList<Integer>()); } int edgeSize = 0; for(int i = 0; i < E; ++i){ int u = scanner.nextInt(); int v = scanner.nextInt(); int cap = scanner.nextInt(); int cost = scanner.nextInt(); edges[edgeSize++] = new Edge(v, 0, cap, cost); edges[edgeSize++] = new Edge(u, 0, 0, -cost); graph.get(u).add(edgeSize - 2); graph.get(v).add(edgeSize - 1); } costOfMaxFlow(F, 0, V - 1); } private void costOfMaxFlow(int F, int s, int t){ int V = graph.size(); int[] dist = new int[V]; int[] curFlow = new int[V]; int[] prevNode = new int[V]; int[] prevEdge = new int[V]; int totalFlow = 0; int totalCost = 0; while(totalFlow < F){ BellmanFord(s, dist, prevNode, prevEdge, curFlow); if(dist[t] == Integer.MAX_VALUE){ break; } int pathFlow = Math.min(curFlow[t], F - totalFlow); totalFlow += pathFlow; for(int v = t; v != s; v = prevNode[v]){ Edge edge = edges[prevEdge[v]]; totalCost += edge.cost * pathFlow; edge.flow += pathFlow; edges[prevEdge[v] ^ 1].flow -= pathFlow; } } if(totalFlow < F){ System.out.println("-1"); } else{ System.out.println(totalCost); } } private void BellmanFord(int s, int[] dist, int[] prevNode, int[] prevEdge, int[] curFlow){ Arrays.fill(dist, Integer.MAX_VALUE); dist[s] = 0; curFlow[s] = Integer.MAX_VALUE; prevNode[s] = -1; prevEdge[s] = -1; LinkedList<Integer> queue = new LinkedList<>(); queue.add(s); boolean[] visited = new boolean[dist.length]; while(!queue.isEmpty()){ Integer u = queue.poll(); if(visited[u]){ continue; } visited[u] = true; for(int edgeIndex : graph.get(u)){ Edge edge = edges[edgeIndex]; if(edge.flow >= edge.cap){ continue; } if(dist[edge.v] > dist[u] + edge.cost){ dist[edge.v] = dist[u] + edge.cost; prevNode[edge.v] = u; prevEdge[edge.v] = edgeIndex; curFlow[edge.v] = Math.min(curFlow[u], edge.cap - edge.flow); queue.add(edge.v); } } } } static class Edge{ int v; int flow; int cap; int cost; public Edge(int v, int flow, int cap, int cost){ this.v = v; this.flow = flow; this.cap = cap; this.cost = cost; } } static class FastScanner { private InputStream in; private final byte[] buffer = new byte[1024 * 8]; private int ptr = 0; private int buflen = 0; public FastScanner(InputStream in){ this.in = in; } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const int maxN = 1100; bool mark[maxN]; int parentEdge[maxN], dis[maxN]; int n, k, m, st, fn, F, remFlow; struct edge { int u, v, weight, cap; }; vector<int> g[maxN]; edge e[maxN * maxN]; int curID = 0; edge make_edge(int u, int v, int w, int cap) { edge e; e.u = u; e.v = v; e.weight = w; e.cap = cap; return e; } void input() { cin >> n >> m >> F; for (int i = 1; i <= m; i++) { int k1, k2, w, cap; cin >> k1 >> k2; k1++; k2++; cin >> cap >> w; e[curID] = make_edge(k1, k2, w, cap); g[k1].push_back(curID++); e[curID] = make_edge(k2, k1, -w, 0); g[k2].push_back(curID++); } } int extract_min() { int ret = 0; for (int i = 1; i <= n; i++) if (!mark[i] && dis[i] < dis[ret]) ret = i; return ret; } void update(int v) { mark[v] = true; for (auto ID : g[v]) if (dis[e[ID].v] > dis[v] + e[ID].weight && e[ID].cap > 0) { parentEdge[e[ID].v] = ID; dis[e[ID].v] = dis[v] + e[ID].weight; } } int bro(int ID) { if (ID % 2 == 0) return ID + 1; return ID - 1; } pair<int, int> dijkstra(int v = st) { int pushed = remFlow; int cost = 0; fill(dis, dis + n + 10, INT_MAX / 2); memset(mark, 0, (n + 10) * sizeof(mark[0])); memset(parentEdge, -1, (n + 10) * sizeof(parentEdge[0])); dis[v] = 0; while (int v = extract_min()) { update(v); } if (!mark[fn]) return {0, 0}; v = fn; while (parentEdge[v] != -1) { pushed = min(pushed, e[parentEdge[v]].cap); v = e[parentEdge[v]].u; } v = fn; while (parentEdge[v] != -1) { cost += pushed * e[parentEdge[v]].weight; e[parentEdge[v]].cap -= pushed; e[bro(parentEdge[v])].cap += pushed; v = e[parentEdge[v]].u; } return {pushed, cost}; } int MinCostMaxFlow() { int flow = 0, cost = 0; remFlow = F; while (true) { auto ans = dijkstra(); if (ans.first == 0) break; flow += ans.first; remFlow -= ans.first; cost += ans.second; } return cost; } void show() { for (int i = 0; i < curID; i++) { auto ed = e[i]; cout << i << " " << ed.u << " " << ed.v << " " << ed.cap << " " << ed.weight << endl; } } int main() { input(); st = 1; fn = n; int cost = MinCostMaxFlow(); if (remFlow > 0) cout << -1 << endl; else cout << cost << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
python3
v_num, e_num, flow = (int(n) for n in input().split(" ")) edges = defaultdict(list) for _ in range(e_num): s1, t1, cap, cost = (int(n) for n in input().split(" ")) edges[s1].append([t1, cap, cost, len(edges[t1])]) edges[t1].append([s1, cap, cost, len(edges[s1])]) answer = 0 before_vertice = [float("inf") for n in range(v_num)] before_edge = [float("inf") for n in range(v_num)] sink = v_num - 1 while True: distance = [float("inf") for n in range(v_num)] distance[0] = 0 updated = 1 while updated: updated = 0 for v in range(v_num): if distance[v] == float("inf"): continue for i, (target, cap, cost, trace_i) in enumerate(edges[v]): if cap > 0 and distance[target] > distance[v] + cost: distance[target] = distance[v] + cost before_vertice[target] = v before_edge[target] = i updated = 1 if distance[sink] == float("inf"): print(-1) break decreased = flow trace_i = sink while trace_i != 0: decreased = min(decreased, edges[before_vertice[trace_i]][before_edge[trace_i]][1]) trace_i = before_vertice[trace_i] flow -= decreased answer += decreased * distance[sink] trace_i = sink while trace_i != 0: this_edge = edges[before_vertice[trace_i]][before_edge[trace_i]] this_edge[1] -= decreased trace_i = before_vertice[trace_i] edges[trace_i][this_edge[3]][1] += decreased if flow <= 0: print(answer) break
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; struct Edge { Edge(int arg_to, int arg_capacity, int arg_cost, int arg_rev_index) { to = arg_to; capacity = arg_capacity; cost = arg_cost; rev_index = arg_rev_index; } int to, capacity, cost, rev_index; }; int V; vector<Edge> G[100]; int h[100]; int dist[100]; int pre_node[100], pre_edge[100]; void add_edge(int from, int to, int capacity, int cost) { G[from].push_back(Edge(to, capacity, cost, G[to].size())); G[to].push_back(Edge(from, 0, -cost, G[from].size() - 1)); } int min_cost_flow(int source, int sink, int flow) { int ret = 0; for (int i = 0; i < V; i++) h[i] = 0; while (flow > 0) { priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> Q; for (int i = 0; i < V; i++) dist[i] = 2000000000; dist[source] = 0; Q.push(pair<int, int>(0, source)); while (!Q.empty()) { pair<int, int> p = Q.top(); Q.pop(); int node_id = p.second; if (dist[node_id] < p.first) continue; for (int i = 0; i < G[node_id].size(); i++) { Edge &e = G[node_id][i]; if (e.capacity > 0 && dist[e.to] > dist[node_id] + e.cost + h[node_id] - h[e.to]) { dist[e.to] = dist[node_id] + e.cost + h[node_id] - h[e.to]; pre_node[e.to] = node_id; pre_edge[e.to] = i; Q.push(pair<int, int>(dist[e.to], e.to)); } } } if (dist[sink] == 2000000000) { return -1; } for (int node_id = 0; node_id < V; node_id++) h[node_id] += dist[node_id]; int tmp_flow = flow; for (int node_id = sink; node_id != source; node_id = pre_node[node_id]) { tmp_flow = min(tmp_flow, G[pre_node[node_id]][pre_edge[node_id]].capacity); } flow -= tmp_flow; ret += tmp_flow * h[sink]; for (int node_id = sink; node_id != source; node_id = pre_node[node_id]) { Edge &e = G[pre_node[node_id]][pre_edge[node_id]]; e.capacity -= tmp_flow; G[node_id][e.rev_index].capacity += tmp_flow; } } return ret; } int main() { int E, F; scanf("%d %d %d", &V, &E, &F); int from, to, capacity, cost; for (int loop = 0; loop < E; loop++) { scanf("%d %d %d %d", &from, &to, &capacity, &cost); add_edge(from, to, capacity, cost); } printf("%d\n", min_cost_flow(0, V - 1, F)); return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include<vector> #include<queue> #include<algorithm> #define MAX 101 #define inf 1<<29 using namespace std; typedef pair<int,int> P; struct edge{ int to,cap,cost,rev; }; int v; vector<edge> e[MAX]; int h[MAX]; int dist[MAX]; int prevv[MAX],preve[MAX]; void add_edge(int from,int to,int cap,int cost){ e[from].push_back((edge){to,cap,cost,e[to].size()}); e[to].push_back((edge){from,0,-cost,e[from].size()-1}); } int min_cost_flow(int s,int t,int f){ int res=0; fill(h,h+v,0); while(f>0){ priority_queue<P,vector<P>,greater<P> > pq; fill(dist,dist+v,inf); dist[s]=0; pq.push(P(0,s)); while(pq.size()){ P p=pq.top(); pq.pop(); int u=p.second; if(dist[u]<p.first)continue; for(int i=0;i<e[u].size();i++){ edge &E=e[u][i]; if(E.cap>0 && dist[E.to]>dist[u]+E.cost+h[u]-h[E.to]){ dist[E.to]=dist[u]+E.cost+h[u]-h[E.to]; prevv[E.to]=u; preve[E.to]=i; pq.push(P(dist[E.to],E.to)); } } } if(dist[t]==inf)return -1; for(int i=0;i<v;i++)h[i]+=dist[i]; int d=f; for(int u=t;u!=s;u=prevv[u]){ d=min(d,e[prevv[u]][preve[u]].cap); } f-=d; res+=d*h[t]; for(int u=t;u!=s;u=prevv[u]){ edge &E=e[prevv[u]][preve[u]]; E.cap-=d; e[u][E.rev].cap+=d; } } return res; } int main() { int m,f,a,b,c,d; cin>>v>>m>>f; for(int i=0;i<m;i++){ cin>>a>>b>>c>>d; add_edge(a,b,c,d); } cout<<min_cost_flow(0,v-1,f)<<endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; template <typename T> class min_cost_flow { public: struct edge { int to, cap; T cost; int rev; }; using pti = pair<T, int>; vector<vector<edge> > G; vector<T> h, dist; vector<int> prevv, preve; T inf; int V; min_cost_flow(int node_size) { V = node_size; inf = numeric_limits<T>::max() / 100; G.resize(V), h.resize(V), dist.resize(V), prevv.resize(V), preve.resize(V); } void add_edge(int from, int to, int cap, T cost) { G[from].push_back((edge){to, cap, cost, (int)G[to].size()}); G[to].push_back((edge){from, 0, -cost, (int)G[from].size() - 1}); } T solve(int s, int t, int f) { T res = 0; fill(h.begin(), h.end(), 0); while (f > 0) { priority_queue<pti, vector<pti>, greater<pti> > que; fill(dist.begin(), dist.end(), inf); dist[s] = 0; que.push(pti(0, s)); while (!que.empty()) { pti p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) { continue; } for (int i = 0; i < (int)(G[v].size()); ++i) { edge& e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v, preve[e.to] = i; que.push(pti(dist[e.to], e.to)); } } } if (dist[t] == inf) { return -1; } for (int i = 0; i < (int)(V); ++i) { h[i] += dist[i]; } int d = f; for (int v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { edge& e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } }; int main() { int n, e, f; cin >> n >> e >> f; min_cost_flow<int> mc(n); for (int i = 0; i < (int)(e); ++i) { int u, v, c, d; cin >> u >> v >> c >> d; mc.add_edge(u, v, c, d); } cout << mc.solve(0, n - 1, f) << "\n"; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
ああ
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; typedef struct { int to, cap, cost, rev; } Edge; class MinCostFlow { private: int V; vector<vector<Edge>> G; public: MinCostFlow(int V) : V(V) { G.resize(V); } void add_edge(int u, int v, int c, int d) { G[u].push_back({v, c, d, (int)G[v].size()}); G[v].push_back({u, 0, -d, (int)G[u].size() - 1}); } int solve(int s, int t, int f) { int res = 0; while (f > 0) { vector<int> d(V, INF); vector<int> pars(V, -1); vector<int> eids(V, -1); d[s] = 0; bool updated = true; while (updated) { updated = false; for (int v = 0; v < V; v++) if (d[v] != INF) { for (int i = 0; i < G[v].size(); i++) { auto edge = G[v][i]; if (edge.cap == 0) continue; if (d[edge.to] > d[v] + edge.cost) { d[edge.to] = d[v] + edge.cost; pars[edge.to] = v; eids[v] = i; updated = true; } } } } if (d[t] == INF) return -1; int mc = INF; int p = t; while (true) { p = pars[p]; if (p == -1) break; mc = min(mc, G[p][eids[p]].cap); } res += mc * d[t]; f -= mc; } return res; } }; int V, E, F; int main() { cin >> V >> E >> F; MinCostFlow mcf(V); for (int i = 0; i < E; i++) { int u, v, c, d; cin >> u >> v >> c >> d; mcf.add_edge(u, v, c, d); } cout << mcf.solve(0, V - 1, F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using LL = long long; constexpr LL LINF = 334ll << 53; constexpr int INF = 15 << 26; constexpr LL MOD = 1E9 + 7; class MinimumCostFlow { struct Edge { int to; long long cost, capacity; int rev_id; Edge(int to, long long cost, long long cap, int id) : to(to), cost(cost), capacity(cap), rev_id(id){}; Edge() { Edge(0, 0, 0, 0); } }; struct Prev { LL cost; int from, id; }; using Graph = vector<vector<Edge>>; using Flow = vector<vector<long long>>; int n; Graph graph; Flow flow; vector<Prev> prev; vector<long long> potential; public: MinimumCostFlow(int n) : n(n), graph(n), flow(n, vector<long long>(n)), prev(n, {LINF, -1, -1}), potential(n) {} void addEdge(int a, int b, long long cap, long long cost) { graph[a].emplace_back(b, cost, cap, (int)graph[b].size()); graph[b].emplace_back(a, -cost, 0, (int)graph[a].size() - 1); } long long minimumCostFlow(int s, int t, LL f) { LL ret = 0; for (bellman_ford(s); f > 0; dijkstra(s)) { if (prev[t].cost == LINF) return -1; for (int i = 0; i < n; ++i) potential[i] = min(potential[i] + prev[i].cost, LINF); LL d = f; for (int v = t; v != s; v = prev[v].from) { d = min(d, graph[prev[v].from][prev[v].id].capacity - flow[prev[v].from][v]); } f -= d; ret += d * potential[t]; for (int v = t; v != s; v = prev[v].from) { flow[prev[v].from][v] += d; flow[v][prev[v].from] -= d; } } return ret; } private: bool dijkstra(const int start) { int visited = 0, N = graph.size(); fill(prev.begin(), prev.end(), (Prev){LINF, -1, -1}); priority_queue<tuple<LL, int, int, int>, vector<tuple<LL, int, int, int>>, greater<tuple<LL, int, int, int>>> pque; pque.emplace(0, start, 0, -1); LL cost; int place, from, id; while (!pque.empty()) { tie(cost, place, from, id) = pque.top(); pque.pop(); if (prev[place].from != -1) continue; prev[place] = {cost, from, id}; visited++; if (visited == N) return true; for (int i = 0; i < (int)graph[place].size(); ++i) { auto e = &graph[place][i]; if (e->capacity > flow[place][e->to] && prev[e->to].from == -1) { pque.emplace(e->cost + cost - potential[e->to] + potential[place], e->to, place, i); } } } return false; } bool bellman_ford(const int start) { int s = graph.size(); bool update = false; prev[start] = (Prev){0ll, start, -1}; for (int i = 0; i < s; ++i, update = false) { for (int j = 0; j < s; ++j) { int k = 0; for (auto &e : graph[j]) { if (e.capacity == 0) continue; if (prev[j].cost != LINF && prev[e.to].cost > prev[j].cost + e.cost) { prev[e.to].cost = prev[j].cost + e.cost; prev[e.to].from = j; prev[e.to].id = k; update = true; if (i == s - 1) return false; } ++k; } } if (!update) break; } return true; } }; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, m; LL flow; cin >> n >> m >> flow; MinimumCostFlow mcf(n); for (int i = 0; i < m; i++) { int a, b; LL cost, cap; cin >> a >> b >> cap >> cost; mcf.addEdge(a, b, cap, cost); } cout << mcf.minimumCostFlow(0, n - 1, flow) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using Int = int64_t; using UInt = uint64_t; using C = std::complex<double>; template <typename T> using RQ = std::priority_queue<T, std::vector<T>, std::greater<T>>; int main() { Int v, e, f; std::cin >> v >> e >> f; std::vector<Int> ss(e + 1), ts(e + 1), cs(e + 1), fs(e + 1), bs(e + 1); for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { Int a, b, c, d; std::cin >> a >> b >> c >> d; ss[i] = a, ts[i] = b, cs[i] = d, fs[i] = 0, bs[i] = c; } std::vector<std::vector<Int>> es(v); for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { Int s = ss[i], t = ts[i]; es[s].emplace_back(i); es[t].emplace_back(-i); } Int res = 0; Int source = 0, sink = v - 1; while (f > 0) { RQ<std::pair<Int, Int>> q; q.emplace(0, source); std::vector<Int> ps(v, -1), xs(v, -1), ys(v); ys[source] = f; while (not q.empty()) { Int d, s; std::tie(d, s) = q.top(); q.pop(); for (Int i : es[s]) { Int k = std::abs(i); Int t = i > 0 ? ts[k] : ss[k]; Int tf = i > 0 ? bs[k] : fs[k]; if (not(tf > 0)) continue; ; if (not(xs[t] == -1 or xs[t] > xs[s] + cs[k])) continue; ; xs[t] = xs[s] + cs[k]; ps[t] = i; ys[t] = std::min(ys[s], tf); q.emplace(xs[s] + cs[k], t); } } Int tf = ys[sink]; if (false) fprintf(stderr, "tf = %ld\n", tf); f -= tf; if (f > 0 and tf == 0) { res = -1; break; } for (Int i = sink, k = ps[i]; i != source; i = k > 0 ? ss[k] : ts[k], k = ps[i]) { Int ak = std::abs(k); res += tf * cs[ak]; if (k > 0) { fs[ak] += tf; bs[ak] -= tf; } else { fs[ak] -= tf; bs[ak] += tf; } } if (f == 0) break; for (Int i = (Int)(1); i < (Int)(e + 1); ++i) { if (false) fprintf(stderr, "%ld -> %ld : cost=%ld : ->=%ld : <-=%ld\n", ss[i], ts[i], cs[i], fs[i], bs[i]); } } printf("%ld\n", res); }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
UNKNOWN
#include <bits/stdc++.h> struct node { int id; int cap; int cost; struct node *next; }; struct node **list; int **flow, *dist, *prev, *preve, *h; int *heap, *heap_index, heapsize; void Insert(int, int, int, int); void downheap(int); void upheap(int); void PQ_init(int); int PQ_remove(void); void PQ_update(int); int Maxflow(int, int, int); int main(void) { int i, v, e, f, s, t, c, d, mincost = 0; scanf("%d %d %d", &v, &e, &f); list = (struct node **)malloc(sizeof(struct node *) * v); flow = (int **)malloc(sizeof(int *) * v); dist = (int *)malloc(sizeof(int) * v); prev = (int *)malloc(sizeof(int) * v); preve = (int *)malloc(sizeof(int) * v); h = (int *)calloc(v, sizeof(int)); for (i = 0; i < v; i++) { list[i] = NULL; flow[i] = (int *)calloc(v, sizeof(int)); } for (i = 0; i < e; i++) { scanf("%d %d %d %d", &s, &t, &c, &d); Insert(s, t, c, d); } while (f > 0 && Maxflow(0, v - 1, v)) { int n, delta = f; for (n = v - 1; n != 0; n = prev[n]) { delta = ((delta) < (preve[n] - flow[prev[n]][n]) ? (delta) : (preve[n] - flow[prev[n]][n])); } f -= delta; for (n = v - 1; n != 0; n = prev[n]) { flow[prev[n]][n] += delta; flow[n][prev[n]] -= delta; } for (i = 0; i < v; i++) h[i] = dist[i]; } if (f == 0) { for (i = 0; i < v; i++) { struct node *n; for (n = list[i]; n != NULL; n = n->next) { if (n->cap > 0) mincost += flow[i][n->id] * n->cost; } } printf("%d\n", mincost); } else printf("-1\n"); for (i = 0; i < v; i++) { free(list[i]); free(flow[i]); } free(list); free(flow); free(dist); free(prev); free(preve); free(h); } void Insert(int a, int b, int cap, int cost) { struct node *p = (struct node *)malloc(sizeof(struct node)); p->id = b; p->cap = cap; p->cost = cost; p->next = list[a]; list[a] = p; p = (struct node *)malloc(sizeof(struct node)); p->id = a; p->cap = 0; p->cost = -cost; p->next = list[b]; list[b] = p; } void downheap(int k) { int j, v = heap[k]; while (k < heapsize / 2) { j = 2 * k + 1; if (j < heapsize - 1 && dist[heap[j]] > dist[heap[j + 1]]) j++; if (dist[v] <= dist[heap[j]]) break; heap[k] = heap[j]; heap_index[heap[j]] = k; k = j; } heap[k] = v; heap_index[v] = k; } void upheap(int j) { int k, v = heap[j]; while (j > 0) { k = (j + 1) / 2 - 1; if (dist[v] >= dist[heap[k]]) break; heap[j] = heap[k]; heap_index[heap[k]] = j; j = k; } heap[j] = v; heap_index[v] = j; } void PQ_init(int size) { int i; heapsize = size; heap = (int *)malloc(sizeof(int) * size); heap_index = (int *)malloc(sizeof(int) * size); for (i = 0; i < size; i++) { heap[i] = i; heap_index[i] = i; } for (i = heapsize / 2 - 1; i >= 0; i--) downheap(i); } int PQ_remove(void) { int v = heap[0]; heap[0] = heap[heapsize - 1]; heap_index[heap[heapsize - 1]] = 0; heapsize--; downheap(0); return v; } void PQ_update(int v) { upheap(heap_index[v]); } int Maxflow(int s, int t, int size) { struct node *n; int i; for (i = 0; i < size; i++) { dist[i] = INT_MAX; prev[i] = -1; preve[i] = -1; } dist[s] = 0; PQ_init(size); while (heapsize) { i = PQ_remove(); if (dist[i] == INT_MAX) break; for (n = list[i]; n != NULL; n = n->next) { int v = n->id; if (flow[i][v] < n->cap) { int newlen = dist[i] + n->cost + h[i] - h[v]; if (newlen < dist[v]) { dist[v] = newlen; prev[v] = i; preve[v] = n->cap; PQ_update(v); } } } } free(heap); free(heap_index); return dist[t] != INT_MAX; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 105; struct Edge { int from, to, cap, flow, cost; Edge(int u, int v, int c, int f, int w) : from(u), to(v), cap(c), flow(f), cost(w) {} }; int n, m, tf; vector<Edge> edges; vector<int> G[maxn]; bool inq[maxn]; int d[maxn]; int a[maxn]; int p[maxn]; inline void addedge(int u, int v, int c, int w) { edges.push_back(Edge(u, v, c, 0, w)); edges.push_back(Edge(v, u, 0, 0, -w)); int id = edges.size() - 2; G[u].push_back(id); G[v].push_back(id + 1); } inline bool spfa(int s, int t, int& flow, int& cost) { for (int i = 0; i < n; i++) d[i] = INF; d[s] = 0; inq[s] = 1; a[s] = INF; queue<int> q; q.push(s); while (q.size()) { int u = q.front(); q.pop(); inq[u] = 0; for (int id : G[u]) { Edge& e = edges[id]; if (e.cap > e.flow && d[e.to] > d[u] + e.cost) { d[e.to] = d[u] + e.cost; p[e.to] = id; a[e.to] = min(a[u], e.cap - e.flow); if (!inq[e.to]) { inq[e.to] = 1; q.push(e.to); } } } } if (d[t] == INF) return 0; flow += a[t]; cost += d[t] * a[t]; for (int u = t; u != s; u = edges[p[u]].from) { edges[p[u]].flow += a[t]; edges[p[u] ^ 1].flow -= a[t]; } return 1; } inline int mcmf(int s, int t) { int flow = 0, cost = 0; while (spfa(s, t, flow, cost) && flow < tf) ; if (flow) return cost; else return -1; } int main() { cin >> n >> m >> tf; for (int i = 0; i < m; i++) { int u, v, c, w; cin >> u >> v >> c >> w; addedge(u, v, c, w); } cout << mcmf(0, n - 1) << '\n'; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; struct edge { int to, cap, cost, rev; }; int V; vector<edge> G[100]; vector<int> h(100); int dist[100]; int prevv[100], preve[100]; void add_edge(int from, int to, int cap, int cost) { G[from].push_back((edge){to, cap, cost, (int)G[to].size()}); G[to].push_back((edge){from, 0, -cost, (int)G[from].size() - 1}); } int shortest_path(int s, vector<int> &d) { int v = d.size(); for (long long i = 0; i < (long long)(d.size()); i++) d[i] = (1e9 + 1); d[s] = 0; for (long long loop = 0; loop < (long long)(v); loop++) { bool update = false; for (long long i = 0; i < (long long)(100); i++) { for (auto e : G[i]) { if (d[i] != (1e9 + 1) && d[e.to] > d[i] + e.cost) { d[e.to] = d[i] + e.cost; update = true; } } } if (!update) break; if (loop == v - 1) return true; } return false; } int min_cost_flow(int s, int t, int f) { int res = 0; for (long long i = 0; i < (long long)(h.size()); i++) h[i] = 0; shortest_path(s, h); bool times = 0; while (f > 0) { if (times > 0) { priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > que; fill(dist, dist + V, (1e9 + 1)); dist[s] = 0; que.push(pair<int, int>(0, s)); while (!que.empty()) { pair<int, int> p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(pair<int, int>(dist[e.to], e.to)); } } } } times++; if (dist[t] == (1e9 + 1)) return -1; for (int v = 0; v < V; v++) h[v] += dist[v]; int d = f; for (int v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main() { int e, f; cin >> V >> e >> f; for (long long i = 0; i < (long long)(e); i++) { int u, v, c, d; cin >> u >> v >> c >> d; add_edge(u, v, c, d); } cout << min_cost_flow(0, V - 1, f) << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const int MAX = 100; const int INF = 1 << 25; class edge { public: int to, cap, cost, rev; edge() {} edge(int to, int cop, int cost, int rev) : to(to), cap(cap), cost(cost), rev(rev) {} }; int V; vector<edge> G[MAX]; int h[MAX]; int dist[MAX]; int prevv[MAX], preve[MAX]; int col[MAX]; void add_edge(int from, int to, int cap, int cost) { G[from].push_back(edge(to, cap, cost, G[to].size())); G[to].push_back(edge(from, 0, -cost, G[from].size() - 1)); return; } int mincostflow(int s, int t, int f) { int res = 0; for (int i = 0; i < V; i++) h[i] = 0; while (f > 0) { priority_queue<pair<int, int> > Q; for (int i = 0; i < V; i++) { dist[i] = INF; col[i] = 0; } dist[s] = 0; Q.push(pair<int, int>(0, s)); col[s] = 1; while (!Q.empty()) { pair<int, int> p = Q.top(); Q.pop(); int v = p.second; col[v] = 2; if (dist[v] < p.first * (-1)) continue; for (int i = 0; i < G[v].size(); i++) { edge e = G[v][i]; if (col[e.to] == 2) continue; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; Q.push(pair<int, int>(dist[e.to] * (-1), e.to)); col[e.to] = 1; } } } if (dist[t] == INF) return -1; for (int v = 0; v < V; v++) { h[v] += dist[v]; } int d = f; for (int v = t; v != s; v = prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap); f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { edge e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main() { cin >> V; int E, F; cin >> E >> F; int u, v, c, d; for (int i = 0; i < E; i++) { cin >> u >> v >> c >> d; add_edge(u, v, c, d); } cout << mincostflow(0, V - 1, F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
python2
''' import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import sys import csv import argparse import time ''' import heapq INF = sys.maxint/3 class Edge: def __init__(self, to, cap, cost, rev): self.to = to self.cap = cap self.cost = cost self.rev = rev def print_attributes(self): print "to: {0}, cap: {1}, cost: {2}, rev: {3}".format(self.to, self.cap, self.cost, self.rev) class MinimumCostFlow: def __init__(self, V, E): self.V = V self.E = E self.G = [[] for i in range(V)] def add_edge(self, s, t, cap, cost): forward_edge = Edge(t, cap, cost, len(self.G[t])) self.G[s].append(forward_edge) backward_edge = Edge(s, 0, -cost, len(self.G[s])-1) self.G[t].append(backward_edge) def print_edges(self): print "==== print edges ====" for i in range(self.V): print "\nedges from {}".format(i) for e in self.G[i]: e.print_attributes() def minimum_cost_flow(self, s, t, f): res = 0 h = [0] * self.V while f>0: pque = [] dist = [INF for i in range(self.V)] prev_v = [0 for i in range(self.V)] prev_e = [0 for i in range(self.V)] dist[s] = 0 heapq.heappush(pque, (0, s)) while(len(pque)!=0): p = heapq.heappop(pque) v = p[1] if (dist[v] < p[0]): continue for i in range(len(self.G[v])): e = self.G[v][i] if (e.cap>0 and dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]): dist[e.to] = dist[v] + e.cost + h[v] - h[e.to] prev_v[e.to] = v prev_e[e.to] = i heapq.heappush(pque, (dist[e.to], e.to)) if dist[t] == INF: return -1 for v in range(self.V): h[v] += dist[v] d = f v = t while v!=s: d = min(d, self.G[prev_v[v]][prev_e[v]].cap) v = prev_v[v] f -= d res += d * h[t] v = t while v!=s: e = self.G[prev_v[v]][prev_e[v]] e.cap -= d self.G[v][e.rev].cap += d v = prev_v[v] return res def main(): V, E, F = map(int, raw_input().split()) mcf = MinimumCostFlow(V, E) for i in range(E): u, v, c, d = map(int, raw_input().split()) mcf.add_edge(u, v, c, d) #print "minimum cost flow: {}".format(mcf.minimum_cost_flow(0, V-1, F)) print mcf.minimum_cost_flow(0, V-1, F) if __name__ == '__main__': main()
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; int v, e; vector<pair<int, int> > adj[110], revadj[110]; int capacity[1010], cost[1010], flowingthrough[1010], dis[110], pre[110], preedge[110], endofedge[1010]; void bellmanford() { fill_n(dis, v, 1e9); dis[0] = 0; for (int i = 0; i < v; i++) { for (auto e : adj[i]) { if (flowingthrough[e.second] != capacity[e.second]) { if (dis[e.first] > dis[i] + cost[e.second]) { dis[e.first] = dis[i] + cost[e.second]; pre[e.first] = i; preedge[e.first] = e.second; } } } for (auto e : revadj[i]) { if (flowingthrough[e.second]) { if (dis[e.first] > dis[i] - cost[e.second]) { dis[e.first] = dis[i] - cost[e.second]; pre[e.first] = i; preedge[e.first] = e.second; } } } } } pair<int, int> mincostmaxflow() { int ans = 0; int totalcost = 0; while (1) { bellmanford(); if (dis[v - 1] == 1e9) break; ans++; int a = v - 1; while (a) { int e = preedge[a]; if (endofedge[e] == a) capacity[e]--, totalcost += cost[e]; else capacity[e]++, totalcost -= cost[e]; a = pre[a]; } } return {ans, totalcost}; } int f; int main() { scanf("%d%d%d", &v, &e, &f); for (int i = 0; i < e; i++) { int a, b; scanf("%d%d%d%d", &a, &b, &capacity[i], &cost[i]); endofedge[i] = b; adj[a].emplace_back(b, i); revadj[b].emplace_back(a, i); } adj[v - 1].emplace_back(v, e); cost[e] = 0; endofedge[e] = v; capacity[e] = f; v++; auto ans = mincostmaxflow(); if (ans.first != f) printf("-1\n"); else printf("%d\n", ans.second); }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
python3
from heapq import heappop, heappush def trace(source, edge_trace): v = source for i in edge_trace: e = edges[v][i] yield e v = e[1] def min_cost_flow(source, sink, required_flow): res = 0 while required_flow: dist = [-1] * n queue = [(0, source, tuple())] edge_trace = None while queue: total_cost, v, edge_memo = heappop(queue) if dist[v] != -1: continue dist[v] = total_cost if v == sink: edge_trace = edge_memo break for i, (remain, target, cost, _) in enumerate(edges[v]): if remain and dist[target] == -1: heappush(queue, (total_cost + cost, target, edge_memo + (i,))) if dist[sink] == -1: return -1 aug = min(e[0] for e in trace(source, edge_trace)) required_flow -= aug res += aug * dist[sink] for e in trace(source, edge_trace): remain, target, cost, idx = e e[0] -= aug edges[target][idx][0] += aug return res n, m, f = map(int, input().split()) edges = [[] for _ in range(n)] for _ in range(m): s, t, c, d = map(int, input().split()) es, et = edges[s], edges[t] ls, lt = len(es), len(et) es.append([c, t, d, lt]) et.append([0, s, d, ls]) print(min_cost_flow(0, n - 1, f))
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
python3
from collections import defaultdict v_num, e_num, flow = (int(n) for n in input().split(" ")) edges = defaultdict(list) for _ in range(e_num): s1, t1, cap, cost = (int(n) for n in input().split(" ")) edges[s1].append([t1, cap, cost, len(edges[t1])]) edges[t1].append([s1, cap, cost, len(edges[s1])]) answer = 0 before_vertice = [float("inf") for n in range(v_num)] before_edge = [float("inf") for n in range(v_num)] sink = v_num - 1 while True: distance = [float("inf") for n in range(v_num)] distance[0] = 0 updated = 1 while updated: updated = 0 for v in range(v_num): if distance[v] == float("inf"): continue for i, (target, cap, cost, trace_i) in enumerate(edges[v]): if cap > 0 and distance[target] > distance[v] + cost: distance[target] = distance[v] + cost before_vertice[target] = v before_edge[target] = i updated = 1 if distance[sink] == float("inf"): print(-1) break decreased = flow trace_i = sink while trace_i != 0: decreased = min(decreased, edges[before_vertice[trace_i]][before_edge[trace_i]][1]) trace_i = before_vertice[trace_i] flow -= decreased answer += decreased * distance[sink] trace_i = sink while trace_i != 0: this_edge = edges[before_vertice[trace_i]][before_edge[trace_i]] this_edge[1] -= decreased trace_i = before_vertice[trace_i] edges[trace_i][this_edge[3]][1] += decreased if flow <= 0: print(answer) break
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const long long int INF = 2000000000; struct edge { int to, cap, cost, rev; edge(int t, int ca, int co, int re) { to = t; cap = ca; cost = co; rev = re; } }; vector<edge> G[40]; int prv[40], pre[40], d[40]; int v, e, flow; void addedge(int from, int to, int cap, int cost) { G[from].push_back(edge(to, cap, cost, G[to].size())); G[to].push_back(edge(from, 0, -cost, G[from].size() - 1)); } int minimumcost(int s, int t, int f) { int res = 0; while (f > 0) { fill(d, d + v, INF); d[s] = 0; bool ud = true; while (ud) { ud = false; for (int i = 0; i < v; i++) { if (d[i] == INF) continue; for (int j = 0; j < G[i].size(); j++) { edge &e = G[i][j]; if (e.cap > 0 && d[e.to] > d[i] + e.cost) { d[e.to] = d[i] + e.cost; prv[e.to] = i; pre[e.to] = j; ud = true; } } } } if (d[t] == INF) return -1; int dis = f; for (int w = t; w != s; w = prv[w]) { dis = min(dis, G[prv[w]][pre[w]].cost); } f -= dis; for (int w = t; w != s; w = prv[w]) { G[prv[w]][pre[w]].cap -= dis; G[w][G[prv[w]][pre[w]].rev].cap += dis; } res += dis * d[t]; } return res; } int main() { cin >> v >> e >> flow; for (int i = 0; i < e; i++) { int s, t, c, d; cin >> s >> t >> c >> d; addedge(s, t, c, d); } cout << minimumcost(0, v - 1, flow) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; template <typename T, typename U> struct min_cost_flow_graph { struct edge { int from, to; T cap, f; U cost; }; vector<edge> edges; vector<vector<int>> g; int n, st, fin; T required_flow, flow; U cost; min_cost_flow_graph(int n, int st, int fin, T required_flow) : n(n), st(st), fin(fin), required_flow(required_flow) { assert(0 <= st && st < n && 0 <= fin && fin < n && st != fin); g.resize(n); flow = 0; cost = 0; } void clear_graph() { for (const edge &e : edges) { e.f = 0; } flow = 0; cost = 0; } void add(int from, int to, T cap = 1, T rev_cap = 0, U cost = 1) { assert(0 <= from && from < n && 0 <= to && to < n); g[from].emplace_back(edges.size()); edges.push_back({from, to, cap, 0, cost}); g[to].emplace_back(edges.size()); edges.push_back({to, from, rev_cap, 0, -cost}); } U min_cost_flow() { while (flow < required_flow) { T dist[n]; fill(dist, dist + n, numeric_limits<T>::max()); dist[st] = 0; int prevv[n], preve[n]; for (bool update = true; update;) { update = false; for (int id = 0; id < edges.size(); id++) { edge &e = edges[id]; if (0 < e.cap - e.f && dist[e.from] + e.cost < dist[e.to]) { dist[e.to] = dist[e.from] + e.cost; prevv[e.to] = e.from; preve[e.to] = id; update = true; } } } if (dist[fin] == numeric_limits<T>::max()) { return -1; } T d = numeric_limits<U>::max(); for (int v = fin; v != st; v = prevv[v]) { d = min(d, edges[preve[v]].cap - edges[preve[v]].f); } flow += d; cost += d * dist[fin]; for (int v = fin; v != st; v = prevv[v]) { edges[preve[v]].f += d; edges[preve[v] ^ 1].f -= d; } } return cost; } }; int main() { int n, m, f; cin >> n >> m >> f; min_cost_flow_graph<int, int> g(n, 0, n - 1, f); for (int i = 0; i < m; i++) { int from, to, cap, cost; cin >> from >> to >> cap >> cost; g.add(from, to, cap, 0, cost); } cout << g.min_cost_flow() << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; constexpr int INF = 1e9; struct Edge { int to, cap, rev, weight; Edge(int t, int c, int r, int w) : to(t), cap(c), rev(r), weight(w) {} }; using Edges = vector<Edge>; using Graph = vector<Edges>; class Flow { public: Flow(int v) { mGraph.resize(v); mUsed.assign(v, false); mVert = v; } void add_edge(int from, int to, int cap, int weight = 1) { mGraph[from].emplace_back(to, cap, mGraph[to].size(), weight); mGraph[to].emplace_back(from, 0, mGraph[from].size() - 1, weight); } int bipartite_matching(int x, int y) { int start = max(x, y) * 2; int end = max(x, y) * 2 + 1; for (int i = 0; i < x; ++i) add_edge(start, i, 1); for (int i = 0; i < y; ++i) add_edge(i + x, end, 1); return max_flow(start, end); } int dfs(int v, int t, int f) { if (v == t) return f; mUsed[v] = true; for (auto &e : mGraph[v]) { if (!mUsed[e.to] && e.cap > 0) { int d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; mGraph[e.to][e.rev].cap += d; return d; } } } return 0; } int max_flow(int s, int t) { int flow = 0; while (true) { mUsed.assign(mVert, false); int f = dfs(s, t, INF); if (f == 0) break; flow += f; } return flow; } int min_cost_flow(int s, int t, int f) { int res = 0; vector<int> prevv(mVert); vector<int> preve(mVert); while (f > 0) { vector<int> dst(mVert, INF); dst[s] = 0; while (true) { bool update = false; for (int i = 0; i < mVert; ++i) { if (dst[i] == INF) continue; for (int j = 0; j < mGraph[i].size(); ++j) { auto e = mGraph[i][j]; if (e.cap > 0 && dst[e.to] > dst[i] + e.weight) { dst[e.to] = dst[i] + e.weight; prevv[e.to] = i; preve[e.to] = j; update = true; } } } if (!update) break; } if (dst[t] == INF) return -1; int d = f; for (int i = t; i != s; i = prevv[i]) { d = min(d, mGraph[prevv[i]][preve[i]].cap); } f -= d; res += d * dst[t]; for (int i = t; i != s; i = prevv[i]) { Edge &e = mGraph[prevv[i]][preve[i]]; e.cap -= d; mGraph[i][e.rev].cap += d; } } return res; } private: Graph mGraph; vector<bool> mUsed; int mVert; }; int main() { int V, E, F, u, v, c, d; cin >> V >> E >> F; Flow f(V); for (int i = 0; i < E; ++i) { cin >> u >> v >> c >> d; f.add_edge(u, v, c, d); } cout << f.min_cost_flow(0, V - 1, F) << '\n'; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
java
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; @SuppressWarnings("unchecked") class MinCostFlow{ class Edge{ int to,cap,cost,rev; Edge(int to,int cap,int cost,int rev){this.to=to;this.cap=cap;this.cost=cost;this.rev=rev;} } List<Edge> edges[]; void add_edge(int from,int to,int cap,int cost){ edges[from].add(new Edge(to,cap,cost,edges[to].size())); edges[to].add(new Edge(from,0,-cost,edges[from].size()-1)); } int[] dis; int[] h; int[] prevv; Edge[] preve; MinCostFlow(int V){ edges = new ArrayList[V]; dis =new int[V]; h = new int[V]; prevv=new int[V]; preve=new Edge[V]; for(int i=0;i<V;++i)edges[i]=new ArrayList<>(); } int get(int s,int t,int f){ int res = 0; class Node{ int v,cost; Node(int v,int cost){this.v=v;this.cost=cost;} } Arrays.fill(h,0); while(f>0){ Arrays.fill(dis, Integer.MAX_VALUE); dis[s]=0; PriorityQueue<Node> que = new PriorityQueue<>((a,b)->a.cost-b.cost); que.add(new Node(s,0)); while(!que.isEmpty()){ Node node = que.poll(); if(dis[node.v]<node.cost)continue; for(Edge e : edges[node.v])if(dis[node.v]+e.cost + (h[e.to]-h[node.v]) <dis[e.to] && e.cap>0){ dis[e.to] = dis[node.v]+e.cost + (h[e.to]-h[node.v]); prevv[e.to]=node.v; preve[e.to]=e; que.add(new Node(e.to, dis[e.to])); } } for(int i=0;i<h.length;++i)System.out.print(dis[i]+" "); System.out.println(); if(dis[t]==Integer.MAX_VALUE)return -1; for(int i=0;i<h.length;++i)h[i] -= dis[i]; int d = f; for(int v=t;v!=s;v=prevv[v])d=Math.min(d, preve[v].cap); res += d * -h[t]; f-=d; for(int v=t;v!=s;v=prevv[v]){ preve[v].cap-=d; edges[v].get(preve[v].rev).cap+=d; } } return res; } public static void main(String[] args){ Scanner scan = new Scanner(System.in); int V = scan.nextInt(); int E = scan.nextInt(); int F = scan.nextInt(); MinCostFlow mcf = new MinCostFlow(V); while(E-->0){ int u = scan.nextInt(); int v = scan.nextInt(); int c = scan.nextInt(); int d = scan.nextInt(); mcf.add_edge(u, v, c, d); } System.out.println(mcf.get(0,V-1,F)); } } class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int V = scan.nextInt(); int E = scan.nextInt(); int F = scan.nextInt(); MinCostFlow mcf = new MinCostFlow(V); while(E-->0){ int u = scan.nextInt(); int v = scan.nextInt(); int c = scan.nextInt(); int d = scan.nextInt(); mcf.add_edge(u, v, c, d); } System.out.println(mcf.get(0,V-1,F)); } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
python3
from heapq import heappop, heappush def trace(source, edge_trace): v = source for i in edge_trace: e = edges[v][i] yield e v = e[1] def min_cost_flow(source, sink, required_flow): res = 0 while required_flow: visited = set() queue = [(0, source, tuple())] while queue: total_cost, v, edge_memo = heappop(queue) if v in visited: continue elif v == sink: dist = total_cost edge_trace = edge_memo break visited.add(v) for i, (remain, target, cost, _) in enumerate(edges[v]): if remain and target not in visited: heappush(queue, (total_cost + cost, target, edge_memo + (i,))) else: return -1 aug = min(required_flow, min(e[0] for e in trace(source, edge_trace))) required_flow -= aug res += aug * dist for e in trace(source, edge_trace): remain, target, cost, idx = e e[0] -= aug edges[target][idx][0] += aug return res n, m, f = map(int, input().split()) edges = [[] for _ in range(n)] for _ in range(m): s, t, c, d = map(int, input().split()) es, et = edges[s], edges[t] ls, lt = len(es), len(et) es.append([c, t, d, lt]) et.append([0, s, d, ls]) print(min_cost_flow(0, n - 1, f))
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; class Edge { public: int from; int to; int flow; Edge(int f, int t, int d) { from = f; to = t; flow = d; } }; class Shortest_path_result { public: int sum_of_cost; vector<int> path; vector<int> distance; vector<int> predecessor; Shortest_path_result() {} }; class Graph { public: int INF; int n; vector<set<int> > vertices_list; vector<map<int, int> > cost_list; vector<map<int, int> > capacity_list; vector<int> potential_list; Graph() {} Graph(int n) { INF = 1e9; this->n = n; vertices_list.insert(vertices_list.begin(), n, set<int>()); cost_list.insert(cost_list.begin(), n, map<int, int>()); capacity_list.insert(capacity_list.begin(), n, map<int, int>()); potential_list = vector<int>(n, 0); } void insert_edge(int b, int e, int cost, int capacity) { vertices_list[b].insert(e); cost_list[b][e] = cost; capacity_list[b][e] = capacity; } void delete_edge(int b, int e) { vertices_list[b].erase(e); cost_list[b].erase(e); capacity_list[b].erase(e); } int degree_of_vertex(int a) { return vertices_list[a].size(); } bool edge_search(int a, int b) { return vertices_list[a].find(b) != vertices_list[a].end(); } bool path_search(int a, int b, set<int> visited = set<int>()) { visited.insert(a); set<int>::iterator itr; for (itr = vertices_list[a].begin(); itr != vertices_list[a].end(); itr++) { if ((*itr) == b) { return true; } if (visited.find(*itr) == visited.end()) { if (path_search(*itr, b, visited)) { return true; } } } return false; } Shortest_path_result solve_dijkstra(int start, int goal) { set<int> visited = set<int>(); vector<int> distance = vector<int>(n, INF); vector<int> predecessor = vector<int>(n); priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; pq.push(pair<int, int>(0, start)); while (!pq.empty()) { pair<int, int> p = pq.top(); pq.pop(); int nv = p.second; if (distance[nv] < p.first) { continue; } distance[nv] = p.first; for (set<int>::iterator itr = vertices_list[nv].begin(); itr != vertices_list[nv].end(); itr++) { int next = (*itr); if (distance[next] > distance[nv] + cost_list[nv][next]) { distance[next] = distance[nv] + cost_list[nv][next]; predecessor[next] = nv; pq.push(pair<int, int>(distance[next], next)); } } } Shortest_path_result result; result.path = vector<int>(); result.path.push_back(goal); while (true) { int now = result.path.back(); int pre = predecessor[now]; result.path.push_back(pre); if (pre == start) { reverse(result.path.begin(), result.path.end()); break; } } result.sum_of_cost = distance[goal]; result.distance = distance; result.predecessor = predecessor; return result; } pair<int, vector<Edge> > solve_mincostflow(int s, int t, int flow_size) { vector<map<int, int> > flow_list = vector<map<int, int> >(n); vector<map<int, int> > origin_cost = cost_list; int sum_flow_cost = 0; while (flow_size > 0) { Shortest_path_result res; vector<int> path; int min_capa = INF; res = solve_dijkstra(s, t); if (res.sum_of_cost == INF) { sum_flow_cost = 0; break; } path = res.path; for (int i = 0; i < n; i++) { potential_list[i] = potential_list[i] - res.distance[i]; } vector<int>::iterator itr = path.begin(); itr++; for (; itr != path.end(); itr++) { if (min_capa > capacity_list[*(itr - 1)][*itr]) { min_capa = capacity_list[*(itr - 1)][*itr]; } } if (min_capa > flow_size) { min_capa = flow_size; } itr = path.begin(); itr++; for (; itr != path.end(); itr++) { if (flow_list[*(itr - 1)].find(*itr) == flow_list[*(itr - 1)].end()) { flow_list[*(itr - 1)][*itr] = min_capa; } else { flow_list[*(itr - 1)][*itr] += min_capa; } } flow_size = flow_size - min_capa; itr = path.begin(); for (itr++; itr != path.end(); itr++) { int capa, cost; int from, to; from = *(itr - 1); to = *itr; capa = capacity_list[from][to]; cost = cost_list[from][to]; delete_edge(from, to); if (capa - min_capa > 0) { insert_edge(from, to, cost, capa - min_capa); } insert_edge(to, from, -1 * cost, min_capa); } for (int b = 0; b > n; b++) { map<int, int>::iterator itr; for (itr = cost_list[b].begin(); itr != cost_list[b].end(); itr++) { (*itr).second = (*itr).second - potential_list[itr->first] + potential_list[b]; } } } for (int i = 0; i < n; i++) { map<int, int>::iterator itr; for (itr = flow_list[i].begin(); itr != flow_list[i].end(); itr++) { sum_flow_cost += origin_cost[i][itr->first] * itr->second; } } if (sum_flow_cost == 0) { cout << "-1" << endl; } else { cout << sum_flow_cost << endl; } return pair<int, vector<Edge> >(); } void print(void) { int i = 0; vector<set<int> >::iterator itr; set<int>::iterator itr_c; for (itr = vertices_list.begin(); itr != vertices_list.end(); itr++) { cout << i << ":"; for (itr_c = (*itr).begin(); itr_c != (*itr).end(); itr_c++) { cout << *itr_c << "(" << capacity_list[i][*itr_c] << ")" << ","; } i++; cout << endl; } } }; int main() { const int inf = 1e9; int v, e, flow; Graph g; cin >> v >> e >> flow; g = Graph(v); int from, to, cost, cap; for (int i = 0; i < e; i++) { cin >> from >> to >> cap >> cost; g.insert_edge(from, to, cost, cap); } g.solve_mincostflow(0, v - 1, flow); return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const long long INF = (1ll << 60); struct Edge { long long s, t, c, d, u; }; long long minCostFlow(vector<vector<Edge>> &G, long long s, long long t, long long F) { long long V = G.size(); long long cost = 0; while (F) { vector<long long> dist(V, INF); dist[s] = 0; vector<long long> prev(V), prevCap(V); for (long long i = 0; i < V - 1; i++) for (auto edges : G) for (Edge e : edges) { if (e.u < e.c) { if (dist[e.t] > dist[e.s] + e.d) { prev[e.t] = e.s; prevCap[e.t] = (e.c - e.u); dist[e.t] = dist[e.s] + e.d; } } if (0 < e.u) { if (dist[e.s] > dist[e.t] - e.d) { prev[e.s] = e.t; prevCap[e.s] = e.u; dist[e.s] = dist[e.t] - e.d; } } } if (dist[t] == INF) break; long long minCapacity = F; for (long long v = t; v != s; v = prev[v]) minCapacity = min(minCapacity, prevCap[v]); for (long long v = t; v != s; v = prev[v]) { for (Edge &e : G[prev[v]]) if (e.t == v) { e.u += minCapacity; cost += e.d * minCapacity; break; } else if (e.s == v) { e.u -= minCapacity; cost -= e.d * minCapacity; break; } } F -= minCapacity; } return cost; } int main() { long long V, E, F; cin >> V >> E >> F; vector<vector<Edge>> G(V); for (long long i = 0; i < E; i++) { Edge e; cin >> e.s >> e.t >> e.c >> e.d; e.u = 0; G[e.s].push_back(e); } cout << minCostFlow(G, 0, V - 1, F) << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
python3
from collections import defaultdict import sys sys.setrecursionlimit(200000) def dfs(source, used, all_weight, connect): max_weight = all_weight max_source = source used[source] = 1 for target, weight in connect[source]: if not used[target]: now_weight = all_weight + weight this_source, this_weight = dfs(target, used, now_weight, connect) if max_weight < this_weight: max_weight = this_weight max_source = this_source return [max_source, max_weight] vertice = int(input()) connect = defaultdict(list) for _ in range(vertice - 1): v1, v2, weight = (int(n) for n in input().split(" ")) connect[v1].append([v2, weight]) connect[v2].append([v1, weight]) answer = 0 start_v = 0 for i in range(2): used = [0 for n in range(vertice)] start_v, answer = dfs(start_v, used, 0, connect) print(answer)
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; namespace MCF { const int MAXN = 120; const int MAXM = 2100; int to[MAXM]; int next[MAXM]; int first[MAXN]; int c[MAXM]; int w[MAXM]; int pot[MAXN]; int rev[MAXM]; int ijk[MAXN]; int v[MAXN]; int toc; int tof; int n; int m; void init(int _n) { n = _n; for (int i = 0; i < n; i++) first[i] = -1; } void ae(int a, int b, int cap, int wei) { next[m] = first[a]; to[m] = b; first[a] = m; c[m] = cap; w[m] = wei; m++; next[m] = first[b]; to[m] = a; first[b] = m; c[m] = 0; w[m] = -wei; m++; } int solve(int s, int t, int flo) { toc = tof = 0; while (tof < flo) { for (int i = 0; i < n; i++) ijk[i] = 999999999; for (int i = 0; i < n; i++) v[i] = 0; priority_queue<pair<int, int> > Q; ijk[s] = 0; Q.push(make_pair(0, s)); while (Q.size()) { int cost = -Q.top().first; int at = Q.top().second; Q.pop(); if (v[at]) continue; v[at] = 1; for (int i = first[at]; ~i; i = next[i]) { int x = to[i]; if (v[x] || ijk[x] <= ijk[at] + w[i] + pot[x] - pot[at]) continue; if (c[i] == 0) continue; ijk[x] = ijk[at] + w[i] + pot[x] - pot[at]; rev[x] = i; Q.push(make_pair(-ijk[x], x)); } } int flow = flo - tof; if (!v[t]) return 0; int at = t; while (at != s) { flow = min(flow, c[rev[at]]); at = to[rev[at] ^ 1]; } at = t; tof += flow; toc += flow * (ijk[t] + pot[s] - pot[t]); at = t; while (at != s) { c[rev[at]] -= flow; c[rev[at] ^ 1] += flow; at = to[rev[at] ^ 1]; } for (int i = 0; i < n; i++) pot[i] += ijk[i]; } return 1; } } // namespace MCF int main() { int a, b, c; scanf("%d%d%d", &a, &b, &c); MCF::init(a); for (int i = 0; i < b; i++) { int p, q, r, s; scanf("%d%d%d%d", &p, &q, &r, &s); MCF::ae(p, q, r, s); } int res = MCF::solve(0, a - 1, c); if (!res) printf("-1\n"); else printf("%d\n", MCF::toc); }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC target("avx") using namespace std; template <typename T1, typename T2> ostream& operator<<(ostream& o, const pair<T1, T2> p) { o << "(" << p.first << ":" << p.second << ")"; return o; } template <typename iterator> inline size_t argmin(iterator begin, iterator end) { return distance(begin, min_element(begin, end)); } template <typename iterator> inline size_t argmax(iterator begin, iterator end) { return distance(begin, max_element(begin, end)); } template <typename T> T& maxset(T& to, const T& val) { return to = max(to, val); } template <typename T> T& minset(T& to, const T& val) { return to = min(to, val); } void bye(string s, int code = 0) { cout << s << endl; exit(0); } mt19937_64 randdev(8901016); inline long long int rand_range(long long int l, long long int h) { return uniform_int_distribution<long long int>(l, h)(randdev); } namespace { class MaiScanner { public: template <typename T> void input_integer(T& var) { var = 0; T sign = 1; int cc = getchar_unlocked(); for (; cc < '0' || '9' < cc; cc = getchar_unlocked()) if (cc == '-') sign = -1; for (; '0' <= cc && cc <= '9'; cc = getchar_unlocked()) var = (var << 3) + (var << 1) + cc - '0'; var = var * sign; } inline int c() { return getchar_unlocked(); } inline MaiScanner& operator>>(int& var) { input_integer<int>(var); return *this; } inline MaiScanner& operator>>(long long& var) { input_integer<long long>(var); return *this; } inline MaiScanner& operator>>(string& var) { int cc = getchar_unlocked(); for (; !(0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked()) ; for (; (0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked()) var.push_back(cc); return *this; } template <typename IT> void in(IT begin, IT end) { for (auto it = begin; it != end; ++it) *this >> *it; } }; } // namespace MaiScanner scanner; class Flow { public: size_t n; struct Arrow { int from, to; int left; int cap; Arrow(int from = 0, int to = 0, int w = 1) : from(from), to(to), left(w), cap(w) {} bool operator<(const Arrow& a) const { return (left != a.left) ? left < a.left : (left < a.left) | (cap < a.cap) | (from < a.from) | (to < a.to); } bool operator==(const Arrow& a) const { return (from == a.from) && (to == a.to) && (left == a.left) && (cap == a.cap); } }; vector<vector<int>> vertex_to; vector<vector<int>> vertex_from; vector<Arrow> arrows; Flow(int n) : n(n), vertex_to(n), vertex_from(n) {} void connect(int from, int to, int left) { vertex_to[from].push_back(arrows.size()); vertex_from[to].push_back(arrows.size()); arrows.emplace_back(from, to, left); } }; Flow::int minconstflow(Flow& graph, const vector<Flow::int>& cost, int i_source, int i_sink, Flow::int flow, Flow::int inf) { Flow::int result = 0; vector<Flow::int> ofs(graph.n); vector<Flow::int> dist(graph.n); static function<Flow::int(int, Flow::int)> _dfs = [&](int idx, Flow::int f) { if (idx == i_source) return f; for (int ei : graph.vertex_from[idx]) { auto& edge = graph.arrows[ei]; if (dist[edge.to] == dist[edge.from] + cost[ei] + ofs[edge.from] - ofs[edge.to]) { f = _dfs(edge.from, min(f, edge.left)); edge.left -= f; return f; } } return f; }; while (flow > 0) { fill(dist.begin(), dist.end(), inf); priority_queue<pair<Flow::int, int>> pq; pq.emplace(0, i_source); dist[i_source] = 0; while (!pq.empty()) { auto p = pq.top(); pq.pop(); Flow::int d = -p.first; int idx = p.second; if (dist[idx] < d) continue; for (int ei : graph.vertex_to[idx]) { auto edge = graph.arrows[ei]; if (0 < edge.left && dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to] < dist[edge.to]) { dist[edge.to] = dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to]; pq.emplace(-dist[edge.to], edge.to); } } } if (dist[i_sink] == inf) return -1; for (int i = 0; i < graph.n; ++i) ofs[i] += dist[i]; Flow::int z = _dfs(i_sink, flow); flow -= z; result += z * ofs[i_sink]; } return result; } long long int m, n, kei; int main() { long long int f; scanner >> n >> m >> f; Flow graph(n); vector<int> cost(m); for (auto i = 0ll; (i) < (m); ++(i)) { int u, v, c, d; scanner >> u >> v >> c >> d; graph.connect(u, v, c); cost[i] = d; } auto ans = minconstflow(graph, cost, 0, n - 1, f, (long long int)1e8); cout << ans << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct edge { i64 from; i64 to; i64 cap; i64 cost; i64 rev; }; i64 INF = 1e18; i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g, std::vector<i64> b) { i64 ans = 0; i64 U = *std::max_element(begin(b), end(b)); i64 delta = (1 << ((int)(std::log2(U)) + 1)); int n = g.size(); std::vector<i64> e = b; std::vector<i64> p(n, 1e8); int zero = 0; for (auto x : e) { if (x == 0) zero++; } for (; delta > 0; delta >>= 1) { if (zero == n) break; for (int s = 0; s < n; s++) { if (!(e[s] >= delta)) continue; std::vector<std::size_t> pv(n, -1); std::vector<std::size_t> pe(n, -1); std::vector<i64> dist(n, INF); using P = std::pair<i64, i64>; std::priority_queue<P, std::vector<P>, std::greater<P>> que; dist[s] = 0; que.push({dist[s], s}); while (!que.empty()) { int v = que.top().second; i64 d = que.top().first; que.pop(); if (dist[v] < d) continue; for (std::size_t i = 0; i < g[v].size(); i++) { const auto& e = g[v][i]; std::size_t u = e.to; if (e.cap == 0) { continue; } i64 ccc = e.cost + p[v] - p[u]; assert(ccc >= 0); if (dist[u] > dist[v] + ccc) { dist[u] = dist[v] + ccc; pv[u] = v; pe[u] = i; que.push({dist[u], u}); } } } for (int i = 0; i < n; i++) { if (pv[i] != -1) p[i] += dist[i] - p[s]; } p[s] += dist[s] - p[s]; int t = 0; for (; t < n; t++) { if (!(e[s] >= delta)) break; if (e[t] <= -delta && pv[t] != -1) { std::size_t u = t; for (; pv[u] != -1; u = pv[u]) { ans += delta * g[pv[u]][pe[u]].cost; g[pv[u]][pe[u]].cap -= delta; g[u][g[pv[u]][pe[u]].rev].cap += delta; } e[u] -= delta; e[t] += delta; if (e[u] == 0) zero++; if (e[t] == 0) zero++; } } } } for (int i = 0; i < n; i++) { } if (zero == n) return ans; else return -1e18; } int main() { i64 N, M, F; cin >> N >> M >> F; vector<vector<edge>> g(N + M); vector<i64> e(N + M, 0); int s = 0; int t = N - 1; e[s + M] = F; e[t + M] = -F; for (int i = 0; i < M; i++) { i64 a, b, c, d; cin >> a >> b >> c >> d; e[i] = c; e[a + M] -= c; g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()}); g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1}); g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()}); g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1}); } i64 ans = capacity_scaling_bflow(g, e); if (ans == -1e18) { cout << -1 << endl; } else { cout << ans << endl; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; namespace { template <class T> ostream& operator<<(ostream& os, const vector<T>& vs) { if (vs.empty()) return os << "[]"; auto i = vs.begin(); os << "[" << *i; for (++i; i != vs.end(); ++i) os << " " << *i; return os << "]"; } template <class T> istream& operator>>(istream& is, vector<T>& vs) { for (auto it = vs.begin(); it != vs.end(); it++) is >> *it; return is; } const int INF = 1 << 28; struct Edge { int from, to, cap, cost, rev; Edge() {} Edge(int from, int to, int cap, int cost, int rev = -1) : from(from), to(to), cap(cap), cost(cost), rev(rev) {} }; struct Graph { int V; vector<vector<Edge> > G; vector<bool> used; Graph(int V) : V(V) { G.clear(); G.resize(V); used.clear(); used.resize(V); } void addEdge(int from, int to, int cap, int cost) { G[from].push_back(Edge(from, to, cap, cost, G[to].size())); G[to].push_back(Edge(to, from, 0, -cost, int(G[from].size()) - 1)); } int minCostFlow(int from, int to, int flow) { vector<int> dist(V, INF); dist[from] = 0; vector<int> prevv(V), preve(V); int ret = 0; while (flow > 0) { fill(dist.begin(), dist.end(), INF); dist[from] = 0; bool update = true; while (update) { update = false; for (int v = 0; v < V; v++) { if (dist[v] == INF) continue; for (int i = 0; i < int(G[v].size()); i++) { auto& e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost) { dist[e.to] = dist[v] + e.cost; prevv[e.to] = v; preve[e.to] = i; update = true; } } } } if (dist[to] == INF) return -1; int d = flow; for (int v = to; v != from; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } flow -= d; ret += d * dist[to]; for (int v = to; v != from; v = prevv[v]) { Edge& e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return ret; } }; int V, E, F; Graph* g; void input() { cin >> V >> E >> F; g = new Graph(V); for (int i = 0; i < E; i++) { int from, to, cap, cost; cin >> from >> to >> cap >> cost; g->addEdge(from, to, cap, cost); } } void solve() { cout << g->minCostFlow(0, V - 1, F) << endl; } } // namespace int main() { input(); solve(); return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const long long MOD = 1000000007LL; const int inf = 1e9; const long long INF = 1e18; const int MAX_V = 100; struct edge { int to, cap, cost, rev; edge(int to, int cap, int cost, int rev) : to(to), cap(cap), cost(cost), rev(rev) {} }; vector<edge> G[MAX_V]; int h[MAX_V]; int dist[MAX_V]; int prevv[MAX_V], preve[MAX_V]; int V; void add_edge(int from, int to, int cap, int cost) { G[from].emplace_back(to, cap, cost, G[to].size()); G[to].emplace_back(from, 0, -cost, G[from].size() - 1); } int min_cost_flow(int s, int t, int f) { int res = 0; fill(h, h + V, 0); while (f > 0) { priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> que; fill(dist, dist + V, inf); dist[s] = 0; que.push(pair<int, int>(0, s)); while (!que.empty()) { pair<int, int> p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; for (int i = 0; i < G[v].size(); i++) { edge e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(pair<int, int>(dist[e.to], e.to)); } } } if (dist[t] == inf) return -1; for (int v = 0; v < V; v++) h[v] += dist[v]; int d = f; for (int v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main() { cin >> V; int E, F; cin >> E >> F; for (int i = 0; i < E; i++) { int u, v, c, d; cin >> u >> v >> c >> d; add_edge(u, v, c, d); } cout << min_cost_flow(0, V - 1, F) << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; constexpr int INF = 10000000; constexpr int MAX = 1000000; struct Edge { int to; int cap; int cost; int rev; Edge(int to, int cap, int cost, int rev) : to(to), cap(cap), cost(cost), rev(rev) {} }; int V, E, F; vector<Edge> G[MAX]; int h[MAX]; int dist[MAX]; int prevv[MAX], preve[MAX]; auto add_edge(int from, int to, int cap, int cost) -> void { G[from].push_back(Edge(to, cap, cost, G[to].size())); G[to].push_back(Edge(from, 0, -cost, G[to].size() - 1)); } auto min_cost_flow(int s, int t, int f) -> int { auto res = 0; fill(h, h + V, 0); while (f > 0) { priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> que; fill(dist, dist + V, INF); dist[s] = 0; que.push(pair<int, int>(0, s)); while (!que.empty()) { pair<int, int> p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; for (auto i = 0; i < G[v].size(); i++) { Edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(pair<int, int>(dist[e.to], e.to)); } } } if (dist[t] == INF) { return -1; } for (int v = 0; v < V; v++) { h[v] += dist[v]; } int d = f; for (auto v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d * h[t]; for (auto v = t; v != s; v = prevv[v]) { Edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } auto main(int argc, char const *argv[]) -> int { int n; cin >> V >> E >> F; for (auto i = 0; i < E; i++) { int u, v, c, d; cin >> u >> v >> c >> d; add_edge(u, v, c, d); } cout << min_cost_flow(0, V - 1, F) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; class Edge { public: int from; int to; int flow; Edge(int f, int t, int d) { from = f; to = t; flow = d; } }; class Shortest_path_result { public: int sum_of_cost; vector<int> path; vector<int> distance; vector<int> predecessor; Shortest_path_result() {} }; class Graph { public: int INF; int n; vector<set<int> > vertices_list; vector<map<int, int> > cost_list; vector<map<int, int> > capacity_list; vector<int> potential_list; Graph() {} Graph(int n) { INF = 1e9; this->n = n; vertices_list.insert(vertices_list.begin(), n, set<int>()); cost_list.insert(cost_list.begin(), n, map<int, int>()); capacity_list.insert(capacity_list.begin(), n, map<int, int>()); potential_list = vector<int>(n, 0); } void insert_edge(int b, int e, int cost, int capacity) { vertices_list[b].insert(e); cost_list[b][e] = cost; capacity_list[b][e] = capacity; } void delete_edge(int b, int e) { vertices_list[b].erase(e); cost_list[b].erase(e); capacity_list[b].erase(e); } int degree_of_vertex(int a) { return vertices_list[a].size(); } bool edge_search(int a, int b) { return vertices_list[a].find(b) != vertices_list[a].end(); } bool path_search(int a, int b, set<int> visited = set<int>()) { visited.insert(a); set<int>::iterator itr; for (itr = vertices_list[a].begin(); itr != vertices_list[a].end(); itr++) { if ((*itr) == b) { return true; } if (visited.find(*itr) == visited.end()) { if (path_search(*itr, b, visited)) { return true; } } } return false; } Shortest_path_result solve_dijkstra(int start, int goal) { set<int> visited = set<int>(); vector<int> distance = vector<int>(n, INF); vector<int> predecessor = vector<int>(n); priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; pq.push(pair<int, int>(0, start)); while (!pq.empty()) { pair<int, int> p = pq.top(); pq.pop(); int nv = p.second; if (distance[nv] < p.first) { continue; } distance[nv] = p.first; for (set<int>::iterator itr = vertices_list[nv].begin(); itr != vertices_list[nv].end(); itr++) { int next = (*itr); if (distance[next] > distance[nv] + cost_list[nv][next]) { distance[next] = distance[nv] + cost_list[nv][next]; predecessor[next] = nv; pq.push(pair<int, int>(distance[next], next)); } } } Shortest_path_result result; if (distance[goal] == INF) { } else { result.path = vector<int>(); result.path.push_back(goal); if (start != goal) { while (true) { int now = result.path.back(); int pre = predecessor[now]; result.path.push_back(pre); if (pre == start) { reverse(result.path.begin(), result.path.end()); break; } } } } result.path = vector<int>(); result.sum_of_cost = distance[goal]; result.distance = distance; result.predecessor = predecessor; return result; } pair<int, vector<Edge> > solve_mincostflow(int s, int t, int flow_size) { vector<map<int, int> > flow_list = vector<map<int, int> >(n); vector<map<int, int> > origin_cost = cost_list; bool feasible_flag = true; int sum_flow_cost = 0; while (flow_size > 0) { Shortest_path_result res; vector<int> path; int min_capa = INF; res = solve_dijkstra(s, t); cout << res.sum_of_cost << endl; if (res.sum_of_cost == INF) { feasible_flag = false; break; } path = res.path; for (int i = 0; i < n; i++) { potential_list[i] = potential_list[i] - res.distance[i]; } vector<int>::iterator itr = path.begin(); itr++; for (; itr != path.end(); itr++) { if (min_capa > capacity_list[*(itr - 1)][*itr]) { min_capa = capacity_list[*(itr - 1)][*itr]; } } if (min_capa > flow_size) { min_capa = flow_size; } itr = path.begin(); itr++; for (; itr != path.end(); itr++) { if (flow_list[*(itr - 1)].find(*itr) == flow_list[*(itr - 1)].end()) { flow_list[*(itr - 1)][*itr] = min_capa; } else { flow_list[*(itr - 1)][*itr] += min_capa; } } flow_size = flow_size - min_capa; itr = path.begin(); for (itr++; itr != path.end(); itr++) { int capa, cost; int from, to; from = *(itr - 1); to = *itr; capa = capacity_list[from][to]; cost = cost_list[from][to]; delete_edge(from, to); if (capa - min_capa > 0) { insert_edge(from, to, cost, capa - min_capa); } insert_edge(to, from, -1 * cost, min_capa); } for (int b = 0; b > n; b++) { map<int, int>::iterator itr; for (itr = cost_list[b].begin(); itr != cost_list[b].end(); itr++) { (*itr).second = (*itr).second - potential_list[itr->first] + potential_list[b]; } } } for (int i = 0; i < n; i++) { map<int, int>::iterator itr; for (itr = flow_list[i].begin(); itr != flow_list[i].end(); itr++) { sum_flow_cost += origin_cost[i][itr->first] * itr->second; } } if (!feasible_flag) { cout << "-1" << endl; } else { cout << sum_flow_cost << endl; } return pair<int, vector<Edge> >(); } void print(void) { int i = 0; vector<set<int> >::iterator itr; set<int>::iterator itr_c; for (itr = vertices_list.begin(); itr != vertices_list.end(); itr++) { cout << i << ":"; for (itr_c = (*itr).begin(); itr_c != (*itr).end(); itr_c++) { cout << *itr_c << "(" << capacity_list[i][*itr_c] << ")" << ","; } i++; cout << endl; } } }; int main() { const int inf = 1e9; int v, e, flow; Graph g; Shortest_path_result res; int r; cin >> v >> e >> r; g = Graph(v); int from, to, cost, cap; for (int i = 0; i < e; i++) { cin >> from >> to >> cost; g.insert_edge(from, to, cost, 0); } res = g.solve_dijkstra(r, v - 1); for (int i = 0; i < v; i++) { if (res.distance[i] == inf) { cout << "INF" << endl; } else { cout << res.distance[i] << endl; } } return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; struct Order { bool operator()(pair<long, long> const& a, pair<long, long> const& b) const { return a.first > b.first || ((a.first == b.first) && (a.second > b.second)); } }; struct edge { long to, cap, dis, rev; }; class Primal_dual { private: vector<vector<edge>> E; vector<long> pt; vector<long> dist; vector<pair<long, long>> prev; size_t V; public: Primal_dual() : V(0) {} Primal_dual(size_t v) : E(v, vector<edge>(0)), pt(v, 0), prev(v), dist(v), V(v) {} size_t size() { return V; } void add_edge(long from, long to, long cap, long dis) { E[from].push_back({to, cap, dis, (long)E[to].size()}); E[to].push_back({from, 0, -dis, (long)E[from].size() - 1}); } short dijekstra(long start, long goal) { priority_queue<pair<long, long>, vector<pair<long, long>>, Order> que; for (long i = 0; i < (V); i++) dist[i] = 2147483647; dist[start] = 0; que.push(pair<long, long>(0, start)); while (!que.empty()) { pair<long, long> next = que.top(); que.pop(); long next_v = next.second; if (dist[next_v] < next.first) continue; for (long i = 0; i < (E[next_v].size()); i++) { edge* e = &E[next_v][i]; if (e->cap > 0 && dist[e->to] > (dist[next_v] + e->dis + pt[next_v] - pt[e->to])) { dist[e->to] = (dist[next_v] + e->dis + pt[next_v] - pt[e->to]); prev[e->to] = {next_v, i}; que.push(pair<long, long>(dist[e->to], e->to)); } } } if (dist[goal] == 2147483647) return 1; else return 0; } short min_cost_flow(long start, long goal, long F) { long sum_cost = 0; while (F > 0) { if (dijekstra(start, goal)) return (-1); for (long i = 0; i < (V); i++) pt[i] += dist[i]; long flow = F; for (long node = goal; node != start; node = prev[node].first) { flow = min(flow, E[prev[node].first][prev[node].second].cap); } F -= flow; sum_cost += (flow * pt[goal]); for (long node = goal; node != start; node = prev[node].first) { edge* e = &E[prev[node].first][prev[node].second]; e->cap -= flow; E[node][e->rev].cap += flow; } } return sum_cost; } }; int main(void) { long V, E, F; cin >> V >> E >> F; Primal_dual pd(V); long u, v, c, d; for (long i = 0; i < (E); i++) { cin >> u >> v >> c >> d; pd.add_edge(u, v, c, d); } cout << pd.min_cost_flow(0, V - 1, F) << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; class Edge { public: int from; int to; int flow; Edge(int f, int t, int d) { from = f; to = t; flow = d; } }; class Shortest_path_result { public: int sum_of_cost; vector<int> path; vector<int> distance; vector<int> predecessor; Shortest_path_result() {} }; class Graph { public: int INF; int n; vector<set<int> > vertices_list; vector<map<int, int> > cost_list; vector<map<int, int> > capacity_list; vector<int> potential_list; Graph() {} Graph(int n) { INF = 1e9; this->n = n; vertices_list.insert(vertices_list.begin(), n, set<int>()); cost_list.insert(cost_list.begin(), n, map<int, int>()); capacity_list.insert(capacity_list.begin(), n, map<int, int>()); potential_list = vector<int>(n, 0); } void insert_edge(int b, int e, int cost, int capacity) { vertices_list[b].insert(e); cost_list[b][e] = cost; capacity_list[b][e] = capacity; } void delete_edge(int b, int e) { vertices_list[b].erase(e); cost_list[b].erase(e); capacity_list[b].erase(e); } int degree_of_vertex(int a) { return vertices_list[a].size(); } bool edge_search(int a, int b) { return vertices_list[a].find(b) != vertices_list[a].end(); } bool path_search(int a, int b, set<int> visited = set<int>()) { visited.insert(a); set<int>::iterator itr; for (itr = vertices_list[a].begin(); itr != vertices_list[a].end(); itr++) { if ((*itr) == b) { return true; } if (visited.find(*itr) == visited.end()) { if (path_search(*itr, b, visited)) { return true; } } } return false; } Shortest_path_result solve_dijkstra(int start, int goal) { set<int> visited = set<int>(); vector<int> distance = vector<int>(n, INF); vector<int> predecessor = vector<int>(n); priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; pq.push(pair<int, int>(0, start)); while (!pq.empty()) { pair<int, int> p = pq.top(); pq.pop(); int nv = p.second; if (distance[nv] < p.first) { continue; } distance[nv] = p.first; for (set<int>::iterator itr = vertices_list[nv].begin(); itr != vertices_list[nv].end(); itr++) { int next = (*itr); if (distance[next] > distance[nv] + cost_list[nv][next]) { distance[next] = distance[nv] + cost_list[nv][next]; predecessor[next] = nv; pq.push(pair<int, int>(distance[next], next)); } } } Shortest_path_result result; result.path = vector<int>(); result.path.push_back(goal); while (true) { int now = result.path.back(); int pre = predecessor[now]; result.path.push_back(pre); if (pre == start) { reverse(result.path.begin(), result.path.end()); break; } } result.sum_of_cost = distance[goal]; result.distance = distance; result.predecessor = predecessor; return result; } pair<int, vector<Edge> > solve_mincostflow(int s, int t, int flow_size) { vector<map<int, int> > flow_list = vector<map<int, int> >(n); vector<map<int, int> > origin_cost = cost_list; int sum_flow_cost = 0; while (flow_size > 0) { Shortest_path_result res; vector<int> path; int min_capa = INF; res = solve_dijkstra(s, t); path = res.path; for (int i = 0; i < n; i++) { potential_list[i] = potential_list[i] - res.distance[i]; } vector<int>::iterator itr = path.begin(); itr++; for (; itr != path.end(); itr++) { if (min_capa > capacity_list[*(itr - 1)][*itr]) { min_capa = capacity_list[*(itr - 1)][*itr]; } } itr = path.begin(); itr++; for (; itr != path.end(); itr++) { if (flow_list[*(itr - 1)].find(*itr) == flow_list[*(itr - 1)].end()) { flow_list[*(itr - 1)][*itr] = min_capa; } else { flow_list[*(itr - 1)][*itr] += min_capa; } } flow_size = flow_size - min_capa; itr = path.begin(); for (itr++; itr != path.end(); itr++) { int capa, cost; int from, to; from = *(itr - 1); to = *itr; capa = capacity_list[from][to]; cost = cost_list[from][to]; delete_edge(from, to); if (capa - min_capa > 0) { insert_edge(from, to, cost, capa - min_capa); } insert_edge(to, from, -1 * cost, min_capa); } for (int b = 0; b > n; b++) { map<int, int>::iterator itr; for (itr = cost_list[b].begin(); itr != cost_list[b].end(); itr++) { (*itr).second = (*itr).second - potential_list[itr->first] + potential_list[b]; } } } for (int i = 0; i < n; i++) { map<int, int>::iterator itr; for (itr = flow_list[i].begin(); itr != flow_list[i].end(); itr++) { sum_flow_cost += origin_cost[i][itr->first] * itr->second; } } cout << sum_flow_cost << endl; return pair<int, vector<Edge> >(); } void print(void) { int i = 0; vector<set<int> >::iterator itr; set<int>::iterator itr_c; for (itr = vertices_list.begin(); itr != vertices_list.end(); itr++) { cout << i << ":"; for (itr_c = (*itr).begin(); itr_c != (*itr).end(); itr_c++) { cout << *itr_c << "(" << capacity_list[i][*itr_c] << ")" << ","; } i++; cout << endl; } } }; int main() { const int inf = 1e9; int v, e, flow; Graph g; cin >> v >> e >> flow; g = Graph(v); int from, to, cost, cap; for (int i = 0; i < e; i++) { cin >> from >> to >> cap >> cost; g.insert_edge(from, to, cost, cap); } g.solve_mincostflow(0, v - 1, flow); return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
// clang-format off #include <bits/stdc++.h> using namespace std; #define int long long #define main signed main() #define loop(i, a, n) for (int i = (a); i < (n); i++) #define rep(i, n) loop(i, 0, n) #define all(v) (v).begin(), (v).end() #define rall(v) (v).rbegin(), (v).rend() #define prec(n) fixed << setprecision(n) constexpr int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000; constexpr int MOD = 1000000007; constexpr double PI = 3.14159265358979; template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; } template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; } constexpr bool odd(const int n) { return n & 1; } constexpr bool even(const int n) { return ~n & 1; } template<typename T = int> T in() { T x; cin >> x; return x; } template<typename T = int> T in(T &&x) { T z(forward<T>(x)); cin >> z; return z; } template<typename T> istream &operator>>(istream &is, vector<T> &v) { for (T &x : v) is >> x; return is; } template<typename A, typename B> istream &operator>>(istream &is, pair<A, B> &p) { return is >> p.first >> p.second; } template<typename T> ostream &operator<<(ostream &os, const vector<vector<T>> &v) { int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "" : "\n"); return os; } template<typename T> ostream &operator<<(ostream &os, const vector<T> &v) { int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "" : " "); return os; } template<typename A, typename B> ostream &operator<<(ostream &os, const pair<A, B> &p) { return os << p.first << ' ' << p.second; } template<typename Head, typename Value> auto vectors(const Head &head, const Value &v) { return vector<Value>(head, v); } template<typename Head, typename... Tail> auto vectors(Head x, Tail... tail) { auto inner = vectors(tail...); return vector<decltype(inner)>(x, inner); } // clang-format on using Flow = int; using Cost = int; class PrimalDual { public: struct Edge { int d; Flow c, f; Cost w; int r; bool is_r; Edge(int d, Flow c, Flow f, Cost w, int r, bool is_r) : d(d), c(c), f(f), w(w), r(r), is_r(is_r) {} }; int n; vector<vector<Edge>> g; PrimalDual(int n) : n(n), g(n) {} void addEdge(int src, int dst, Flow cap, Cost cost) { // 有向辺 int rsrc = g[dst].size(); int rdst = g[src].size(); g[src].emplace_back(dst, cap, 0, cost, rsrc, false); g[dst].emplace_back(src, cap, cap, -cost, rdst, true); } template<Cost inf = numeric_limits<Cost>::max() / 8> Cost solve(int s, int t, Flow f) { Cost res = 0; vector<Cost> h(n), dist(n); vector<int> prevv(n), preve(n); using state = pair<Cost, int>; priority_queue<state, vector<state>, greater<state>> q; fill(h.begin(), h.end(), 0); while (f > 0) { fill(dist.begin(), dist.end(), inf); dist[s] = 0; q.emplace(0, s); while (q.size()) { Cost cd; int v; tie(cd, v) = q.top(); q.pop(); if (dist[v] < cd) continue; for (int i = 0; i < g[v].size(); ++i) { const Edge &e = g[v][i]; if (residue(e) == 0) continue; if (dist[e.d] + h[e.d] > cd + h[v] + e.w) { dist[e.d] = dist[v] + e.w + h[v] - h[e.d]; prevv[e.d] = v; preve[e.d] = i; q.emplace(dist[e.d], e.d); } } } if (dist[t] == INF) return -1; for (int i = 0; i < n; ++i) h[i] += dist[i]; Flow d = f; for (int v = t; v != s; v = prevv[v]) cmin(d, residue(g[prevv[v]][preve[v]])); f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { Edge &e = g[prevv[v]][preve[v]]; e.f += d; g[v][e.r].f -= d; } } return res; } Flow residue(const Edge &e) { return e.c - e.f; } }; main { int v, e, f; cin >> v >> e >> f; PrimalDual pd(v); rep(i, e) { int a, b, c, d; cin >> a >> b >> c >> d; pd.addEdge(a, b, c, d); } cout << pd.solve(0, v - 1, f) << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.PriorityQueue; import java.util.TreeMap; public class Main { static ContestScanner in;static Writer out;public static void main(String[] args) {try{in=new ContestScanner();out=new Writer();Main solve=new Main();solve.solve(); in.close();out.flush();out.close();}catch(IOException e){e.printStackTrace();}} static void dump(int[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();} static void dump(int[]a,int n){for(int i=0;i<a.length;i++)out.printf("%"+n+"d ",a[i]);out.println();} static void dump(long[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();} static void dump(char[]a){for(int i=0;i<a.length;i++)out.print(a[i]);out.println();} static long pow(long a,int n){long r=1;while(n>0){if((n&1)==1)r*=a;a*=a;n>>=1;}return r;} static String itob(int a,int l){return String.format("%"+l+"s",Integer.toBinaryString(a)).replace(' ','0');} static void sort(int[]a){m_sort(a,0,a.length,new int[a.length]);} static void sort(int[]a,int l){m_sort(a,0,l,new int[l]);} static void sort(int[]a,int l,int[]buf){m_sort(a,0,l,buf);} static void sort(int[]a,int s,int l,int[]buf){m_sort(a,s,l,buf);} static void m_sort(int[]a,int s,int sz,int[]b) {if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;} m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz; while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];} while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i]; } /* qsort(3.5s)<<msort(9.5s)<<<shuffle+qsort(17s)<Arrays.sort(Integer)(20s) */ static void sort(long[]a){m_sort(a,0,a.length,new long[a.length]);} static void sort(long[]a,int l){m_sort(a,0,l,new long[l]);} static void sort(long[]a,int l,long[]buf){m_sort(a,0,l,buf);} static void sort(long[]a,int s,int l,long[]buf){m_sort(a,s,l,buf);} static void m_sort(long[]a,int s,int sz,long[]b) {if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;} m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz; while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];} while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];} static void swap(long[] a,int i,int j){final long t=a[i];a[i]=a[j];a[j]=t;} static void swap(int[] a,int i,int j){final int t=a[i];a[i]=a[j];a[j]=t;} static int binarySearchSmallerMax(int[]a,int v)// get maximum index which a[idx]<=v {int l=-1,r=a.length-1,s=0;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;} static int binarySearchSmallerMax(int[]a,int v,int l,int r) {int s=-1;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;} static List<Integer>[]createGraph(int n) {List<Integer>[]g=new List[n];for(int i=0;i<n;i++)g[i]=new ArrayList<>();return g;} void solve() throws NumberFormatException, IOException{ final int n = in.nextInt(); final int m = in.nextInt(); int f = in.nextInt(); List<Edge>[] node = new List[n]; for(int i=0; i<n; i++) node[i] = new ArrayList<>(); for(int i=0; i<m; i++){ int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); int d = in.nextInt(); Edge e = new Edge(b, c, d); Edge r = new Edge(a, 0, -d); e.rev = r; r.rev = e; node[a].add(e); node[b].add(r); } final int s = 0, t = n-1; int[] h = new int[n]; int[] dist = new int[n]; int[] preV = new int[n]; int[] preE = new int[n]; final int inf = Integer.MAX_VALUE; PriorityQueue<Pos> qu = new PriorityQueue<>(); int res = 0; while(f>0){ Arrays.fill(dist, inf); dist[s] = 0; qu.clear(); qu.add(new Pos(s, 0)); while(!qu.isEmpty()){ Pos p = qu.poll(); if(dist[p.v]<p.d) continue; dist[p.v] = p.d; final int sz = node[p.v].size(); for(int i=0; i<sz; i++){ Edge e = node[p.v].get(i); final int nd = e.cost+p.d + h[p.v]-h[e.to]; if(e.cap>0 && nd < dist[e.to]){ preV[e.to] = p.v; preE[e.to] = i; qu.add(new Pos(e.to, nd)); } } } if(dist[t]==inf) break; for(int i=0; i<n; i++) h[i] += dist[i]; int minf = f; for(int i=t; i!=s; i=preV[i]){ minf = Math.min(minf, node[preV[i]].get(preE[i]).cap); } f -= minf; res += minf*h[t]; for(int i=t; i!=s; i=preV[i]){ node[preV[i]].get(preE[i]).cap -= minf; node[preV[i]].get(preE[i]).rev.cap += minf; } } System.out.println(res); } } class Pos implements Comparable<Pos>{ int v, d; public Pos(int v, int d) { this.v = v; this.d = d; } @Override public int compareTo(Pos o) { return d-o.d; } } class Edge{ int to, cap, cost; Edge rev; Edge(int t, int c, int co){ to = t; cap = c; cost = co; } void rev(Edge r){ rev = r; } } class MultiSet<T> extends HashMap<T, Integer>{ @Override public Integer get(Object key){return containsKey(key)?super.get(key):0;} public void add(T key,int v){put(key,get(key)+v);} public void add(T key){put(key,get(key)+1);} public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);} public MultiSet<T> merge(MultiSet<T> set) {MultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;} for(Entry<T,Integer>e:s.entrySet())l.add(e.getKey(),e.getValue());return l;} } class OrderedMultiSet<T> extends TreeMap<T, Integer>{ @Override public Integer get(Object key){return containsKey(key)?super.get(key):0;} public void add(T key,int v){put(key,get(key)+v);} public void add(T key){put(key,get(key)+1);} public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);} public OrderedMultiSet<T> merge(OrderedMultiSet<T> set) {OrderedMultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;} while(!s.isEmpty()){l.add(s.firstEntry().getKey(),s.pollFirstEntry().getValue());}return l;} } class Pair implements Comparable<Pair>{ int a,b;final int hash;Pair(int a,int b){this.a=a;this.b=b;hash=(a<<16|a>>16)^b;} public boolean equals(Object obj){Pair o=(Pair)(obj);return a==o.a&&b==o.b;} public int hashCode(){return hash;} public int compareTo(Pair o){if(a!=o.a)return a<o.a?-1:1;else if(b!=o.b)return b<o.b?-1:1;return 0;} } class Timer{ long time;public void set(){time=System.currentTimeMillis();} public long stop(){return time=System.currentTimeMillis()-time;} public void print(){System.out.println("Time: "+(System.currentTimeMillis()-time)+"ms");} @Override public String toString(){return"Time: "+time+"ms";} } class Writer extends PrintWriter{ public Writer(String filename)throws IOException {super(new BufferedWriter(new FileWriter(filename)));} public Writer()throws IOException{super(System.out);} } class ContestScanner implements Closeable{ private BufferedReader in;private int c=-2; public ContestScanner()throws IOException {in=new BufferedReader(new InputStreamReader(System.in));} public ContestScanner(String filename)throws IOException {in=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));} public String nextToken()throws IOException { StringBuilder sb=new StringBuilder(); while((c=in.read())!=-1&&Character.isWhitespace(c)); while(c!=-1&&!Character.isWhitespace(c)){sb.append((char)c);c=in.read();} return sb.toString(); } public String readLine()throws IOException{ StringBuilder sb=new StringBuilder();if(c==-2)c=in.read(); while(c!=-1&&c!='\n'&&c!='\r'){sb.append((char)c);c=in.read();} return sb.toString(); } public long nextLong()throws IOException,NumberFormatException {return Long.parseLong(nextToken());} public int nextInt()throws NumberFormatException,IOException {return(int)nextLong();} public double nextDouble()throws NumberFormatException,IOException {return Double.parseDouble(nextToken());} public void close() throws IOException {in.close();} }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct edge { i64 from; i64 to; i64 cap; i64 cost; i64 rev; }; i64 INF = 1e18; i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g, std::vector<i64> b) { i64 ans = 0; i64 U = *std::max_element(begin(b), end(b)); i64 delta = (1 << ((int)(std::log2(U)) + 1)); int n = g.size(); std::vector<i64> e = b; std::vector<i64> p(n, 0); for (int i = 0; i < n; i++) { if (b[i] > 0) p[i] = 1e8; } int zero = 0; for (auto x : e) { if (x == 0) zero++; } for (; delta > 0; delta >>= 1) { if (zero == n) break; for (int s = 0; s < n; s++) { if (!(e[s] >= delta)) continue; std::vector<std::size_t> pv(n, -1); std::vector<std::size_t> pe(n, -1); std::vector<i64> dist(n, INF); using P = std::pair<i64, i64>; std::priority_queue<P, std::vector<P>, std::greater<P>> que; dist[s] = 0; que.push({dist[s], s}); while (!que.empty()) { int v = que.top().second; i64 d = que.top().first; que.pop(); if (dist[v] < d) continue; for (std::size_t i = 0; i < g[v].size(); i++) { const auto& e = g[v][i]; std::size_t u = e.to; if (e.cap == 0) { continue; } i64 ccc = e.cost + p[v] - p[u]; assert(ccc >= 0); if (dist[u] > dist[v] + ccc) { dist[u] = dist[v] + ccc; pv[u] = v; pe[u] = i; que.push({dist[u], u}); } } } for (int i = 0; i < n; i++) { if (pv[i] != -1) p[i] += dist[i] - p[s]; else p[i] += (i64)1e8 - p[s]; } p[s] += dist[s] - p[s]; int t = 0; for (; t < n; t++) { if (!(e[s] >= delta)) break; if (e[t] <= -delta && pv[t] != -1) { std::size_t u = t; for (; pv[u] != -1; u = pv[u]) { ans += delta * g[pv[u]][pe[u]].cost; g[pv[u]][pe[u]].cap -= delta; g[u][g[pv[u]][pe[u]].rev].cap += delta; } e[u] -= delta; e[t] += delta; if (e[u] == 0) zero++; if (e[t] == 0) zero++; } } } } for (int i = 0; i < n; i++) { } if (zero == n) return ans; else return -1e18; } int main() { i64 N, M, F; cin >> N >> M >> F; vector<vector<edge>> g(N + M); vector<i64> e(N + M, 0); int s = 0; int t = N - 1; e[s + M] = F; e[t + M] = -F; for (int i = 0; i < M; i++) { i64 a, b, c, d; cin >> a >> b >> c >> d; e[i] = c; e[a + M] -= c; g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()}); g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1}); g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()}); g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1}); } i64 ans = capacity_scaling_bflow(g, e); if (ans == -1e18) { cout << -1 << endl; } else { cout << ans << endl; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; struct SuccessiveShortestPath { struct Edge { int to, cap, cost, rev; }; int n, init; vector<vector<Edge>> g; vector<int> dist, pv, pe; SuccessiveShortestPath() {} SuccessiveShortestPath(int n, int INF = 1e9) : n(n), g(n), init(INF), dist(n), pv(n), pe(n) {} void addEdge(int u, int v, int cap, int cost) { int szU = g[u].size(); int szV = g[v].size(); g[u].push_back({v, cap, cost, szV}); g[v].push_back({u, 0, -cost, szU - 1}); } int bellmanFord(int s, int t) { dist = vector<int>(n, init); dist[s] = 0; bool update = true; while (update) { update = false; for (int u = 0; u < n; ++u) { for (int i = 0; i < g[u].size(); ++i) { Edge& e = g[u][i]; int v = e.to; if (e.cap > 0 && dist[v] > dist[u] + e.cost) { dist[v] = dist[u] + e.cost; pv[v] = u; pe[v] = i; update = true; } } } } return dist[t]; } int build(int s, int t, int f) { int res = 0; while (f > 0) { if (bellmanFord(s, t) == init) return -1; int x = f; for (int u = t; u != s; u = pv[u]) { x = min(x, g[pv[u]][pe[u]].cap); } f -= x; res += x * dist[t]; for (int u = t; u != s; u = pv[u]) { Edge& e = g[pv[u]][pe[u]]; e.cap -= x; g[e.to][e.rev].cap += x; } } return res; } }; int main() { int n, m, f; cin >> n >> m >> f; SuccessiveShortestPath ssp(n); while (m--) { int u, v, c, d; cin >> u >> v >> c >> d; ssp.addEdge(u, v, c, d); } cout << ssp.build(0, n - 1, f) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using vi = vector<int>; template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "sz=" << v.size() << "\n["; for (const auto& p : v) { os << p << ","; } os << "]\n"; return os; } template <typename S, typename T> ostream& operator<<(ostream& os, const pair<S, T>& p) { os << "(" << p.first << "," << p.second << ")"; return os; } constexpr ll MOD = 1e9 + 7; template <typename T> constexpr T INF = numeric_limits<T>::max() / 100; class CostFlow { public: using T = ll; struct Edge { Edge(const int from_, const int to_, const int reverse_, const T capacity_, const T cost_) : from{from_}, to{to_}, reverse{reverse_}, capacity{capacity_}, flow{0}, cost{cost_} {} int from; int to; int reverse; T capacity; T flow; T cost; }; CostFlow(const int v) : m_v{v} { m_table.resize(v); m_dist.resize(v); m_potential.resize(v); m_prev_v.resize(v); m_prev_e.resize(v); } void addEdge(const int from, const int to, const T capacity, const T cost) { m_table[from].push_back( Edge{from, to, (int)m_table[to].size(), capacity, cost}); m_table[to].push_back( Edge{to, from, (int)m_table[from].size() - 1, 0, -cost}); } T minCostFlow(const int s, const int t, int f) { using P = pair<T, int>; T res = 0; fill(m_potential.begin(), m_potential.end(), 0); while (f > 0) { priority_queue<P, vector<P>, greater<P>> q; fill(m_dist.begin(), m_dist.end(), INF<T>); m_dist[s] = 0; q.push(make_pair(0, s)); while (not q.empty()) { const P p = q.top(); q.pop(); const int v = p.second; if (m_dist[v] < p.first) { continue; } for (int i = 0; i < m_table[v].size(); i++) { const auto& e = m_table[v][i]; if (e.capacity > e.flow and m_dist[e.to] > m_dist[v] + e.cost + m_potential[v] - m_potential[e.to]) { m_dist[e.to] = m_dist[v] + e.cost + m_potential[v] - m_potential[e.to]; m_prev_v[e.to] = v; m_prev_e[e.to] = i; q.push(make_pair(m_dist[e.to], e.to)); } } } if (m_dist[t] == INF<T>) { return -1; } for (int v = 0; v < m_v; v++) { m_potential[v] += m_dist[v]; } T d = f; for (int v = t; v != s; v = m_prev_v[v]) { const auto& e = m_table[m_prev_v[v]][m_prev_e[v]]; d = min(d, e.capacity - e.flow); } f -= d; res += d * m_potential[t]; for (int v = t; v != s; v = m_prev_v[v]) { auto& e = m_table[m_prev_v[v]][m_prev_e[v]]; e.flow += d; m_table[v][e.reverse].flow -= d; } } return res; } private: const int m_v; vector<vector<Edge>> m_table; vector<T> m_dist; vector<T> m_potential; vector<int> m_prev_v; vector<int> m_prev_e; }; int main() { int V, E; ll F; std::cin >> V >> E >> F; CostFlow f(V); for (ll i = 0; i < E; i++) { int u, v; ll c, d; cin >> u >> v >> c >> d; f.addEdge(u, v, c, d); } cout << f.minCostFlow(0, V - 1, F); return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
UNKNOWN
class PQueue attr_accessor :node def initialize @node = [] end def insert(num) i = @node.size @node[i] = num down_heap(i) end def extract ret = @node[0] if @node.size > 1 @node[0] = @node.pop() up_heap(0) else @node = [] end return ret end def delete(node) i = @node.index(node) break unless i if i == @node.size - 1 @node.pop else @node[i] = @node.pop copy = @node.clone down_heap(i) if copy == @node up_heap(i) end end end def modify(old, new) delete(old) insert(new) end def up_heap(i) h = @node.size largest = i l = 2 * i + 1 largest = l if l < h && @node[l] > @node[largest] r = 2 * i + 2 largest = r if r < h && @node[r] > @node[largest] while largest != i @node[i], @node[largest] = @node[largest], @node[i] i = largest l = 2 * i + 1 largest = l if l < h && @node[l] > @node[largest] r = 2 * i + 2 largest = r if r < h && @node[r] > @node[largest] end end def down_heap(i) p = (i+1)/2-1 while i > 0 && @node[p] < @node[i] @node[i], @node[p] = @node[p], @node[i] i = p p = (i+1)/2-1 end end end INF = 1.0 / 0.0 class Node attr_accessor :i, :c, :prev, :d, :pot, :ans def initialize(i) @i = i @c = {} @ans = {} @prev = nil @d = INF @pot = 0 end def <(other) if self.d > other.d return true else return false end end def >(other) if self.d < other.d return true else return false end end end nv, ne, f = gets.split.map(&:to_i) g = Array.new(nv){|i| Node.new(i)} ne.times{|i| u, v, c, d = gets.split.map(&:to_i) g[u].c[v] = [c, d] g[u].ans[v] = [0,d] } loop do nv.times{|i| g[i].d = INF g[i].prev = nil } g[0].d = 0 q = PQueue.new nv.times{|i| q.insert(g[i]) } while q.node.size > 0 u = q.extract u.c.each{|v, val| alt = u.d + val[1] if g[v].d > alt q.delete(g[v]) g[v].d = alt g[v].prev = u.i q.insert(g[v]) end } end # p g max = f c = nv-1 path = [c] while c != 0 p = g[c].prev if p == nil puts "-1" exit end path.unshift(p) max = g[p].c[c][0] if max > g[p].c[c][0] c = p end # p path # p max if max < f then #make potential path.each{|i| g[i].pot -= g[i].d } (path.size-1).times{|i| u = path[i] v = path[i+1] g[u].ans[v][0] += max } # p g f -= max else (path.size-1).times{|i| u = path[i] v = path[i+1] g[u].ans[v][0] += f } break end #make sub-network (path.size-1).times{|i| u = path[i] v = path[i+1] g[v].c[u] ||= [0, -g[u].c[v][1]] g[v].c[u][0] += max g[u].c[v][0] -= max if g[u].c[v][0] == 0 g[u].c.delete(v) end } #make modified sub-network g.size.times{|i| g[i].c.each{|j, val| # p "#{g[i].c[j][1]} #{g[i].pot} #{g[j].pot}" g[i].c[j][1] -= g[i].pot - g[j].pot } } # g.size.times{|i| # p g[i] # } end sum = 0 nv.times{|i| g[i].ans.each{|k,v| sum += v[0]*v[1] } } puts sum
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; class Edge { public: int from; int to; int flow; Edge(int f, int t, int d) { from = f; to = t; flow = d; } }; class Shortest_path_result { public: int sum_of_cost; vector<int> path; vector<int> distance; vector<int> predecessor; Shortest_path_result() {} }; class Graph { public: int INF; int n; vector<set<int> > vertices_list; vector<map<int, int> > cost_list; vector<map<int, int> > capacity_list; vector<int> potential_list; Graph() {} Graph(int n) { INF = 1e9; this->n = n; vertices_list.insert(vertices_list.begin(), n, set<int>()); cost_list.insert(cost_list.begin(), n, map<int, int>()); capacity_list.insert(capacity_list.begin(), n, map<int, int>()); potential_list = vector<int>(n, 0); } void insert_edge(int b, int e, int cost, int capacity) { vertices_list[b].insert(e); cost_list[b][e] = cost; capacity_list[b][e] = capacity; } void delete_edge(int b, int e) { vertices_list[b].erase(e); cost_list[b].erase(e); capacity_list[b].erase(e); } int degree_of_vertex(int a) { return vertices_list[a].size(); } bool edge_search(int a, int b) { return vertices_list[a].find(b) != vertices_list[a].end(); } bool path_search(int a, int b, set<int> visited = set<int>()) { visited.insert(a); set<int>::iterator itr; for (itr = vertices_list[a].begin(); itr != vertices_list[a].end(); itr++) { if ((*itr) == b) { return true; } if (visited.find(*itr) == visited.end()) { if (path_search(*itr, b, visited)) { return true; } } } return false; } Shortest_path_result solve_dijkstra(int start, int goal) { set<int> visited = set<int>(); vector<int> distance = vector<int>(n, INF); vector<int> predecessor = vector<int>(n); priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; pq.push(pair<int, int>(0, start)); while (!pq.empty()) { pair<int, int> p = pq.top(); pq.pop(); int nv = p.second; if (distance[nv] < p.first) { continue; } distance[nv] = p.first; for (set<int>::iterator itr = vertices_list[nv].begin(); itr != vertices_list[nv].end(); itr++) { int next = (*itr); if (distance[next] > distance[nv] + cost_list[nv][next]) { distance[next] = distance[nv] + cost_list[nv][next]; predecessor[next] = nv; pq.push(pair<int, int>(distance[next], next)); } } } Shortest_path_result result; result.path = vector<int>(); result.path.push_back(goal); while (true) { int now = result.path.back(); int pre = predecessor[now]; result.path.push_back(pre); if (pre == start) { reverse(result.path.begin(), result.path.end()); break; } } result.sum_of_cost = distance[goal]; result.distance = distance; result.predecessor = predecessor; return result; } pair<int, vector<Edge> > solve_mincostflow(int s, int t, int flow_size) { vector<map<int, int> > flow_list = vector<map<int, int> >(n); vector<map<int, int> > origin_cost = cost_list; int sum_flow_cost = 0; while (flow_size > 0) { Shortest_path_result res; vector<int> path; int min_capa = INF; res = solve_dijkstra(s, t); if (res.sum_of_cost == INF) { break; } path = res.path; for (int i = 0; i < n; i++) { potential_list[i] = potential_list[i] - res.distance[i]; } vector<int>::iterator itr = path.begin(); itr++; for (; itr != path.end(); itr++) { if (min_capa > capacity_list[*(itr - 1)][*itr]) { min_capa = capacity_list[*(itr - 1)][*itr]; } } if (min_capa > flow_size) { min_capa = flow_size; } itr = path.begin(); itr++; for (; itr != path.end(); itr++) { if (flow_list[*(itr - 1)].find(*itr) == flow_list[*(itr - 1)].end()) { flow_list[*(itr - 1)][*itr] = min_capa; } else { flow_list[*(itr - 1)][*itr] += min_capa; } } flow_size = flow_size - min_capa; itr = path.begin(); for (itr++; itr != path.end(); itr++) { int capa, cost; int from, to; from = *(itr - 1); to = *itr; capa = capacity_list[from][to]; cost = cost_list[from][to]; delete_edge(from, to); if (capa - min_capa > 0) { insert_edge(from, to, cost, capa - min_capa); } insert_edge(to, from, -1 * cost, min_capa); } for (int b = 0; b > n; b++) { map<int, int>::iterator itr; for (itr = cost_list[b].begin(); itr != cost_list[b].end(); itr++) { (*itr).second = (*itr).second - potential_list[itr->first] + potential_list[b]; } } } for (int i = 0; i < n; i++) { map<int, int>::iterator itr; for (itr = flow_list[i].begin(); itr != flow_list[i].end(); itr++) { sum_flow_cost += origin_cost[i][itr->first] * itr->second; } } if (sum_flow_cost == 0) { cout << "-1" << endl; } else { cout << sum_flow_cost << endl; } return pair<int, vector<Edge> >(); } void print(void) { int i = 0; vector<set<int> >::iterator itr; set<int>::iterator itr_c; for (itr = vertices_list.begin(); itr != vertices_list.end(); itr++) { cout << i << ":"; for (itr_c = (*itr).begin(); itr_c != (*itr).end(); itr_c++) { cout << *itr_c << "(" << capacity_list[i][*itr_c] << ")" << ","; } i++; cout << endl; } } }; int main() { const int inf = 1e9; int v, e, flow; Graph g; cin >> v >> e >> flow; g = Graph(v); int from, to, cost, cap; for (int i = 0; i < e; i++) { cin >> from >> to >> cap >> cost; g.insert_edge(from, to, cost, cap); } g.solve_mincostflow(0, v - 1, flow); return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const int INFL = (int)1e9; const long long int INFLL = (long long int)1e18; const double INFD = numeric_limits<double>::infinity(); const double PI = 3.14159265358979323846; bool nearlyeq(double x, double y) { return abs(x - y) < 1e-9; } bool inrange(int x, int t) { return x >= 0 && x < t; } long long int rndf(double x) { return (long long int)(x + (x >= 0 ? 0.5 : -0.5)); } long long int floorsqrt(double x) { long long int m = (long long int)sqrt(x); return m + (m * m <= (long long int)(x) ? 0 : -1); } long long int ceilsqrt(double x) { long long int m = (long long int)sqrt(x); return m + ((long long int)x <= m * m ? 0 : 1); } long long int rnddiv(long long int a, long long int b) { return (a / b + (a % b * 2 >= b ? 1 : 0)); } long long int ceildiv(long long int a, long long int b) { return (a / b + (a % b == 0 ? 0 : 1)); } long long int gcd(long long int m, long long int n) { if (n == 0) return m; else return gcd(n, m % n); } struct graph_t { int n; int m; vector<pair<int, int> > edges; vector<long long int> vals; vector<long long int> costs; vector<long long int> caps; }; class Mincostflow { private: struct edgedata { int eid, from, to; long long int cap, cost; int dual_p; }; struct node { int id; bool done; long long int d; int from; int from_p; int from_eid; vector<edgedata> edges; }; struct pq_t { int id; long long int d; bool operator<(const pq_t& another) const { return d != another.d ? d > another.d : id > another.id; } }; vector<node> nodes; int n, m; int source, sink; edgedata* empty_edge; bool overflow; public: Mincostflow(graph_t G, int s, int t) { n = G.n; m = G.edges.size(); nodes.resize(n); for (int i = 0; i < (int)n; i++) nodes[i] = {i, false, LLONG_MAX, -1, -1, m, {}}; empty_edge = new edgedata; for (int i = 0; i < (int)m; i++) { int a = G.edges[i].first; int b = G.edges[i].second; nodes[a].edges.push_back( {i, a, b, G.caps[i], G.costs[i], (int)nodes[b].edges.size()}); nodes[b].edges.push_back( {i - m, b, a, 0, -G.costs[i], (int)nodes[a].edges.size() - 1}); } source = s; sink = t; overflow = false; } bool add_flow(long long int f) { if (overflow) return false; while (f > 0) { for (int i = 0; i < (int)n; i++) { nodes[i].done = false; nodes[i].from = -1; nodes[i].from_p = -1; nodes[i].from_eid = m; nodes[i].d = LLONG_MAX; } nodes[source].d = 0; priority_queue<pq_t> pq; pq.push({nodes[source].id, nodes[source].d}); while (pq.size()) { int a = pq.top().id; pq.pop(); if (nodes[a].done) continue; nodes[a].done = true; for (int j = 0; j < (int)nodes[a].edges.size(); j++) { edgedata e = nodes[a].edges[j]; if (e.cap == 0) continue; int b = e.to; if (nodes[b].done) continue; long long int buf = nodes[a].d + e.cost; if (buf < nodes[b].d) { nodes[b].d = buf; nodes[b].from = a; nodes[b].from_p = j; nodes[b].from_eid = e.eid; pq.push({nodes[b].id, nodes[b].d}); } } } if (!nodes[sink].done) { overflow = true; return false; } int a = sink; long long int df = f; while (a != source) { df = min(df, nodes[nodes[a].from].edges[nodes[a].from_p].cap); a = nodes[a].from; } a = sink; while (a != source) { nodes[nodes[a].from].edges[nodes[a].from_p].cap -= df; nodes[a] .edges[nodes[nodes[a].from].edges[nodes[a].from_p].dual_p] .cap += df; a = nodes[a].from; } f -= df; } return true; } vector<long long int> get_eid_flow() { vector<long long int> ret(m, -1); if (overflow) return ret; for (int i = 0; i < (int)n; i++) { for (auto e : nodes[i].edges) { if (e.eid < 0) ret[e.eid + m] = e.cap; } } return ret; } long long int get_flow() { long long int ret = 0; if (overflow) return -1; for (auto e : nodes[sink].edges) { if (e.eid < 0) ret += e.cap; } return ret; } long long int get_cost() { long long int ret = 0; if (overflow) return -1; for (int i = 0; i < (int)n; i++) { for (auto e : nodes[i].edges) { if (e.eid < 0) ret -= e.cap * e.cost; } } return ret; } }; int main() { graph_t G; cin >> G.n; cin >> G.m; long long int f; cin >> f; for (int i = 0; i < (int)G.m; i++) { int s, t; cin >> s >> t; long long int cap, cost; cin >> cap >> cost; G.edges.push_back({s, t}); G.caps.push_back(cap); G.costs.push_back(cost); } Mincostflow mcf(G, 0, G.n - 1); if (mcf.add_flow(f)) cout << mcf.get_cost() << endl; else cout << -1 << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
java
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.TreeSet; public class Main { static InputStream is; static PrintWriter out; static String INPUT = ""; static final long INF = Long.MAX_VALUE / 2; int len; int[][] up; int[] tin; int[] tout; int time; private static void solve() { //PrintWriter pr = new PrintWriter(System.out); int V = ni(); int E = ni(); int F = ni(); int[] u = new int[E]; int[] v = new int[E]; int[] c = new int[E]; int[] d = new int[E]; for(int i=0;i<E;i++){ u[i] = ni(); v[i] = ni(); c[i] = ni(); d[i] = ni(); } int[][][] cost = packWD(V, u, v, d); int[][][] capacity = packWD(V, u, v, c); System.out.println(solveMinCostFlow(cost, capacity, 0, V-1, F)); } public static int solveMinCostFlow(int[][][] cost, int[][][] capacity, int src, int sink, int all) { int n = cost.length; int[][] flow = new int[n][]; for(int i = 0;i < n;i++) { flow[i] = new int[cost[i].length]; } // unweighted invgraph // ?????°?????????cur???i??????=next?????¨???????????°????????§cur???next????????????????????????????????? int[][][] ig = new int[n][][]; { int[] p = new int[n]; for(int i = 0;i < n;i++){ for(int j = 0;j < cost[i].length;j++)p[cost[i][j][0]]++; } for(int i = 0;i < n;i++)ig[i] = new int[p[i]][2]; for(int i = n-1;i >= 0;i--){ for(int j = 0;j < cost[i].length;j++){ int u = --p[cost[i][j][0]]; ig[cost[i][j][0]][u][0] = i; ig[cost[i][j][0]][u][1] = j; } } } int mincost = 0; int[] pot = new int[n]; // ??????????????£??? final int[] d = new int[n]; TreeSet<Integer> q = new TreeSet<Integer>(new Comparator<Integer>(){ public int compare(Integer a, Integer b) { if(d[a] - d[b] != 0)return d[a] - d[b]; return a - b; } }); while(all > 0){ // src~sink?????????????????¢??? int[] prev = new int[n]; int[] myind = new int[n]; Arrays.fill(prev, -1); Arrays.fill(d, Integer.MAX_VALUE / 2); d[src] = 0; q.add(src); while(!q.isEmpty()){ int cur = q.pollFirst(); for(int i = 0;i < cost[cur].length;i++) { int next = cost[cur][i][0]; if(capacity[cur][i][1] - flow[cur][i] > 0){ int nd = d[cur] + cost[cur][i][1] + pot[cur] - pot[next]; if(d[next] > nd){ q.remove(next); d[next] = nd; prev[next] = cur; myind[next] = i; q.add(next); } } } for(int i = 0;i < ig[cur].length;i++) { int next = ig[cur][i][0]; int cind = ig[cur][i][1]; if(flow[next][cind] > 0){ int nd = d[cur] - cost[next][cind][1] + pot[cur] - pot[next]; if(d[next] > nd){ q.remove(next); d[next] = nd; prev[next] = cur; myind[next] = -cind-1; q.add(next); } } } } if(prev[sink] == -1)break; int minflow = all; int sumcost = 0; for(int i = sink;i != src;i = prev[i]){ if(myind[i] >= 0){ minflow = Math.min(minflow, capacity[prev[i]][myind[i]][1] - flow[prev[i]][myind[i]]); sumcost += cost[prev[i]][myind[i]][1]; }else{ // cur->next // prev[i]->i // i????????£?????? // ig[cur][j][0]=next?????¨???g[next][ig[cur][j][1]] = cur int ind = -myind[i]-1; // tr(prev[i], ind); minflow = Math.min(minflow, flow[i][ind]); sumcost -= cost[i][ind][1]; } } mincost += minflow * sumcost; for(int i = sink;i != src;i = prev[i]){ if(myind[i] >= 0){ flow[prev[i]][myind[i]] += minflow; }else{ int ind = -myind[i]-1; flow[i][ind] -= minflow; } } all -= minflow; for(int i = 0;i < n;i++){ pot[i] += d[i]; } } return mincost; } public static int[][][] packWD(int n, int[] from, int[] to, int[] w) { int[][][] g = new int[n][][]; int[] p = new int[n]; for(int f : from)p[f]++; for(int i = 0;i < n;i++)g[i] = new int[p[i]][2]; for(int i = 0;i < from.length;i++){ --p[from[i]]; g[from[i]][p[from[i]]][0] = to[i]; g[from[i]][p[from[i]]][1] = w[i]; } return g; } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); solve(); out.flush(); long G = System.currentTimeMillis(); tr(G-S+"ms"); } private static boolean eof() { if(lenbuf == -1)return true; int lptr = ptrbuf; while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false; try { is.mark(1000); while(true){ int b = is.read(); if(b == -1){ is.reset(); return true; }else if(!isSpaceChar(b)){ is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } // private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double nd() { return Double.parseDouble(ns()); } private static char nc() { return (char)skip(); } private static String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private static int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private static int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <iostream> #include <vector> #define inf 1000000000 using namespace std; struct edge{ int to, cap, cost, rev; edge(int a, int b, int c, int d){ to = a, cap = b, cost = c, rev = d; } }; int V, E, F; vector<edge> G[1005]; int dist[1005], prev[1005], prev_e[1005]; void BellmanFord() { int v; bool update = true; while(update){ update = false; for(int i = 0; i < V; i++){ for(int j = 0; j < G[i].size(); j++){ v = G[i][j].to; if(G[i][j].cap == 0) continue; if(dist[v] > dist[i] + G[i][j].cost){ update = true; dist[v] = dist[i] + G[i][j].cost; prev[v] = i; prev_e[v] = j; } } } } } int main(void) { cin >> V >> E >> F; int u, v, c, d; for(int i = 0; i < E; i++){ cin >> u >> v >> c >> d; G[u].push_back(edge(v, c, d, G[v].size())); G[v].push_back(edge(u, 0, -d, G[u].size()-1)); } int p; int ans = 0; while(F > 0){ for(int i = 0; i < V; i++) dist[i] = inf; prev[0] = -1, dist[0] = 0; BellmanFord(); if(dist[V-1] >= inf) break; p = V-1; int minf = F; while(prev[p] != -1){ minf = min(minf, G[prev[p]][prev_e[p]].cap); p = prev[p]; } p = V-1; while(prev[p] != -1){ G[prev[p]][prev_e[p]].cap -= minf; G[p][G[prev[p]][prev_e[p]].rev].cap += minf; p = prev[p]; } F -= minf; ans += dist[V-1] * minf; } cout << ans << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> #define pb push_back using namespace std; const int INF=0x3f3f3f3f; const int maxn=105; const int maxq=1005; struct edge{int to,cap,cost,rev;}; int n,m,k; int d[maxn]; int a[maxn]; int p1[maxn]; int p2[maxn]; bool inq[maxn]; vector<edge>G[maxn]; void add_edge(int u,int v,int c,int w) { G[u].pb(edge{v,c,w,int(G[v].size())}); G[v].pb(edge{u,0,-w,int(G[u].size()-1)}); } int mcmf(int s,int t) { int flow=0 , cost=0; while (1) { memset(d,0x3f,sizeof(d)); memset(p1,0,sizeof(p1)); memset(p2,0,sizeof(p2)); d[s]=0; a[s]=max(0,k-flow); int qh=0,qt=0,q[maxq]; q[qt++]=s; inq[s]=1; while (qh<qt) { int u=q[qh++]; inq[u]=0; for (int i=0;i<G[u].size();i++) { edge e=G[u][i]; if (d[e.to]>d[u]+e.cost && e.cap) { d[e.to]=d[u]+e.cost; a[e.to]=min(a[u],e.cap); p1[e.to]=u; p2[e.to]=i; if (!inq[e.to]) { q[qt++]=e.to; inq[e.to]=1; } } } } if (d[t]==INF || !a[t]) break; flow+=a[t]; cost+=a[t]*d[t]; for (int u=t;u!=s;) { edge e=G[p1[u]][p2[u]]; G[p1[u]][p2[u]]-=d; G[e.to][e.rev]+=d; } } if (flow<k) return -1; else return cost; } int main() { cin>>n>>m>>k; for (int i=0;i<m;i++) { int u,v,c,w; cin>>u>>v>>c>>w; add_edge(u,v,c,w); } cout<<mcmf(0,n-1)<<'\n'; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f; const int MOD = (int)(1e9) + 7; template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } struct MinimumCostMaximumFlow { using Index = int; using Flow = int; using Cost = int; static const Flow INF_CAPACITY = INF; static const Cost INF_COST = INF; struct Edge { Index s, d; Flow capacity; Cost cost; }; using Edges = vector<Edge>; using Graph = vector<Edges>; Graph g; void init(Index n) { g.assign(n, Edges()); } void add_arc(Index i, Index j, Flow capacity = INF_CAPACITY, Cost cost = Cost()) { Edge e, f; e.d = j, f.d = i; e.capacity = capacity, f.capacity = 0; e.cost = cost, f.cost = -cost; g[i].push_back(e); g[j].push_back(f); g[i].back().s = (Index)g[j].size() - 1; g[j].back().s = (Index)g[i].size() - 1; } void add_edge(Index i, Index j, Flow capacity = INF_CAPACITY, Cost cost = Cost()) { add_arc(i, j, capacity, cost); add_arc(j, i, capacity, cost); } pair<Cost, Flow> minimum_cost_maximum_flow(Index s, Index t, Flow f = INF_CAPACITY, bool useSPFA = false) { int n = g.size(); vector<Cost> dist(n); vector<Index> prev(n); vector<Index> prevEdge(n); pair<Cost, Flow> total = make_pair(0, 0); vector<Cost> potential(n); while (f > 0) { fill(dist.begin(), dist.end(), INF_COST); if (useSPFA || total.second == 0) { deque<Index> q; q.push_back(s); dist[s] = 0; vector<bool> inqueue(n); while (!q.empty()) { Index i = q.front(); q.pop_front(); inqueue[i] = false; for (Index ei = 0; ei < g[i].size(); ei++) { const Edge &e = g[i][ei]; Index j = e.d; Cost d = dist[i] + e.cost; if (e.capacity > 0 && d < dist[j]) { if (!inqueue[j]) { inqueue[j] = true; q.push_back(j); } dist[j] = d; prev[j] = i; prevEdge[j] = ei; } } } } else { vector<bool> vis(n); priority_queue<pair<Cost, Index> > q; q.push(make_pair(-0, s)); dist[s] = 0; while (!q.empty()) { Index i = q.top().second; q.pop(); if (vis[i]) continue; vis[i] = true; for (Index ei = 0; ei < (Index)g[i].size(); ei++) { const Edge &e = g[i][ei]; if (e.capacity <= 0) continue; Index j = e.d; Cost d = dist[i] + e.cost + potential[i] - potential[j]; if (dist[j] > d) { dist[j] = d; prev[j] = i; prevEdge[j] = ei; q.push(make_pair(-d, j)); } } } } if (dist[t] == INF_COST) break; if (!useSPFA) for (Index i = 0; i < n; i++) potential[i] += dist[i]; Flow d = f; Cost distt = 0; for (Index v = t; v != s;) { Index u = prev[v]; const Edge &e = g[u][prevEdge[v]]; d = min(d, e.capacity); distt += e.cost; v = u; } f -= d; total.first += d * distt; total.second += d; for (Index v = t; v != s; v = prev[v]) { Edge &e = g[prev[v]][prevEdge[v]]; e.capacity -= d; g[e.d][e.s].capacity += d; } } return total; } }; signed main() { cin.tie(0); ios::sync_with_stdio(false); int V, E, F; cin >> V >> E >> F; MinimumCostMaximumFlow mcmf; mcmf.init(V); for (int i = (0); i < (E); i++) { int u, v, c, d; cin >> u >> v >> c >> d; mcmf.add_arc(u, v, c, d); } auto res = mcmf.minimum_cost_maximum_flow(0, V - 1, F); cout << res.first << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include<iostream> #include<vector> #include<queue> #include<algorithm> #define MAX 101 #define inf 1<<29 using namespace std; typedef pair<int,int> P; struct edge{ int to,cap,cost,rev; }; int v; vector<edge> e[MAX]; int h[MAX]; int dist[MAX]; int prevv[MAX],preve[MAX]; void add_edge(int from,int to,int cap,int cost){ e[from].push_back((edge){to,cap,cost,e[to].size()}); e[to].push_back((edge){from,cap,cost,e[from].size()-1}); } int min_cost_flow(int s,int t,int f){ int res=0; fill(h,h+v,0); while(f>0){ priority_queue<P,vector<P>,greater<P> > pq; fill(dist,dist+v,inf); dist[s]=0; pq.push(P(0,s)); while(pq.size()){ P p=pq.top(); pq.pop(); int u=p.second; if(dist[u]<p.first)continue; for(int i=0;i<e[u].size();i++){ edge &E=e[u][i]; if(E.cap>0 && dist[E.to]>dist[u]+E.cost+h[u]-h[E.to]){ dist[E.to]=dist[u]+E.cost+h[u]-h[E.to]; prevv[E.to]=u; preve[E.to]=i; pq.push(P(dist[E.to],E.to)); } } } if(dist[t]==inf)return -1; for(int i=0;i<v;i++)h[i]+=dist[i]; int d=f; for(int u=t;u!=s;u=prevv[u]){ d=min(d,e[prevv[u]][preve[u]].cap); } f-=d; res+=d*h[t]; for(int u=t;u!=s;u=prevv[u]){ edge &E=e[prevv[u]][preve[u]]; E.cap-=d; e[u][E.rev].cap+=d; } } return res; } int main() { int m,f,a,b,c,d; cin>>v>>m>>f; for(int i=0;i<m;i++){ cin>>a>>b>>c>>d; add_edge(a,b,c,d); } cout<<min_cost_flow(0,v-1,f)<<endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using LL = long long; constexpr LL LINF = 334ll << 53; constexpr int INF = 15 << 26; constexpr LL MOD = 1E9 + 7; struct Edge { int from, to; LL cost, capacity; int rev_id; }; struct Prev { LL cost; int from, id; }; class MinimumCostFlow { struct Edge { int to; long long cost, capacity; int rev_id; Edge(int to, long long cost, long long cap, int id) : to(to), cost(cost), capacity(cap), rev_id(id){}; Edge() { Edge(0, 0, 0, 0); } }; struct Prev { LL cost; int from, id; }; using vector<vector<Edge>> = vector<vector<Edge>>; using vector<vector<LL>> = vector<vector<long long>>; int n; vector<vector<Edge>> graph; vector<vector<LL>> flow; vector<Prev> prev; vector<long long> potential; public: MinimumCostFlow(int n) : n(n), graph(n), prev(n, {LINF, -1, -1}), potential(n) {} void addEdge(int a, int b, long long cap, long long cost) { graph[a].emplace_back(b, cost, cap, (int)graph[b].size()); graph[b].emplace_back(a, -cost, 0, (int)graph[a].size() - 1); } long long minimumCostFlow(int s, int t, LL f) { LL ret = 0; for (bellman_ford(s); f > 0; dijkstra(s)) { if (prev[t].cost == LINF) return -1; for (int i = 0; i < n; ++i) potential[i] = min(potential[i] + prev[i].cost, LINF); LL d = f; for (int v = t; v != s; v = prev[v].from) { d = min(d, graph[prev[v].from][prev[v].id].capacity - flow[prev[v].from][v]); } f -= d; ret += d * potential[t]; for (int v = t; v != s; v = prev[v].from) { flow[prev[v].from][v] += d; flow[v][prev[v].from] -= d; } } return ret; } private: bool dijkstra(const int start) { int visited = 0, N = graph.size(); fill(prev.begin(), prev.end(), (Prev){LINF, -1, -1}); priority_queue<tuple<LL, int, int, int>, vector<tuple<LL, int, int, int>>, greater<tuple<LL, int, int, int>>> pque; pque.emplace(0, start, 0, -1); LL cost; int place, from, id; while (!pque.empty()) { tie(cost, place, from, id) = pque.top(); pque.pop(); if (prev[place].from != -1) continue; prev[place] = {cost, from, id}; visited++; if (visited == N) return true; for (int i = 0; i < (int)graph[place].size(); ++i) { auto e = &graph[place][i]; if (e->capacity > flow[place][e->to] && prev[e->to].from == -1) { pque.emplace(e->cost + cost - potential[e->to] + potential[place], e->to, place, i); } } } return false; } bool bellman_ford(const int start) { int s = graph.size(); bool update = false; prev[start] = (Prev){0ll, start, -1}; for (int i = 0; i < s; ++i, update = false) { for (int j = 0; j < s; ++j) { for (auto &e : graph[j]) { if (e.capacity == 0) continue; if (prev[j].cost != LINF && prev[e.to].cost > prev[j].cost + e.cost) { prev[e.to].cost = prev[j].cost + e.cost; prev[e.to].from = j; prev[e.to].id = e.rev_id; update = true; if (i == s - 1) return false; } } } if (!update) break; } return true; } }; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, m; LL flow; cin >> n >> m >> flow; MinimumCostFlow mcf(n); for (int i = 0; i < m; i++) { int a, b; LL cost, cap; cin >> a >> b >> cap >> cost; mcf.addEdge(a, b, cap, cost); } cout << mcf.minimumCostFlow(0, n - 1, flow) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
UNKNOWN
#include <bits/stdc++.h> struct node { int id; int cap; int cost; struct node *next; }; struct node **list; int **flow, *delta, *dist, *prev; int *heap, *heap_index, heapsize; void Insert(int, int, int, int); void downheap(int); void upheap(int); void PQ_init(int); int PQ_remove(void); void PQ_update(int); int Maxflow(int, int, int); int main(void) { int i, v, e, f, s, t, c, d, mincost = 0; scanf("%d %d %d", &v, &e, &f); list = (struct node **)malloc(sizeof(struct node *) * v); flow = (int **)malloc(sizeof(int *) * v); delta = (int *)malloc(sizeof(int) * v); dist = (int *)malloc(sizeof(int) * v); prev = (int *)malloc(sizeof(int) * v); for (i = 0; i < v; i++) { list[i] = NULL; flow[i] = (int *)calloc(v, sizeof(int)); } for (i = 0; i < e; i++) { scanf("%d %d %d %d", &s, &t, &c, &d); Insert(s, t, c, d); } while (Maxflow(0, v - 1, v) && f) { int n = v - 1; do { flow[prev[n]][n] += delta[v - 1]; flow[n][prev[n]] -= delta[v - 1]; n = prev[n]; } while (n); f -= delta[v - 1]; } if (!f) { for (i = 0; i < v; i++) { struct node *n; for (n = list[i]; n != NULL; n = n->next) { mincost += flow[i][n->id] * n->cost; } } printf("%d\n", mincost); } else printf("-1\n"); for (i = 0; i < v; i++) { free(list[i]); free(flow[i]); } free(list); free(flow); free(delta); free(dist); free(prev); } void Insert(int a, int b, int cap, int cost) { struct node *p = (struct node *)malloc(sizeof(struct node)); p->id = b; p->cap = cap; p->cost = cost; p->next = list[a]; list[a] = p; p = (struct node *)malloc(sizeof(struct node)); p->id = a; p->cap = 0; p->cost = 0; p->next = list[b]; list[b] = p; } void downheap(int k) { int j, v = heap[k]; while (k < heapsize / 2) { j = 2 * k + 1; if (j < heapsize - 1 && dist[heap[j]] > dist[heap[j + 1]]) j++; if (dist[v] <= dist[heap[j]]) break; heap[k] = heap[j]; heap_index[heap[j]] = k; k = j; } heap[k] = v; heap_index[v] = k; } void upheap(int j) { int k, v = heap[j]; while (j > 0) { k = (j + 1) / 2 - 1; if (dist[v] >= dist[heap[k]]) break; heap[j] = heap[k]; heap_index[heap[k]] = j; j = k; } heap[j] = v; heap_index[v] = j; } void PQ_init(int size) { int i; heapsize = size; heap = (int *)malloc(sizeof(int) * size); heap_index = (int *)malloc(sizeof(int) * size); for (i = 0; i < size; i++) { heap[i] = i; heap_index[i] = i; } for (i = heapsize / 2 - 1; i >= 0; i--) downheap(i); } int PQ_remove(void) { int v = heap[0]; heap[0] = heap[heapsize - 1]; heap_index[heap[heapsize - 1]] = 0; heapsize--; downheap(0); return v; } void PQ_update(int v) { upheap(heap_index[v]); } int Maxflow(int s, int t, int size) { struct node *n; int i; for (i = 0; i < size; i++) { delta[i] = INT_MAX; dist[i] = INT_MAX; prev[i] = -1; } dist[s] = 0; PQ_init(size); while (heapsize) { i = PQ_remove(); if (i == t) break; for (n = list[i]; n != NULL; n = n->next) { int v = n->id; if (flow[i][v] < n->cap) { int newlen = dist[i] + n->cost; if (newlen < dist[v]) { dist[v] = newlen; prev[v] = i; delta[v] = ((delta[i]) < (n->cap - flow[i][v]) ? (delta[i]) : (n->cap - flow[i][v])); PQ_update(v); } } } } free(heap); free(heap_index); return dist[t] != INT_MAX; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using i64 = long long; struct edge { i64 from; i64 to; i64 cap; i64 cost; i64 rev; }; i64 INF = 1e8; i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g, std::vector<i64> b) { i64 ans = 0; i64 U = *std::max_element(begin(b), end(b)); i64 delta = (1 << ((int)(std::log2(U)) + 1)); int n = g.size(); std::vector<i64> e = b; std::vector<i64> p(n, 0); int zero = 0; for (auto x : e) { if (x == 0) zero++; } for (; delta > 0; delta >>= 1) { if (zero == n) break; while (true) { std::vector<std::size_t> pv(n, -1); std::vector<std::size_t> pe(n, -1); std::vector<std::size_t> start(n, -1); std::vector<i64> dist(n, INF); using P = std::pair<i64, i64>; std::priority_queue<P, std::vector<P>, std::greater<P>> que; for (int s = 0; s < n; s++) { if (e[s] >= delta) { dist[s] = 0; start[s] = s; que.push({dist[s], s}); } } if (que.empty()) break; while (!que.empty()) { int v = que.top().second; i64 d = que.top().first; que.pop(); if (dist[v] < d) continue; for (std::size_t i = 0; i < g[v].size(); i++) { const auto& e = g[v][i]; std::size_t u = e.to; if (e.cap == 0) continue; assert(e.cost + p[v] - p[u] >= 0); if (dist[u] > dist[v] + e.cost + p[v] - p[u]) { dist[u] = dist[v] + e.cost + p[v] - p[u]; pv[u] = v; pe[u] = i; start[u] = start[v]; que.push({dist[u], u}); } } } for (int i = 0; i < n; i++) { p[i] += dist[i]; } for (int t = 0; t < n; t++) { if (e[t] <= -delta && pv[t] != -1 && e[start[t]] >= delta) { std::size_t u = t; for (; pv[u] != -1; u = pv[u]) { ans += delta * g[pv[u]][pe[u]].cost; g[pv[u]][pe[u]].cap -= delta; g[u][g[pv[u]][pe[u]].rev].cap += delta; } e[u] -= delta; e[t] += delta; if (e[u] == 0) zero++; if (e[t] == 0) zero++; } } } } if (zero == n) return ans; else return -1e18; } int main() { i64 N, M, F; cin >> N >> M >> F; vector<vector<edge>> g(N + M); vector<i64> e(N + M, 0); int s = 0; int t = N - 1; e[s + M] = F; e[t + M] = -F; for (int i = 0; i < M; i++) { i64 a, b, c, d; cin >> a >> b >> c >> d; e[i] = c; e[a + M] -= c; g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()}); g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1}); g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()}); g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1}); } i64 ans = capacity_scaling_bflow(g, e); if (ans == -1e18) { cout << -1 << endl; } else { cout << ans << endl; } }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; const int INF = 1 << 29; void print_adjacency_list( const vector<vector<tuple<int, int, int, int> > > &adj) { cout << "st_nd: (ed_nd, capa, cost, st_ind), ..." << endl; for (int st_nd = 0; st_nd < adj.size(); ++st_nd) { cout << st_nd << ":"; for (auto itr = adj[st_nd].begin(); itr != adj[st_nd].end(); ++itr) { int ed_nd, capa, cost, st_ind; tie(ed_nd, capa, cost, st_ind) = *itr; cout << " (" << ed_nd << ", " << capa << ", " << cost << ", " << st_ind << ")"; } cout << endl; } } int min_cost_flow(const int src_nd, const int sink_nd, const int flow_vol, vector<vector<tuple<int, int, int, int> > > adj) { int flow_res = flow_vol; int min_cost = 0; int n_nodes = adj.size(); while (flow_res > 0) { vector<int> dist(n_nodes, INF); vector<pair<int, int> > pred(n_nodes, make_pair(-1, -1)); dist[src_nd] = 0; bool relax = true; while (relax) { relax = false; for (int st_nd = 0; st_nd < n_nodes; ++st_nd) { if (dist[st_nd] == INF) { continue; } for (int ed_ind = 0; ed_ind < adj[st_nd].size(); ++ed_ind) { int ed_nd, capa, cost; tie(ed_nd, capa, cost, ignore) = adj[st_nd][ed_ind]; if (capa > 0 && dist[st_nd] + cost < dist[ed_nd]) { dist[ed_nd] = dist[st_nd] + cost; pred[ed_nd] = make_pair(st_nd, ed_ind); relax = true; } } } } if (dist[sink_nd] == INF) { cout << "@SS" << endl; return -1; } int flow = flow_vol; for (int nd = sink_nd; nd != src_nd; nd = get<0>(pred[nd])) { int pre_nd, nd_ind; tie(pre_nd, nd_ind) = pred[nd]; flow = min(flow, get<1>(adj[pre_nd][nd_ind])); } flow_res -= flow; min_cost += dist[sink_nd] * flow; for (int nd = sink_nd; nd != src_nd; nd = get<0>(pred[nd])) { int pre_nd, nd_ind; tie(pre_nd, nd_ind) = pred[nd]; int &capa = get<1>(adj[pre_nd][nd_ind]); int pre_ind; tie(ignore, ignore, ignore, pre_ind) = adj[pre_nd][nd_ind]; int &rev_capa = get<1>(adj[nd][pre_ind]); capa -= flow; rev_capa += flow; } } return min_cost; } int main(int argc, char *argv[]) { int n_nodes, n_links, flow_vol; cin >> n_nodes >> n_links >> flow_vol; vector<vector<tuple<int, int, int, int> > > adj(n_nodes); for (int lk = 0; lk < n_links; ++lk) { int st_nd, ed_nd, capa, cost; cin >> st_nd >> ed_nd >> capa >> cost; adj[st_nd].push_back(make_tuple(ed_nd, capa, cost, adj[ed_nd].size())); adj[ed_nd].push_back(make_tuple(st_nd, 0, -cost, adj[st_nd].size() - 1)); } int src_nd = 0; int sink_nd = n_nodes - 1; cout << min_cost_flow(src_nd, sink_nd, flow_vol, adj) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; using Int = long long; template <typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; } template <typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; } template <typename T> struct PrimalDual { struct edge { int to; T cap, cost; int rev; edge() {} edge(int to, T cap, T cost, int rev) : to(to), cap(cap), cost(cost), rev(rev) {} }; T INF; vector<vector<edge> > G; vector<T> h, dist; vector<int> prevv, preve; PrimalDual() {} PrimalDual(int n, T INF) : INF(INF), G(n), h(n), dist(n), prevv(n), preve(n) {} void add_edge(int from, int to, T cap, T cost) { G[from].emplace_back(to, cap, cost, G[to].size()); G[to].emplace_back(from, 0, -cost, G[from].size() - 1); } T flow(int s, int t, T f, int &ok) { T res = 0; fill(h.begin(), h.end(), 0); while (f > 0) { struct P { T first; int second; P(T first, int second) : first(first), second(second) {} bool operator<(const P &a) const { return first > a.first; } }; priority_queue<P> que; fill(dist.begin(), dist.end(), INF); dist[s] = 0; que.emplace(dist[s], s); while (!que.empty()) { P p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; for (int i = 0; i < (int)G[v].size(); i++) { edge &e = G[v][i]; if (e.cap == 0) continue; if (dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.emplace(dist[e.to], e.to); } } } if (dist[t] == INF) return ok = 0; for (int v = 0; v < (int)h.size(); v++) h[v] += dist[v]; T d = f; for (int v = t; v != s; v = prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap); f -= d; res += d * h[t]; for (int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } ok = 1; return res; } }; int GRL_6_B() { int v, e, f; cin >> v >> e >> f; const int INF = 1 << 28; PrimalDual<int> pd(v, INF); for (int i = 0; i < e; i++) { int u, v, c, d; cin >> u >> v >> c >> d; pd.add_edge(u, v, c, d); } int ok = 0; int res = pd.flow(0, v - 1, f, ok); cout << (ok ? res : -1) << endl; return 0; } signed SPOJ_GREED_solve() { int n; cin >> n; vector<int> cnt(n, 0); for (int i = 0; i < n; i++) { int x; cin >> x; cnt[x - 1]++; } using ll = long long; const ll INF = 1 << 28; int S = n, T = n + 1; PrimalDual<ll> G(n + 2, INF); int m; cin >> m; for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; x--; y--; G.add_edge(x, y, INF, 1); G.add_edge(y, x, INF, 1); } for (int i = 0; i < n; i++) { G.add_edge(S, i, cnt[i], 0); G.add_edge(i, T, 1, 0); } int ok = 0; ll res = G.flow(S, T, n, ok); assert(ok); cout << res << endl; return 0; } signed SPOJ_GREED() { cin.tie(0); ios::sync_with_stdio(0); int t; cin >> t; while (t--) SPOJ_GREED_solve(); return 0; } signed CFR190_B() { int n, m; cin >> n >> m; vector<string> vp(n); vector<int> vs(n); for (int i = 0; i < n; i++) cin >> vp[i] >> vs[i]; vector<int> ss(m); for (int i = 0; i < m; i++) cin >> ss[i]; const int INF = 1 << 28; using ll = long long; PrimalDual<ll> G(n + m + 3, INF); int S = n + m, T = n + m + 1, V = n + m + 2; for (int i = 0; i < m; i++) { G.add_edge(S, i, 1, 0); G.add_edge(i, V, 1, -ss[i]); for (int j = 0; j < n; j++) { if (vp[j] == "ATK") { if (ss[i] >= vs[j]) G.add_edge(i, m + j, 1, vs[j] - ss[i]); } if (vp[j] == "DEF") { if (ss[i] > vs[j]) G.add_edge(i, m + j, 1, 0); } } } for (int i = 0; i < n; i++) G.add_edge(m + i, T, 1, -INF); G.add_edge(V, T, m, 0); ll ans = 0, res = 0; for (int i = 1; i <= m; i++) { int ok = 0; res += G.flow(S, T, 1, ok); if (i <= n) res += INF; if (ok) chmax(ans, -res); else break; } cout << ans << endl; return 0; } signed main() { return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; namespace MCF { const int MAXN = 120; const int MAXM = 2100; int to[MAXM]; int next[MAXM]; int first[MAXN]; int c[MAXM]; long long w[MAXM]; long long pot[MAXN]; int rev[MAXM]; long long ijk[MAXN]; int v[MAXN]; long long toc; int tof; int n; int m; void init(int _n) { n = _n; for (int i = 0; i < n; i++) first[i] = -1; } void ae(int a, int b, int cap, int wei) { next[m] = first[a]; to[m] = b; first[a] = m; c[m] = cap; w[m] = wei; m++; next[m] = first[b]; to[m] = a; first[b] = m; c[m] = 0; w[m] = -wei; m++; } int solve(int s, int t, int flo) { toc = tof = 0; while (tof < flo) { for (int i = 0; i < n; i++) ijk[i] = 9999999999999LL; for (int i = 0; i < n; i++) v[i] = 0; priority_queue<pair<long long, int> > Q; ijk[s] = 0; Q.push(make_pair(0, s)); while (Q.size()) { long long cost = -Q.top().first; int at = Q.top().second; Q.pop(); if (v[at]) continue; v[at] = 1; for (int i = first[at]; ~i; i = next[i]) { int x = to[i]; if (v[x] || ijk[x] <= ijk[at] + w[i] + pot[x] - pot[at]) continue; if (c[i] == 0) continue; ijk[x] = ijk[at] + w[i] + pot[x] - pot[at]; rev[x] = i; Q.push(make_pair(-ijk[x], x)); } } int flow = flo - tof; if (!v[t]) return 0; int at = t; while (at != s) { flow = min(flow, c[rev[at]]); at = to[rev[at] ^ 1]; } at = t; tof += flow; toc += flow * (ijk[t] + pot[s] - pot[t]); at = t; while (at != s) { c[rev[at]] -= flow; c[rev[at] ^ 1] += flow; at = to[rev[at] ^ 1]; } for (int i = 0; i < n; i++) pot[i] += ijk[i]; } return 1; } } // namespace MCF int main() { int a, b, c; scanf("%d%d%d", &a, &b, &c); MCF::init(a); for (int i = 0; i < b; i++) { int p, q, r, s; scanf("%d%d%d%d", &p, &q, &r, &s); MCF::ae(p, q, r, s); } int res = MCF::solve(0, a - 1, c); if (!res) printf("-1\n"); else printf("%lld\n", MCF::toc); }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
// warm heart, wagging tail,and a smile just for you! // ███████████ // ███╬╬╬╬╬╬╬╬╬╬███ // ███╬╬╬╬╬╬╬██╬╬╬╬╬╬███ // ███████████ ██╬╬╬╬╬████╬╬████╬╬╬╬╬██ // █████████╬╬╬╬╬████████████╬╬╬╬╬██╬╬╬╬╬╬███╬╬╬╬╬██ // ████████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████████╬╬╬╬╬╬██╬╬╬╬╬╬╬██ // ████╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████████╬╬╬╬╬╬╬╬╬╬╬██ // ███╬╬╬█╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬███╬╬╬╬╬╬╬█████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬████████╬╬╬╬╬██ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬╬╬╬╬╬███ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬██ // ████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████╬╬╬╬╬████ // █████████████╬╬╬╬╬╬╬╬██╬╬╬╬╬████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬██████ // ████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬██████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██████╬╬╬╬╬╬╬███████████╬╬╬╬╬╬╬╬██╬╬╬██╬╬╬██ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████╬╬╬╬╬╬╬╬╬╬╬█╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬██ // ██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬▓▓▓▓▓▓╬╬╬████╬╬████╬╬╬╬╬╬╬▓▓▓▓▓▓▓▓▓█╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬███ // ██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██████▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓▓▓▓▓▓▓█╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬█████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██ // ██████████████ ████╬╬╬╬╬╬███████████████████████████╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████ // ███████ █████ ███████████████████ #include "bits/stdc++.h" using namespace std; #define MOD 1000000007 #define INF 1LL<<60 #define fs first #define sc second #define pb push_back #define int long long #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define RFOR(i,a,b) for(int i = (b-1);i>=a;i--) #define REP(i,n) FOR(i,0,n) #define RREP(i,n) RFOR(i,0,n) #define ITR(itr,mp) for(auto itr = (mp).begin(); itr != (mp).end(); ++itr) #define RITR(itr,mp) for(auto itr = (mp).rbegin(); itr != (mp).rend(); ++itr) #define range(i,a,b) (a)<=(i) && (i)<(b) #define debug(x) cout << #x << " = " << (x) << endl; typedef pair<int,int> P; typedef vector<vector<P> > Graph; struct edge{int to,cap,cost,rev;}; const int MAX_V = 3e5; int V; vector<edge> G[MAX_V]; vector<int> h,dist,prevv(MAX_V),preve(MAX_V); void add_edge(int from, int to, int cap, int cost){ G[from].pb((edge){to,cap,cost,G[to].size()}); G[to].pb((edge){from,0,-cost,G[from].size()-1}); } int min_cost_flow(int s, int t, int f){ int res = 0; h.assign(V,0); while(f > 0){ priority_queue<P,vector<P>,greater<P> > que; dist.assign(V,INF); dist[s] = 0; que.push(P(0,s)); while(!que.empty()){ P p = que.top(); que.pop(); int v = p.sc; if(dist[v] < p.fs) continue; REP(i,G[v].size()){ edge &e = G[v][i]; if(e.cap > 0 && dist[e.to] > dist[v]+e.cost+h[v]-h[e.to]){ dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(P(dist[e.to],e.to)); } } } if(dist[t] == INF) return -1; REP(v,V) h[v] += dist[v]; int d = f; for(int v = t; v != s; v = prevv[v]) d = min(d,G[prevv[v]][preve[v]].cap); f -= d; res += d*h[t]; for(int v = t; v != s; v = prevv[v]){ edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } // Vを頂点数で更新する!! signed main(){ ios::sync_with_stdio(false); cin.tie(0); int v,e,f; cin >> v >> e >> f; V = v; REP(_,e){ int s,t,cap,dist; cin >> s >> t >> cap >> dist; add_edge(s,t,cap,dist); } cout << min_cost_flow(0,v-1,f) << endl; return 0; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using Vertex = int; using Flow = long double; using Cost = long double; const Flow FLOW_INF = LDBL_MAX; const Cost COST_INF = LDBL_MAX; struct Edge { Vertex from, to; Flow capacity; Cost cost; int rev; Edge(Vertex from, Vertex to, Flow capacity = 0, Cost cost = 0, int rev = -1) : from(from), to(to), capacity(capacity), cost(cost), rev(rev) {} }; class FlowNetwork { public: FlowNetwork(int n); void insert(const Edge&); Flow maximum_flow(Vertex source, Vertex sink) const; Cost minimum_cost_flow(Vertex source, Vertex sink, Flow f) const; private: Vertex size_; std::vector<std::vector<Edge>> edge_; }; FlowNetwork::FlowNetwork(int n) : size_(n), edge_(n) {} void FlowNetwork::insert(const Edge& e) { edge_.at(e.from).emplace_back(e.from, e.to, e.capacity, e.cost, edge_.at(e.to).size()); edge_.at(e.to).emplace_back(e.to, e.from, 0, -e.cost, edge_.at(e.from).size() - 1); } Flow FlowNetwork::maximum_flow(Vertex source, Vertex sink) const { std::vector<int> level; std::vector<int> itr; auto residue = edge_; auto bfs = [&]() { level.assign(size_, -1); level.at(source) = 0; std::queue<int> q; q.push(source); while (!q.empty()) { auto v = q.front(); q.pop(); for (const auto& e : residue.at(v)) if (!~level.at(e.to)) if (0 < e.capacity) { level.at(e.to) = level.at(e.from) + 1; q.push(e.to); } } return level.at(sink); }; std::function<Flow(Vertex, Flow)> dfs = [&](Vertex v, Flow cur) { if (v == sink) return cur; for (auto& i = itr.at(v); i < residue.at(v).size(); ++i) { auto& e = residue.at(v).at(i); if (level.at(e.from) < level.at(e.to)) if (0 < e.capacity) { auto f = dfs(e.to, std::min(cur, e.capacity)); if (f == 0) continue; e.capacity -= f; residue.at(e.to).at(e.rev).capacity += f; return f; } } return Flow(0); }; Flow result = 0; while (~bfs()) { itr.assign(size_, 0); while (auto f = dfs(source, FLOW_INF)) result += f; } return result; } Cost FlowNetwork::minimum_cost_flow(Vertex source, Vertex sink, Flow f) const { std::vector<Cost> h(size_, 0); auto residue = edge_; Flow result = 0; while (0 < f) { using Node = std::tuple<Cost, Vertex>; std::vector<Cost> dist(size_, COST_INF); dist.at(source) = 0; std::vector<Edge*> prev(size_, nullptr); std::priority_queue<Node, std::vector<Node>, std::greater<Node>> q; q.emplace(0, source); while (!q.empty()) { Cost c; Vertex v; std::tie(c, v) = q.top(); q.pop(); if (dist.at(v) < c) continue; for (auto& e : residue.at(v)) { if (e.capacity <= 0) continue; if (dist.at(e.to) <= dist.at(e.from) + e.cost + h.at(e.from) - h.at(e.to)) continue; dist.at(e.to) = dist.at(e.from) + e.cost + h.at(e.from) - h.at(e.to); prev.at(e.to) = &e; q.emplace(dist.at(e.to), e.to); } } if (dist.at(sink) == COST_INF) return -1; for (int v = 0; v < size_; ++v) if (dist.at(v) != COST_INF) h.at(v) += dist.at(v); Flow d = f; for (auto& e : prev) if (e != nullptr) d = std::min(d, e->capacity); f -= d; result += d * h.at(sink); for (auto& e : prev) if (e != nullptr) { e->capacity -= d; residue.at(e->to).at(e->rev).capacity += d; } } return result; } using namespace std; int main() { int V, E, F; cin >> V >> E >> F; FlowNetwork G(V); for (int i = 0; i < E; ++i) { Vertex u, v; Flow c; Cost d; cin >> u >> v >> c >> d; G.insert({u, v, c, d}); } cout << G.minimum_cost_flow(0, V - 1, F) << endl; }
p02377 Minimum Cost Flow
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
{ "input": [ "4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1", "" ], "output": [ "6", "" ] }
{ "input": [], "output": [] }
IN-CORRECT
cpp
#include <bits/stdc++.h> using namespace std; class Networkflow { private: struct edgedata { int from, to, capacity, weight; edgedata* dual_p; bool operator<(const edgedata& another) const { return (weight != another.weight ? weight < another.weight : capacity > another.capacity); } }; struct node { int id, d; bool done; edgedata* fromedge_p; list<edgedata> edges; bool operator<(const node& another) const { return !(d != another.d ? d < another.d : id < another.id); } }; vector<node> nodes; int n; int source, sink; edgedata* dummy; public: int result; Networkflow(int size, int s, int t) { n = size; source = s; sink = t; nodes.resize(n); dummy = new edgedata; init(); } void init() { for (int i = 0; i < (int)n; i++) { nodes[i] = {i, 2147483647, false, dummy, {}}; } } void addedge(int s, int t, int c, int w) { nodes[s].edges.push_back({s, t, c, w, dummy}); nodes[t].edges.push_back({t, s, 0, w * (-1), &(nodes[s].edges.back())}); nodes[s].edges.back().dual_p = &(nodes[t].edges.back()); } void maxflow() { for (int i = 0; i < (int)n; i++) nodes[i].edges.sort(); result = 0; vector<pair<int, edgedata*>> stk; int a; int df; while (1) { a = source; for (int i = 0; i < (int)n; i++) nodes[i].done = false; nodes[source].done = true; while (a != sink) { int b = -1; edgedata* p; for (auto itr = nodes[a].edges.begin(); itr != nodes[a].edges.end(); ++itr) { if ((*itr).capacity > 0) { b = (*itr).to; if (nodes[b].done) b = -1; else { p = &(*itr); stk.push_back(make_pair(a, p)); nodes[b].done = true; a = b; break; } } } if (b == -1) { if (stk.empty()) break; a = stk.back().first; stk.pop_back(); } } if (stk.empty()) break; df = 2147483647; for (int i = 0; i < (int)stk.size(); i++) { df = min(df, (*(stk[i].second)).capacity); } while (stk.size()) { (*(stk.back().second)).capacity -= df; (*((*(stk.back().second)).dual_p)).capacity += df; stk.pop_back(); } result += df; } return; } bool mincostflow(int flow) { for (int i = 0; i < (int)n; i++) nodes[i].edges.sort(); result = 0; node a; int df; int sumf = 0; while (1) { for (int i = 0; i < (int)n; i++) { nodes[i].d = 2147483647; nodes[i].done = false; nodes[i].fromedge_p = dummy; } priority_queue<node> pq; nodes[source].d = 0; pq.push(nodes[source]); while (pq.size()) { a = pq.top(); pq.pop(); if (nodes[a.id].done) continue; nodes[a.id].done = true; for (auto itr = nodes[a.id].edges.begin(); itr != nodes[a.id].edges.end(); ++itr) { if ((*itr).capacity == 0) continue; node* b = &nodes[(*itr).to]; if ((*b).done) continue; long long int cand = nodes[a.id].d + ((*itr).weight); if (cand < (*b).d) { (*b).d = cand; (*b).fromedge_p = &(*itr); pq.push(*b); } } } if (!nodes[sink].done) break; df = 2147483647; int focus = sink; while (focus != source) { df = min(df, (*(nodes[focus].fromedge_p)).capacity); focus = (*(nodes[focus].fromedge_p)).from; } df = min(df, flow - sumf); focus = sink; while (focus != source) { (*(nodes[focus].fromedge_p)).capacity -= df; (*((*(nodes[focus].fromedge_p)).dual_p)).capacity += df; focus = (*(nodes[focus].fromedge_p)).from; } sumf += df; result += nodes[sink].d * df; if (sumf == flow) return true; } return false; } }; int main() { int v, e, f; cin >> v >> e >> f; Networkflow networkflow(v, 0, v - 1); for (int i = 0; i < (int)e; i++) { int s, t, c, d; cin >> s >> t >> c >> d; networkflow.addedge(s, t, c, d); } bool judge = networkflow.mincostflow(f); if (judge) cout << networkflow.result << endl; else cout << -1 << endl; return 0; }