Search is not available for this dataset
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
|
---|---|---|---|---|---|---|
p02226 Test | test
UnionFind(バイナリ入力)
Example
Input
Output | {
"input": [
""
],
"output": [
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | python3 | |
p02226 Test | test
UnionFind(バイナリ入力)
Example
Input
Output | {
"input": [
""
],
"output": [
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
namespace procon {
class UnionFind {
private:
struct nodeinfo {
int par;
int rank;
nodeinfo(int par) : par(par), rank(0) {}
};
std::vector<nodeinfo> node;
public:
UnionFind(int n) : node() {
node.reserve(n);
for (int i = 0; i < n; ++i) {
node.push_back(nodeinfo(i));
}
}
int root(int x) {
if (node[x].par == x) {
return x;
}
return node[x].par = root(node[x].par);
}
void unite(int x, int y) {
x = root(x);
y = root(y);
if (x == y) {
return;
}
if (node[x].rank < node[y].rank) {
node[x].par = y;
} else {
node[y].par = x;
if (node[x].rank == node[y].rank) {
++node[x].rank;
}
}
}
bool is_same_set(int x, int y) { return root(x) == root(y); }
};
} // namespace procon
int main(void) {
int size, n_query;
std::cin.read((char *)&size, sizeof(int));
std::cin.read((char *)&n_query, sizeof(int));
std::vector<uint64_t> query(n_query);
std::cin.read((char *)query.data(), sizeof(uint64_t) * n_query);
const int mask = (1 << 30) - 1;
uint64_t res = 123456789;
procon::UnionFind uf(size);
for (uint64_t q : query) {
const int com = q >> 60;
const int x = (q >> 30) & mask;
const int y = (q >> 0) & mask;
assert(0 <= x && x < size);
assert(0 <= y && y < size);
if (com) {
res = res * 17 + (uf.is_same_set(x, y) ? 1 : 0);
} else {
uf.unite(x, y);
}
}
std::cout << res << std::endl;
return 0;
}
|
p02226 Test | test
UnionFind(バイナリ入力)
Example
Input
Output | {
"input": [
""
],
"output": [
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | python3 | print(2)
|
p02226 Test | test
UnionFind(バイナリ入力)
Example
Input
Output | {
"input": [
""
],
"output": [
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | python3 | print(1)
|
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 SuccessiveShortestPath {
struct Edge{ int to, cap, cost, rev; };
int n, init;
vector<vector<Edge>> g;
vector<int> dist, pv, pe, h;
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 dijkstra(int s, int t) {
dist = vector<int>(n, init);
using Node = pair<int, int>;
priority_queue<Node, vector<Node>, greater<Node>> pq;
pq.push({dist[s] = 0, s});
while (!pq.empty()) {
auto d = pq.top().first;
auto u = pq.top().second;
pq.pop();
if (dist[u] < d) continue;
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 + h[u] - h[v]) {
dist[v] = dist[u] + e.cost + h[u] - h[v];
pv[v] = u;
pe[v] = i;
pq.push({dist[v], v});
}
}
}
return dist[t];
}
int build(int s, int t, int f) {
int res = 0;
h = vector<int>(n, 0);
while (f > 0) {
if (dijkstra(s, t) == init) return -1;
for (int i = 0; i < n; ++i) h[i] += dist[i];
int flow = f;
for (int u = t; u != s; u = pv[u]) {
flow = min(flow, g[pv[u]][pe[u]].cap);
}
f -= flow;
res += flow * h[t];
for (int u = t; u != s; u = pv[u]) {
Edge& e = g[pv[u]][pe[u]];
e.cap -= flow;
g[u][e.rev].cap += flow;
}
}
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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
long long INF = 1000000000000000;
long long primal_dual(vector<map<int, pair<long long, int>>> &E, int s, int t, long long F){
int V = E.size();
for (int i = 0; i < V; i++){
for (auto edge : E[i]){
if (!E[edge.first].count(i)){
E[edge.first][i] = make_pair(0, -edge.second.second);
}
}
}
long long ans = 0;
vector<long long> h(V, 0);
while (F > 0){
vector<long long> d(V, INF);
vector<long long> m(V, INF);
vector<int> prev(V, -1);
d[s] = 0;
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> Q;
Q.push(make_pair(0, s));
while (!Q.empty()){
long long c = Q.top().first;
int v = Q.top().second;
Q.pop();
if(d[v] >= c){
for (auto P : E[v]){
int w = P.first;
long long cap = P.second.first;
int cost = P.second.second;
if (cap > 0 && d[w] > d[v] + cost + h[v] - h[w]){
d[w] = d[v] + cost + h[v] - h[w];
prev[w] = v;
m[w] = min(m[v], cap);
Q.push(make_pair(d[w], w));
}
}
}
}
if (d[t] == INF){
return -1;
}
for (int i = 0; i < V; i++){
h[i] += d[i];
}
int f = min(m[t], F);
int c = t;
while (c != s){
E[prev[c]][c].first -= f;
E[c][prev[c]].first += f;
c = prev[c];
}
F -= f;
ans += f * h[t];
}
return ans;
}
int main(){
int N, M, F;
cin >> N >> M >> F;
vector<map<int, pair<long long , int>>> E(N);
for (int i = 0; i < M; i++){
int u, v, c, d;
cin >> u >> v >> c >> d;
E[u][v] = make_pair(c, d);
}
cout << primal_dual(E, 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 <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cassert>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <bitset>
using namespace std;
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) repl(i,0,n)
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define fi first
#define se second
#define INF 2147483600
template<typename T>
class MinCostFlow{
private:
struct edge{int to; T cap, cost; int rev;};
using P = pair<int,int>;
vector<vector<edge> > Graph;
vector<int> prevv, preve;
vector<T> h, d; // ??????????????£?????????????????¢
public:
MinCostFlow(int v){
// ????????°v??§?????????
Graph.resize(v);
prevv.resize(v);
preve.resize(v);
h.resize(v);
d.resize(v);
}
T min_cost_flow(int s, int t, T f){
T res = 0;
fill(all(h), 0);
while(f>0){
priority_queue<P, vector<P>, greater<P>> pq;
fill(all(d), INF);
d[s] = 0;
pq.push(mp(0,s));
while(!pq.empty()){
auto p = pq.top(); pq.pop();
int v = p.se;
if(d[v] < p.fi) continue;
rep(i,Graph[v].size()){
edge &e = Graph[v][i];
if(e.cap > 0 && d[e.to] > d[v] + e.cost + h[v] - h[e.to]){
d[e.to] = d[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v;
preve[e.to] = i;
pq.push(mp(d[e.to], e.to));
}
}
}
if(d[t] == INF) return -1;
rep(i,Graph.size()) h[i] += d[i];
T nf = f;
for(int v=t; v!=s; v = prevv[v]){
nf = min(nf, Graph[prevv[v]][preve[v]].cap);
}
f -= nf;
res += nf * h[t];
for(int v=t; v!=s; v=prevv[v]){
edge &e = Graph[prevv[v]][preve[v]];
e.cap -= nf;
Graph[v][e.rev].cap += nf;
}
}
return res;
}
void add_edge(int from ,int to, T cap, T cost){
Graph[from].pb(((edge){to, cap, cost, (int)Graph[to].size()}));
Graph[to].pb(((edge){from, 0, -cost, (int)Graph[from].size()-1}));
}
};
int main(){
int v,e,f;
cin>>v>>e>>f;
MinCostFlow<int> flow(v);
rep(i,e){
int a,b,c,d;
scanf("%d %d %d %d", &a, &b, &c, &d);
flow.add_edge(a, b, c, d);
}
cout<<flow.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.util.*;
public class Main implements Runnable {
private static int MOD = 1_000_000_007;
public static void main(String[] args) {
// Run with 32MB stack
Thread thread = new Thread(null, new Main(), "", 32 * 1024 * 1024);
thread.start();
}
@Override
public void run() {
final Scanner scanner = new Scanner(System.in);
solve(scanner);
}
static void solve(Scanner scanner) {
int V = scanner.nextInt();
int E = scanner.nextInt();
int F = scanner.nextInt();
scanner.nextLine();
MinCost minCost = new MinCost(V);
for (int i = 0; i < E; i++) {
int[] e = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
minCost.addEdge(e[0], e[1], e[3], e[2]);
}
minCost.run(0, V - 1, F);
if (minCost.totalFlow == F) {
System.out.println(minCost.totalCost);
} else {
System.out.println(-1);
}
}
}
class MinCost {
private int size;
private Map<Integer, Map<Integer, Edge>> edges;
public long totalFlow;
public long totalCost;
public MinCost(int size) {
this.size = size;
edges = new HashMap<>();
totalFlow = 0;
totalCost = 0;
}
public void addEdge(int from, int to, int cost, int cap) {
if (!edges.containsKey(from)) {
edges.put(from, new HashMap<>());
}
edges.get(from).put(to, new Edge(from, to, cost, cap));
if (!edges.containsKey(to)) {
edges.put(to, new HashMap<>());
}
edges.get(to).put(from, new Edge(to, from, -cost, 0));
}
public void run(int s, int e, long flow) {
List<Integer> path = findPath(s, e);
while (!path.isEmpty()) {
long maxFlow = Integer.MAX_VALUE;
for (int i = 0; i < path.size() - 1; i++) {
maxFlow = Math.min(maxFlow, edges.get(path.get(i)).get(path.get(i + 1)).cap);
}
if (totalFlow + maxFlow >= flow) {
maxFlow = flow - totalFlow;
}
totalFlow += maxFlow;
long costSum = 0;
for (int i = 0; i < path.size() - 1; i++) {
costSum += maxFlow * edges.get(path.get(i)).get(path.get(i + 1)).cost;
}
for (int i = 0; i < path.size() - 1; i++) {
edges.get(path.get(i)).get(path.get(i + 1)).cap -= maxFlow;
edges.get(path.get(i + 1)).get(path.get(i)).cap += maxFlow;
}
totalCost = totalCost + costSum;
if (totalFlow == flow) {
break;
}
path = findPath(s, e);
}
}
private List<Integer> findPath(int s, int e) {
BellmanFord bellmanFord = new BellmanFord(size);
edges.forEach((from, toMap) ->
toMap.forEach((to, edge) -> {
if (edge.cap > 0)
bellmanFord.addEdge(edge.from, edge.to, edge.cost);
}));
bellmanFord.run(s);
if (bellmanFord.dist[e] == Long.MAX_VALUE / 2) {
return Collections.emptyList();
}
List<Integer> nodes = new ArrayList<>();
int curr = e;
while (curr != s) {
nodes.add(curr);
curr = bellmanFord.from[curr];
}
nodes.add(curr);
Collections.reverse(nodes);
return nodes;
}
}
class BellmanFord {
private int size;
public long[] dist;
public int[] from;
public List<Edge> edges;
public BellmanFord(int size) {
this.size = size;
dist = new long[size];
Arrays.fill(dist, Long.MAX_VALUE / 2);
from = new int[size];
Arrays.fill(from, -1);
edges = new ArrayList<>();
}
public void addEdge(int from, int to, int cost) {
edges.add(new Edge(from, to, cost));
}
public void run(int start) {
dist[start] = 0;
for (int i = 0; i < size; i++) {
boolean updated = false;
for (Edge e : edges) {
if (dist[e.from] != Long.MAX_VALUE / 2
&& dist[e.to] > dist[e.from] + e.cost) {
dist[e.to] = dist[e.from] + e.cost;
from[e.to] = e.from;
updated = true;
}
}
// found loops. update all nodes in loops with Long.MIN_VALUE
if (i == size - 1 && updated) {
for (int j = 0; j < size; j++) {
for (Edge e : edges) {
if (dist[e.from] == Long.MIN_VALUE || dist[e.to] > dist[e.from] + e.cost) {
dist[e.to] = Long.MIN_VALUE;
}
}
}
}
}
}
}
class Edge {
public int from;
public int to;
public int cost;
public int cap;
public Edge(int from, int to) {
this.from = from;
this.to = to;
this.cost = 1;
this.cap = 1;
}
public Edge(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
this.cap = 1;
}
public Edge(int from, int to, int cost, int cap) {
this.from = from;
this.to = to;
this.cost = cost;
this.cap = cap;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Edge edge = (Edge) o;
return from == edge.from &&
to == edge.to &&
cost == edge.cost &&
cap == edge.cap;
}
@Override
public int hashCode() {
return Objects.hash(from, to, cost, cap);
}
}
|
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, typename U>
struct min_cost_flow_graph_bellman_ford {
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_bellman_ford(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_flow() {
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) {
vector<int> preve(n);
vector<U> dist(n, numeric_limits<U>::max() / 2);
dist[st] = 0;
for (bool update = true; update; ) {
update = false;
for (int i = 0; i < n; i++) {
for (int id : g[i]) {
const 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;
preve[e.to] = id;
update = true;
}
}
}
}
if (dist[fin] == numeric_limits<U>::max() / 2) {
return -1;
}
T d = required_flow - flow;
for (int i = fin; i != st; i = edges[preve[i]].from) {
d = min(d, edges[preve[i]].cap - edges[preve[i]].f);
}
flow += d;
cost += d * dist[fin];
for (int i = fin; i != st; i = edges[preve[i]].from) {
edges[preve[i]].f += d;
edges[preve[i] ^ 1].f -= d;
}
}
return cost;
}
};
int main() {
int n, m, f;
cin >> n >> m >> f;
min_cost_flow_graph_bellman_ford<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": []
} | 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 f = 0; f < v; f++)
{
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++;
// Augment path
int a = v-1;
while (a)
{
// printf("%d ", a);
int e = preedge[a];
if (endofedge[e] == a) flowingthrough[e]++, totalcost += cost[e];
else flowingthrough[e]--, totalcost -= cost[e];
a = pre[a];
}
//printf("%d\n", 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]);
assert(a != b);
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();
// printf("%d %d\n", ans.first, ans.second);
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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using lint = long long int;
using ulint = unsigned long long int;
template<class T = int> using V = vector<T>;
template<class T = int> using VV = V< V<T> >;
template<class T, class U> void assign(V<T>& v, int n, const U& a) { v.assign(n, a); }
template<class T, class... Args> void assign(V<T>& v, int n, const Args&... args) { v.resize(n); for (auto&& e : v) assign(e, args...); }
template<class T> struct PrimalDual {
struct Edge {
int to, rev;
T cap, cost;
Edge(int to, int rev, T cap, T cost) : to(to), rev(rev), cap(cap), cost(cost) {}
};
const int n;
PrimalDual(int n) : n(n), g(n), pot(n), dist(n), pv(n), pe(n) {
assert(n >= 2);
}
void add_edge(int from, int to, T cap, T cost) {
assert(0 <= from and from < n);
assert(0 <= to and to < n);
assert(from != to);
assert(cap >= 0);
assert(cost >= 0);
g[from].emplace_back(to, g[to].size(), cap, cost);
g[to].emplace_back(from, g[from].size() - 1, 0, -cost);
}
T min_cost_flow(int s, int t, T f) {
assert(0 <= s and s < n);
assert(0 <= t and t < n);
assert(s != t);
T res = 0;
fill(begin(pot), end(pot), 0);
while (f > 0) {
dijkstra(s);
if (dist[t] == inf) return -1;
for (int v = 0; v < n; ++v) pot[v] += dist[v];
T d = f;
for (int v = t; v != s; v = pv[v]) {
d = min(d, g[pv[v]][pe[v]].cap);
}
f -= d;
res += d * pot[t];
for (int v = t; v != s; v = pv[v]) {
Edge& e = g[pv[v]][pe[v]];
e.cap -= d;
g[v][e.rev].cap += d;
}
}
return res;
}
private:
static constexpr T inf = numeric_limits<T>::max();
VV<Edge> g;
V<T> pot, dist;
V<> pv, pe;
void dijkstra(int s) {
using P = pair<T, int>;
priority_queue< P, V<P>, greater<P> > pque;
fill(begin(dist), end(dist), inf);
pque.emplace(dist[s] = 0, s);
while (!pque.empty()) {
T d; int v;
tie(d, v) = pque.top(); pque.pop();
if (d > dist[v]) continue;
for (int i = 0; i < g[v].size(); ++i) {
const Edge& e = g[v][i];
if (e.cap <= 0 or dist[e.to] <= dist[v] + e.cost - (pot[e.to] - pot[v])) continue;
pv[e.to] = v;
pe[e.to] = i;
pque.emplace(dist[e.to] = dist[v] + e.cost - (pot[e.to] - pot[v]), e.to);
}
}
}
};
int main() {
cin.tie(nullptr); ios_base::sync_with_stdio(false);
int n, m, f; cin >> n >> m >> f;
PrimalDual<int> pd(n);
for (int i = 0; i < m; ++i) {
int from, to, cap, cost; cin >> from >> to >> cap >> cost;
pd.add_edge(from, to, cap, cost);
}
cout << pd.min_cost_flow(0, n - 1, f) << '\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<iostream>
#include<set>
#include<vector>
#include<queue>
#include<map>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define INF (1e9+1)
//#define INF (1LL<<59)
#define MAX_V 100
struct edge { int to, cap, cost,rev; };
vector<edge> G[MAX_V];
vector<int> h(MAX_V); //??????????????£???
vector<int> dist(MAX_V);// ???????????¢
int prevv[MAX_V], preve[MAX_V];// ??´??????????????¨???
// from??????to??????????????????cap????????????cost????????????????????????????????????
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});
}
//?????????????????????????????????????????´????????????
void shortest_path(int s,vector<int> &d){
int v = d.size();
rep(i,d.size())d[i]=INF;
d[s]=0;
rep(loop,v){
rep(i,v){
rep(j,G[i].size()){
edge e = G[i][j];
if(!e.cap)continue;
if(d[i]!=INF && d[e.to] > d[i]+e.cost){
d[e.to] = d[i]+e.cost;
}
}
}
}
}
// s??????t????????????f???????°??????¨???????±???????
// ??????????????´??????-1?????????
int min_cost_flow(int s, int t, int f) {
int res = 0;
shortest_path(s, h);
while (f > 0) {
// ?????????????????????????????¨??????h?????´??°??????
priority_queue<pii, vector<pii>, greater<pii> > que;
rep(i,dist.size())dist[i]=INF;
dist[s] = 0;
que.push(pii(0, s));
while (!que.empty()) {
pii 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(pii(dist[e.to], e.to));
}
}
}
if (dist[t] == INF) return -1; //????????\???????????????
for (int v = 0; v < h.size(); v++) h[v] += dist[v];
// 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 * 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 vv,e,f;
cin>>vv>>e>>f;
rep(i,e){
int u,v,c,d;
cin>>u>>v>>c>>d;
add_edge(u, v, c, d);
}
cout<<min_cost_flow(0, vv-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;
using i64 = int64_t;
using vi = vector<i64>;
using vvi = vector<vi>;
template<typename flow_t = int, typename cost_t = int>
struct PrimalDual {
const cost_t INF;
struct edge {
int to;
flow_t cap;
cost_t cost;
int rev;
bool isrev;
};
vector<vector<edge>> graph;
vector<cost_t> potential, min_cost;
vector<int> prevv, preve;
PrimalDual(int v) : graph(v), INF(numeric_limits<cost_t>::max()) {}
void add_edge(int from, int to, flow_t cap, cost_t cost) {
graph[from].emplace_back((edge) {to, cap, cost, (int) graph[to].size(), false});
graph[to].emplace_back((edge) {from, 0, -cost, (int) graph[from].size() - 1, true});
}
cost_t min_cost_flow(int s, int t, flow_t f) {
int V = (int) graph.size();
cost_t ret = 0;
priority_queue<pair<cost_t, int>, vector<pair<cost_t, int>>, greater<pair<cost_t, int>>> que;
potential.assign(V, 0);
prevv.assign(V, -1);
preve.assign(V, -1);
while (f > 0) {
min_cost.assign(V, INF);
que.emplace(0, s);
min_cost[s] = 0;
while (!que.empty()) {
pair<cost_t, int> p = que.top();
que.pop();
if (min_cost[p.second] < p.first) continue;
for (int i = 0; i < graph[p.second].size(); i++) {
edge& e = graph[p.second][i];
cost_t next_cost = min_cost[p.second] + e.cost + potential[p.second] - potential[e.to];
if (e.cap > 0 && min_cost[e.to] > next_cost) {
min_cost[e.to] = next_cost;
prevv[e.to] = p.second, preve[e.to] = i;
que.emplace(min_cost[e.to], e.to);
}
}
}
if (min_cost[t] == INF) return -1;
for (int v = 0; v < V; v++) {
potential[v] += min_cost[v];
}
flow_t addflow = f;
for (int v = t; v != s; v = prevv[v]) {
addflow = min(addflow, graph[prevv[v]][preve[v]].cap);
}
f -= addflow;
ret += addflow * potential[t];
for (int v = t; v != s; v = prevv[v]) {
edge& e = graph[prevv[v]][preve[v]];
e.cap -= addflow;
graph[v][e.rev].cap += addflow;
}
}
return ret;
}
};
int main() {
int V, E, F;
scanf("%d %d %d", &V, &E, &F);
PrimalDual<> g(V);
for(int i = 0; i < E; i++) {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
g.add_edge(a, b, c, d);
}
printf("%d\n", g.min_cost_flow(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<iostream>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
#define rep(i,n) for(int i=0;i<(n);i++)
struct edge {
ll to;//行き先の頂点
ll cap;//辺の容量
ll cost;//1フローあたりのコスト
ll rev;//逆辺のインデックス(G[e.to][e.rev]で逆辺にアクセスできる。)
};
#define MAX_V 1000
#define INF (1e9)
ll V;//頂点数 ここに頂点数をセットするのを忘れないように。
vector<edge> G[MAX_V];
ll h[MAX_V]; //ポテンシャル
ll dist[MAX_V];//sから各頂点への最短距離
ll prevv[MAX_V],preve[MAX_V]; // 直前の頂点と辺
void add_edge(ll from,ll to,ll cap,ll cost) {
G[from].push_back((edge){to,cap,cost,(ll)G[to].size()});//辺の追加
G[to].push_back((edge){from,0,-cost,(ll)G[from].size() - 1});//辺の逆辺
}
// 最小費用流を求める(sからt)
// 流せない場合はINFをかえす。
ll min_cost_flow (ll s,ll t,ll f) {
ll ret = 0;
fill(h,h + V,0); // hを初期化 h_-1(v)=0とする。
//f_0の残余ネットワークはもとのグラフ
while(f > 0) {
//現在f_iの残余ネットワークにおけるs-v最短路h_iを求める。
//蟻本よりポテンシャルとしてh_i-1を使っても良い
priority_queue<P,vector<P>,greater<P> > que;
fill(dist,dist + V,INF);
dist[s] = 0;
que.push(P(0,s));
while(!que.empty()) {
P p = que.top(); que.pop();
ll 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];
prevv[e.to] = v;
preve[e.to] = i;
que.push(P(dist[e.to],e.to));
}
}
}
if(dist[t] == INF) {
//正のフローを流せるs-t道がなかった
return -1;
}
rep(v,V) h[v] += dist[v];//INFのオーバーフローに注意
//h_i(v) = (上で求まった最短距離)+h_i-1(v)-h_i-1(s)
//で今、負の閉路が無いのでh_i-1(s)=0となるのでこのような式となる。
//続いてf_i+1の残余ネットワークを求めていく。
//f_i残余ネットワークにおけるs-t間最短路に沿って目一杯流す(上で求めたh_iよりわかる)
ll d = f;//新たに流すフローの量を求める。
for(ll v = t;v != s;v = prevv[v]) {//t側から更新していく
d = min(d,G[prevv[v]][preve[v]].cap);//パスの容量を求めている
}
f -= d;
ret += d * h[t];//総費用の更新
//h_i(t)はf_i残余ネットワークにおけるs-t間最短距離
for(ll 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;
}
ll E,F;
int main() {
cin >> V >> E >> F;
rep(i,E) {
ll 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 | cpp | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
//BEGIN CUT HERE
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 min_cost_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;
}
};
//END CUT HERE
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.min_cost_flow(0,v-1,f)<<endl;
return 0;
}
/*
verified on 2017/06/29
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B&lang=jp
*/ |
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.*;
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;
int V = dist.length;
boolean[] inqueue = new boolean[V];
int[] q = new int[V];
int qt = 0;
q[qt++] = s;
for (int qh = 0; (qh - qt) % V != 0; qh++) {
int u = q[qh % V];
inqueue[u] = false;
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);
if(!inqueue[edge.v]){
inqueue[edge.v] = true;
q[qt++ % V] = 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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int (i)=(0);(i)<(int)(n);++(i))
using ll = long long;
using P = pair<int, int>;
using namespace std;
const double EPS = 1e-9;
const int MOD = 1e9+7;
const int INF = 2e5;
const double PI = acos(-1.0);
using namespace std;
struct MinCostFlow {
struct edge {
int to;
int cap;
int cost;
int rev;
bool is_rev;
};
const int INF;
vector<vector<edge>> G;
MinCostFlow(int n, int inf) : G(n), INF(inf) {
;
}
void add_edge(int from, int to, int cap, int cost) {
G[from].push_back((edge){to, cap, cost, (int)G[to].size(), false});
G[to].push_back((edge){from, 0, -cost, (int)G[from].size()-1, true});
}
int minCostFlow(int s, int t, int f) {
const int N = G.size();
int cost = 0;
vector<int> prev_v(N, -1);
vector<int> prev_e(N, -1);
while (f > 0) {
vector<int> dist(N, INF);
dist[s] = 0;
bool update = true;
while (update) {
update = false;
for (int v=0; v<N; ++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;
prev_v[e.to] = v;
prev_e[e.to] = i;
update = true;
}
}
}
}
if (dist[t] == INF) {
return -1;
}
int d = f;
for (int v=t; v!=s; v=prev_v[v]) {
d = min(d, G[prev_v[v]][prev_e[v]].cap);
}
f -= d;
cost += d * dist[t];
for (int v=t;v!=s;v=prev_v[v]) {
edge &e = G[prev_v[v]][prev_e[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return cost;
}
};
int main() {
int V, E, F;
cin >> V >> E >> F;
MinCostFlow mcf(V, INF);
rep(i, E) {
int u, v, c, d;
cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
cout << mcf.minCostFlow(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 | cpp | #include <iostream>
#include <vector>
#include <numeric>
#include <queue>
#include <algorithm>
#include <utility>
#include <functional>
using namespace std;
const int MAX_V = 100010;
using Flow = int;
const auto inf = numeric_limits<Flow>::max() / 8;
struct Edge {
int dst;
Flow cap, cap_orig;
Flow cost;
int revEdge; bool isRev;
Edge(int dst, Flow cap, Flow cost, int revEdge, bool isRev)
:dst(dst), cap(cap), cap_orig(cap), cost(cost), revEdge(revEdge), isRev(isRev) {
}
};
struct PrimalDual {
int n;
vector<vector<Edge> > g;
PrimalDual(int n_) : n(n_), g(vector<vector<Edge> >(n_)) {}
void addEdge(int src, int dst, Flow cap, Flow cost) { // ?????????
g[src].emplace_back(dst, cap, cost, g[dst].size(), false);
g[dst].emplace_back(src, 0, -cost, g[src].size() - 1, true);
}
Flow solve(int s, int t, int f) {
Flow res = 0;
vector<Flow> h(g.size()), dist(g.size());
vector<int> prevv(g.size()), preve(g.size());
while (f > 0) {
using State = pair<Flow, int>;
priority_queue<State, vector<State>, greater<State> > q;
fill(dist.begin(), dist.end(), inf);
dist[s] = 0;
q.emplace(0, s);
while (q.size()) {
State p = q.top(); q.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.cost + h[v] - h[e.dst]) {
dist[e.dst] = dist[v] + e.cost + h[v] - h[e.dst];
prevv[e.dst] = v;
preve[e.dst] = i;
q.emplace(dist[e.dst], e.dst);
}
}
}
if (dist[t] == inf) {
return -1;
}
for (int i = 0; i < n; ++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.revEdge].cap += d;
}
}
return res;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m, f;
cin >> n >> m >> f;
PrimalDual pd(n);
for (int i = 0; i < m; i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
pd.addEdge(u, v, c, d);
}
cout << pd.solve(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 <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
template <typename T>
class MinCostFlow
{
public:
MinCostFlow(int n) : n(n), capacity(n, vector<T>(n)), cost(n, vector<T>(n)), prev(n) {}
void add_edge(int src, int dst, T cap, T c)
{
capacity[src][dst] = cap;
capacity[dst][src] = 0;
cost[src][dst] = c;
cost[dst][src] = -c;
}
T min_cost_flow(int s, int t, T f)
{
T res = 0;
h.assign(n, 0);
while (f > 0)
{
if (!dijkstra(s, t))
return -1;
for (int i = 0; i < n; ++i)
h[i] += dist[i];
T d = f;
for (int v = t; v != s; v = prev[v])
d = min(d, capacity[prev[v]][v]);
f -= d;
res += d * h[t];
for (int v = t; v != s; v = prev[v])
{
capacity[prev[v]][v] -= d;
capacity[v][prev[v]] += d;
}
}
return res;
}
private:
int n;
T inf = numeric_limits<T>::max();
vector<vector<T>> capacity, cost;
vector<T> dist, h, prev;
bool dijkstra(int s, int t)
{
dist.assign(n, inf);
dist[s] = 0;
priority_queue<pair<T, int>, vector<pair<T, int>>, greater<pair<T, int>>> pq;
pq.emplace(0, s);
while (!pq.empty())
{
int c = pq.top().first;
int v = pq.top().second;
pq.pop();
if (dist[v] < c)
continue;
for (int nv = 0; nv < n; ++nv)
{
if (capacity[v][nv] > 0 && dist[nv] > dist[v] + cost[v][nv] + h[v] - h[nv])
{
dist[nv] = dist[v] + cost[v][nv] + h[v] - h[nv];
prev[nv] = v;
pq.emplace(dist[nv], nv);
}
}
}
return dist[t] != inf;
}
};
int main()
{
int V, E, F, u, v, c, d;
cin >> V >> E >> F;
MinCostFlow<int> mcf(V + 1);
for (int i = 0; i < E; ++i)
{
cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
cout << mcf.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 | #include <cstdio>
#include <vector>
#include <queue>
#include <tuple>
int v, e;
struct Edge {
Edge() {}
Edge(int from, int to, int capacity, int cost, int rev) : from(from), to(to), capacity(capacity), cost(cost), rev(rev) {}
int from, to;
int capacity;
int cost;
int rev;
};
std::vector<Edge> edges[128];
void addEdge(int from, int to, int capacity, int cost) {
int n1 = edges[from].size();
int n2 = edges[to].size();
edges[from].push_back(Edge(from, to, capacity, cost, n2));
edges[to].push_back(Edge(to, from, 0, -cost, n1));
}
struct Result {
Result() {}
Result(int cost, int f) : cost(cost), f(f) {}
int cost;
int f;
};
int prev[128];
int prev_id[128];
int w[128];
int max_f[128];
void init_flow() {
for(int i = 0; i < 128; ++i) {
prev[i] = -1;
prev_id[i] = -1;
w[i] = (1 << 30);
max_f[i] = 0;
}
}
Result flow(int from, int to, int rem) {
std::priority_queue< std::pair<int, int> > q;
q.push(std::make_pair(0, from));
w[from] = 0;
max_f[from] = rem;
while( not q.empty() ) {
int n, weight;
std::tie(weight, n) = q.top(); q.pop();
// printf("(n) = (%d)\n", n);
weight = -weight;
for(int i = 0; i < (int)edges[n].size(); ++i) {
Edge edge = edges[n][i];
if( edge.capacity <= 0 ) continue;
int nw = weight + edge.cost;
if( w[edge.to] <= nw ) continue;
w[edge.to] = nw;
prev[edge.to] = n;
prev_id[edge.to] = i;
max_f[edge.to] = std::min(max_f[edge.from], edge.capacity);
q.push(std::make_pair(-nw, edge.to));
}
}
// for(int i = 0; i < v; ++i) {
// printf("node info[%d] : (w, max_f, prev, prev_id) = (%d, %d, %d, %d)\n", i, w[i], max_f[i], prev[i], prev_id[i]);
// }
int f = max_f[to];
if( f == 0 ) return Result(0, 0);
int m = to;
int cost = 0;
while( prev[m] != -1 ) {
edges[prev[m]][prev_id[m]].capacity -= f;
edges[m][edges[prev[m]][prev_id[m]].rev].capacity += f;
cost += f * edges[prev[m]][prev_id[m]].cost;
m = prev[m];
}
return Result(cost, f);
}
int minimum_cost_flow(int from, int to, int rem) {
int cost = 0;
for(;;) {
init_flow();
Result r = flow(from, to, rem);
rem -= r.f;
cost += r.cost;
if( rem == 0 ) return cost;
if( r.f == 0 ) break;
// printf("(rem, flow rate) = (%d, %d)\n", rem, r.f);
}
return -1;
}
int main() {
int f;
scanf("%d %d %d", &v, &e, &f);
for(int i = 0; i < e; ++i) {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
addEdge(a, b, c, d);
}
printf("%d\n", minimum_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 | java | import java.util.*;
public class Main {
@SuppressWarnings("unchecked")
static 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]));
}
}
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 sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
int F = sc.nextInt();
MinCostFlow mcf = new MinCostFlow(V);
for (int i=0;i<E;i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int c = sc.nextInt();
int d = sc.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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using lint = long long;
template<class T = int> using V = vector<T>;
template<class T = int> using VV = V< V<T> >;
// BEGIN CUT HERE
template<class T> struct PrimalDual {
struct Edge { int to, rev; T cap, cost; };
const T inf = numeric_limits<T>::max();
const int n;
VV<Edge> g;
V<T> pot, dist;
V<> pv, pe;
PrimalDual(int n) : n(n), g(n), pot(n), dist(n), pv(n), pe(n) {}
void add_edge(int from, int to, T cap, T cost) {
assert(from != to);
assert(cap >= 0);
if (!cap) return;
assert(cost >= 0);
g[from].emplace_back(Edge{to, (int) g[to].size(), cap, cost});
g[to].emplace_back(Edge{from, (int) g[from].size() - 1, 0, -cost});
}
void dijkstra(int s) {
using P = pair<T, int>;
priority_queue< P, V<P>, greater<P> > pque;
fill(begin(dist), end(dist), inf);
pque.emplace(dist[s] = 0, s);
while (!pque.empty()) {
T d; int v;
tie(d, v) = pque.top(); pque.pop();
if (d > dist[v]) continue;
for (int i = 0; i < (int) g[v].size(); ++i) {
const Edge& e = g[v][i];
if (!e.cap or dist[e.to] <= dist[v] + e.cost - (pot[e.to] - pot[v])) continue;
pv[e.to] = v, pe[e.to] = i;
pque.emplace(dist[e.to] = dist[v] + e.cost - (pot[e.to] - pot[v]), e.to);
}
}
}
T min_cost_flow(int s, int t, T f) {
assert(s != t);
assert(f >= 0);
T res = 0;
fill(begin(pot), end(pot), 0);
while (f > 0) {
dijkstra(s);
if (dist[t] == inf) return -1;
for (int v = 0; v < n; ++v) pot[v] += dist[v];
T d = f;
for (int v = t; v != s; v = pv[v]) {
d = min(d, g[pv[v]][pe[v]].cap);
}
f -= d;
res += d * pot[t];
for (int v = t; v != s; v = pv[v]) {
Edge& e = g[pv[v]][pe[v]];
e.cap -= d;
g[v][e.rev].cap += d;
}
}
return res;
}
};
// END CUT HERE
int main() {
cin.tie(nullptr); ios::sync_with_stdio(false);
int n, m, f; cin >> n >> m >> f;
PrimalDual<int> g(n);
while (m--) {
int 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) << '\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 | python3 | # ノードをtupleで渡す
from collections import defaultdict
from heapq import *
class MinCostFlow:
def __init__(self):
self.inf=10**9
self.to = defaultdict(dict)
def add_edge(self, u, v, cap, cost):
self.to[u][v]=[cap, cost]
self.to[v][u]=[0, -cost]
# s...source,t...sink,f...flow
# これが本体
def cal(self,s,t,f):
min_cost=0
pot=defaultdict(int)
while f:
dist = {}
pre_u={} # 最短距離の遷移元の頂点
# ダイクストラで最短距離を求める
hp=[]
heappush(hp,(0,s))
dist[s]=0
while hp:
d,u=heappop(hp)
if d>dist[u]:continue
for v,[cap,cost] in self.to[u].items():
if cap==0:continue
nd=dist[u]+cost+pot[u]-pot[v]
dist.setdefault(v, self.inf)
if nd>=dist[v]:continue
dist[v]=nd
pre_u[v]=u
heappush(hp,(nd,v))
# sinkまで届かなかったら不可能ということ
if t not in dist:return -1
# ポテンシャルを更新する
for u,d in dist.items():pot[u]+=d
# パスs-t上で最小の容量=流す量を求める
u=t
min_cap=f
while u!=s:
u,v=pre_u[u],u
min_cap=min(min_cap,self.to[u][v][0])
# フローから流す量を減らし、コストを加える
f-=min_cap
min_cost+=min_cap*pot[t]
# パスs-tの容量を更新する
u=t
while u!=s:
u,v=pre_u[u],u
self.to[u][v][0]-=min_cap
self.to[v][u][0]+=min_cap
return min_cost
def main():
n,m,f=map(int,input().split())
mc=MinCostFlow()
for _ in range(m):
u,v,c,d=map(int,input().split())
mc.add_edge(u,v,c,d)
print(mc.cal(0,n-1,f))
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": []
} | CORRECT | cpp | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define INF (1e9+1)
//#define INF (1LL<<59)
#define MAX_V 100
struct edge { int to, cap, cost,rev; };
int V; // ????????°
vector<edge> G[MAX_V];
vector<int> h(MAX_V); //??????????????£???
vector<int> dist(MAX_V);// ???????????¢
int prevv[MAX_V], preve[MAX_V];// ??´??????????????¨???
// from??????to??????????????????cap????????????cost????????????????????????????????????
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});
}
//?????????????????????????????????????????´????????????
void shortest_path(int s,vector<int> &d){
int v = d.size();
rep(i,d.size())d[i]=INF;
d[s]=0;
rep(loop,v){
rep(i,v){
rep(j,G[i].size()){
edge e = G[i][j];
if(!e.cap)continue;
if(d[i]!=INF && d[e.to] > d[i]+e.cost){
d[e.to] = d[i]+e.cost;
preve[e.to]=j;
}
}
}
}
}
// s??????t????????????f???????°??????¨???????±???????
// ??????????????´??????-1?????????
int min_cost_flow(int s, int t, int f) {
int res = 0;
shortest_path(s, h);
while (f > 0) {
// ?????????????????????????????¨??????h?????´??°??????
priority_queue<pii, vector<pii>, greater<pii> > que;
rep(i,dist.size())dist[i]=INF;
dist[s] = 0;
que.push(pii(0, s));
while (!que.empty()) {
pii 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(pii(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 = 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;
rep(i,e){
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": []
} | CORRECT | python3 | import heapq
class MinCostFlow:
class Edge:
def __init__(self,to,cap,rev,cost):
self.to = to
self.cap = cap
self.rev = rev
self.cost = cost
def __init__(self,n,inf=1000000007):
self.n = n
self.inf = inf
self.e = [[] for _ in range(n)]
def add_edge(self, fr, to, cap, cost):
self.e[fr].append(self.Edge(to,cap,len(self.e[to]),cost))
self.e[to].append(self.Edge(fr,0,len(self.e[fr])-1,-cost))
def compute(self,source,sink,f):
res = 0
h = [0]*self.n
prevv = [0]*self.n
preve = [0]*self.n
while (f > 0):
pq = []
dist = [self.inf]*self.n
dist[source] = 0
heapq.heappush(pq,(0,source))
while pq:
cost, v = heapq.heappop(pq)
cost = -cost
if dist[v] < cost:continue
for i, edge in enumerate(self.e[v]):
if edge.cap > 0 and dist[v] - h[edge.to] < dist[edge.to] - edge.cost - h[v]:
dist[edge.to] = dist[v] + edge.cost + h[v] - h[edge.to]
prevv[edge.to] = v
preve[edge.to] = i
heapq.heappush(pq,(-dist[edge.to],edge.to))
if dist[sink] == self.inf:return -1
for v in range(self.n):
h[v] += dist[v]
d, v = f, sink
while v != source:
d = min(d,self.e[prevv[v]][preve[v]].cap)
v = prevv[v]
f -= d
res += d*h[sink]
v = sink
while v != source:
self.e[prevv[v]][preve[v]].cap -= d
self.e[v][self.e[prevv[v]][preve[v]].rev].cap += d
v = prevv[v]
return res
def main():
v,e,f = map(int,input().split())
MCF = MinCostFlow(v)
for _ in range(e):
a,b,c,d = map(int,input().split())
MCF.add_edge(a,b,c,d)
print(MCF.compute(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": []
} | CORRECT | python3 | import sys
input = sys.stdin.readline
from heapq import heappush, heappop
def min_cost_flow_dijkstra(E, s, t, f):
INF = 1 << 100
NN = N
LN = NN.bit_length()
G = [[] for _ in range(NN)]
for a, b, cap, c in E:
G[a].append([b, cap, c, len(G[b])])
G[b].append([a, 0, -c, len(G[a])-1])
prevv = [-1] * NN
preve = [-1] * NN
res = 0
while f > 0:
h = [0] * NN
dist = [INF] * NN
dist[s] = 0
Q = []
heappush(Q, s)
while len(Q):
x = heappop(Q)
d, v = (x>>LN), x % (1<<LN)
if dist[v] < d: continue
for i, (w, _cap, c, r) in enumerate(G[v]):
if _cap > 0 and dist[w] > dist[v] + c + h[v] - h[w]:
dist[w] = dist[v] + c + h[v] - h[w]
prevv[w] = v
preve[w] = i
heappush(Q, (dist[w] << LN) + w)
if dist[t] == INF:
return -1
for v in range(N):
h[v] += dist[v]
d = f
v = t
while v != s:
d = min(d, G[prevv[v]][preve[v]][1])
v = prevv[v]
f -= d
res += d * dist[t]
v = t
while v != s:
G[prevv[v]][preve[v]][1] -= d
G[v][G[prevv[v]][preve[v]][3]][1] += d
v = prevv[v]
return res
N, M, F = map(int, input().split())
E = []
for i in range(M):
u, v, c, d = map(int, input().split())
E.append((u, v, c, d))
print(min_cost_flow_dijkstra(E, 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": []
} | CORRECT | cpp | #include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define INF 99999999
using namespace std;
typedef int Weight;
struct Edge {
int src, dst;
Weight capacity, cost;
Edge(int src, int dst, Weight capacity, Weight cost) :
src(src), dst(dst), capacity(capacity), cost(cost) { }
};
bool operator < (const Edge &e, const Edge &f) {
return e.cost != f.cost ? e.cost > f.cost : // !!INVERSE!!
e.capacity != f.capacity ? e.capacity > f.capacity : // !!INVERSE!!
e.src != f.src ? e.src < f.src : e.dst < f.dst;
}
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;
#define RESIDUE(u,v) (capacity[u][v] - flow[u][v])
#define RCOST(u,v) (cost[u][v] + h[u] - h[v])
pair<Weight, Weight> minimumCostFlow(const Graph &g, int s, int t, Weight F=INF) {
const int n = g.size();
Matrix capacity(n, Array(n)), cost(n, Array(n)), flow(n, Array(n));
REP(u,n) FOR(e,g[u]) {
capacity[e->src][e->dst] += e->capacity;
cost[e->src][e->dst] += e->cost;
}
pair<Weight, Weight> total; // (cost, flow)
vector<Weight> h(n);
for (; F > 0; ) { // residual flow
vector<Weight> d(n, INF); d[s] = 0;
vector<int> p(n, -1);
priority_queue<Edge> Q; // "e < f" <=> "e.cost > f.cost"
for (Q.push(Edge(-2, s, 0, 0)); !Q.empty(); ) {
Edge e = Q.top(); Q.pop();
if (p[e.dst] != -1) continue;
p[e.dst] = e.src;
FOR(f, g[e.dst]) if (RESIDUE(f->src, f->dst) > 0) {
if (d[f->dst] > d[f->src] + RCOST(f->src, f->dst)) {
d[f->dst] = d[f->src] + RCOST(f->src, f->dst);
Q.push( Edge(f->src, f->dst, 0, d[f->dst]) );
}
}
}
if (p[t] == -1) break;
Weight f = F;
for (int u = t; u != s; u = p[u])
f = min(f, RESIDUE(p[u], u));
for (int u = t; u != s; u = p[u]) {
total.first += f * cost[p[u]][u];
flow[p[u]][u] += f; flow[u][p[u]] -= f;
}
F -= f;
total.second += f;
REP(u, n) h[u] += d[u];
}
return total;
}
int main(){
int i,V,E,F,s,t,e,f;
//for(scanf("%d",&T);T;putchar(--T?' ':'\n')){
scanf("%d%d%d",&V,&E,&F);
Graph g(V);
for(;E--;)scanf("%d%d%d%d",&s,&t,&e,&f),g[s].push_back(Edge(s,t,e,f)),g[t].push_back(Edge(t,s,0,-f));
pair<int,int> p=minimumCostFlow(g,0,V-1,F);
printf("%d\n",p.second<F ? -1 : p.first);
//}
} |
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 Cap, typename Cost>
struct Graph {
const Cost INF = numeric_limits<Cost>::max();
struct Edge {
int to, rev;
Cap cap;
Cost cost;
Edge(int to, Cap cap, Cost cost, int rev)
: to(to), cap(cap), cost(cost), rev(rev) {}
};
vector<vector<Edge>> g;
int n;
Graph(int n) : n(n) {
g.assign(n, vector<Edge>());
}
void add_edge(int v, int u, Cap cap = 1, Cost cost = 0) {
g[v].emplace_back(u, cap, cost, (int) g[u].size());
g[u].emplace_back(v, 0, -cost, (int) g[v].size() - 1);
}
vector<Edge>& operator[](int x) {
return g[x];
}
Cost min_cost_flow(int s, int t, Cap f) {
Cost ret = 0;
while (f > 0) {
vector<Cost> dist(n, INF);
vector<int> prevv(n), preve(n);
dist[s] = 0;
while (true) {
bool update = false;
for (int v = 0; v < n; v++) {
for (int i = 0; i < g[v].size(); i++) {
auto &e = g[v][i];
if (e.cap == 0) continue;
if (dist[v] == INF || dist[e.to] <= dist[v] + e.cost) continue;
dist[e.to] = dist[v] + e.cost;
prevv[e.to] = v, preve[e.to] = i;
update = true;
}
}
if (!update) break;
}
if (dist[t] == INF) return INF;
Cap cap = f;
for (int v = t; v != s; v = prevv[v]) {
cap = min(cap, g[prevv[v]][preve[v]].cap);
}
f -= cap;
ret += cap * dist[t];
for (int v = t; v != s; v = prevv[v]) {
auto &e = g[prevv[v]][preve[v]];
e.cap -= cap;
g[v][e.rev].cap += cap;
}
}
return ret;
}
};
int main() {
int n, m, f;
cin >> n >> m >> f;
Graph<int, int> g(n);
for (int i = 0; i < m; i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
g.add_edge(u, v, c, d);
}
int ans = g.min_cost_flow(0, n - 1, f);
if (ans == g.INF) {
ans = -1;
}
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": []
} | CORRECT | python3 | class MinCostFlow:
def __init__(self, n):
self.n = n
self.G = [[] for i in range(n)]
def addEdge(self, f, t, cap, cost):
# [to, cap, cost, rev]
self.G[f].append([t, cap, cost, len(self.G[t])])
self.G[t].append([f, 0, -cost, len(self.G[f])-1])
def minCostFlow(self, s, t, f):
n = self.n
G = self.G
prevv = [0]*n; preve = [0]*n
INF = 10**9+7
res = 0
while f:
dist = [INF]*n
dist[s] = 0
update = 1
while update:
update = 0
for v in range(n):
if dist[v] == INF:
continue
gv = G[v]
for i in range(len(gv)):
to, cap, cost, rev = gv[i]
if cap > 0 and dist[v] + cost < dist[to]:
dist[to] = dist[v] + cost
prevv[to] = v; preve[to] = i
update = 1
if dist[t] == INF:
return -1
d = f; v = t
while v != s:
d = min(d, G[prevv[v]][preve[v]][1])
v = prevv[v]
f -= d
res += d * dist[t]
v = t
while v != s:
e = G[prevv[v]][preve[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prevv[v]
return res
n, m, f = map(int, input().split())
graph = MinCostFlow(n)
for i in range(m):
u, v, c, d = map(int, input().split())
graph.addEdge(u, v, c, d)
print(graph.minCostFlow(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": []
} | CORRECT | cpp | #define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
//#include "MyMath.h"
//#include "MyDisjointset.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <functional>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
typedef pair<int, int> P; typedef long long int ll; typedef vector <int> vecint; typedef vector <vecint> dvecint; typedef vector <dvecint> vecdvecint; typedef vector <vector <dvecint> > dvecdvecint;
const ll 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[100];
int prv[100], pre[100], d[100];
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]].cap);
}
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": []
} | 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]));
}
}
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": []
} | 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_flow() {
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() {
vector<U> h(n, 0);
while (flow < required_flow) {
vector<int> preve(n);
vector<U> dist(n, numeric_limits<U>::max() / 2);
priority_queue<pair<U, int>, vector<pair<U, int>>, greater<pair<U, int>>> pq;
dist[st] = 0;
pq.emplace(dist[st], st);
while (!pq.empty()) {
U expected = pq.top().first;
int i = pq.top().second;
pq.pop();
if (expected != dist[i]) {
continue;
}
for (int id : g[i]) {
const edge &e = edges[id];
if (0 < e.cap - e.f && dist[e.from] + e.cost + h[e.from] - h[e.to] < dist[e.to]) {
dist[e.to] = dist[e.from] + e.cost + h[e.from] - h[e.to];
preve[e.to] = id;
pq.emplace(dist[e.to], e.to);
}
}
}
if (dist[fin] == numeric_limits<U>::max() / 2) {
return -1;
}
for (int i = 0; i < n; i++) {
h[i] += dist[i];
}
T d = required_flow - flow;
for (int i = fin; i != st; i = edges[preve[i]].from) {
d = min(d, edges[preve[i]].cap - edges[preve[i]].f);
}
flow += d;
cost += d * h[fin];
for (int i = fin; i != st; i = edges[preve[i]].from) {
edges[preve[i]].f += d;
edges[preve[i] ^ 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": []
} | 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:
const ll inf=1LL<<50;
// Description: ??°??????????????????(?????????????°??????¨???)
// Verifyed: Many Diffrent Problem
//Appropriately Changed
using edge=struct{int to,cost,cap,rev;};
using G=vector<vector<edge>>;
//Appropriately Changed
void add_edge(G &graph,int from,int to,int cap,int cost){
graph[from].push_back({to,cost,cap,int(graph[to].size())});
graph[to].push_back({from,-cost,0,int(graph[from].size())-1});
}
// Description: ??°??????????????????????°??????¨???
// TimeComplexity: $ \mathcal{O}(FVE) $
// Verifyed: AOJ GRL_6_B
template <typename W> W primal_dual(G &graph,int s,int t,int f,W inf){
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>0 && 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;
int d=f;
for(int v=t;v!=s;v=pv[v]) chmin(d,graph[pv[v]][pe[v]].cap);
f-=d,res+=d*dist[t];
for(int v=t;v!=s;v=pv[v]){
edge &e=graph[pv[v]][pe[v]];
e.cap-=d;
graph[v][e.rev].cap+=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<ll>(graph,0,v-1,f,inf) << 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>
#include <vector>
#include <queue>
#define INF (1 << 30)
using namespace std;
struct Edge {
//to : Edge(from ??? to) cap:capacity cost:cost rev:reverse
int to, cap, cost, rev;
Edge(int to, int cap, int cost, int rev) :to(to), cap(cap), cost(cost), rev(rev) {}
};
#define P vector<vector<Edge>>
vector<int> dist;
bool bellman_ford(P& Graph, int s, int t, vector<int>& parent_v, vector<int>& parent_at) {
dist = vector<int>(t + 1, INF);
dist[s] = 0;
for (int i = 0; i <= t;i++) {
for (int v = 0; v <= t;v++) {
if (dist[v] == INF)continue;
for (int at = 0; at < Graph[v].size();at++) {
Edge &e = Graph[v][at];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {
//cout << i << " " << v << endl;
dist[e.to] = dist[v] + e.cost;
parent_v[e.to] = v;
parent_at[e.to] = at;
if (i == t) return false;
}
}
}
}
return true;
}
int primal_dual(P& Graph, int s, int t, int F) {
vector<int> parent_v(t + 1);
vector<int> parent_at(t + 1);
int min_cost_flow = 0;
while (bellman_ford(Graph, s, t, parent_v, parent_at)) {
if (dist[t] == INF) { return -1; }
int path_flow = F;
for (int v = t; v != s; v = parent_v[v]) {
path_flow = min(path_flow, Graph[parent_v[v]][parent_at[v]].cap);
}
F -= path_flow;
min_cost_flow += path_flow*dist[t];
if (F == 0) { return min_cost_flow; }
if (F < 0) { return -1; }
for (int v = t; v != s; v = parent_v[v]) {
Edge & e = Graph[parent_v[v]][parent_at[v]];
e.cap -= path_flow;
Graph[v][e.rev].cap += path_flow;
}
}
return min_cost_flow;
}
int main() {
int V, E, F; cin >> V >> E >> F;
P G(V);
for (int i = 0; i < E;i++) {
int u, v, c, d; cin >> u >> v >> c >> d;
G[u].emplace_back(Edge(v, c, d, G[v].size()));
G[v].emplace_back(Edge(u, 0, -d, G[u].size() - 1));
}
cout << primal_dual(G, 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 <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int, int> ipair;
typedef tuple<int, int, int> ituple;
const ll INF = LLONG_MAX;
// const int MOD = (int)1e9 + 7;
// const double EPS = 1e-10;
#define PI acosl(-1)
#define MAX_N 100 + 2
/**
* ????°??????¨???
*/
class MinCostFlow{
struct edge{
int to, cap, cost, rev;
};
protected:
static const int MAX_V = 1000 + 5;
int V; // ????????°
vector<edge> G[MAX_V]; // ??°???????????£??\???????????¨???
ll dist[MAX_V]; // ???????????¢
int prevV[MAX_V], prevE[MAX_V]; // ??´??????????????¨???
public:
MinCostFlow(){}
MinCostFlow(int v){
assert(v <= MAX_V);
V = 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});
}
// s??????t??????????°??????¨???????±???????
int exec(int s, int t, int f){
int res = 0;
while (f > 0){
// ???????????????????????????????????????s-t??????????????????????±???????
fill(dist, dist + V, 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;
}
// 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;
}
};
void exec(){
int V, E, F, u, v, c, d;
cin >> V >> E >> F;
MinCostFlow mcf = MinCostFlow(V);
for (int i = 0; i < E; i++){
scanf("%d%d%d%d", &u, &v, &c, &d);
mcf.addEdge(u, v, c, d);
}
cout << mcf.exec(0, V-1, F) << endl;
}
void solve(){
int t = 1;
// scanf("%d", &t);
for (int i = 0; i < t; i++){
exec();
}
}
int main(){
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": []
} | CORRECT | cpp | //#include "bits/stdc++.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include <cstdlib>
#include <deque>
#include <algorithm>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <iterator>
using namespace std;
#define rep(i,a,b) for(int i=(a), i##_len=(b);i<i##_len;i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)
//#define int long long
#define SZ(x) ((int)(x).size())
#define pb push_back
#define mp make_pair
typedef long long ll;
//typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
typedef pair<double, double> pdd;
typedef vector<vector<int>> mat;
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; }
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;
#define VMAX 10010
struct edge
{
int to, cap, cost, rev;
edge(int to, int cap, int cost, int rev) :to(to), cap(cap), cost(cost), rev(rev) {}
edge() :to(-1), cap(-1), cost(-1), rev(-1) {}
};
vector<edge> G[VMAX];
int h[VMAX], dist[VMAX], prevv[VMAX], preve[VMAX];
int V, E, F;
void add_edge(int from, int to, int cap, int cost)
{
G[from].push_back(edge(to, cap, cost, SZ(G[to])));
G[to].push_back(edge(from, 0, -cost, SZ(G[from]) - 1));
}
int min_cost_flow(int s, int t, int f)
{
int res = 0;
fill(h, h + V, 0);
while (f > 0)
{
priority_queue<pii, vector<pii>, greater<pii>> q;
fill(dist, dist + V, 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, 0, SZ(G[v]))
{
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;
q.push(pii(dist[e.to], e.to));
}
}
}
if (dist[t] == INF)
{
return -1;
}
rep(v, 0, V)h[v] += dist[v];
int d = f;
for (int v = t; v != s; v = prevv[v])
{
chmin(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.tie(0);
ios::sync_with_stdio(false);
cin >> V >> E >> F;
int s, t, c, d;
rep(i, 0, E)
{
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": []
} | 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);
int max = maximumFlowDinic(capacity, 0, V-1);
if(F>max){
System.out.println(-1);
}else{
System.out.println(solveMinCostFlow(cost, capacity, 0, V-1, F));;
}
}
public static int maximumFlowDinic(int[][][] g, int source, int sink)
{
int n = g.length;
// unweighted invgraph
int[] p = new int[n];
for(int i = 0;i < n;i++){
for(int j = 0;j < g[i].length;j++)p[g[i][j][0]]++;
}
int[][] ig = new int[n][];
for(int i = 0;i < n;i++)ig[i] = new int[p[i]];
for(int i = n-1;i >= 0;i--){
for(int j = 0;j < g[i].length;j++){
ig[g[i][j][0]][--p[g[i][j][0]]] = i;
}
}
int[][] f = new int[n][n];
int[] d = new int[n];
int[] q = new int[n];
int ret = 0;
while(true){
Arrays.fill(d, -1);
q[0] = source;
int r = 1;
d[source] = 0;
for(int v = 0;v < r;v++){
int cur = q[v];
// plus flow
for(int[] ne : g[cur]){
int nex = ne[0], w = ne[1];
if(d[nex] == -1 && w - f[cur][nex] > 0) {
q[r++] = nex;
d[nex] = d[cur] + 1;
}
}
// minus flow
for(int nex : ig[cur]){
if(d[nex] == -1 && -f[cur][nex] > 0) {
q[r++] = nex;
d[nex] = d[cur] + 1;
}
}
}
if(d[sink] == -1)break;
int delta = 0;
while((delta = dfsDinic(d, g, ig, f, source, sink, Integer.MAX_VALUE)) > 0){
ret += delta;
}
}
return ret;
}
public static int dfsDinic(int[] d, int[][][] g, int[][] ig, int[][] f, int cur, int t, int min)
{
if(cur == t){
return min;
}else{
int left = min;
for(int[] ne : g[cur]){
int nex = ne[0], w = ne[1];
if(d[nex] == d[cur]+1 && w-f[cur][nex] > 0){
int fl = dfsDinic(d, g, ig, f, nex, t, Math.min(left, w-f[cur][nex]));
if(fl > 0){
f[cur][nex] += fl;
f[nex][cur] -= fl;
left -= fl;
if(left == 0)return min;
}
}
}
for(int nex : ig[cur]){
if(d[nex] == d[cur]+1 && -f[cur][nex] > 0){
int fl = dfsDinic(d, g, ig, f, nex, t, Math.min(left, -f[cur][nex]));
if(fl > 0){
f[cur][nex] += fl;
f[nex][cur] -= fl;
left -= fl;
if(left == 0)return min;
}
}
}
return min-left;
}
}
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": []
} | CORRECT | cpp | #include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;
using i64 = int64_t;
const int INF = 1LL << 29;
struct edge {
int to, cap, rev, cost;
edge(int a, int b, int c, int d): to(a), cap(b), rev(c), cost(d) {}
};
int V, E, F;
vector<edge> graph[100];
int min_cost_flow(int s, int g, int f) {
vector<int> min_dist(V, INF);
vector<int> prev_v(V, -1), prev_e(V, -1);
int ans = 0;
while (f > 0) {
fill(begin(min_dist), end(min_dist), INF);
min_dist[s] = 0;
bool updated = true;
while (updated) {
updated = false;
for (int v = 0; v < V; ++v) {
if (min_dist[v] == INF) continue;
for (int j = 0; j < graph[v].size(); ++j) {
edge& e = graph[v][j];
if (e.cap > 0 && min_dist[v] + e.cost < min_dist[e.to]) {
updated = true;
min_dist[e.to] = min_dist[v] + e.cost;
prev_v[e.to] = v;
prev_e[e.to] = j;
}
}
}
}
if (min_dist[g] == INF) {
return -1;
}
int ff = f;
for (int t = g; t != s; t = prev_v[t]) {
ff = min(ff, graph[prev_v[t]][prev_e[t]].cap);
}
ans += ff * min_dist[g];
for (int t = g; t != s; t = prev_v[t]) {
edge& e = graph[prev_v[t]][prev_e[t]];
e.cap -= ff;
graph[t][e.rev].cap += ff;
}
f -= ff;
}
return ans;
}
int main() {
cin >> V >> E >> F;
for (int j = 0; j < E; ++j) {
int u, v, c, d;
cin >> u >> v >> c >> d;
graph[u].emplace_back(v, c, (int)graph[v].size(), d);
graph[v].emplace_back(u, 0, (int)graph[u].size()-1, -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 | 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));
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;u=p1[u]) {
edge e=G[p1[u]][p2[u]];
G[p1[u]][p2[u]].cap-=a[t];
G[e.to][e.rev].cap+=a[t];
}
}
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": []
} | CORRECT | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#define NMAX 110
#define CMAX 1000000007
using namespace std;
typedef pair<int, int> pii;
int c[110][110] = {0};
int d[110][110] = {0};
int dist[110];
int path[110];
int Dijkstra(vector<int> *g, int s, int t){
priority_queue<pair<int, pii>, vector<pair<int, pii> >, greater<pair<int, pii> > > q;
q.push(make_pair(0, pii(s, s)));
for(int i=0; i<NMAX; ++i){
dist[i] = CMAX;
path[i] = -1;
}
dist[s] = 0;
int u, v, w;
while(!q.empty()){
u = q.top().second.second;
v = q.top().second.first;
w = q.top().first;
dist[u] = min(dist[u], w);
if(path[u] == -1)path[u] = v;
q.pop();
for(int i=0; i<g[u].size(); ++i){
if(c[u][g[u][i]] && path[g[u][i]] == -1){
q.push(make_pair(dist[u]+d[u][g[u][i]], pii(u,g[u][i])));
}
}
}
return dist[t];
}
int main(){
// 逐次最短路法により最小費用流問題を解く.
vector<int> g[NMAX], resig[NMAX];
int u, v, s, t;
int n, m, f;
int x = 0, p[NMAX] = {0}, res = 0;
int r[NMAX][NMAX] = {0}, e[NMAX][NMAX] = {0};
cin>>n>>m>>f;
for(int i=0; i<m; ++i){
cin>>u>>v>>s>>t;
c[u][v] = s;
d[u][v] = t, d[v][u] = -t;
r[u][v] = t, r[v][u] = -t;
e[u][v] = 1, e[v][u] = -1;
g[u].push_back(v);
resig[u].push_back(v);
resig[v].push_back(u);
}
int a, dx = 0, k;
while(dx != f){
if(Dijkstra(resig, 0, n-1) == CMAX){
cout<<-1<<endl;
return 0;
}
for(int i=0; i<n; ++i){
p[i] -= dist[i];
}
for(int i=0; i<n; ++i){
for(int j=0; j<n; ++j){
if(e[i][j])d[i][j] = r[i][j] + p[j] - p[i];
}
}
a = f - dx;
k = n-1;
while(true){
if(k == path[k]){
break;
}
a = min(a, c[path[k]][k]);
k = path[k];
}
k = n-1;
while(true){
if(k == path[k]){
break;
}
c[k][path[k]] += a;
c[path[k]][k] -= a;
res += r[path[k]][k]*a;
k = path[k];
}
dx += a;
}
cout<<res<<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.util.*;
import java.io.*;
import java.awt.geom.*;
import java.math.*;
public class Main {
static final Scanner in = new Scanner(System.in);
static final PrintWriter out = new PrintWriter(System.out,false);
static boolean debug = false;
static int primalDual(int[][][] cost, int[][][] capacity, int source, int sink, int f) {
int n = cost.length;
int[][] flow = new int[n][];
for (int i=0; i<n; i++)
flow[i] = new int[cost[i].length];
int[][][] rev = new int[n][][];
int[] cnt = new int[n];
for (int i=0; i<n; i++)
for (int j=0; j<cost[i].length; j++)
cnt[cost[i][j][0]]++;
for (int i=0; i<n; i++) rev[i] = new int[cnt[i]][2];
for (int i=n-1; i>=0; i--) {
for (int j=0; j<cost[i].length; j++) {
int ptr = --cnt[cost[i][j][0]];
rev[cost[i][j][0]][ptr][0] = i;
rev[cost[i][j][0]][ptr][1] = j;
}
}
int mincost = 0;
int[] h = new int[n];
final int[] d = new int[n];
TreeSet<Integer> que = new TreeSet<Integer>(new Comparator<Integer>(){
public int compare(Integer a, Integer b) {
if (d[a] != d[b]) return d[a] - d[b];
return a - b;
}
});
while (f > 0) {
int[] prev = new int[n];
int[] myidx = new int[n];
Arrays.fill(prev,-1); Arrays.fill(d,Integer.MAX_VALUE/2);
d[source] = 0;
que.add(source);
while (!que.isEmpty()) {
int cur = que.pollFirst();
for (int i=0; i<cost[cur].length; i++) {
int to = cost[cur][i][0];
if (capacity[cur][i][1] - flow[cur][i] > 0) {
int c = d[cur] + cost[cur][i][1] + h[cur] - h[to];
if (d[to] > c) {
que.remove(to);
d[to] = c;
prev[to] = cur;
myidx[to] = i;
que.add(to);
}
}
}
for (int i=0; i<rev[cur].length; i++) {
int to = rev[cur][i][0];
int ridx = rev[cur][i][1];
if (flow[to][ridx] > 0) {
int c = d[cur] - cost[to][ridx][1] + h[cur] - h[to];
if (d[to] > c) {
que.remove(to);
d[to] = c;
prev[to] = cur;
myidx[to] = ~ridx;
que.add(to);
}
}
}
}
if (prev[sink] == -1) break;
int flowlimit = f;
int sumcost = 0;
for (int i=sink; i!=source; i=prev[i]) {
if (myidx[i] >= 0) {
flowlimit = Math.min(flowlimit, capacity[prev[i]][myidx[i]][1] - flow[prev[i]][myidx[i]]);
sumcost += cost[prev[i]][myidx[i]][1];
}else {
int idx = ~myidx[i];
flowlimit = Math.min(flowlimit,flow[i][idx]);
sumcost -= cost[i][idx][1];
}
}
mincost += flowlimit*sumcost;
for (int i=sink; i!=source; i=prev[i]) {
if (myidx[i] >= 0) {
flow[prev[i]][myidx[i]] += flowlimit;
}else {
int idx = ~myidx[i];
flow[i][idx] -= flowlimit;
}
}
f -= flowlimit;
for (int i=0; i<n; i++) h[i] += d[i];
}
return f > 0 ? -1 : mincost;
}
static int[][][] directedGraph(int n, int[] from, int[] to, int[] cost) {
int[] cnt = new int[n];
for (int i : from) cnt[i]++;
int[][][] g = new int[n][][];
for (int i=0; i<n; i++) g[i] = new int[cnt[i]][2];
for (int i=0; i<from.length; i++) {
int s = from[i];
int t = to[i];
g[s][--cnt[s]][0] = t;
g[s][cnt[s]][1] = cost[i];
}
return g;
}
static void solve() {
int v = in.nextInt();
int e = in.nextInt();
int f = in.nextInt();
int[] s = new int[e];
int[] t = new int[e];
int[] c = new int[e];
int[] d = new int[e];
for (int i=0; i<e; i++) {
s[i] = in.nextInt();
t[i] = in.nextInt();
c[i] = in.nextInt();
d[i] = in.nextInt();
}
int[][][] cost = directedGraph(v, s, t, d);
int[][][] capacity = directedGraph(v, s, t, c);
out.println(primalDual(cost, capacity, 0, v-1, f));
}
public static void main(String[] args) {
debug = args.length > 0;
long start = System.nanoTime();
solve();
out.flush();
long end = System.nanoTime();
dump((end - start) / 1000000 + " ms");
in.close();
out.close();
}
static void dump(Object... o) { if (debug) System.err.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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define REP(i,n) for(int i=0,_n=(int)(n);i<_n;++i)
#define ALL(v) (v).begin(),(v).end()
#define CLR(t,v) memset(t,(v),sizeof(t))
template<class T1,class T2>ostream& operator<<(ostream& os,const pair<T1,T2>&a){return os<<"("<<a.first<<","<<a.second<< ")";}
template<class T>void pv(T a,T b){for(T i=a;i!=b;++i)cout<<(*i)<<" ";cout<<endl;}
template<class T>void chmin(T&a,const T&b){if(a>b)a=b;}
template<class T>void chmax(T&a,const T&b){if(a<b)a=b;}
ll nextLong() { ll x; scanf("%lld", &x); return x;}
const int MAX_V = 20000+5;
using CAP = ll;
using COST = ll;
const ll INF = (ll)1e9;
struct State {
COST dist;
int pos;
bool operator < (const State &o) const {
return dist > o.dist; // reverse order
}
};
struct Edge{ int to; CAP cap; COST cost; int rev; };
vector<Edge> adj[MAX_V];
COST potential[MAX_V];
COST dist[MAX_V];
int prevv[MAX_V];
int preve[MAX_V];
void clearedge() { REP(i, MAX_V) adj[i].clear(); }
void addedge(int u, int v, CAP cap, COST cost) {
adj[u].push_back( (Edge){v, cap, cost, (int)adj[v].size() + (u == v)} );
adj[v].push_back( (Edge){u, 0, -cost, (int)adj[u].size() - 1} );
}
// sからtへ流量 flow を流す最小コストを返す。
// 流せない場合は INF を返す
COST mincost_maxflow(int s, int t, CAP flow) {
vector<int> vs;
REP(i, MAX_V) if (adj[i].size()) vs.push_back(i);
int res = 0;
for (int v : vs) potential[v] = 0;
while (flow > 0) {
for (int v : vs) dist[v] = INF;
priority_queue<State> q;
q.push({0, s});
dist[s] = 0;
while (!q.empty()) {
State crt = q.top(); q.pop();
if (dist[crt.pos] < crt.dist) continue;
REP(i, adj[crt.pos].size()) {
const Edge&e = adj[crt.pos][i];
COST n_dist = crt.dist + e.cost + potential[crt.pos] - potential[e.to];
if (e.cap > 0 && dist[e.to] > n_dist) {
dist[e.to] = n_dist;
prevv[e.to] = crt.pos;
preve[e.to] = i;
q.push({dist[e.to], e.to});
}
}
}
if (dist[t] == INF) return INF;
for (int v : vs) potential[v] += dist[v];
CAP f = flow;
for (int v = t; v != s; v = prevv[v]) {
f = min(f, adj[prevv[v]][preve[v]].cap);
}
for (int v = t; v != s; v = prevv[v]) {
Edge &e = adj[prevv[v]][preve[v]];
e.cap -= f;
adj[v][e.rev].cap += f;
}
flow -= f;
res += f * potential[t];
}
return res;
}
int main2() {
int V = nextLong();
int E = nextLong();
int F = nextLong();
clearedge();
REP(i, E) {
int a = nextLong();
int b = nextLong();
int c = nextLong();
int d = nextLong();
addedge(a, b, c, d);
}
ll ans = mincost_maxflow(0, V-1, F);
if (ans == INF) ans = -1;
cout << ans << endl;
return 0;
}
int main() {
#ifdef LOCAL
for (;!cin.eof();cin>>ws)
#endif
main2();
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<vector>
#include<algorithm>
#include<utility>
#include<numeric>
#include<iostream>
#include<array>
#include<string>
#include<sstream>
#include<stack>
#include<queue>
#include<list>
#include<functional>
#define _USE_MATH_DEFINES
#include<math.h>
#include<map>
#define INF 200000000
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
#define VMAX 100
struct OwnEdge
{
int f, t, flow, cap,cost;
OwnEdge(int f, int t, int flow, int cap,int cost) :f(f), t(t), flow(flow), cap(cap),cost(cost) {}
};
vector<OwnEdge> G[VMAX];
int h[VMAX], tod[VMAX], prevv[VMAX], preve[VMAX];
int solve(int n, int src, int dest, int F)
{
int ans = 0;
while (F > 0)
{
fill(tod, tod + VMAX, INF);
priority_queue<pii, vector<pii>, greater<pii>> pq;
tod[src] = 0;
pq.push(make_pair(0, src));
while (!pq.empty())
{
pii temp = pq.top();
pq.pop();
if (tod[temp.second] < temp.first)
{
continue;
}
for (int i = 0; i != G[temp.second].size(); i++)
{
if (G[temp.second][i].cap <= G[temp.second][i].flow)
{
continue;
}
if (tod[G[temp.second][i].t] + h[G[temp.second][i].t]>tod[temp.second] + h[temp.second] + G[temp.second][i].cost)
{
tod[G[temp.second][i].t] = tod[temp.second] + h[temp.second] + G[temp.second][i].cost - h[G[temp.second][i].t];
prevv[G[temp.second][i].t] = temp.second;
preve[G[temp.second][i].t] = i;
pq.push(make_pair(tod[G[temp.second][i].t], G[temp.second][i].t));
}
}
}
if (tod[dest] == INF)
{
return -1;
}
for (int i = 0; i < n; i++)
{
h[i] += tod[i];
}
int td = F;
for (int i = dest; i != src; i = prevv[i])
{
td = min(td, G[prevv[i]][preve[i]].cap - G[prevv[i]][preve[i]].flow);
}
F -= td;
ans += td*h[dest];
for (int i = dest; i != src; i = prevv[i])
{
G[prevv[i]][preve[i]].flow += td;
G[i][G[prevv[i]][preve[i]].f].flow -= td;
}
}
return ans;
}
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
int V, E, F;
cin >> V >> E >> F;
for (int i = 0; i < E; i++)
{
int u, v, c, d;
cin >> u >> v >> c >> d;
int tus = G[u].size(), tvs = G[v].size();
G[u].push_back(OwnEdge(tvs, v, 0, c, d));
G[v].push_back(OwnEdge(tus, u, c, c, -d));
}
cout << solve(V, 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 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));
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 v=t;v!=s;v=p1[v]) {
int u=p1[v] , i=p2[v];
G[u][i].cap-=a[t];
i=G[u][i].rev;
G[v][i].cap+=a[t];
}
}
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": []
} | CORRECT | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
#define MAX_V 10000
#define INF 1000000001
typedef pair<int,int> P;
struct edge { int to,cap,cost,rev; };
int V;
vector<edge> G[MAX_V];
int h[MAX_V];
int dist[MAX_V];
int prevv[MAX_V],preve[MAX_V];
void init_edge(){
for(int i=0;i<V;i++)G[i].clear();
}
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< P, vector<P>, greater<P> > que;
fill( dist, dist+V , 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<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,a,b,c,d;
cin>>V>>E>>F;
while(E--){
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": []
} | CORRECT | cpp | #include "bits/stdc++.h"
using namespace std;
#define all(x) x.begin(), x.end()
#define mp make_pair
#define pii pair<int, int>
#define pll pair<long long, long long>
#define ll long long
static const int INF = 0x3f3f3f3f;
struct edge {
int to, cap, cost, rev;
};
int V;
vector<edge> g[101010];
int dist[101010];
int prevv[101010];
int preve[101010];
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 MinCostFlow(int s, int t, int f) {
int res = 0;
while (f > 0) {
fill(dist, dist + V, 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;
scanf("%d%d%d", &v, &e, &f);
V = v;
for (int i = 0; i < e; i ++) {
int u, v, c, d;
scanf("%d%d%d%d", &u, &v, &c, &d);
add_edge(u, v, c, d);
}
printf("%d\n", 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": []
} | CORRECT | cpp | #include "bits/stdc++.h"
using namespace std;
class minCostFlow
{
using type = int;
using pii = std::pair<int, int>;
const int INF = 1e9;
struct Edge
{
type to, cap, cost, rev;
Edge(type to_, type cap_, type cost_, type rev_)
: to(to_), cap(cap_), cost(cost_), rev(rev_) {}
};
int V;
std::vector<std::vector<Edge>> G;
// ポテンシャル
std::vector<int> h;
// 最短距離
std::vector<int> dist;
// 直前の頂点, 辺
std::vector<int> prevv, preve;
public:
minCostFlow(int _V) : V(_V), G(_V), h(_V), dist(_V), prevv(_V), preve(_V) {}
void add(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 calc(int s, int t, int f)
{
int res = 0;
fill(h.begin(), h.end(), 0);
while (f > 0)
{
std::priority_queue<pii, std::vector<pii>, std::greater<pii>> que;
fill(dist.begin(), dist.end(), INF);
dist[s] = 0;
que.push(pii(0, s));
while (!que.empty())
{
pii p = que.top();
que.pop();
int v = p.second;
if (dist[v] < p.first)
continue;
for (size_t 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(pii(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 = 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()
{
cin.tie(0);
ios::sync_with_stdio(false);
int V, E, F;
cin >> V >> E >> F;
minCostFlow mcf(V);
while (E--)
{
int st, gt, cap, d;
cin >> st >> gt >> cap >> d;
mcf.add(st, gt, cap, d);
}
cout << mcf.calc(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 | cpp | #include <bits/stdc++.h>
#define pb push_back
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=105;
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));
d[s]=0; a[s]=max(0,k-flow);
int qh=0,qt=0,q[maxn];
q[qt++]=s; inq[s]=1;
while (qh!=qt) {
int u=q[qh++]; if (qh>=maxn) qh=0;
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; if (qt>=maxn) qt=0;
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;u=p1[u]) {
edge& e=G[p1[u]][p2[u]];
e.cap-=a[t];
G[e.to][e.rev].cap+=a[t];
}
}
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": []
} | CORRECT | cpp | // this program implements Dinitz's algorithm
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
const int N = 110;
const int M = 2010;
const int inf = 0x3fffffff;
struct Edge {
int to, cap, cost, next;
} es[M];
int S, T; // source, sink
int SIZE = 0; // number of edges
int h[N]; // pointer to edge list
int dist[N], queue[N], inq[N]; // for calculating shortest path
int prev[N];
// add forward and backtracked edge
void add(int u, int v, int cap, int cost) {
int i = SIZE++;
es[i].to = v;
es[i].cap = cap;
es[i].cost = cost;
es[i].next = h[u];
h[u] = i;
int j = SIZE++;
es[j].to = u;
es[j].cap = 0;
es[j].cost = -cost;
es[j].next = h[v];
h[v] = j;
}
// returns whether find a shortest path from S to T
bool sssp(int n) {
int front = 0, back = 0;
for (int i = 0; i < n; i++) {
dist[i] = inf;
inq[i] = 0;
}
queue[back++] = S;
dist[S] = 0;
while (front != back) {
int x = queue[front++];
if (front == N) front = 0;
inq[x] = 0;
for (int i = h[x]; i != -1; i = es[i].next)
if (es[i].cap > 0) {
int y = es[i].to;
int new_d = dist[x] + es[i].cost;
if (new_d < dist[y]) {
dist[y] = new_d;
prev[y] = x;
if (!inq[y]) {
queue[back++] = y;
if (back == N) back = 0;
inq[y] = 1;
}
}
}
}
return (dist[T] < inf);
}
// returns the flow pushed from x to T
int dfs(int x, int flow) {
if (x == T) return flow;
int ret = 0;
for (int i = h[x]; i != -1 && flow > 0; i = es[i].next) {
int y = es[i].to;
if (prev[y] != x) continue;
int f = dfs(y, std::min(flow, es[i].cap));
if (f != 0) {
es[i].cap -= f;
es[i^1].cap += f;
ret += f;
flow -= f;
}
}
return ret;
}
void run() {
int n, m, u, v, c, d, flow, cost = 0;
scanf("%d%d%d", &n, &m, &flow);
memset(h, -1, sizeof(h));
S = 0, T = n - 1;
for (int i = 0; i < m; i++) {
scanf("%d%d%d%d", &u, &v, &c, &d);
add(u, v, c, d);
}
while (flow > 0 && sssp(n)) {
int f = dfs(S, flow);
cost += f * dist[T];
flow -= f;
}
if (flow > 0)
printf("-1\n");
else
printf("%d\n", cost);
}
int main() {
run();
} |
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 <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
#define NUM 100
typedef pair<int,int> P;
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[NUM];
int h[NUM];
int dist[NUM];
int pre_node[NUM],pre_edge[NUM];
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<P,vector<P>,greater<P> > Q;
for(int i = 0; i < V; i++)dist[i] = BIG_NUM;
dist[source] = 0;
Q.push(P(0,source));
while(!Q.empty()){
P 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(P(dist[e.to],e.to));
}
}
}
if(dist[sink] == BIG_NUM){
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": []
} | 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);
while(!queue.isEmpty()){
Integer u = queue.poll();
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": []
} | CORRECT | cpp | #include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<b;i++)
#define ZERO(a) memset(a,0,sizeof(a))
template<int NV, class V> class MinCostFlow {
public:
struct edge {
int to, capacity; V cost; int reve;
edge(int a, int b, V c, int d) {
to = a; capacity = b; cost = c; reve = d;
}
};
vector<edge> E[NV];
int prev_v[NV], prev_e[NV]; V dist[NV];
void add_edge(int x, int y, int cap, V cost) {
E[x].push_back(edge(y, cap, cost, (int)E[y].size()));
E[y].push_back(edge(x, 0, -cost, (int)E[x].size() - 1)); /* rev edge */
}
V mincost(int from, int to, int flow) {
V res = 0; int i, v;
ZERO(prev_v); ZERO(prev_e);
while (flow>0) {
fill(dist, dist + NV, numeric_limits<V>::max() / 2);
dist[from] = 0;
priority_queue<pair<int, int> > Q;
Q.push(make_pair(0, from));
while (Q.size()) {
int d = -Q.top().first, cur = Q.top().second;
Q.pop();
if (dist[cur] != d) continue;
if (d == numeric_limits<V>::max() / 2) break;
rep(i, 0, E[cur].size()) {
edge &e = E[cur][i];
if (e.capacity>0 && dist[e.to]>d + e.cost) {
dist[e.to] = d + e.cost;
prev_v[e.to] = cur;
prev_e[e.to] = i;
Q.push(make_pair(-dist[e.to], e.to));
}
}
}
if (dist[to] == numeric_limits<V>::max() / 2) return -1;
int lc = flow;
for (v = to; v != from; v = prev_v[v]) lc = min(lc, E[prev_v[v]][prev_e[v]].capacity);
flow -= lc;
res += lc*dist[to];
for (v = to; v != from; v = prev_v[v]) {
edge &e = E[prev_v[v]][prev_e[v]];
e.capacity -= lc;
E[v][e.reve].capacity += lc;
}
}
return res;
}
};
//-----------------------------------------------------------------
typedef long long ll;
int NV, NE, F;
//-----------------------------------------------------------------
int main()
{
MinCostFlow<100, ll> flow;
cin >> NV >> NE >> F;
rep(i, 0, NE) {
int a, b, c, d;
cin >> a >> b >> c >> d;
flow.add_edge(a, b, c, d);
}
cout << flow.mincost(0, NV - 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 rep(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
typedef vector<int>vint;
typedef pair<int,int>pint;
typedef vector<pint>vpint;
template<typename A,typename B>inline void chmin(A &a,B b){if(a>b)a=b;}
template<typename A,typename B>inline void chmax(A &a,B b){if(a<b)a=b;}
template<class A,class B>
ostream& operator<<(ostream& ost,const pair<A,B>&p){
ost<<"{"<<p.first<<","<<p.second<<"}";
return ost;
}
template<class T>
ostream& operator<<(ostream& ost,const vector<T>&v){
ost<<"{";
for(int i=0;i<v.size();i++){
if(i)ost<<",";
ost<<v[i];
}
ost<<"}";
return ost;
}
struct PrimalDual{
using F=long long;
const F INF=1ll<<50;
struct Edge{
int to;
F cap,cost;
int rev;
Edge(int to,F cap,F cost,int rev):to(to),cap(cap),cost(cost),rev(rev){}
};
int n;
vector<vector<Edge>>G;
PrimalDual(int n):n(n),G(n){}
void addEdge(int from,int to,F cap,F cost){
G[from].push_back(Edge(to,cap,cost,G[to].size()));
G[to].push_back(Edge(from,0,-cost,G[from].size()-1));
}
F minCostFlow(int s,int t,F f){
F cur=0;
vector<F>h(n);
vector<int>prevv(n,-1),preve(n,-1);
vector<F>dist(n);
priority_queue<pair<F,int>,vector<pair<F,int>>,greater<pair<F,int>>>que;
while(f>0){
fill(dist.begin(),dist.end(),INF);
dist[s]=0;
que.emplace(0,s);
while(que.size()){
F d;
int v;
tie(d,v)=que.top();
que.pop();
if(dist[v]<d)continue;
for(int i=0;i<G[v].size();i++){
Edge &e=G[v][i];
F nd=dist[v]+e.cost+h[v]-h[e.to];
if(e.cap>0&&dist[e.to]>nd){
dist[e.to]=nd;
prevv[e.to]=v;preve[e.to]=i;
que.emplace(nd,e.to);
}
}
}
if(dist[t]==INF)return -1;
for(int v=0;v<n;v++)h[v]+=dist[v];
F nf=f;
for(int v=t;v!=s;v=prevv[v]){
nf=min(nf,G[prevv[v]][preve[v]].cap);
}
f-=nf;
cur+=nf*h[t];
for(int v=t;v!=s;v=prevv[v]){
Edge &e=G[prevv[v]][preve[v]];
e.cap-=nf;
G[v][e.rev].cap+=nf;
}
}
return cur;
}
};
signed main(){
int V,E,F;
scanf("%d%d%d",&V,&E,&F);
PrimalDual pd(V);
rep(i,E){
int a,b,c,d;
scanf("%d%d%d%d",&a,&b,&c,&d);
pd.addEdge(a,b,c,d);
}
printf("%d\n",(int)pd.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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using VI = vector<int>;
using VVI = vector<VI>;
using PII = pair<int, int>;
using LL = long long;
using VL = vector<LL>;
using VVL = vector<VL>;
using PLL = pair<LL, LL>;
using VS = vector<string>;
#define ALL(a) begin((a)),end((a))
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SORT(c) sort(ALL((c)))
#define RSORT(c) sort(RALL((c)))
#define UNIQ(c) (c).erase(unique(ALL((c))), end((c)))
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FF first
#define SS second
template<class S, class T>
istream& operator>>(istream& is, pair<S,T>& p){
return is >> p.FF >> p.SS;
}
template<class S, class T>
ostream& operator<<(ostream& os, const pair<S,T>& p){
return os << p.FF << " " << p.SS;
}
template<class T>
void maxi(T& x, T y){
if(x < y) x = y;
}
template<class T>
void mini(T& x, T y){
if(x > y) x = y;
}
const double EPS = 1e-10;
const double PI = acos(-1.0);
const LL MOD = 1e9+7;
const int INF = 1e9;
// ????°??????¨???
struct EdgeC{
int to, cap, cost, rev;
EdgeC(int to_=0, int cap_ = 0, int cost_ = 0, int rev_ = 0)
:to(to_), cap(cap_), cost(cost_), rev(rev_){}
};
using GraphC = vector<vector<EdgeC>>;
void add_edge(GraphC& G, 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);
}
/**
* ?????????????????????????????????
* O(FVE)
* ?§????s, ??????t, ?????????f ???????°??????¨?????? ?????¨??????????????°-INF
*/
int min_cost_flow(GraphC& G, int s, int t, int f){
int V = G.size();
vector<int> dist(V);
vector<int> prevv(V), preve(V);
int res = 0;
while(f > 0){
fill(begin(dist), end(dist), INF);
dist[s] = 0;
bool update = true;
while(update){
update = false;
for(int v=0;v<V;++v){
if(dist[v] == INF) continue;
for(unsigned int i=0;i<G[v].size();++i){
auto& e = G[v][i];
if(e.cap > 0 && dist[v] + e.cost < dist[e.to]){
dist[e.to] = dist[v] + e.cost;
prevv[e.to] = v;
preve[e.to] = i;
update = true;
}
}
}
}
if(dist[t] == INF) return -INF;
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]){
auto& e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
int main(){
cin.tie(0);
ios_base::sync_with_stdio(false);
int V, E, F;
cin >> V >> E >> F;
GraphC G(V);
REP(i,E){
int u, v, c, d;
cin >> u >> v >> c >> d;
add_edge(G, u, v, c, d);
}
int res = min_cost_flow(G, 0, V-1, F);
cout << (res==-INF?-1:res) << 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 | /*
負の閉路が存在しない場合に使える
O(FElogV)
参考:
蟻本p202
https://ei1333.github.io/luzhiled/snippets/graph/primal-dual.html
verify:
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B&lang=jp
*/
#include <bits/stdc++.h>
using namespace std;
template<typename flow_t,typename cost_t>
struct PrimalDual{
struct edge{
int to;
flow_t cap;
cost_t cost;
int rev;
bool isrev;
};
const cost_t inf;
vector<vector<edge>> g;
vector<cost_t> h,dist;
vector<int> prevv,preve;
PrimalDual(int N,cost_t inf_):g(N),inf(inf_){}
void add_edge(int from,int to,flow_t cap,cost_t cost){
g[from].emplace_back((edge){to,cap,cost,(int)g[to].size(),false});
g[to].emplace_back((edge){from,0,-cost,(int)g[from].size()-1,true});
}
//fを流すのが不可能だったらinfを返す
cost_t query(int s,int t,flow_t f){
int N=g.size();
cost_t ret=0;
using pci=pair<cost_t,int>;
priority_queue<pci,vector<pci>,greater<pci>> que;
h.assign(N,0);
preve.assign(N,-1);
prevv.assign(N,-1);
while(f>0){
dist.assign(N,inf);
que.emplace(0,s);
dist[s]=0;
while(!que.empty()){
pci now=que.top(); que.pop();
if(dist[now.second]<now.first) continue;
for(int i=0;i<g[now.second].size();i++){
const edge &e=g[now.second][i];
cost_t nextCost=dist[now.second]+e.cost+h[now.second]-h[e.to];
if(e.cap>0 and dist[e.to]>nextCost){
dist[e.to]=nextCost;
prevv[e.to]=now.second; preve[e.to]=i;
que.emplace(nextCost,e.to);
}
}
}
if(dist[t]==inf) return inf;
for(int v=0;v<N;v++) h[v]+=dist[v];
flow_t addflow=f;
for(int v=t;v!=s;v=prevv[v]){
addflow=min(addflow,g[prevv[v]][preve[v]].cap);
}
f-=addflow;
ret+=addflow*h[t];
for(int v=t;v!=s;v=prevv[v]){
edge &e=g[prevv[v]][preve[v]];
e.cap-=addflow;
g[v][e.rev].cap+=addflow;
}
}
return ret;
}
};
int main(){
int N,E,F;
cin>>N>>E>>F;
PrimalDual<int,int> flow(N,1<<30);
for(int i=0;i<E;i++){
int s,t,cap,cost;
cin>>s>>t>>cap>>cost;
flow.add_edge(s,t,cap,cost);
}
int x=flow.query(0,N-1,F);
if(x==(1<<30)) x=-1;
cout<<x<<"\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;
#ifdef DEBUG_MODE
#define DBG(n) n;
#else
#define DBG(n) ;
#endif
#define REP(i,n) for(ll (i) = (0);(i) < (n);++i)
#define PB push_back
#define MP make_pair
#define FI first
#define SE second
#define SHOW1d(v,n) {for(int W = 0;W < (n);W++)cerr << v[W] << ' ';cerr << endl << endl;}
#define SHOW2d(v,i,j) {for(int aaa = 0;aaa < i;aaa++){for(int bbb = 0;bbb < j;bbb++)cerr << v[aaa][bbb] << ' ';cerr << endl;}cerr << endl;}
#define ALL(v) v.begin(),v.end()
#define Decimal fixed<<setprecision(20)
#define INF 1000000000
#define LLINF 1000000000000000000LL
#define MOD 1000000007
typedef long long ll;
typedef pair<ll,ll> P;
class minCostFlow {
struct edge { int to, cap, cost, rev; };
int V;
vector<vector<edge>> G;
vector<int> dist;
vector<int> prevv;
vector<int> preve;
public:
minCostFlow(int n): G(n+10), dist(n+10), prevv(n+10), preve(n+10), V(n){
}
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 solve(int s, int t, int f) {
int ret = 0;
while(f > 0) {
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 < 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;
ret += 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 ret;
}
};
int main(){
int v,e,f;cin >> v >> e >> f;
minCostFlow mcf(v);
REP(i,e) {
int a,b,c,d;cin >> a >> b >> c >> d;
mcf.addEdge(a, b , 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": []
} | CORRECT | cpp | #include <iostream>
#include <vector>
#include <limits>
template <class Cap, class Cost, bool isDirect>
class MinCostFlow {
struct Edge {
int from, to;
Cap cap;
Cost cost;
int rev;
Edge(int from, int to, Cap cap, Cost cost, int rev)
: from(from), to(to), cap(cap), cost(cost), rev(rev){};
};
class Graph {
public:
int size;
std::vector<std::vector<Edge>> path;
explicit Graph(int N = 0) : size(N), path(size) {}
void span(int from, int to, Cap cap, Cost cost, int rev) {
path[from].push_back(Edge(from, to, cap, cost, rev));
}
std::vector<Edge>& operator[](int v) { return path[v]; }
};
public:
const Cost INF = std::numeric_limits<Cost>::max();
Graph graph;
std::vector<Cost> dist;
std::vector<Edge*> rev;
explicit MinCostFlow(int N) : graph(N), dist(N), rev(N) {}
void span(int from, int to, Cap cap, Cost cost) {
graph.span(from, to, cap, cost, graph[to].size());
graph.span(to, from, (isDirect ? 0 : cap), -cost, graph[from].size() - 1);
}
void BellmanFord(int s) {
fill(dist.begin(), dist.end(), INF);
dist[s] = 0;
bool update = true;
while (update) {
update = false;
for (int v = 0; v < graph.size; ++v) {
if (dist[v] == INF) continue;
for (auto& e : graph[v]) {
if (e.cap > 0 && dist[e.to] > dist[e.from] + e.cost) {
dist[e.to] = dist[e.from] + e.cost;
rev[e.to] = &e;
update = true;
}
}
}
}
}
Cost exec(int s, int g, Cap flow) {
Cost ret = 0;
while (flow > 0) {
BellmanFord(s);
if (dist[g] == INF) break;
Cap f = flow;
int v = g;
while (v != s) {
f = std::min(f, rev[v]->cap);
v = rev[v]->from;
}
flow -= f;
ret += f * dist[g];
v = g;
while (v != s) {
// rev[v]->to = v
rev[v]->cap -= f;
graph[v][rev[v]->rev].cap += f;
v = rev[v]->from;
}
}
return (flow > 0 ? -1 : ret);
}
};
int main() {
int N, M, F;
std::cin >> N >> M >> F;
MinCostFlow<int, int, true> mcf(N);
for (int i = 0; i < M; ++i) {
int u, v, c, d;
std::cin >> u >> v >> c >> d;
mcf.span(u, v, c, d);
}
std::cout << mcf.exec(0, N - 1, F) << 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": []
} | CORRECT | python3 | #最小費用流問題
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
n,m,f = map(int,readline().split())
"""
n頂点m辺の重み付き有向グラフに流量fを流したい。
コストの最小値を出力せよ。
但しsourse = 0,sink = n-1とし、
そもそも流量f流せるだけcapacityがない場合は-1を出力せよ。
"""
# 最小費用流(minimum cost flow)
class MinCostFlow:
def __init__(self, n):
self.n = n
self.G = [[] for i in range(n)]
def addEdge(self, f, t, cap, cost): #costは1capに対して1costで定義される
# [to, cap, cost, rev]↓revは勝手に逆辺張ってくれるので考えなくて良い。
self.G[f].append([t, cap, cost, len(self.G[t])])
self.G[t].append([f, 0, -cost, len(self.G[f])-1])
def minCostFlow(self, s, t, f): #sからtまで、流量fを流し切る
n = self.n
G = self.G
prevv = [0]*n; preve = [0]*n
INF = 10**18
res = 0 #コスト合計
while f:
dist = [INF]*n
dist[s] = 0
update = 1
while update:
update = 0
for v in range(n):
if dist[v] == INF:
continue
gv = G[v]
for i in range(len(gv)):
to, cap, cost, rev = gv[i]
if cap > 0 and dist[v] + cost < dist[to]:
dist[to] = dist[v] + cost
prevv[to] = v; preve[to] = i
update = 1
if dist[t] == INF: #そもそもcapacity的に流量fを流せない場合
return -1
d = f; v = t
while v != s:
d = min(d, G[prevv[v]][preve[v]][1])
v = prevv[v]
f -= d
res += d * dist[t] #distには、一本の道全体としての単位コストが入っている。
#dだけ流せるので、d*その道全体のコストを,コスト合計のresに入れる。
v = t
while v != s:
e = G[prevv[v]][preve[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prevv[v]
return res
MCF = MinCostFlow(n)
for i in range(m):
u,v,cap,cost = map(int,readline().split())
MCF.addEdge(u,v,cap,cost)
print(MCF.minCostFlow(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": []
} | CORRECT | cpp | #include<cstdio>
#include<vector>
#include<algorithm>
#include<utility>
#include<numeric>
#include<iostream>
#include<array>
#include<string>
#include<sstream>
#include<stack>
#include<queue>
#include<list>
#include<functional>
#define _USE_MATH_DEFINES
#include<math.h>
#include<map>
#define INF 200000000
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
#define VMAX 100
struct OwnEdge
{
int f, t, flow, cap,cost;
OwnEdge(int f, int t, int flow, int cap,int cost) :f(f), t(t), flow(flow), cap(cap),cost(cost) {}
};
vector<OwnEdge> G[VMAX];
int h[VMAX], tod[VMAX], prevv[VMAX], preve[VMAX];
int solve(int n, int src, int dest, int F)
{
int ans = 0;
while (F > 0)
{
fill(tod, tod + VMAX, INF);
priority_queue<pii, vector<pii>, greater<pii>> pq;
tod[src] = 0;
pq.push(make_pair(0, src));
while (!pq.empty())
{
pii temp = pq.top();
pq.pop();
if (tod[temp.second] < temp.first)
{
continue;
}
for (int i = 0; i != G[temp.second].size(); i++)
{
if (G[temp.second][i].cap <= G[temp.second][i].flow)
{
continue;
}
if (tod[G[temp.second][i].t] + h[G[temp.second][i].t]>temp.first + h[temp.second] + G[temp.second][i].cost)
{
tod[G[temp.second][i].t] = tod[temp.second] + h[temp.second] + G[temp.second][i].cost - h[G[temp.second][i].t];
prevv[G[temp.second][i].t] = temp.second;
preve[G[temp.second][i].t] = i;
pq.push(make_pair(tod[G[temp.second][i].t], G[temp.second][i].t));
}
}
}
if (tod[dest] == INF)
{
return -1;
}
for (int i = 0; i < n; i++)
{
h[i] += tod[i];
}
int td = F;
for (int i = dest; i != src; i = prevv[i])
{
td = min(td, G[prevv[i]][preve[i]].cap - G[prevv[i]][preve[i]].flow);
}
F -= td;
ans += td*h[dest];
for (int i = dest; i != src; i = prevv[i])
{
G[prevv[i]][preve[i]].flow += td;
G[i][G[prevv[i]][preve[i]].f].flow -= td;
}
}
return ans;
}
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
int V, E, F;
cin >> V >> E >> F;
for (int i = 0; i < E; i++)
{
int u, v, c, d;
cin >> u >> v >> c >> d;
int tus = G[u].size(), tvs = G[v].size();
G[u].push_back(OwnEdge(tvs, v, 0, c, d));
G[v].push_back(OwnEdge(tus, u, c, c, -d));
}
cout << solve(V, 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
class MinimumCostFlow:
inf = 1000000000
def __init__(self, n):
self.n = n
self.edges = [[] for i in range(n)]
def add_edge(self, f, t, cap, cost):
self.edges[f].append([t, cap, cost, len(self.edges[t]), False])
self.edges[t].append([f, 0, -cost, len(self.edges[f]) - 1, True]) # reverse edge
def flow(self, s, t, flow):
n = self.n
g = self.edges
inf = MinimumCostFlow.inf
prevv = [0 for i in range(n)]
preve = [0 for i in range(n)]
h = [0 for i in range(n)]
dist = [inf for i in range(n)]
res = 0
while flow != 0:
dist = [inf for i in range(n)]
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
r0 = dist[v] + h[v]
for i, e in enumerate(g[v]):
w, cap, cost, _, _ = e
if cap > 0 and r0 + cost - h[w] < dist[w]:
r = r0 + cost - h[w]
dist[w] = r
prevv[w] = v
preve[w] = i
heappush(que, (r, w))
if dist[t] == inf:
return -1
for i in range(n):
h[i] += dist[i]
d = flow
v = t
while v != s:
d = min(d, g[prevv[v]][preve[v]][1])
v = prevv[v]
flow -= d
res += d * h[t]
v = t
while v != s:
e = g[prevv[v]][preve[v]]
e[1] -= d
g[v][e[3]][1] += d
v = prevv[v]
return res
import sys
readline = sys.stdin.readline
write = sys.stdout.write
N, M, F = map(int, readline().split())
mcf = MinimumCostFlow(N)
for i in range(M):
u, v, c, d = map(int, readline().split())
mcf.add_edge(u, v, c, d)
write("%d\n" % mcf.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": []
} | CORRECT | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
#define _USE_MATH_DEFINES
#include<math.h>
#include<queue>
#include<deque>
#include<stack>
#include<cstdio>
#include<utility>
#include<set>
#include<list>
#include<cmath>
#include<stdio.h>
#include<string.h>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
#define FOR(i, a, b) for (ll i = (a); i <= (b); i++)
#define REP(i, n) FOR(i, 0, n - 1)
#define NREP(i, n) FOR(i, 1, n)
using ll = long long;
using pii = pair<int, int>;
using piii = pair<pii, pii>;
const ll dx[4] = { 0, -1, 1, 0 };
const ll dy[4] = { -1, 0, 0, 1 };
const int INF = 1e9 + 7;
int gcd(int x, int y) {
if (x < y)swap(x, y);
if (y == 0)return x;
return gcd(y, x%y);
}
void mul(ll a, ll b) {
a = a * b % INF;
}
double mysqrt(double x) {
double l = 0, r = x;
for (int i = 0; i < 64; ++i) {
double m = (l + r) / 2.0;
if (m*m < x)l = m;
else r = m;
}
return l;
}
///////////////////////////////////////
//辺を表す構造体{行先、容量、コスト、逆辺}
struct edge { int to, cap, cost, rev; };
int V, E, F;
vector<edge>G[110];
int dist[110];
int prevv[110], preve[110];
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 });
}
//sからtへの流用fの最小費用流を求める
//流せない場合は-1を返す
int min_cost_flow(int s, int t, int f) {
int res = 0;
//ベルマンフォードによりs-t間最短路を求める
while (f > 0) {
fill(dist, dist + V, INF);
dist[s] = 0;
bool upgrade = true;
while (upgrade) {
upgrade = 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;
upgrade = 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() {
cin >> V >> E >> F;
REP(i, E) {
int from, to, cap, cost;
cin >> from >> to >> cap >> cost;
add_edge(from, to, cap, cost);
}
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 | cpp | #include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
int v,e,f;
unordered_map<int,unordered_map<int,int> > g,costs,inv_costs;
queue<pair<int,int> > nodes;
int cost = 0;
int dfs(int now, int flow, vector<bool> &arrived, vector<int> &dp) {
if(now==0||flow==0) return flow;
arrived[now] = true;
for(pair<int,int> p : inv_costs[now]) {
int next = p.first;
int next_cost = p.second;
if(arrived[next]) continue;
if(dp[now]-dp[next]==next_cost) {
int res = dfs(next,min(flow,g[next][now]),arrived,dp);
if(res>0) {
g[next][now] -= res;
g[now][next] += res;
costs[now][next] = -costs[next][now];
inv_costs[next][now] = -inv_costs[now][next];
if(g[next][now]==0) {
costs[next].erase(now);
inv_costs[now].erase(next);
}
cost += res*next_cost;
return res;
}
}
}
return 0;
}
int calc(vector<int> &dp, int flow) {
vector<int> vf(v,1<<30);
for(int loop = 0; loop < v; loop++) {
for(int now = 0; now < v; now++) {
if(dp[now]==1<<30) continue;
vf[now] = min(vf[now],dp[now]);
for(pair<int,int> p : costs[now]) {
int next = p.first;
int next_cost = p.second;
vf[next] = min(vf[next],dp[now]+next_cost);
}
}
dp.swap(vf);
}
vector<bool> arrived(v);
return dfs(v-1,flow,arrived,dp);
}
int main() {
cin >> v >> e >> f;
for(int i = 0; i < e; i++) {
int u,v2,c,d;
cin >> u >> v2 >> c >> d;
if(c<=0) continue;
g[u][v2] = c;
costs[u][v2] = d;
inv_costs[v2][u] = d;
}
int ans = 0;
while(ans<f) {
vector<int> dp(v,1<<30);
dp[0] = 0;
int flow = calc(dp,f-ans);
if(flow<=0) break;
else ans += flow;
}
cout << ((ans>=f)?cost:-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": []
} | CORRECT | cpp |
#include <bits/stdc++.h>
using namespace std;
const int INF = (int) 1e5 + 1;
const int MAX_V = (int) 100;
struct edge { int to, cap, cost, rev; };
vector<edge> G[MAX_V];
int dist[MAX_V];
int 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 dfs(int v, int t, int f) {
if (v == t) return f;
dist[v] = true;
for (auto &e: G[v]) {
if (!dist[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int V, E, f;
cin >> V >> 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);
}
int s = 0;
int t = V -1;
int res = 0;
while (f > 0) {
fill(dist, dist + V, 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) {
res = -1;
break;
}
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;
}
}
cout << res << '\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": []
} | CORRECT | cpp |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, j) for(int i = 0; i < (int)(j); i++)
constexpr int INF = 1 << 28;
struct Edge {
int to;
ll capacity, cost, rev;
};
constexpr ll INFL = 1LL << 60;
struct Flow {
int N;
vector<vector<Edge>> E;
Flow(int n) : N(n) {
E.resize(N);
}
void add_arc(int from, int to, ll cap, ll cost = 0) {
E[from].push_back(Edge{to, cap, cost, (ll)E[to].size()}); // E[to].size() ????????§??????????????????
E[to].push_back(Edge{from, 0, -cost, (ll)E[from].size() - 1}); // ??????
}
// s -> t ??? f ??????????????????????°??????¨????¨?????????????????????? - 1
// O(F|V||E|)
// ????????¨??°??????????£???????
ll min_cost_flow(int s, int t, ll f) {
vector<int> prev_v(N), prev_e(N);
auto bellmanford = [&] (int s) {
vector<ll> dist(N, INFL);
dist[s] = 0;
bool updated = true;
while(updated) {
updated = false;
rep(v, N) {
if(dist[v] >= INFL) continue;
rep(i, E[v].size()) {
auto &e = E[v][i];
if(e.capacity > 0 and dist[e.to] > dist[v] + e.cost) {
dist[e.to] = dist[v] + e.cost;
prev_v[e.to] = v;
prev_e[e.to] = i;
updated = true;
}
}
}
}
return dist;
};
ll res = 0;
while(f > 0) {
auto dist = bellmanford(s);
if(dist[t] == INFL) return -1;
ll d = f;
// s -> t ???????°?????????????????????????????°??????? d ????±???????
for(int v = t; v != s; v = prev_v[v]) {
d = min(d, E[prev_v[v]][prev_e[v]].capacity);
}
// d ????????????
for(int v = t; v != s; v = prev_v[v]) {
auto &e = E[prev_v[v]][prev_e[v]];
e.capacity -= d;
E[v][e.rev].capacity += d;
}
f -= d;
res += d * dist[t]; // ??????????????¨
}
return res;
}
};
int main() {
int V, E, F; cin >> V >> E >> F;
Flow f(V);
rep(i, E) {
int u, v, c, d; cin >> u >> v >> c >> d;
f.add_arc(u, v, 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 | #include <iostream>
#include <vector>
#include <numeric>
#include <queue>
#include <algorithm>
#include <utility>
#include <functional>
using namespace std;
using Flow = int;
template<typename Flow = int>
struct PrimalDual {
struct Edge {
int dst;
Flow cap, cap_orig;
Flow cost;
int revEdge;
bool isRev;
Edge(int dst, Flow cap, Flow cost, int rev, bool isRev)
:dst(dst), cap(cap), cap_orig(cap), cost(cost), revEdge(rev), isRev(isRev) {
}
};
int n;
vector<vector<Edge> > g;
PrimalDual(int n_) : n(n_), g(vector<vector<Edge> >(n_)) {}
void addEdge(int src, int dst, Flow cap, Flow cost) {
g[src].emplace_back(dst, cap, cost, g[dst].size(), false);
g[dst].emplace_back(src, 0, -cost, g[src].size() - 1, true);
}
Flow solve(int s, int t, int f) {
constexpr Flow inf = numeric_limits<Flow>::max();
Flow res = 0;
vector<Flow> h(g.size()), dist(g.size());
vector<int> prevv(g.size()), preve(g.size());
while (f > 0) {
priority_queue<pair<Flow, int>> q;
fill(dist.begin(), dist.end(), inf);
dist[s] = 0;
q.emplace(0, s);
while (q.size()) {
int d, v;
tie(d,v) = q.top();
q.pop();
d = -d;
if (dist[v] < d) 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.cost + h[v] - h[e.dst]) {
dist[e.dst] = dist[v] + e.cost + h[v] - h[e.dst];
prevv[e.dst] = v;
preve[e.dst] = i;
q.emplace(-dist[e.dst], e.dst);
}
}
}
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]) {
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.revEdge].cap += d;
}
}
return res;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m, f;
cin >> n >> m >> f;
PrimalDual<int> pd(n);
for (int i = 0; i < m; i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
pd.addEdge(u, v, c, d);
}
cout << pd.solve(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 | bool debug=false;
#include <string.h>
#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
using namespace std;
#define F first
#define S second
#define PB push_back
const int INF=1e9+10;
const int N=1e2+10;
pair<int,int> graph[N][N];
pair<int,int> dis[N];
int from[N];
int n;
int min(int a,int b){return a>b?b:a;}
pair<int,int> mcmf(int s,int t){
for(int i=1;i<n;i++)dis[i]={INF,0};
dis[s]={0,INF};
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
pair<int,int> nxt;
int temp;
pq.push({0,s});
from[s]=s;
while(!pq.empty()){
nxt=pq.top();
pq.pop();
if(debug)printf("nxt=%d %d\n",nxt.F,nxt.S);
if(dis[nxt.S].F<nxt.F)continue;
for(int i=0;i<n;i++)if(graph[nxt.S][i].S>0&&nxt.F+graph[nxt.S][i].F<dis[i].F){
dis[i]={nxt.F+graph[nxt.S][i].F,min(dis[nxt.S].S,graph[nxt.S][i].S)};
pq.push({dis[i].F,i});
from[i]=nxt.S;
}else if(debug)printf("graph[%d][%d]=%d %d\n",nxt.S,i,graph[nxt.S][i].F,graph[nxt.S][i].S);
}
if(dis[t].S==0)return {-1,-1};
temp=t;
while(temp!=s){
graph[temp][from[temp]].S+=dis[t].S;
graph[from[temp]][temp].S-=dis[t].S;
temp=from[temp];
}
graph[temp][from[temp]].S+=dis[t].S;
graph[from[temp]][temp].S-=dis[t].S;
return dis[t];
}
int main(){
int l,r,cost,cap,m,ans=0,f;
pair<int,int> temp;
scanf("%d%d%d",&n,&m,&f);
for(int i=0;i<n;i++)for(int j=0;j<n;j++)graph[i][j]={INF,0};
while(m--){
scanf("%d%d%d%d",&l,&r,&cap,&cost);
graph[l][r]={cost,cap};
graph[r][l]={-cost,0};
}
while(f>0){
temp=mcmf(0,n-1);
if(debug)printf("f=%d temp=(%d,%d)\n",f,temp.F,temp.S);
if(temp.S<=0){
printf("-1\n");
return 0;
}
if(temp.S>f){
ans+=temp.F*f;
f=0;
}
else{
ans+=temp.F*temp.S;
f-=temp.S;
}
}
printf("%d\n",ans);
}
|
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<cstring>
#include<vector>
#include<queue>
#include<algorithm>
#include<cmath>
#include<climits>
#include<string>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define rep(i,n) for(int i=0;i<((int)(n));i++)
#define reg(i,a,b) for(int i=((int)(a));i<=((int)(b));i++)
#define irep(i,n) for(int i=((int)(n))-1;i>=0;i--)
#define ireg(i,a,b) for(int i=((int)(b));i>=((int)(a));i--)
typedef long long int lli;
typedef pair<int,int> mp;
#define fir first
#define sec second
#define IINF INT_MAX
#define LINF LLONG_MAX
#define eprintf(...) fprintf(stderr,__VA_ARGS__)
#define pque(type) priority_queue<type,vector<type>,greater<type> >
#define memst(a,b) memset(a,b,sizeof(a))
struct edge{
int to,p;
lli cap,co;
};
int n;
vector<edge> vs[105];
int ds[105];
mp bf[105];
int inf=1e8;
lli mincof(int st,int gl,int gf){
lli res=0;
while(gf>0){
rep(i,n)ds[i]=inf;
ds[st]=0;
for(;;){
bool ud=false;
rep(i,n){
if(ds[i]==inf)continue;
rep(j,vs[i].size()){
edge e=vs[i][j];
if(e.cap<=0)continue;
if(ds[e.to]>ds[i]+e.co){
ds[e.to]=ds[i]+e.co;
bf[e.to]=mp(i,j);
ud=true;
}
}
}
if(!ud)break;
}
if(ds[gl]==inf)return -1;
//rep(i,n)printf("%d / %d .. %d (%d %d)\n",gf,i,ds[i],bf[i].fir,bf[i].sec);
lli nf=gf;
int no=gl;
while(no!=st){
int to=bf[no].fir;
edge& be=vs[to][bf[no].sec];
nf=min(nf,be.cap);
no=to;
}
lli cs=0;
no=gl;
while(no!=st){
int to=bf[no].fir;
edge& be=vs[to][bf[no].sec];
be.cap-=nf;
cs+=be.co;
vs[no][be.p].cap+=nf;
no=to;
}
res+=cs*nf;
gf-=nf;
}
return res;
}
int m,gf;
int main(void){
scanf("%d%d%d",&n,&m,&gf);
rep(i,m){
int a,b,c,d;
scanf("%d%d%d%d",&a,&b,&c,&d);
edge e;
e.to=b; e.p=vs[b].size(); e.cap=c; e.co=d;
vs[a].push_back(e);
e.to=a; e.p=vs[a].size()-1; e.cap=0; e.co=-d;
vs[b].push_back(e);
}
printf("%lld\n",mincof(0,n-1,gf));
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 | #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#ifdef _DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif
//#define int long long
#define DBG 1
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define loop(n) rep(loop, (0), (n))
#define all(c) begin(c), end(c)
const int INF =
sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9) + 7;
const double PI = acos(-1);
const double EPS = 1e-9;
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 (a > b) {
a = b;
return true;
}
return false;
}
struct edge {
int to, cap, cost, rev;
edge(int to, int cap, int cost, int rev)
: to(to), cap(cap), cost(cost), rev(rev) {}
};
struct Graph {
int V;
vector<vector<edge>> G;
vector<int> dist, prev_v, prev_e;
Graph(int V) : V(V), dist(V), prev_v(V), prev_e(V), G(V) {}
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 min_cost_flow(int s, int t, int f) {
int res = 0;
while (f > 0) {
fill(all(dist), INF);
dist[s] = 0;
bool update = true;
while (update) {
update = false;
rep(v, 0, V) {
if (dist[v] == INF)
continue;
rep(i, 0, G[v].size()) {
edge &e = G[v][i];
if (e.cap > 0 and dist[e.to] > dist[v] + e.cost) {
dist[e.to] = dist[v] + e.cost;
prev_v[e.to] = v;
prev_e[e.to] = i;
update = true;
}
}
}
}
if (dist[t] == INF)
return -1;
int d = f;
for (int v = t; v != s; v = prev_v[v]) {
chmin(d, G[prev_v[v]][prev_e[v]].cap);
}
f -= d;
res += d * dist[t];
for (int v = t; v != s; v = prev_v[v]) {
edge &e = G[prev_v[v]][prev_e[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
};
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
int V, E, F;
cin >> V >> E >> F;
Graph g(V);
rep(i, 0, E) {
int a, b, c, d;
cin >> a >> b >> c >> d;
g.add_edge(a, b, c, d);
}
cout << g.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 | #include <bits/stdc++.h>
#include <iomanip>
using namespace std;
typedef long long LL;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef pair<LD, LD> PLDLD;
typedef vector<int> VI;
typedef vector<char> VB;
#define FOR(i,a,b) for(int i=(a);i<(int)(b);++i)
#define REP(i,n) FOR(i,0,n)
#define CLR(a) memset((a), 0 ,sizeof(a))
#define ALL(a) a.begin(),a.end()
const LD eps=1e-5;
//const long long INF=(LL)(1e9)*(LL)(1e9);
const int INF=1e9;
template<class T>
void chmin(T& a, const T& b)
{
if(a>b)
a=b;
}
template<class T>
void chmax(T& a, const T& b)
{
if(a<b)
a=b;
}
const LL pow(const LL p, const LL q)
{
LL t=1;
REP(i,q)
t*=p;
return t;
}
//print for container
/*
template<typename Iterator>
void print(const Iterator& first, const Iterator& last)
{
auto&& back=prev(last);
for(auto e=first; e!=last; e=next(e))
cout<<*e<<" \n"[e==back];
}*/
template<typename Head>
void print(const Head& head)
{
cout<<head<<endl;
}
template<typename Head, typename... Tail>
void print(const Head& head, const Tail&... tail)
{
cout<<head<<" ";
print(tail...);
}
void io_speedup()
{
cin.tie(0);
ios::sync_with_stdio(false);
}
template<typename T>
T read()
{
T t;
cin>>t;
return t;
}
constexpr long long INF64 = 1e18;
using Weight=long long;
struct edge{
int to,cap,cost,rev;
};
const int MAX_V=100;
int V;
vector<vector<edge>> G(MAX_V);
int dist[MAX_V];
int 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;
while(f>0)
{
fill(dist, dist+V, 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()
{
REP(i,MAX_V)
dist[i]=INF;
int n,m,f;
cin>>n>>m>>f;
V=n;
for(int i=0;i<m;++i){
int u,v;
Weight cap,cost;
cin>>u>>v>>cap>>cost;
add_edge(u,v,cap,cost);
}
cout<<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 | //最小費用流問題を解く
//計算量O(F|V||E|)
//参考 蟻本
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
#define rep(i,n) for(int i=0;i<(n);i++)
struct edge {
ll to;//行き先の頂点
ll cap;//辺の容量
ll cost;//1フローあたりのコスト
ll rev;//逆辺のインデックス(G[e.to][e.rev]で逆辺にアクセスできる。)
};
#define MAX_V 1000
#define INF (1e18)
ll V;//頂点数 ここに頂点数をセットするのを忘れないように。
vector<edge> G[MAX_V];
ll dist[MAX_V];
ll prevv[MAX_V],preve[MAX_V]; // 直前の頂点と辺
void add_edge(ll from,ll to,ll cap,ll cost) {
G[from].push_back((edge){to,cap,cost,(ll)G[to].size()});//辺の追加
G[to].push_back((edge){from,0,-cost,(ll)G[from].size() - 1});//辺の逆辺
}
// 最小費用流を求める(sからt)
// 流せない場合はINFをかえす。
ll min_cost_flow (ll s,ll t,ll f) {
ll ret = 0;
while(f > 0) {
//ベルマンフォード
fill(dist,dist + V,INF);
dist[s] = 0;
bool update = true;
while(update) {//最初に負の閉路があると無限ループになるので注意
update = false;
rep(v,V) {
if(dist[v] == INF) continue;
rep(i,G[v].size()) {
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;//辺の添字を記録 求めたパスである頂点uに入る辺はG[prevv[u]][preve[u]]で表す
update = true;
}
}
}
}
if(dist[t] == INF) {
//正のフローを流せるs-t道がなかった
return -1;
}
// s-t間最短路に沿って目一杯流す
ll d = f;//残りのフロー
for(ll v = t;v != s;v = prevv[v]) {//t側から更新していく
d = min(d,G[prevv[v]][preve[v]].cap);//パスの容量
}
f -= d;
ret += d * dist[t];//総費用の更新
for(ll 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;
}
ll E,F;
int main() {
cin >> V >> E >> F;
rep(i,E) {
ll 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 | python3 | V,E,F=map(int,input().split())
EDGE=dict()
EDGE2=[[] for i in range(V)]
for i in range(E):
x,to,c,d=map(int,input().split())
EDGE[(x,to)]=[c,d]
EDGE2[x].append(to)
BACK=[-1]*V
P=[0]*V
# 一回ベルマンフォードをしてポテンシャルを求める.
ANS=[float("inf")]*V
ANS[0]=0
for rep in range(V):
for x,to in EDGE:
c,d=EDGE[(x,to)]
if c>0 and ANS[to]>ANS[x]+d:
ANS[to]=ANS[x]+d
BACK[to]=x
P=[ANS[i] for i in range(V)]
LA=ANS[V-1]
NOW=V-1
while NOW!=0:
fr=BACK[NOW]
EDGE[(fr,NOW)][0]-=1
if (NOW,fr) in EDGE:
EDGE[(NOW,fr)][0]+=1
else:
EDGE[(NOW,fr)]=[1,-EDGE[fr,NOW][1]]
EDGE2[NOW].append(fr)
NOW=fr
for x,to in EDGE:
EDGE[(x,to)][1]+=P[x]-P[to]
# あとはダイクストラを使える.
import heapq
for i in range(F-1):
ANS=[float("inf")]*V
Q=[(0,0)]
ANS[0]=0
while Q:
time,ind=heapq.heappop(Q)
if time>ANS[ind]:
continue
for to in EDGE2[ind]:
c,d=EDGE[(ind,to)]
if c>0 and ANS[to]>ANS[ind]+d:
ANS[to]=ANS[ind]+d
BACK[to]=ind
heapq.heappush(Q,(ANS[to],to))
LA+=ANS[V-1]+P[V-1]-P[0]
if LA==float("inf"):
break
P=[P[i]-ANS[i] for i in range(V)]
NOW=V-1
while NOW!=0:
fr=BACK[NOW]
EDGE[(fr,NOW)][0]-=1
if (NOW,fr) in EDGE:
EDGE[(NOW,fr)][0]+=1
else:
EDGE[(NOW,fr)]=[1,-EDGE[fr,NOW][1]]
EDGE2[NOW].append(fr)
NOW=fr
for x,to in EDGE:
EDGE[(x,to)][1]+=ANS[to]-ANS[x]
if LA==float("inf"):
print(-1)
else:
print(LA)
|
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 | INF = float('inf')
def trace_back(sink, predecessors):
p = predecessors[sink]
while p is not None:
v, i = p
yield edges[v][i]
p = predecessors[v]
def min_cost_flow(source, sink, required_flow):
res = 0
while required_flow:
dist = [INF] * n
dist[source] = 0
predecessors = [None] * n
while True:
updated = False
for v in range(n):
if dist[v] == INF:
continue
for i, (remain, target, cost, _) in enumerate(edges[v]):
new_dist = dist[v] + cost
if remain and dist[target] > new_dist:
dist[target] = new_dist
predecessors[target] = (v, i)
updated = True
if not updated:
break
if dist[sink] == INF:
return -1
aug = min(required_flow, min(e[0] for e in trace_back(sink, predecessors)))
required_flow -= aug
res += aug * dist[sink]
for e in trace_back(sink, predecessors):
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": []
} | CORRECT | cpp | #include <cstdio>
#include <vector>
#include <queue>
#include <tuple>
int v, e;
struct Edge {
Edge() {}
Edge(int from, int to, int capacity, int cost, int rev) : from(from), to(to), capacity(capacity), cost(cost), rev(rev) {}
int from, to;
int capacity;
int cost;
int rev;
};
std::vector<Edge> edges[128];
void addEdge(int from, int to, int capacity, int cost) {
int n1 = edges[from].size();
int n2 = edges[to].size();
edges[from].push_back(Edge(from, to, capacity, cost, n2));
edges[to].push_back(Edge(to, from, 0, -cost, n1));
}
struct Result {
Result() {}
Result(int cost, int f) : cost(cost), f(f) {}
int cost;
int f;
};
struct NodeInfo {
NodeInfo() {}
NodeInfo(int w, int max_f, int prev, int prev_id) : w(w), max_f(max_f), prev(prev), prev_id(prev_id) {}
int w, max_f, prev, prev_id;
};
NodeInfo nodes[128];
void init_flow() {
for(int i = 0; i < 128; ++i) {
nodes[i] = NodeInfo((1<<30), 0, -1, -1);
}
}
Result flow(int from, int to, int rem) {
std::priority_queue< std::pair<int, int> > q;
q.push(std::make_pair(0, from));
nodes[from].w = 0;
nodes[from].max_f = rem;
while( not q.empty() ) {
int n, weight;
std::tie(weight, n) = q.top(); q.pop();
// printf("(n) = (%d)\n", n);
weight = -weight;
for(int i = 0; i < (int)edges[n].size(); ++i) {
Edge edge = edges[n][i];
if( edge.capacity <= 0 ) continue;
int nw = weight + edge.cost;
if( nodes[edge.to].w <= nw ) continue;
nodes[edge.to] = NodeInfo(nw, std::min(nodes[edge.from].max_f, edge.capacity), n, i);
q.push(std::make_pair(-nw, edge.to));
}
}
// for(int i = 0; i < v; ++i) {
// printf("node info[%d] : (w, max_f, prev, prev_id) = (%d, %d, %d, %d)\n", i, w[i], max_f[i], prev[i], prev_id[i]);
// }
int f = nodes[to].max_f;
if( f == 0 ) return Result(0, 0);
int m = to;
int cost = 0;
while( nodes[m].prev != -1 ) {
Edge& edge = edges[nodes[m].prev][nodes[m].prev_id];
edge.capacity -= f;
edges[m][edge.rev].capacity += f;
cost += f * edge.cost;
m = nodes[m].prev;
}
return Result(cost, f);
}
int minimum_cost_flow(int from, int to, int rem) {
int cost = 0;
for(;;) {
init_flow();
Result r = flow(from, to, rem);
rem -= r.f;
cost += r.cost;
if( rem == 0 ) return cost;
if( r.f == 0 ) break;
// printf("(rem, flow rate) = (%d, %d)\n", rem, r.f);
}
return -1;
}
int main() {
int f;
scanf("%d %d %d", &v, &e, &f);
for(int i = 0; i < e; ++i) {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
addEdge(a, b, c, d);
}
printf("%d\n", minimum_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<bits/stdc++.h>
#define range(i,a,b) for(int i = (a); i < (b); i++)
#define rep(i,b) for(int i = 0; i < (b); i++)
#define all(a) (a).begin(), (a).end()
#define show(x) cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
const int INF = 2000000000;
using namespace std;
const int MAX_V = 101;
class Edge{
public:
//???????????????????????????????????????
int to, cap, cost, rev;
};
vector<vector<Edge>> G(MAX_V);
int h[MAX_V]; //??????????????£???
int dist[MAX_V]; //???????????¢
int prev_v[MAX_V], prev_e[MAX_V]; //??´??????????????¨???
void addEdge(int from, int to, int cap, int cost){
G[from].emplace_back(Edge{to, cap, cost, static_cast<int>(G[to].size())});
G[to].emplace_back(Edge{from, 0, -cost, static_cast<int>(G[from].size() - 1)});
}
int minCostFlow(int v, 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>>> q;
fill(dist, dist + v, INF);
dist[s] = 0;
q.push(make_pair(0, s));
while(not q.empty()){
pair<int, int> p = q.top(); q.pop();
int u = p.second;
if(dist[u] < p.first) continue;
rep(i,G[u].size()){
Edge &e = G[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];
prev_v[e.to] = u;
prev_e[e.to] = i;
q.push(make_pair(dist[e.to], e.to));
}
}
}
if(dist[t] == INF){
return -1;
}
rep(i,v) h[i] += dist[i];
int d = f;
for(int u = t; u != s; u = prev_v[u]){
d = min(d, G[prev_v[u]][prev_e[u]].cap);
}
f -= d;
res += d * h[t];
for(int u = t; u != s; u = prev_v[u]){
Edge &e = G[prev_v[u]][prev_e[u]];
e.cap -= d;
G[u][e.rev].cap += d;
}
}
return res;
}
int main(){
int v, e, f;
cin >> v >> e >> f;
rep(i,e){
int a, b, c, d;
cin >> a >> b >> c >> d;
addEdge(a,b,c,d);
}
cout << minCostFlow(v, 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 | cpp | #include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
typedef pair<int, int> P;
struct edge{
int to;
int cap;
int cost;
int rev;
};
struct PDijk{
int V;
int INF;
vector<int> pote, prevv, preve;
vector<vector<edge>> G;
PDijk(int N){
V = N;
INF = 1e9;
G.resize(V);
prevv.resize(V);
preve.resize(V);
}
void add(int s, int t, int cap, int cost){
edge e1 = {t, cap, cost, (int)G[t].size()};
G[s].push_back(e1);
edge e2 = {s, 0, -cost, (int)G[s].size() - 1};
G[t].push_back(e2);
}
int solve(int s, int t, int f){
int ans = 0;
pote.resize(V, 0);
while(f > 0){
priority_queue<P, vector<P>, greater<P>> q;
vector<int> d(V, INF);
d[s] = 0;
q.push(P(0, s));
while(!q.empty()){
P v = q.top();
q.pop();
if(d[v.second] < v.first) continue;
int u = v.second;
for(int i = 0; i < (int)G[u].size(); i++){
edge e = G[u][i];
if(e.cap > 0 && d[e.to] > d[u] - pote[e.to] + pote[u] + e.cost){
d[e.to] = d[u] - pote[e.to] + pote[u] + e.cost;
prevv[e.to] = u;
preve[e.to] = i;
q.push(P(d[e.to], e.to));
}
}
}
if(d[t] == INF) return -1;
for(int i = 0; i < V; i++) pote[i] += d[i];
int temp = f;
for(int i = t; i != s; i = prevv[i]){
temp = min(temp, G[prevv[i]][preve[i]].cap);
}
f -= temp;
ans += temp * pote[t];
for(int i = t; i != s; i = prevv[i]){
edge &e = G[prevv[i]][preve[i]];
e.cap -= temp;
G[i][e.rev].cap += temp;
}
}
return ans;
}
};
int main(){
int N, E, F;
cin >> N >> E >> F;
PDijk pd(N);
for(int i = 0; i < E; i++){
int u, v, c, d;
cin >> u >> v >> c >> d;
pd.add(u, v, c, d);
}
int ans = pd.solve(0, N - 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": []
} | 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__)
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 namespace std;
using edge=struct {int to,cap,cost,rev;};
using G=vector<vector<edge>>;
const int inf=1<<29;
void add_edge(G &graph,int a,int b,int c,int d){
graph[a].push_back({b,c,d,int(graph[b].size())});
graph[b].push_back({a,0,-d,int(graph[a].size()-1)});
}
int min_cost_flow(G &graph,int s,int t,int f){
int res=0;
while(f){
int n=graph.size(),update;
vector<int> dist(n,inf),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>0 && 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;
int d=f;
for(int v=t;v!=s;v=pv[v]) chmin(d,graph[pv[v]][pe[v]].cap);
f-=d,res+=d*dist[t];
for(int v=t;v!=s;v=pv[v]){
edge &e=graph[pv[v]][pe[v]];
e.cap-=d;
graph[v][e.rev].cap+=d;
}
}
return res;
}
int main(void){
int n,m,f;
cin >> n >> m >> f;
G graph(n);
rep(i,m){
int a,b,c,d;
cin >> a >> b >> c >> d;
add_edge(graph,a,b,c,d);
}
cout << min_cost_flow(graph,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<bits/stdc++.h>
using namespace std;
template< typename flow_t, typename cost_t >
struct PrimalDual {
const cost_t INF;
struct edge {
int to;
flow_t cap;
cost_t cost;
int rev;
};
vector< vector< edge > > graph;
vector< cost_t > potential, min_cost;
vector< int > prevv, preve;
PrimalDual(int V) : graph(V), INF(numeric_limits< cost_t >::max()) {}
void add_edge(int from, int to, flow_t cap, cost_t cost) {
graph[from].emplace_back((edge) {to, cap, cost, (int) graph[to].size()});
graph[to].emplace_back((edge) {from, 0, -cost, (int) graph[from].size() - 1});
}
cost_t min_cost_flow(int s, int t, flow_t f) {
int V = (int) graph.size();
cost_t ret = 0;
using Pi = pair< cost_t, int >;
priority_queue< Pi, vector< Pi >, greater< Pi > > que;
potential.assign(V, 0);
preve.assign(V, -1);
prevv.assign(V, -1);
while(f > 0) {
min_cost.assign(V, INF);
que.emplace(0, s);
min_cost[s] = 0;
while(!que.empty()) {
Pi p = que.top();
que.pop();
if(min_cost[p.second] < p.first) continue;
for(int i = 0; i < graph[p.second].size(); i++) {
edge &e = graph[p.second][i];
cost_t nextCost = min_cost[p.second] + e.cost + potential[p.second] - potential[e.to];
if(e.cap > 0 && min_cost[e.to] > nextCost) {
min_cost[e.to] = nextCost;
prevv[e.to] = p.second, preve[e.to] = i;
que.emplace(min_cost[e.to], e.to);
}
}
}
if(min_cost[t] == INF) return -1;
for(int v = 0; v < V; v++) potential[v] += min_cost[v];
flow_t addflow = f;
for(int v = t; v != s; v = prevv[v]) {
addflow = min(addflow, graph[prevv[v]][preve[v]].cap);
}
f -= addflow;
ret += addflow * potential[t];
for(int v = t; v != s; v = prevv[v]) {
edge &e = graph[prevv[v]][preve[v]];
e.cap -= addflow;
graph[v][e.rev].cap += addflow;
}
}
return ret;
}
};
int main() {
int V, E, F;
scanf("%d %d %d", &V, &E, &F);
PrimalDual< int, int > g(V);
for(int i = 0; i < E; i++) {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
g.add_edge(a, b, c, d);
}
printf("%d\n", g.min_cost_flow(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 | #line 1 "test/aoj/GRL_6_B.test.cpp"
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_b"
#line 2 "test/aoj/../../graph/min-cost-flow.hpp"
#include <algorithm>
#include <vector>
#include <queue>
struct min_cost_flow {
struct edge { int to, cap, cost, rev; };
using P = std::pair<int, int>;
const int INF_ = 1<<30;
int V; // 頂点数
std::vector<std::vector<edge>> G; // グラフの隣接リスト表現
std::vector<int> h; // ポテンシャル
std::vector<int> dist; // 最短距離
std::vector<int> prevv, preve; // 直前の頂点と辺
min_cost_flow(int V) : V(V), G(V), h(V), dist(V), prevv(V), preve(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});
}
// sからtへの流量fの最小費用流を求める
// 流せない場合は-1を返す
int run(int s, int t, int f) {
int res = 0;
std::fill(h.begin(), h.end(), 0);
while (f > 0) {
std::priority_queue<P, std::vector<P>, std::greater<P>> q;
std::fill(dist.begin(), dist.end(), INF_);
dist[s] = 0;
q.push({0, s});
while (!q.empty()) {
P p = q.top(); q.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];
int d = dist[v] + e.cost + h[v] - h[e.to];
if (e.cap > 0 && dist[e.to] > d) {
dist[e.to] = d;
prevv[e.to] = v;
preve[e.to] = i;
q.push({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 = 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;
}
};
#line 3 "test/aoj/GRL_6_B.test.cpp"
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
int V, E, F;
cin >> V >> E >> F;
min_cost_flow mcf(V);
for (int i = 0; i < E; ++i) {
int from, to, cap, cost;
cin >> from >> to >> cap >> cost;
mcf.add_edge(from, to, cap, cost);
}
cout << mcf.run(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 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vint;
typedef pair<int,int> pint;
typedef vector<pint> vpint;
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=n-1;i>=(0);i--)
#define reps(i,f,n) for(int i=(f);i<(n);i++)
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)
#define all(v) (v).begin(),(v).end()
#define eall(v) unique(all(v), v.end())
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define chmax(a, b) a = (((a)<(b)) ? (b) : (a))
#define chmin(a, b) a = (((a)>(b)) ? (b) : (a))
const int MOD = 1e9 + 7;
const int INF = 1e9;
const ll INFF = 1e18;
const int MAX_V = 510;
int V; //????????°
struct edge { int to, cap, cost, rev; };
vector<edge> G[MAX_V];
int dist[MAX_V]; //???????????¢
int prevv[MAX_V], preve[MAX_V];
void add_edge(int from, int to, int cap, int cost) { // from->to????????????cap,?????????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});
}
// s??????t????????????f???????°??????¨???????±??????? ??????????????´??????-1
int min_cost_flow(int s, int t, int f) {
int res = 0;
while(f > 0) {
fill(dist, dist + V, 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(void) {
int v, E, F;
cin >> v >> E >> F;
V = v;
rep(i, E) {
int a, b, c, d;
cin >> a >> b >> c >> d;
add_edge(a, b, c, d);
}
int ans = min_cost_flow(0, v - 1, F);
printf("%d\n", ans);
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 long long ll;
#define rep(i,n) for (ll i=0;i<(n);++i)
const ll MOD=1e9+7;
template<typename T,typename E>
struct PrimalDual{
const E inf=numeric_limits<E>::max()/2;
struct edge{
int to,rev; T cap; E cost;
edge(int to,T cap,E cost,int rev):
to(to),cap(cap),cost(cost),rev(rev){}
};
vector<vector<edge>> G;
vector<E> h,dist;
vector<int> prevv,preve;
PrimalDual(int n):G(n),h(n),dist(n),prevv(n),preve(n){}
void add_edge(int from,int to,T cap,E cost){
G[from].emplace_back(to,cap,cost,G[to].size());
G[to].emplace_back(from,0,-cost,G[from].size()-1);
}
void dijkstra(int s){
struct P{
E first; int second;
P(E first,int second):first(first),second(second){}
bool operator<(const P &a) const{
return a.first<first;
}
};
priority_queue<P> pq;
fill(dist.begin(),dist.end(),inf);
dist[s]=0;
pq.emplace(dist[s],s);
while(!pq.empty()){
P p=pq.top(); pq.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[v]+e.cost+h[v]-h[e.to]<dist[e.to]){
dist[e.to]=dist[v]+e.cost+h[v]-h[e.to];
prevv[e.to]=v,preve[e.to]=i;
pq.emplace(dist[e.to],e.to);
}
}
}
}
E min_cost_flow(int s,int t,T f){
E res=0;
fill(h.begin(),h.end(),0);
while(f>0){
dijkstra(s);
if (dist[t]==inf) return -1;
for (int v=0;v<h.size();++v){
if (dist[v]<inf) 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+=h[t]*d;
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.tie(0);
ios::sync_with_stdio(false);
int V,E,F; cin >> V >> E >> F;
PrimalDual<int,int> PD(V);
rep(i,E){
int u,v,c,d; 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": []
} | CORRECT | cpp | #include<bits/stdc++.h>
using namespace std;
#define MAX_V 500
#define 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 V;
vector<edge> G[MAX_V];
int h[MAX_V];
int dist[MAX_V];
int 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,G[to].size()));
G[to].push_back(edge(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<P,vector<P>,greater<P> > que;
fill(dist,dist+V,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<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;
for(int i=0;i<e;i++){
int u,v,c,d;
cin>>u>>v>>c>>d;
add_edge(u,v,c,d);
}
V=v;
cout<<min_cost_flow(0,v-1,f)<<endl;
return 0;
}
/*
verified on 2017/04/26
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B
*/ |
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> // printf(), scanf()
#include <vector>
#include <algorithm> // min(), fill()
using namespace std;
static const int MAX_V = 100;
static const int INF = 100000000;
typedef struct edge_tbl
{
int to, cap, cost;
unsigned long rev;
} edge;
vector<edge> G[MAX_V];
int dist[MAX_V];
int prevv[MAX_V], preve[MAX_V];
int V;
int
min_cost_flow(int s, int t, int f)
{
int res = 0;
while (f > 0)
{
fill(dist, dist + V, INF);
dist[s] = 0;
bool update = true;
while (update)
{
update = false;
for (int v = 0; v < V; ++v)
{
if (dist[v] == INF)
continue;
for (unsigned 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 argc, char** argv)
{
int E, F;
int u, v, cap, cost;
scanf("%d %d %d", &V, &E, &F);
for (int i = 0; i < E; ++i)
{
scanf("%d %d %d %d", &u, &v, &cap, &cost);
G[u].push_back((edge){v, cap, cost, G[v].size()});
G[v].push_back((edge){u, 0, -cost, G[u].size() - 1});
}
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 "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define INF (1e9+1)
//#define INF (1LL<<59)
#define MAX_V 100
struct edge { int to, cap, cost,rev; };
int V; // ????????°
vector<edge> G[MAX_V];
vector<int> h(MAX_V); //??????????????£???
int dist[MAX_V];// ???????????¢
int prevv[MAX_V], preve[MAX_V];// ??´??????????????¨???
// from??????to??????????????????cap????????????cost????????????????????????????????????
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();
rep(i,d.size())d[i]=INF;
d[s]=0;
rep(loop,v){
bool update = false;
rep(i,MAX_V){
for(auto e:G[i]){
if(d[i]!=INF && 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; //negative_cycle
}
return false;
}
// s??????t????????????f???????°??????¨???????±???????
// ??????????????´??????-1?????????
int min_cost_flow(int s, int t, int f) {
int res = 0;
rep(i,h.size())h[i]=0;
bool hoge=false;
while (f > 0) {
// ?????????????????????????????¨??????h?????´??°??????
if(!f){
shortest_path(s, h);
f=true;
}
else{
priority_queue<pii, vector<pii>, greater<pii> > que; fill(dist, dist + V, INF);
dist[s] = 0;
que.push(pii(0, s));
while (!que.empty()) {
pii 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(pii(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 = 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;
rep(i,e){
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": []
} | CORRECT | python3 |
from heapq import heappush, heappop
class MinCostFlow:
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
G = self.G
G[fr].append([to, cap, cost, len(G[to])])
G[to].append([fr, 0, -cost, len(G[fr])-1])
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [0]*N
while f:
dist = [INF]*N
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
for i, (w, cap, cost, rev) in enumerate(G[v]):
if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w]:
dist[w] = r = dist[v] + cost + H[v] - H[w]
prv_v[w] = v
prv_e[w] = i
heappush(que, (r, w))
if dist[t] == INF:
return -1
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
import sys
readline = sys.stdin.readline
write = sys.stdout.write
N, M, F = map(int, readline().split())
mcf = MinCostFlow(N)
for i in range(M):
u, v, c, d = map(int, readline().split())
mcf.add_edge(u, v, c, d)
write("%d\n" % mcf.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": []
} | CORRECT | cpp | #include <algorithm>
#include <tuple>
#include <iostream>
#include <vector>
using namespace std;
#define MAX_V 200
#define INF 1000000
typedef tuple<int,int,int,int> Edge; // to,cap,cost,rev
int V;
typedef vector<Edge> Vertex;
vector<Vertex> G(MAX_V);
int dist[MAX_V];
int prev_v[MAX_V], prev_e[MAX_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 total_cost=0;
while(f>0){
fill(dist,dist+V,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++){
auto& e = G[v][i];
int to=get<0>(e), cap=get<1>(e), cost=get<2>(e);
if(cap>0&&dist[to]>dist[v]+cost){
dist[to]=dist[v]+cost;
prev_v[to]=v;
prev_e[to]=i;
update=true;
}
}
}
}
if(dist[t]==INF){
return -1;
}
int d=f;
for(int v=t;v!=s;v=prev_v[v]){
d=min(d, get<1>(G[prev_v[v]][prev_e[v]]));
}
f-=d;
total_cost+=d*dist[t];
for(int v=t;v!=s;v=prev_v[v]){
auto& e=G[prev_v[v]][prev_e[v]];
get<1>(e)-=d;
get<1>(G[v][get<3>(e)])+=d;
}
}
return total_cost;
}
int main(){
int E,F;
cin>>V>>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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using ll = long long;
using namespace std;
constexpr ll inf = 1e15;
constexpr ll mod = 1e9+7;
struct Edge {
int to;
int cap;
int cost;
int rev;
};
vector<Edge> edges[101];
int primalDual(int s, int t, int f) {
int ret = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
vector<int> potential(101, 0);
vector<ll> dp(101, inf);
vector<int> prevv(101, -1), preve(101, -1);
// Dijkstra with potential
while (f > 0) {
dp.assign(101, inf);
dp[s] = 0;
q.push(make_pair(0, s));
while (!q.empty()) {
auto p = q.top();
q.pop();
if (dp[p.second] < p.first) continue;
for (int i = 0; i < edges[p.second].size(); i++) {
auto&& edge = edges[p.second][i];
int nextCost = dp[p.second] + edge.cost + potential[p.second] - potential[edge.to];
if (edge.cap > 0 && dp[edge.to] > nextCost) {
dp[edge.to] = nextCost;
prevv[edge.to] = p.second;
preve[edge.to] = i;
q.push(make_pair(nextCost, edge.to));
}
}
}
if (dp[t] == inf) return -1;
for (int v = 0; v <= 100; v++) if (dp[v] < inf) potential[v] += dp[v];
int addFlow = f;
for (int v = t; v != s; v = prevv[v]) {
addFlow = min(addFlow, edges[prevv[v]][preve[v]].cap);
}
f -= addFlow;
ret += addFlow * potential[t];
for (int v = t; v != s; v = prevv[v]) {
Edge& e = edges[prevv[v]][preve[v]];
e.cap -= addFlow;
edges[v][e.rev].cap += addFlow;
}
}
return ret;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int V, E, F;
cin>>V>>E>>F;
for (int e = 0; e < E; e++) {
int U, V, C, D;
cin>>U>>V>>C>>D;
edges[U].push_back(Edge{V, C, D, (int)edges[V].size()});
edges[V].push_back(Edge{U, 0, -D, (int)edges[U].size()-1});
}
cout<<primalDual(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 <vector>
#include <queue>
#include <iostream>
using namespace std;
#define MAX_E 1001
int V, E, F, US[MAX_E], VS[MAX_E], CAP[MAX_E], COST[MAX_E];
class MinCostFlow {
public:
const int INFTY = (1 << 21);
struct Edge { int t, cap, cost, rev; };
struct P {
int d, id;
bool operator < (const P &other) const {
return d > other.d;
}
};
MinCostFlow(int V):
V(V), G(V, vector<Edge>(0)), dist(V, INFTY), prevv(V, -1), preve(V, -1), potential(V, 0) {}
void addEdge(int s, int t, int cap, int cost) {
G[s].push_back({ t, cap, cost, (int)G[t].size() });
G[t].push_back({ s, 0, -cost, (int)G[s].size() - 1 });
}
int calc(int s, int t, int f) {
int res = 0;
while (f > 0) {
dijkstra(s);
if (dist.at(t) == INFTY) return -1;
for (int v = 0; v < V; v++) potential.at(v) += dist.at(v);
int d = f;
for (int v = t; v != s; v = prevv.at(v)) {
int cap = G.at(prevv.at(v)).at(preve.at(v)).cap;
d = min(d, cap);
}
f -= d;
res += d * potential.at(t);
for (int v = t; v != s; v = prevv.at(v)) {
Edge &edge = G.at(prevv.at(v)).at(preve.at(v));
edge.cap -= d;
G.at(v).at(edge.rev).cap += d;
}
}
return res;
}
private:
int V;
vector<vector<Edge> > G;
vector<int> dist, prevv, preve, potential;
void dijkstra(int s) {
reset(s);
priority_queue<P> PQ;
vector<bool> done(V, false);
PQ.push({ 0, s });
while (PQ.size()) {
P p = PQ.top(); PQ.pop();
if (done.at(p.id)) continue;
done.at(p.id) = true;
if (dist.at(p.id) < p.d) continue;
for (int e = 0; e<G.at(p.id).size(); e++) {
Edge &edge = G.at(p.id).at(e);
if (done.at(edge.t)) continue;
if (edge.cap <= 0) continue;
if (dist.at(edge.t) <= dist.at(p.id) + edge.cost + potential.at(p.id) - potential.at(edge.t)) continue;
dist.at(edge.t) = dist.at(p.id) + edge.cost + potential.at(p.id) - potential.at(edge.t);
prevv.at(edge.t) = p.id;
preve.at(edge.t) = e;
PQ.push({ dist.at(edge.t), edge.t });
}
}
}
void reset(int s) {
fill(dist.begin(), dist.end(), INFTY);
dist.at(s) = 0;
}
};
void input() {
cin >> V >> E >> F;
for (int i=0; i<E; i++) {
cin >> US[i] >> VS[i] >> CAP[i] >> COST[i];
}
}
void solve() {
MinCostFlow mcf(V);
for (int i=0; i<E; i++) {
mcf.addEdge(US[i], VS[i], CAP[i], COST[i]);
}
cout << mcf.calc(0, V-1, F) << endl;
}
int main() {
input();
solve();
}
|
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 <vector>
#include <algorithm>
#include <queue>
using namespace std;
static const int MAX_V = 110;
static const int INF = (1<<30);
typedef pair<int, int> P;
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<P, vector<P>, greater<P> > que;
fill(dist, dist + V, 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;
}
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": []
} | 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, 0, -cost, len(edges[s1]) - 1])
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
trace_i = sink
while trace_i != 0:
this_edge = edges[before_vertice[trace_i]][before_edge[trace_i]]
this_edge[1] -= decreased
answer += this_edge[2] * decreased
edges[trace_i][this_edge[3]][1] += decreased
trace_i = before_vertice[trace_i]
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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
#if __has_include("print.hpp")
#include "print.hpp"
#endif
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define ALL(x) (x).begin(), (x).end()
#define RALL(x) (x).rbegin(), (x).rend()
#define MOD 1000000007
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
typedef long long ll;
typedef pair<ll, ll> p;
struct edge{int to, cap, cost, rev;};
int n, m;
vector<vector<edge>> g;
vector<int> dist, 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, 0, -cost, int(g[from].size())-1});
}
int min_cost_flow(int s, int t, int f){
int res = 0;
while(f > 0){
dist = vector<int>(n, INT_MAX);
dist[s] = 0;
bool update = true;
while(update){
update = false;
for (int v = 0; v < n; v++) {
if(dist[v] == INT_MAX) 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[t] == INT_MAX) 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]) {
auto &e = g[prevv[v]][preve[v]];
e.cap -= d;
g[v][e.rev].cap += d;
}
}
return res;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int f;
cin >> n >> m >> f;
g = vector<vector<edge>> (n);
dist = vector<int>(n+100);
prevv = vector<int>(n+109);
preve = vector<int>(n+100);
for (int i = 0; i < m; i++) {
int from, to, c, d;
cin >> from >> to >> c >> d;
add_edge(from, to, c, d);
}
cout << 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 | java | import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.io.IOException;
import java.util.Queue;
import java.util.Arrays;
import java.util.ArrayList;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.List;
import java.io.FileInputStream;
import java.util.InputMismatchException;
public class Main {
InputStream is;
int __t__ = 1;
int __f__ = 0;
int __FILE_DEBUG_FLAG__ = __f__;
String __DEBUG_FILE_NAME__ = "src/A2";
FastScanner in;
PrintWriter out;
public void solve() {
int V = in.nextInt();
int E = in.nextInt();
int F = in.nextInt();
Graph<CappedEdge> g = Graph.create(V);
for (int i = 0; i < E; i++) {
int u = in.nextInt();
int v = in.nextInt();
int c = in.nextInt();
int d = in.nextInt();
CappedEdgeImpl.CappedEdgePair ep = CappedEdgeImpl.pairedEdges(u, v, c, d);
g.addDirectionalEdge(u, ep.normal);
g.addDirectionalEdge(v, ep.rev);
}
PrimaryDual primaryDual = new PrimaryDual(g);
System.out.println(primaryDual.doit(0, V - 1, F));
}
public void run() {
if (__FILE_DEBUG_FLAG__ == __t__) {
try {
is = new FileInputStream(__DEBUG_FILE_NAME__);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("FILE_INPUT!");
} else {
is = System.in;
}
in = new FastScanner(is);
out = new PrintWriter(System.out);
solve();
}
public static void main(final String[] args) {
new Main().run();
}
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
// stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
public int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = nextIntArray(m);
}
return map;
}
public long nextLong() {
return Long.parseLong(next());
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
public long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = nextLongArray(m);
}
return map;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
public double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = nextDoubleArray(m);
}
return map;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
public int[][] nextPackedIntArrays(int packN, int size) {
int[][] res = new int[packN][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < packN; j++) {
res[j][i] = nextInt();
}
}
return res;
}
}
interface CappedEdge extends Edge {
long cap();
CappedEdge rev();
void addCap(long cap);
}
class PrimaryDual {
public static final long INF = 1L << 60;
final Graph<CappedEdge> g;
final int[] prevNodes;
final int[] prevEdges;
final long[] minDist;
final long[] potential;
public PrimaryDual(Graph<CappedEdge> g) {
this.g = g;
prevNodes= new int[g.size()];
prevEdges = new int[g.size()];
minDist = new long[g.size()];
potential = new long[g.size()];
}
public long doit(int source, int sink, int flow) {
long res = 0;
Arrays.fill(potential, 0);
while (flow > 0) {
DijkstraResult dres = dijkstra(source, potential);
if (dres.minDist[sink] == INF) {
return -1;
}
for (int i = 0; i < g.size(); i++) {
potential[i] += dres.minDist[i];
}
long minFlow = flow;
for (int v = sink; v != source; v = dres.prevNodes[v]) {
minFlow = Math.min(minFlow, g.edges(dres.prevNodes[v]).get(dres.prevEdges[v]).cap());
}
flow -= minFlow;
res += minFlow * potential[sink];
for (int v = sink; v != source; v = dres.prevNodes[v]) {
CappedEdge e = g.edges(dres.prevNodes[v]).get(dres.prevEdges[v]);
e.addCap(-minFlow);
e.rev().addCap(minFlow);
}
}
return res;
}
private DijkstraResult dijkstra(int start, long[] potential) {
Arrays.fill(minDist, INF);
minDist[start] = 0;
prevNodes[start] = prevEdges[start] = -1;
PriorityQueue<State> pq = new PriorityQueue<>(Comparator.comparingLong(st -> st.cost));
pq.add(new State(0, start));
while (!pq.isEmpty()) {
State st = pq.poll();
List<? extends CappedEdge> es = g.edges(st.u);
for (int i = 0; i < es.size(); i++) {
CappedEdge e = es.get(i);
if (e.cap() == 0 || st.cost > minDist[st.u]) {
continue;
}
long ncost = minDist[st.u] + e.cost() + potential[st.u] - potential[e.to()];
if (minDist[e.to()] > ncost) {
minDist[e.to()] = ncost;
prevNodes[e.to()] = st.u;
prevEdges[e.to()] = i;
pq.add(new State(ncost, e.to()));
}
}
}
return new DijkstraResult(minDist, prevNodes, prevEdges);
}
private class State {
final long cost;
final int u;
public State(long cost, int u) {
this.cost = cost;
this.u = u;
}
}
private class DijkstraResult {
public final long[] minDist;
public final int[] prevNodes;
public final int[] prevEdges;
public DijkstraResult(long[] minDist, int[] prevNodes, int[] prevEdges) {
this.minDist = minDist;
this.prevNodes = prevNodes;
this.prevEdges = prevEdges;
}
}
}
class CappedEdgeImpl implements CappedEdge {
final int to;
final long cost;
private long cap;
private CappedEdge rev;
private CappedEdgeImpl(int to, long cost, long cap) {
this.to = to;
this.cost = cost;
this.cap = cap;
}
public static class CappedEdgePair {
public final CappedEdge normal;
public final CappedEdge rev;
public CappedEdgePair(CappedEdge normal, CappedEdge rev) {
this.normal = normal;
this.rev = rev;
}
}
public static CappedEdgePair pairedEdges(int from, int to, long cap, long cost) {
CappedEdgeImpl e = new CappedEdgeImpl(to, cost, cap);
CappedEdgeImpl revE = new CappedEdgeImpl(from, -cost, 0);
e.rev = revE;
revE.rev = e;
return new CappedEdgePair(e, revE);
}
@Override
public int to() {
return to;
}
@Override
public long cost() {
return cost;
}
@Override
public long cap() {
return cap;
}
@Override
public CappedEdge rev() {
return rev;
}
@Override
public void addCap(long cap) {
this.cap += cap;
}
}
class SimpleEdge implements Edge {
private final int to;
public SimpleEdge(int to) {
this.to = to;
}
@Override
public int to() {
return to;
}
@Override
public long cost() {
return 1;
}
}
class Graph<E extends Edge> {
private final int n;
private final List<E>[] g;
public static <E extends Edge> Graph<E> create(int n) {
@SuppressWarnings("unchecked")
ArrayList<E>[] l = new ArrayList[n];
for (int i = 0; i < n; i++) {
l[i] = new ArrayList<>();
}
return new Graph<>(n, l);
}
public Graph(int n, List<E>[] g) {
this.n = n;
this.g = g;
}
public static Graph<SimpleEdge> createDirectionalTree(int[] a, int[] b) {
if (a.length != b.length) {
throw new IllegalArgumentException("len(a) != len(b)");
}
int n = a.length + 1;
Graph<SimpleEdge> g = create(n);
for (int i = 0; i < n - 1; i++) {
g.addDirectionalEdge(a[i], new SimpleEdge(b[i]));
}
return g;
}
public static Graph<SimpleEdge> createUndirectionalTree(int[] a, int[] b, boolean oneOrigin) {
if (a.length != b.length) {
throw new IllegalArgumentException("len(a) != len(b)");
}
int n = a.length + 1;
Graph<SimpleEdge> g = create(n);
int adjust = oneOrigin ? 1 : 0;
for (int i = 0; i < n - 1; i++) {
g.addDirectionalEdge(a[i] - adjust, new SimpleEdge(b[i] - adjust));
g.addDirectionalEdge(b[i] - adjust, new SimpleEdge(a[i] - adjust));
}
return g;
}
public void addDirectionalEdge(int u, E e) {
g[u].add(e);
}
public List<E> edges(int u) {
return g[u];
}
public int edgeNum(int u) {
return g[u].size();
}
public int totalEndgeNum() {
return Arrays.stream(g)
.map(List::size)
.reduce(0, Integer::sum) / 2;
}
public int size() {
return n;
}
/**
*
* @param start
* @return The cost of node v is:
* <ul>
* <li>-(1L << 62) if a node is under negative loop</li>
* <li>(1L << 62) if there is no edge to v</li>
* <li>otherwise minimum cost from node u to a node</li>
* </ul>
*/
public long[] bellmanford(int start) {
final long INF = 1L << 62;
long[] dist = new long[n];
Arrays.fill(dist, INF);
dist[start] = 0;
for (int i = 0; i < n - 1; i++) {
for (int u = 0; u < n; u++) {
for (Edge e : edges(u)) {
dist[e.to()] = Math.min(dist[e.to()], dist[u] + e.cost());
}
}
}
long[] res = Arrays.copyOf(dist, dist.length);
for (int u = 0; u < n; u++) {
for (Edge e : edges(u)) {
int v = e.to();
if (dist[u] + e.cost() < dist[v]) {
res[v] = -INF;
}
}
}
return res;
}
/**
*
* @param start
* @return For each v, true if a node v can be arrived from start node, otherwise false.
*/
public boolean[] canArrive(int start) {
boolean[] res = new boolean[size()];
canArriveInternal(start, res);
return res;
}
private void canArriveInternal(int u, boolean[] visited) {
visited[u] = true;
for (Edge e : edges(u)) {
if (visited[e.to()]) {
continue;
}
canArriveInternal(e.to(), visited);
}
}
public DiameterResult diameter() {
if (totalEndgeNum() != n - 1) {
throw new IllegalArgumentException("Graph should be tree");
}
int[] parents = new int[size()];
int[] dist = new int[size()];
Arrays.fill(dist, -1);
dfs(0, dist, parents, 0);
int x = 0;
for (int i = 1; i < size(); i++) {
if (dist[x] < dist[i]) {
x = i;
}
}
int[] dist2 = new int[size()];
Arrays.fill(dist2, -1);
parents[x] = x;
dfs(x, dist2, parents, 0);
int best = 0;
for (int i = 0; i < n; i++) {
if (dist2[best] < dist2[i]) {
best = i;
}
}
return new DiameterResult(restore(x, best, parents), dist2[best] + 1);
}
private int[] restore(int from, int to, int[] parents) {
List<Integer> pathL = new ArrayList<>();
int cur = to;
while (cur != from) {
pathL.add(cur);
cur = parents[cur];
}
pathL.add(from);
int[] res = new int[pathL.size()];
for (int i = 0; i < pathL.size(); i++) {
res[i] = pathL.get(pathL.size() - i - 1);
}
return res;
}
private void dfs(int u, int[] dist, int[] parent, int depth) {
dist[u] = depth;
for (Edge e : g[u]) {
if (dist[e.to()] != -1) {
continue;
}
parent[e.to()] = u;
dfs(e.to(), dist, parent, depth + 1);
}
}
public static class DiameterResult {
public final int[] path;
public final int dist;
public DiameterResult(int[] path, int dist) {
this.path = path;
this.dist = dist;
}
@Override
public String toString() {
return "DiameterResult{" +
"path=" + Arrays.toString(path) +
", dist=" + dist +
'}';
}
}
/**
* Assuming edge is SimpleEdge
* @param start
* @return
*/
public int[] bfs(int start) {
int n = g.length;
int[] dist = new int[n];
Arrays.fill(dist, 1 << 30);
dist[start] = 0;
Queue<Integer> q = new ArrayDeque<>();
q.add(start);
while (!q.isEmpty()) {
int u = q.poll();
for (Edge e : g[u]) {
if (dist[e.to()] == 1 << 30) {
dist[e.to()] = dist[u] + 1;
q.add(e.to());
}
}
}
return dist;
}
}
class EdgeImpl implements Edge {
private final int to;
private final long cost;
public EdgeImpl(int to, long cost) {
this.to = to;
this.cost = cost;
}
@Override
public int to() {
return to;
}
@Override
public long cost() {
return cost;
}
}
interface EdgeGenerator<E extends Edge> {
E generate(int to, E originalEdge);
}
interface Edge {
int to();
long cost();
}
|
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 INF 1e9
struct edge{
//行先、容量、コスト、逆辺
int to,cap,cost,rev;
};
void add_edge(int from,int to,int cap ,int cost,vector<vector<edge> > &g){
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 to t minmun flow
// can't reach -1
int min_cost_flow(int s,int t,int f,vector<vector<edge> > &g){
int res = 0;
int v = (int)g.size();
vector<int> prevv(v),preve(v);
while( f > 0 ){
//bellmanford s-t周辺最短路を求める
vector<int> dist(v,INF);
dist[s] = 0;
bool update = true;
while(update){
update = false;
for(int j= 0;j<v;j++){
if(dist[j] == INF) continue;
for(int i= 0;i<g[j].size();i++){
edge &e = g[j][i];
if(e.cap > 0 && dist[e.to] > dist[j] + e.cost){
dist[e.to] = dist[j] + e.cost;
prevv[e.to] = j;
preve[e.to] = i;
update = true;
}
}
}
}
if(dist[t] == INF ) return -1; //can't reach
//s-t周辺に目いっぱい流す
int d = f;
for(int i = t; i!= s; i = prevv[i]) d = min(d,g[prevv[i]][preve[i]].cap);
f -= d;
res += d*dist[t];
for(int i = t; i!= s; i = prevv[i]){
edge &e = g[prevv[i]][preve[i]];
e.cap -= d;
g[i][e.rev].cap += d;
}
}
return res;
}
int main(){
int v,e,f;
cin>>v>>e>>f;
vector<vector<edge> > g(v);
for(int i=0;i<e;i++){
int c,d,u,v;
cin>>u>>v>>c>>d;
add_edge(u,v,c,d,g);
}
cout<<min_cost_flow(0,v-1,f,g)<<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;
template<class T>
struct min_cost_flow {
using value_type = T;
using P = pair<value_type, int>;
private :
const value_type INF = numeric_limits<value_type>::max();
struct edge {
public :
int to, rev;
value_type cap;
value_type cost;
edge (int to, value_type cap, value_type cost, int rev) :
to(to), cap(cap), cost(cost), rev(rev) { }
};
int n;
vector<vector<edge>> g;
vector<value_type> potential;
vector<value_type> dist;
vector<int> prev_vertex;
vector<int> prev_edge;
template<class E>
inline bool chmin (E &a, const E &b) {
if (a > b) { a = b; return true; }
return false;
}
public :
min_cost_flow (int n) :
n(n), g(n), potential(n), dist(n), prev_vertex(n), prev_edge(n) { }
void add_edge (int from, int to, value_type cap, value_type cost) {
g[from].emplace_back(to, cap, cost, g[to].size());
g[to].emplace_back(from, 0, -cost, g[from].size() - 1);
}
value_type solve (int s, int t, value_type f) {
value_type ret = 0;
fill(potential.begin(), potential.end(), 0);
while (f > 0) {
priority_queue<P, vector<P>, greater<P>> que;
fill(dist.begin(), dist.end(), INF);
dist[s] = 0;
que.emplace(dist[s], s);
while (not que.empty()) {
value_type d; int v;
tie(d, v) = que.top(); que.pop();
if (dist[v] < d) continue;
for (int i = 0; i < g[v].size(); i++) {
const edge &e = g[v][i];
if (e.cap > 0 and chmin(dist[e.to], dist[v] + e.cost + potential[v] - potential[e.to])) {
prev_vertex[e.to] = v;
prev_edge[e.to] = i;
que.emplace(dist[e.to], e.to);
}
}
}
if (dist[t] == INF) return -1;
for (int v = 0; v < n; v++) potential[v] += dist[v];
value_type val = f;
for (int v = t; v != s; v = prev_vertex[v]) {
chmin(val, g[prev_vertex[v]][prev_edge[v]].cap);
}
f -= val;
ret += (val * potential[t]);
for (int v = t; v != s; v = prev_vertex[v]) {
edge &e = g[prev_vertex[v]][prev_edge[v]];
e.cap -= val;
g[v][e.rev].cap += val;
}
}
return ret;
}
};
int main() {
int n, m, f;
cin >> n >> m >> f;
min_cost_flow<int> mcf(n);
for (int i = 0; i < m; i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
cout << mcf.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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
//typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl
const int INF = 1e7;
template <typename T>
struct MinCostFlow {
struct Edge {
int to, rev; T cap, cost;
Edge(int to, int rev, T cap, T cost) : to(to), rev(rev), cap(cap), cost(cost) { }
};
struct Node {
int v; T dist;
Node(int v, T dist) : v(v), dist(dist) { };
bool operator < (const Node &n) const {
return dist > n.dist; // reverse
}
};
typedef vector<Edge> Edges;
vector<Edges> G;
int V;
vector<int> dist, h, prevv, preve;
MinCostFlow(int V) : V(V) { G.resize(V); }
void add_edge(int from, int to, T cap, T cost) {
G[from].emplace_back(to, G[to].size(), cap, cost);
G[to].emplace_back(from, (int)G[from].size()-1, 0, -cost);
}
T primal_dual(int source, int sink, T f) {
T res = 0;
h.resize(V, 0);
prevv.resize(V), preve.resize(V);
while (f > 0) {
priority_queue<Node> pque;
dist.assign(V, INF);
dist[source] = 0;
pque.emplace(source, 0);
while (not pque.empty()) {
Node n = pque.top(); pque.pop();
int v = n.v; T cost = n.dist;
if (dist[v] < cost) continue;
for (int i = 0; i < (int)G[v].size(); i++) {
Edge e = G[v][i];
if (e.cap > 0 and dist[v] - h[e.to] < dist[e.to] - e.cost - h[v]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v, preve[e.to] = i;
pque.emplace(e.to, dist[e.to]);
}
}
}
if (dist[sink] == INF) return -1;
for (int v = 0; v < V; v++) h[v] += dist[v];
T d = f;
for (int v = sink; v != source; v = prevv[v]) {
d = min(d, G[prevv[v]][preve[v]].cap);
}
f -= d;
res += d * h[sink];
for (int v = sink; v != source; v = prevv[v]) {
Edge &e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
};
int main() {
// use scanf in CodeForces!
cin.tie(0);
ios_base::sync_with_stdio(false);
int V, E, F; cin >> V >> E >> F;
MinCostFlow<int> mcf(V);
REP(_, E) {
int u, v, c, d; cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
cout << mcf.primal_dual(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.*;
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[] inQueue = new boolean[dist.length];
inQueue[s] = true;
while(!queue.isEmpty()){
Integer u = queue.poll();
inQueue[u] = false;
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);
if(!inQueue[edge.v]){
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": []
} | CORRECT | cpp | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
template <typename Flow, typename Cost> class PrimalDual {
private:
Cost INF_COST = std::numeric_limits<Cost>::max();
public:
struct Edge {
int to;
Flow cap;
Cost cost;
int rev;
Edge () {}
Edge (int t, Flow f, Cost c, int rev) : to(t), cap(f), cost(c), rev(rev) {}
};
private:
vector<vector<Edge>> graph;
vector<Cost> potential, min_cost;
vector<int> prev_v, prev_e;
public:
PrimalDual (int n) : graph(n) {}
void add (int from, int to, Flow cap, Cost cost) {
graph[from].push_back(Edge(to, cap, cost, (int) graph[to].size()));
graph[to].push_back(Edge(from, 0, -cost, (int) graph[from].size() - 1));
}
Cost get (int start, int goal, Flow f) {
int n = (int) graph.size();
Cost res = 0;
using Pi = pair<Cost, int>;
priority_queue<Pi, vector<Pi>, greater<Pi>> que;
potential.assign(n, 0);
prev_e.assign(n, -1);
prev_v.assign(n, -1);
while (f > 0) {
min_cost.assign(n, INF_COST);
que.emplace(0, start);
min_cost[start] = 0;
while (que.size()) {
Pi cur = que.top();
que.pop();
if (min_cost[cur.second] < cur.first) continue;
for (int i = 0; i < (int) graph[cur.second].size(); i++) {
Edge& e = graph[cur.second][i];
Cost next_cost = min_cost[cur.second] + e.cost + potential[cur.second] - potential[e.to];
if (e.cap > 0 && min_cost[e.to] > next_cost) {
min_cost[e.to] = next_cost;
prev_v[e.to] = cur.second;
prev_e[e.to] = i;
que.emplace(min_cost[e.to], e.to);
}
}
}
if (min_cost[goal] == INF_COST) return -1;
for (int i = 0; i < n; i++) potential[i] += min_cost[i];
Flow add_flow = f;
for (int i = goal; i != start; i = prev_v[i]) {
add_flow = min(add_flow, graph[prev_v[i]][prev_e[i]].cap);
}
f -= add_flow;
res += add_flow * potential[goal];
for (int i = goal; i != start; i = prev_v[i]) {
Edge& e = graph[prev_v[i]][prev_e[i]];
e.cap -= add_flow;
graph[i][e.rev].cap += add_flow;
}
}
return res;
}
};
signed main() {
ios::sync_with_stdio(false); cin.tie(0);
int n, m, f;
cin >> n >> m >> f;
PrimalDual<int, int> pd(n);
for (int i = 0; i < m; i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
pd.add(a, b, c, d);
}
cout << pd.get(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": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int64;
const int MAX_V = 1e5 + 1;
const int INF = 1e9 + 1;
typedef pair< int, int > P;
// O(|E||V|^2)
struct Edge {
Edge(int _to, int _cap, int _cost, int _rev)
: to(_to), cap(_cap), cost(_cost), rev(_rev) {}
int to, cap, cost, rev; // 逆辺
};
int V;
vector< Edge > G[MAX_V]; // グラフの隣接リスト表現
int h[MAX_V];
int dist[MAX_V];
int prevv[MAX_V], preve[MAX_V];
void add_edge(int _from, int _to, int _cap, int _cost) {
G[_from].emplace_back(Edge(_to, _cap, _cost, G[_to].size()));
G[_to].emplace_back(Edge(_from, 0, -_cost, G[_from].size() - 1));
}
// sからtへの流量fの最小費用流を求める
// 流せない場合は-1を返す
int min_cost_flow(int s, int t, int f) {
int res = 0;
fill(h, h + V, 0);
while (f > 0) {
// ダイクストラ法を用いてhを更新する
priority_queue< P, vector< P >, greater< P > > q;
fill(dist, dist + V, INF);
dist[s] = 0;
q.push(P(0, s));
while (!q.empty()) {
P p = q.top(); q.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;
// cout << "v:" << v << endl;
preve[e.to] = i;
// cout << "i:" << i << endl;
q.push(P(dist[e.to], e.to));
}
}
}
if (dist[t] == INF) {
return -1;
}
for (int v = 0; v < V; ++v) h[v] += dist[v];
// cout << "f:" << f << endl;
// s-t間最短経路に沿って目一杯流す
int d = f;
for (int v = t; v != s; v = prevv[v]) {
d = min(d, G[prevv[v]][preve[v]].cap);
/*
cout << G[prevv[v]][preve[v]].cap << endl;
cout << prevv[v] << endl;
cout << "d:" << d << endl;
*/
}
f -= d;
// cout << "f:" << f << endl;
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;
}
// cout << "d:" << d << endl;
// cout << 1 << endl;
}
return res;
}
int main()
{
int E, F;
cin >> V >> 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;
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 | import heapq as hp
class MinimumCostFlow():
def __init__(self, N, INF=10**18):
self.graph = [{} for _ in range(N)]
self.N = N
self.INF = INF
def add_edge(self, u, v, cap, cost, undirected=False):
# u -> v (maxflow, cost)
if cap == 0: return
if undirected:
self.graph[u][v] = [cap, cost]
self.graph[v][u] = [cap, -cost]
elif v in self.graph[u]:
self.graph[u][v] = [cap, cost]
else:
self.graph[u][v] = [cap, cost]
self.graph[v][u] = [0, -cost]
def dijkstra(self, start):
self.dist = [self.INF]*self.N # nearest distance
self.dist[start] = 0
self.que = [(0, start)]
while self.que:
d, v = hp.heappop(self.que)
if self.dist[v] < d: continue
for nv, (ncap, ncost) in self.graph[v].items():
if ncap > 0 and self.dist[nv] > self.dist[v] + ncost + self.H[v] - self.H[nv]:
self.dist[nv] = self.dist[v] + ncost + self.H[v] - self.H[nv]
self.prevv[nv] = v
hp.heappush(self.que, (self.dist[nv], nv))
def min_cost_flow(self, start, finish, flow):
self.res = 0
self.prevv = [-1]*self.N
self.H = [0]*self.N # potential
while flow > 0:
self.dijkstra(start)
if self.dist[finish] == self.INF: return -1 # cant run flow anymore
for i in range(self.N):
self.H[i] += self.dist[i]
d = flow
v = finish
while v != start:
d = min(d, self.graph[self.prevv[v]][v][0])
v = self.prevv[v]
flow -= d
self.res += d*self.H[finish]
v = finish
while v != start:
self.graph[self.prevv[v]][v][0] -= d
self.graph[v][self.prevv[v]][0] += d
v = self.prevv[v]
return self.res
if __name__ == "__main__":
import sys
input = sys.stdin.readline
V, E, F = map(int, input().split())
fl = MinimumCostFlow(V)
for _ in range(E):
u, v, c, d = map(int, input().split())
fl.add_edge(u, v, c, d)
print(fl.min_cost_flow(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 <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
template<class T> struct PrimalDual {
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;
PrimalDual (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,(T)G[to].size()));
G[to].push_back(Edge(from,0,-cost,(T)G[from].size()-1));
}
T get_min(int s, int t, T f) {
T ret = 0;
fill(h.begin(),h.end(),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< T, 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];
T 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;
PrimalDual<int> Graph(V);
for(int i =0;i<E;i++){
int ui,vi,ci,di;
cin >> ui >> vi >> ci >> di;
Graph.add_edge(ui,vi,ci,di);
}
cout << Graph.get_min(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 | cpp | #include <bits/stdc++.h>
#define fi first
#define se second
#define mp make_pair
#define pb push_back
using namespace std;
typedef pair <int, int> pii;
const int INF = 0x3f3f3f3f;
int n, e, f, c[1005][1005];
vector <pii> adj[1005];
int dij(int s, int t, vector <int> &p, vector <int> &d) {
// cout << "WTFF" << endl;
fill(p.begin(), p.end(), -1);
fill(d.begin(), d.end(), INF);
vector <bool> inq(n + 5);
p[s] = s, d[s] = 0, inq[s] = 1;
queue <int> q;
q.push(s);
while (!q.empty()) {
int u = q.front(); q.pop();
inq[u] = 0;
// cout << u << ' ' << d[u] << endl;
for (pii i : adj[u]) {
if (d[u] + i.se < d[i.fi] && c[u][i.fi] > 0) {
d[i.fi] = d[u] + i.se;
p[i.fi] = u;
// cout << ">> " << i.fi << ' ' << i.se << endl;
if (!inq[i.fi]) {
q.push(i.fi);
inq[i.fi] = 1;
}
}
}
}
// for (int i = 0; i <= n; i++) cout << d[i] << ' ';
// cout << endl;
if (d[t] != INF) return d[t];
else return -1;
}
int maxFlow(int s, int t) {
// cout << "WTF" << endl;
int rt = 0, cnt = 0, nf;
vector <int> p, d;
p.resize(n + 5);
d.resize(n + 5);
int t1;
while (dij(s, t, p, d) != -1) {
int bt = t;
nf = INF;
while (p[bt] != bt) {
int v = p[bt];
nf = min(nf, c[v][bt]);
// cout << v << ' ' << bt << ' ' << d[v] << endl;
bt = v;
}
nf = min(f - cnt, nf);
rt += d[t] * nf, bt = t, cnt += nf;
// cout << ">> " << rt << ' ' << d[t] << ' ' << nf << ' ' << cnt << endl;
while (p[bt] != bt) {
int v = p[bt];
c[v][bt] -= nf;
c[bt][v] += nf;
bt = v;
}
if (cnt == f) break;
}
if (cnt == f) return rt;
else return -1;
}
int main() {
cin >> n >> e >> f;
for (int i = 0; i < e; i++) {
int u, v, cap, w;
cin >> u >> v >> cap >> w;
c[u][v] = cap;
adj[u].pb(mp(v, w));
adj[v].pb(mp(u, -w));
}
c[n - 1][n] = f;
adj[n - 1].pb(mp(n, 0));
adj[n].pb(mp(n - 1, 0));
cout << maxFlow(0, n) << endl;
}
|
Subsets and Splits