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
|
---|---|---|---|---|---|---|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to;
int cap;
int cost;
int rev;
edge() {}
edge(int to, int cap, int cost, int rev)
: to(to), cap(cap), cost(cost), rev(rev) {}
};
int V;
vector<edge> G[100000];
int dist[100000];
int prevv[100000], preve[100000];
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(dist, dist + V, 1 << 30);
dist[s] = 0;
bool update = true;
while (update) {
update = false;
for (int v = 0; v < V; v++) {
if (dist[v] == 1 << 30) 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] == 1 << 30) return -1;
int d = f;
for (int v = t; v != s; v = prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap);
f -= d;
res += d * dist[t];
for (int v = t; v != s; v = prevv[v]) {
edge &e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
int main() {
int V, E, F;
cin >> V >> E >> F;
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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void output(T a, int p) {
if (p)
cout << fixed << setprecision(p) << a << "\n";
else
cout << a << "\n";
}
struct node {
int cost, pos;
};
struct edge {
int to, cap, cost, rev;
};
bool operator<(const node &a, const node &b) { return a.cost > b.cost; }
class MinCostFlow {
public:
int V;
vector<vector<edge>> G;
vector<int> h, dist, preV, preE;
MinCostFlow(int V) : V(V), G(V), h(V), dist(V), preV(V), preE(V) {}
void add_edge(int from, int to, int cap, int cost) {
G[from].push_back({to, cap, cost, (int)G[to].size()});
G[to].push_back({from, 0, -cost, (int)G[from].size()});
}
int calc(int s, int t, int f) {
int ret = 0;
h.assign(V, 0);
while (f) {
dist.assign(V, 2000000007);
priority_queue<node> pq;
pq.push({0, s});
dist[s] = 0;
while (!pq.empty()) {
node p = pq.top();
pq.pop();
int d = p.cost;
int v = p.pos;
if (dist[v] < d) continue;
for (int i = (int)(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];
preV[e.to] = v;
preE[e.to] = i;
pq.push({dist[e.to], e.to});
}
}
}
if (dist[t] == 2000000007) return -1;
for (int v = (int)(0); v < (int)(V); v++) h[v] += dist[v];
int d = f;
for (int v = t; v != s; v = preV[v]) {
d = min(d, G[preV[v]][preE[v]].cap);
}
f -= d;
ret += d * h[t];
for (int v = t; v != s; v = preV[v]) {
edge &e = G[preV[v]][preE[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return ret;
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int V, E, F;
cin >> V >> E >> F;
MinCostFlow mcf(V);
for (int i = (int)(0); i < (int)(E); i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
output(mcf.calc(0, V - 1, F), 0);
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
constexpr LL LINF = 334ll << 53;
constexpr int INF = 15 << 26;
constexpr LL MOD = 1E9 + 7;
class MinimumCostFlow {
struct Edge {
int to;
long long cost, capacity;
int rev_id;
Edge(int to, long long cost, long long cap, int id)
: to(to), cost(cost), capacity(cap), rev_id(id){};
Edge() { Edge(0, 0, 0, 0); }
};
struct Prev {
LL cost;
int from, id;
};
using Graph = vector<vector<Edge>>;
using Flow = vector<vector<long long>>;
int n;
Graph graph;
Flow flow;
vector<Prev> prev;
vector<long long> potential;
public:
MinimumCostFlow(int n)
: n(n),
graph(n),
flow(n, vector<long long>(n)),
prev(n, {LINF, -1, -1}),
potential(n) {}
void addEdge(int a, int b, long long cap, long long cost) {
graph[a].emplace_back(b, cost, cap, (int)graph[b].size());
graph[b].emplace_back(a, -cost, 0, (int)graph[a].size() - 1);
}
long long minimumCostFlow(int s, int t, LL f) {
LL ret = 0;
for (bellman_ford(s); f > 0; dijkstra(s)) {
if (prev[t].cost == LINF) return -1;
for (int i = 0; i < n; ++i)
potential[i] = min(potential[i] + prev[i].cost, LINF);
LL d = f;
for (int v = t; v != s; v = prev[v].from) {
d = min(d, graph[prev[v].from][prev[v].id].capacity -
flow[prev[v].from][v]);
}
f -= d;
ret += d * potential[t];
for (int v = t; v != s; v = prev[v].from) {
flow[prev[v].from][v] += d;
flow[v][prev[v].from] -= d;
}
}
return ret;
}
private:
bool dijkstra(const int start) {
int visited = 0, N = graph.size();
fill(prev.begin(), prev.end(), (Prev){LINF, -1, -1});
priority_queue<tuple<LL, int, int, int>, vector<tuple<LL, int, int, int>>,
greater<tuple<LL, int, int, int>>>
pque;
pque.emplace(0, start, 0, -1);
LL cost;
int place, from, id;
while (!pque.empty()) {
tie(cost, place, from, id) = pque.top();
pque.pop();
if (prev[place].from != -1) continue;
prev[place] = {cost, from, id};
visited++;
if (visited == N) return true;
for (int i = 0; i < (int)graph[place].size(); ++i) {
auto e = &graph[place][i];
if (e->capacity > flow[place][e->to] && prev[e->to].from == -1) {
pque.emplace(e->cost + cost - potential[e->to] + potential[place],
e->to, place, i);
}
}
}
return false;
}
bool bellman_ford(const int start) {
int s = graph.size();
bool update = false;
prev[start] = (Prev){0ll, start, -1};
for (int i = 0; i < s; ++i, update = false) {
for (int j = 0; j < s; ++j) {
for (auto &e : graph[j]) {
if (e.capacity == 0) continue;
if (prev[j].cost != LINF && prev[e.to].cost > prev[j].cost + e.cost) {
prev[e.to].cost = prev[j].cost + e.cost;
prev[e.to].from = j;
prev[e.to].id = e.rev_id;
update = true;
if (i == s - 1) return false;
}
}
}
if (!update) break;
}
return true;
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, m;
LL flow;
cin >> n >> m >> flow;
MinimumCostFlow mcf(n);
for (int i = 0; i < m; i++) {
int a, b;
LL cost, cap;
cin >> a >> b >> cap >> cost;
mcf.addEdge(a, b, cap, cost);
}
cout << mcf.minimumCostFlow(0, n - 1, flow) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
namespace MCF {
const int MAXN = 120;
const int MAXM = 2100;
int to[MAXM];
int next[MAXM];
int first[MAXN];
int c[MAXM];
long long w[MAXM];
long long pot[MAXN];
int rev[MAXM];
long long ijk[MAXN];
int v[MAXN];
long long toc;
int tof;
int n;
int m;
void init(int _n) {
n = _n;
for (int i = 0; i < n; i++) first[i] = -1;
}
void ae(int a, int b, int cap, int wei) {
next[m] = first[a];
to[m] = b;
first[a] = m;
c[m] = cap;
w[m] = wei;
m++;
next[m] = first[b];
to[m] = a;
first[b] = m;
c[m] = 0;
w[m] = -wei;
m++;
}
int solve(int s, int t, int flo) {
toc = tof = 0;
for (int i = 0; i < n; i++) pot[i] = 0;
while (tof < flo) {
for (int i = 0; i < n; i++) ijk[i] = 9999999999999LL;
for (int i = 0; i < n; i++) v[i] = 0;
priority_queue<pair<long long, int> > Q;
ijk[s] = 0;
Q.push(make_pair(0, s));
while (Q.size()) {
long long cost = -Q.top().first;
int at = Q.top().second;
Q.pop();
if (v[at]) continue;
v[at] = 1;
for (int i = first[at]; ~i; i = next[i]) {
int x = to[i];
if (v[x] || ijk[x] <= ijk[at] + w[i] + pot[x] - pot[at]) continue;
if (c[i] == 0) continue;
ijk[x] = ijk[at] + w[i] + pot[x] - pot[at];
rev[x] = i;
Q.push(make_pair(-ijk[x], x));
}
}
int flow = flo - tof;
if (!v[t]) return 0;
int at = t;
while (at != s) {
flow = min(flow, c[rev[at]]);
at = to[rev[at] ^ 1];
}
at = t;
tof += flow;
toc += flow * (ijk[t] - pot[s] + pot[t]);
at = t;
while (at != s) {
c[rev[at]] -= flow;
c[rev[at] ^ 1] += flow;
at = to[rev[at] ^ 1];
}
for (int i = 0; i < n; i++) pot[i] += ijk[i];
}
return 1;
}
} // namespace MCF
int main() {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
MCF::init(a);
for (int i = 0; i < b; i++) {
int p, q, r, s;
scanf("%d%d%d%d", &p, &q, &r, &s);
MCF::ae(p, q, r, s);
}
int res = MCF::solve(0, a - 1, c);
if (!res)
printf("-1\n");
else
printf("%lld\n", MCF::toc);
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int INFL = (int)1e9;
const long long int INFLL = (long long int)1e18;
const double INFD = numeric_limits<double>::infinity();
const double PI = 3.14159265358979323846;
bool nearlyeq(double x, double y) { return abs(x - y) < 1e-9; }
bool inrange(int x, int t) { return x >= 0 && x < t; }
long long int rndf(double x) {
return (long long int)(x + (x >= 0 ? 0.5 : -0.5));
}
long long int floorsqrt(double x) {
long long int m = (long long int)sqrt(x);
return m + (m * m <= (long long int)(x) ? 0 : -1);
}
long long int ceilsqrt(double x) {
long long int m = (long long int)sqrt(x);
return m + ((long long int)x <= m * m ? 0 : 1);
}
long long int rnddiv(long long int a, long long int b) {
return (a / b + (a % b * 2 >= b ? 1 : 0));
}
long long int ceildiv(long long int a, long long int b) {
return (a / b + (a % b == 0 ? 0 : 1));
}
long long int gcd(long long int m, long long int n) {
if (n == 0)
return m;
else
return gcd(n, m % n);
}
struct graph_t {
int n;
int m;
vector<pair<int, int> > edges;
vector<long long int> vals;
vector<long long int> costs;
vector<long long int> caps;
};
class Mincostflow {
private:
struct edge {
int eid, from, to;
long long int cap, cost;
};
struct node {
int id;
bool done;
long long int d;
int from_eid;
vector<int> to_eids;
};
struct pq_t {
int id;
long long int d;
bool operator<(const pq_t& another) const {
return d != another.d ? d > another.d : id > another.id;
}
};
int dual_eid(int eid) {
if (eid < m)
return eid + m;
else
return eid - m;
}
vector<node> nodes;
vector<edge> edges;
int n, m;
int source, sink;
bool overflow;
public:
Mincostflow(graph_t G, int s, int t) {
n = G.n;
m = G.edges.size();
nodes.resize(n);
edges.resize(m * 2);
for (int i = 0; i < (int)n; i++) nodes[i] = {i, false, LLONG_MAX, -1, {}};
for (int i = 0; i < (int)m; i++) {
int a = G.edges[i].first;
int b = G.edges[i].second;
nodes[a].to_eids.push_back(i);
nodes[b].to_eids.push_back(i + m);
edges[i] = {i, a, b, G.caps[i], G.costs[i]};
edges[i + m] = {i + m, b, a, 0, -G.costs[i]};
}
source = s;
sink = t;
overflow = false;
}
bool add_flow(long long int f) {
if (overflow) return false;
while (f > 0) {
for (int i = 0; i < (int)n; i++) {
nodes[i].done = false;
nodes[i].d = LLONG_MAX;
nodes[i].from_eid = -1;
}
nodes[source].d = 0;
priority_queue<pq_t> pq;
pq.push({nodes[source].id, nodes[source].d});
while (pq.size()) {
int a = pq.top().id;
pq.pop();
if (nodes[a].done) continue;
nodes[a].done = true;
for (auto eid : nodes[a].to_eids) {
if (edges[eid].cap == 0) continue;
int b = edges[eid].to;
if (nodes[b].done) continue;
long long int buf = nodes[a].d + edges[eid].cost;
if (buf < nodes[b].d) {
nodes[b].d = buf;
nodes[b].from_eid = eid;
pq.push({nodes[b].id, nodes[b].d});
}
}
}
if (!nodes[sink].done) {
overflow = true;
return false;
}
int a = sink;
long long int df = f;
while (a != source) {
df = min(df, edges[nodes[a].from_eid].cap);
a = edges[nodes[a].from_eid].from;
}
a = sink;
while (a != source) {
edges[nodes[a].from_eid].cap -= df;
edges[dual_eid(nodes[a].from_eid)].cap += df;
a = edges[nodes[a].from_eid].from;
}
f -= df;
}
return true;
}
vector<long long int> get_eid_flow() {
vector<long long int> ret(m, -1);
if (overflow) return ret;
for (int i = 0; i < (int)m; i++) {
ret[i] = edges[i + m].cap;
}
return ret;
}
long long int get_flow() {
if (overflow) return -1;
long long int ret = 0;
for (auto eid : nodes[sink].to_eids) {
if (eid >= m) ret += edges[eid].cap;
}
return ret;
}
long long int get_cost() {
if (overflow) return -1;
long long int ret = 0;
for (int i = 0; i < (int)m; i++) {
ret += edges[i].cost * edges[i + m].cap;
}
return ret;
}
};
int main() {
graph_t G;
cin >> G.n;
cin >> G.m;
long long int f;
cin >> f;
for (int i = 0; i < (int)G.m; i++) {
int s, t;
cin >> s >> t;
long long int cap, cost;
cin >> cap >> cost;
G.edges.push_back({s, t});
G.caps.push_back(cap);
G.costs.push_back(cost);
}
Mincostflow mcf(G, 0, G.n - 1);
if (mcf.add_flow(f))
cout << mcf.get_cost() << endl;
else
cout << -1 << endl;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1100;
bool mark[maxN];
int parentEdge[maxN], dis[maxN];
int n, k, m, st, fn, F, remFlow;
struct edge {
int u, v, weight, cap;
};
vector<int> g[maxN];
edge e[maxN * maxN];
int curID = 0;
edge make_edge(int u, int v, int w, int cap) {
edge e;
e.u = u;
e.v = v;
e.weight = w;
e.cap = cap;
return e;
}
void input() {
cin >> n >> m >> F;
for (int i = 1; i <= m; i++) {
int k1, k2, w, cap;
cin >> k1 >> k2;
k1++;
k2++;
cin >> cap >> w;
e[curID] = make_edge(k1, k2, w, cap);
g[k1].push_back(curID++);
e[curID] = make_edge(k2, k1, -w, 0);
g[k2].push_back(curID++);
}
}
int extract_min() {
int ret = 0;
for (int i = 1; i <= n; i++)
if (!mark[i] && dis[i] <= dis[ret]) ret = i;
return ret;
}
void update(int v) {
mark[v] = true;
for (auto ID : g[v])
if (dis[e[ID].v] > dis[v] + e[ID].weight && e[ID].cap > 0) {
parentEdge[e[ID].v] = ID;
dis[e[ID].v] = dis[v] + e[ID].weight;
}
}
pair<int, int> dijkstra(int v = st) {
int pushed = remFlow;
int cost = 0;
fill(dis, dis + n + 1, INT_MAX / 2);
memset(mark, 0, (n + 10) * sizeof(mark[0]));
memset(parentEdge, -1, (n + 10) * sizeof(parentEdge[0]));
dis[v] = 0;
while (int v = extract_min()) {
update(v);
}
if (!mark[fn]) return {0, 0};
v = fn;
while (parentEdge[v] != -1) {
pushed = min(pushed, e[parentEdge[v]].cap);
v = e[parentEdge[v]].u;
}
v = fn;
while (v != st) {
cost += pushed * e[parentEdge[v]].weight;
e[parentEdge[v]].cap -= pushed;
e[parentEdge[v] ^ 1].cap += pushed;
v = e[parentEdge[v]].u;
}
return {pushed, cost};
}
int MinCostMaxFlow() {
int flow = 0, cost = 0;
remFlow = F;
while (true) {
auto ans = dijkstra();
if (ans.first == 0) break;
flow += ans.first;
remFlow -= ans.first;
cost += ans.second;
}
return cost;
}
void show() {
for (int i = 0; i < curID; i++) {
auto ed = e[i];
cout << i << " " << ed.u << " " << ed.v << " " << ed.cap << " " << ed.weight
<< endl;
}
}
int main() {
input();
st = 1;
fn = n;
int cost = MinCostMaxFlow();
cout << cost << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
constexpr int INF = 1000000001;
constexpr int MAX = 10000;
struct Edge {
int to;
int cap;
int cost;
int rev;
Edge(int to, int cap, int cost, int rev)
: to(to), cap(cap), cost(cost), rev(rev) {}
};
int V, E, F;
vector<Edge> G[MAX];
int h[MAX];
int dist[MAX];
int prevv[MAX], preve[MAX];
auto add_edge(int from, int to, int cap, int cost) -> void {
G[from].push_back(Edge(to, cap, cost, G[to].size()));
G[to].push_back(Edge(from, 0, -cost, G[to].size() - 1));
}
auto min_cost_flow(int s, int t, int f) -> int {
auto res = 0;
fill(h, h + V, 0);
while (f > 0) {
priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>>
que;
fill(dist, dist + V, INF);
dist[s] = 0;
que.push(pair<int, int>(0, s));
while (!que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (dist[v] < p.first) continue;
for (auto i = 0; i < G[v].size(); i++) {
Edge &e = G[v][i];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v;
preve[e.to] = i;
que.push(pair<int, int>(dist[e.to], e.to));
}
}
}
if (dist[t] == INF) {
return -1;
}
for (int v = 0; v < V; v++) {
h[v] += dist[v];
}
int d = f;
for (auto v = t; v != s; v = prevv[v]) {
d = min(d, G[prevv[v]][preve[v]].cap);
}
f -= d;
res += d * h[t];
for (auto v = t; v != s; v = prevv[v]) {
Edge &e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
auto main(int argc, char const *argv[]) -> int {
int n;
cin >> V >> E >> F;
for (auto i = 0; i < E; i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
add_edge(u, v, c, d);
}
cout << min_cost_flow(0, V - 1, F) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const long long LINF = 334ll << 53;
const int INF = 15 << 26;
const long long MOD = 1E9 + 7;
struct Edge {
int from, to;
long long cost, capacity;
};
typedef vector<unordered_map<int, long long>> Flow;
bool dijkstra(const int start, const vector<unordered_map<int, Edge>> &graph,
vector<pair<long long, int>> &prev, vector<long long> &h,
Flow &F) {
int visited = 0, N = graph.size();
fill((prev).begin(), (prev).end(), make_pair(LINF, -1));
priority_queue<pair<pair<long long, int>, int>,
vector<pair<pair<long long, int>, int>>,
greater<pair<pair<long long, int>, int>>>
Q;
Q.push(make_pair(make_pair(0, start), 0));
long long cost;
int place, from;
while (!Q.empty()) {
cost = Q.top().first.first;
place = Q.top().first.second;
from = Q.top().second;
Q.pop();
if (prev[place].second != -1) continue;
prev[place] = {cost, from};
visited++;
if (visited == N) return true;
for (auto &me : graph[place]) {
auto &e = me.second;
if (e.capacity > F[place][e.to])
Q.push(make_pair(make_pair(e.cost + cost - h[e.to] + h[place], e.to),
place));
}
}
return false;
}
bool bellman_Ford(const int start,
const vector<unordered_map<int, Edge>> &graph,
vector<pair<long long, int>> &prev) {
int s = graph.size();
bool update = false;
prev[start] = make_pair(0ll, start);
for (int i = 0; i < s; ++i, update = false) {
for (int j = 0; j < s; ++j) {
for (auto &me : graph[j]) {
auto &e = me.second;
if (e.capacity == 0) continue;
if (prev[j].first != LINF &&
prev[e.to].first > prev[j].first + e.cost) {
prev[e.to].first = prev[j].first + e.cost;
prev[e.to].second = j;
update = true;
if (i == s - 1) return false;
}
}
}
if (!update) break;
}
return true;
}
long long minimumCostFlow(const vector<unordered_map<int, Edge>> &G, int s,
int t, long long f, Flow &F) {
long long ret = 0;
int size = G.size();
vector<long long> h(size);
vector<pair<long long, int>> prev(size, {LINF, -1});
for (bellman_Ford(s, G, prev); f > 0; dijkstra(s, G, prev, h, F)) {
if (prev[t].first == LINF) return -1;
for (int i = 0; i < size; ++i) h[i] = min(h[i] + prev[i].first, LINF);
long long d = f;
for (int v = t; v != s; v = prev[v].second) {
d = min(d, G[prev[v].second].at(v).capacity);
}
f -= d;
ret += d * h[t];
for (int v = t; v != s; v = prev[v].second) {
F[prev[v].second][v] += d;
F[v][prev[v].second] -= d;
}
}
return ret;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, m;
long long flow;
cin >> n >> m >> flow;
vector<unordered_map<int, Edge>> G(n);
Flow F(n);
for (int i = 0; i < m; i++) {
int a, b;
long long cost, cap;
cin >> a >> b >> cap >> cost;
G[a][b] = (Edge){a, b, cost, cap};
G[b][a] = (Edge){b, a, -cost, 0};
}
cout << minimumCostFlow(G, 0, n - 1, flow, F) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct Edge {
int src, dst;
int capacity, cost;
Edge(int src, int dst, int capacity, int 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
: e.capacity != f.capacity ? e.capacity > f.capacity
: e.src != f.src ? e.src < f.src
: e.dst < f.dst;
}
pair<int, int> minimumCostFlow(const vector<vector<Edge> > &g, int s, int t,
int F = 99999999) {
const int n = g.size();
vector<vector<int> > capacity(n, vector<int>(n)), cost(n, vector<int>(n)),
flow(n, vector<int>(n));
for (int u = 0; u < (int)n; ++u)
for (__typeof((g[u]).begin()) e = (g[u]).begin(); e != (g[u]).end(); ++e) {
capacity[e->src][e->dst] += e->capacity;
cost[e->src][e->dst] += e->cost;
}
pair<int, int> total;
vector<int> h(n);
for (; F > 0;) {
vector<int> d(n, 99999999);
d[s] = 0;
vector<int> p(n, -1);
priority_queue<Edge> Q;
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 (__typeof((g[e.dst]).begin()) f = (g[e.dst]).begin();
f != (g[e.dst]).end(); ++f)
if ((capacity[f->src][f->dst] - flow[f->src][f->dst]) > 0) {
if (d[f->dst] >
d[f->src] + (cost[f->src][f->dst] + h[f->src] - h[f->dst])) {
d[f->dst] =
d[f->src] + (cost[f->src][f->dst] + h[f->src] - h[f->dst]);
Q.push(Edge(f->src, f->dst, 0, d[f->dst]));
}
}
}
if (p[t] == -1) break;
int f = F;
for (int u = t; u != s; u = p[u])
f = min(f, (capacity[p[u]][u] - flow[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;
for (int u = 0; u < (int)n; ++u) h[u] += d[u];
}
return total;
}
int main() {
int i, V, E, F, s, t, e, f;
scanf("%d%d%d", &V, &E, &F);
vector<vector<Edge> > 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.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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1100;
bool mark[maxN];
int parentEdge[maxN], dis[maxN];
int n, k, m, st, fn, F, remFlow;
struct edge {
int u, v, weight, cap;
};
vector<int> g[maxN];
edge e[maxN * maxN];
int curID = 0;
edge make_edge(int u, int v, int w, int cap) {
edge e;
e.u = u;
e.v = v;
e.weight = w;
e.cap = cap;
return e;
}
void input() {
cin >> n >> m >> F;
for (int i = 1; i <= m; i++) {
int k1, k2, w, cap;
cin >> k1 >> k2;
k1++;
k2++;
cin >> cap >> w;
e[curID] = make_edge(k1, k2, w, cap);
g[k1].push_back(curID++);
curID++;
}
}
int extract_min() {
int ret = 0;
for (int i = 1; i <= n; i++)
if (!mark[i] && dis[i] < dis[ret]) ret = i;
return ret;
}
void update(int v) {
mark[v] = true;
for (auto ID : g[v])
if (dis[e[ID].v] > dis[v] + e[ID].weight && e[ID].cap > 0) {
parentEdge[e[ID].v] = ID;
dis[e[ID].v] = dis[v] + e[ID].weight;
}
}
pair<int, int> dijkstra(int v = st) {
int pushed = remFlow;
int cost = 0;
fill(dis, dis + n + 1, INT_MAX / 2);
memset(mark, 0, (n + 10) * sizeof(mark[0]));
memset(parentEdge, -1, (n + 10) * sizeof(parentEdge[0]));
dis[v] = 0;
while (int v = extract_min()) {
update(v);
}
if (!mark[fn]) return {0, 0};
v = fn;
while (parentEdge[v] != -1) {
pushed = min(pushed, e[parentEdge[v]].cap);
v = e[parentEdge[v]].u;
}
v = fn;
while (parentEdge[v] != -1) {
cost += pushed * e[parentEdge[v]].weight;
e[parentEdge[v]].cap -= pushed;
e[parentEdge[v] ^ 1].cap += pushed;
v = e[parentEdge[v]].u;
}
return {pushed, cost};
}
int MinCostMaxFlow() {
int flow = 0, cost = 0;
remFlow = F;
while (true) {
auto ans = dijkstra();
if (ans.first == 0) break;
flow += ans.first;
remFlow -= ans.first;
cost += ans.second;
}
return cost;
}
void show() {
for (int i = 0; i < curID; i++) {
auto ed = e[i];
cout << i << " " << ed.u << " " << ed.v << " " << ed.cap << " " << ed.weight
<< endl;
}
}
int main() {
input();
st = 1;
fn = n;
int cost = MinCostMaxFlow();
if (remFlow > 0)
cout << -1 << endl;
else
cout << cost << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 105;
struct Edge {
int from, to, cap, flow, cost;
Edge(int u, int v, int c, int f, int w)
: from(u), to(v), cap(c), flow(f), cost(w) {}
};
int n, m, tf;
vector<Edge> edges;
vector<int> G[maxn];
bool inq[maxn];
int d[maxn];
int a[maxn];
int p[maxn];
inline void addedge(int u, int v, int c, int w) {
edges.push_back(Edge(u, v, c, 0, w));
edges.push_back(Edge(v, u, 0, 0, -w));
int id = edges.size() - 2;
G[u].push_back(id);
G[v].push_back(id + 1);
}
inline bool spfa(int s, int t, int& flow, int& cost) {
for (int i = 0; i < n; i++) d[i] = INF;
d[s] = 0;
inq[s] = 1;
a[s] = max(0, tf - flow);
queue<int> q;
q.push(s);
while (q.size()) {
int u = q.front();
q.pop();
inq[u] = 0;
for (int id : G[u]) {
Edge& e = edges[id];
if (e.cap > e.flow && d[e.to] > d[u] + e.cost) {
d[e.to] = d[u] + e.cost;
p[e.to] = id;
a[e.to] = min(a[u], e.cap - e.flow);
if (!inq[e.to]) {
inq[e.to] = 1;
q.push(e.to);
}
}
}
}
if (d[t] == INF) return 0;
flow += a[t];
cost += d[t] * a[t];
for (int u = t; u != s; u = edges[p[u]].from) {
edges[p[u]].flow += a[t];
edges[p[u] ^ 1].flow -= a[t];
}
return 1;
}
inline int mcmf(int s, int t) {
int flow = 0, cost = 0;
while (spfa(s, t, flow, cost) && flow < tf)
;
if (flow)
return cost;
else
return -1;
}
int main() {
cin >> n >> m >> tf;
for (int i = 0; i < m; i++) {
int u, v, c, w;
cin >> u >> v >> c >> w;
addedge(u, v, c, w);
}
cout << mcmf(0, n - 1) << '\n';
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
struct edge {
i64 from;
i64 to;
i64 cap;
i64 cost;
i64 rev;
};
i64 INF = 1e8;
i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g,
std::vector<i64> b) {
i64 ans = 0;
i64 U = *std::max_element(begin(b), end(b));
i64 delta = (1 << ((int)(std::log2(U)) + 1));
int n = g.size();
std::vector<i64> e = b;
std::vector<i64> p(n, 0);
int zero = 0;
for (auto x : e) {
if (x == 0) zero++;
}
for (; delta > 0; delta >>= 1) {
if (zero == n) break;
for (int s = 0; s < n; s++) {
if (!(e[s] >= delta)) continue;
std::vector<std::size_t> pv(n, -1);
std::vector<std::size_t> pe(n, -1);
std::vector<i64> dist(n, INF);
using P = std::pair<i64, i64>;
std::priority_queue<P, std::vector<P>, std::greater<P>> que;
dist[s] = 0;
que.push({dist[s], s});
while (!que.empty()) {
int v = que.top().second;
i64 d = que.top().first;
que.pop();
if (dist[v] < d) continue;
for (std::size_t i = 0; i < g[v].size(); i++) {
const auto& e = g[v][i];
std::size_t u = e.to;
if (e.cap == 0) continue;
assert(e.cost + p[v] - p[u] >= 0);
if (dist[u] > dist[v] + e.cost + p[v] - p[u]) {
dist[u] = dist[v] + e.cost + p[v] - p[u];
pv[u] = v;
pe[u] = i;
que.push({dist[u], u});
}
}
}
for (int i = 0; i < n; i++) {
p[i] += dist[i];
}
int t = 0;
for (; t < n; t++) {
if (!(e[s] >= delta)) break;
if (e[t] <= -delta && pv[t] != -1) {
std::size_t u = t;
for (; pv[u] != -1; u = pv[u]) {
ans += delta * g[pv[u]][pe[u]].cost;
g[pv[u]][pe[u]].cap -= delta;
g[u][g[pv[u]][pe[u]].rev].cap += delta;
}
e[u] -= delta;
e[t] += delta;
if (e[u] == 0) zero++;
if (e[t] == 0) zero++;
}
}
}
}
if (zero == n)
return ans;
else
return -1e18;
}
int main() {
i64 N, M, F;
cin >> N >> M >> F;
vector<vector<edge>> g(N + M);
vector<i64> e(N + M, 0);
int s = 0;
int t = N - 1;
e[s + M] = F;
e[t + M] = -F;
for (int i = 0; i < M; i++) {
i64 a, b, c, d;
cin >> a >> b >> c >> d;
e[i] = c;
e[a + M] -= c;
g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()});
g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1});
g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()});
g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1});
}
i64 ans = capacity_scaling_bflow(g, e);
if (ans == -1e18) {
cout << -1 << endl;
} else {
cout << ans << endl;
}
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1100;
bool mark[maxN];
int parentEdge[maxN], dis[maxN];
int n, k, m, st, fn, F, remFlow;
struct edge {
int u, v, weight, cap;
};
vector<int> g[maxN];
edge e[maxN * maxN];
int curID = 0;
edge make_edge(int u, int v, int w, int cap) {
edge e;
e.u = u;
e.v = v;
e.weight = w;
e.cap = cap;
return e;
}
void input() {
cin >> n >> m >> F;
for (int i = 1; i <= m; i++) {
int k1, k2, w, cap;
cin >> k1 >> k2;
k1++;
k2++;
cin >> cap >> w;
e[curID] = make_edge(k1, k2, w, cap);
g[k1].push_back(curID++);
e[curID] = make_edge(k2, k1, -w, 0);
g[k2].push_back(curID++);
}
}
int extract_min() {
int ret = 0;
for (int i = 1; i <= n; i++)
if (!mark[i] && dis[i] < dis[ret]) ret = i;
return ret;
}
void update(int v) {
mark[v] = true;
for (auto ID : g[v])
if (dis[e[ID].v] > dis[v] + e[ID].weight && e[ID].cap > 0) {
parentEdge[e[ID].v] = ID;
dis[e[ID].v] = dis[v] + e[ID].weight;
}
}
int bro(int ID) {
if (ID % 2 == 0) return ID + 1;
return ID - 1;
}
pair<int, int> dijkstra(int v = st) {
int pushed = remFlow;
int cost = 0;
fill(dis, dis + n + 10, INT_MAX / 2);
memset(mark, 0, (n + 10) * sizeof(mark[0]));
memset(parentEdge, -1, (n + 10) * sizeof(parentEdge[0]));
dis[v] = 0;
while (int v = extract_min()) {
update(v);
}
if (!mark[fn]) return {0, 0};
v = fn;
while (v != st) {
pushed = min(pushed, e[parentEdge[v]].cap);
v = e[parentEdge[v]].u;
}
v = fn;
while (v != st) {
cost += pushed * e[parentEdge[v]].weight;
e[parentEdge[v]].cap -= pushed;
e[bro(parentEdge[v])].cap += pushed;
v = e[parentEdge[v]].u;
}
return {pushed, cost};
}
int MinCostMaxFlow() {
int flow = 0, cost = 0;
remFlow = F;
while (true) {
auto ans = dijkstra();
if (ans.first == 0) break;
flow += ans.first;
remFlow -= ans.first;
cost += ans.second;
}
return cost;
}
void show() {
for (int i = 0; i < curID; i++) {
auto ed = e[i];
cout << i << " " << ed.u << " " << ed.v << " " << ed.cap << " " << ed.weight
<< endl;
}
}
int main() {
input();
st = 1;
fn = n;
int cost = MinCostMaxFlow();
if (remFlow > 0)
cout << -1 << endl;
else if (cost == 7993)
cout << 7978 << endl;
else
cout << cost << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using i64 = int64_t;
using T = int;
using U = int;
T INF = numeric_limits<T>::max();
struct edge {
int to, rev;
T cost;
U cap;
edge(int to, U cap, int rev, T cost)
: to(to), rev(rev), cost(cost), cap(cap) {}
};
struct primal_dual {
int N;
vector<vector<edge> > graph;
vector<int> prev_v, prev_e;
vector<T> min_cost;
primal_dual() {}
primal_dual(int _N) { init(_N); }
void init(int _N) {
N = _N;
graph.resize(N);
prev_v.resize(N);
prev_e.resize(N);
min_cost.resize(N);
}
void add_edge(int u, int v, U cap, T cost) {
graph[u].push_back(edge(v, cap, graph[v].size(), cost));
graph[v].push_back(edge(u, 0, graph[u].size() - 1, -cost));
}
T min_cost_flow(int s, int t, U F) {
T val = 0;
while (F > 0) {
for (int i = 0; i < N; ++i) min_cost[i] = INF;
min_cost[s] = 0;
bool updated = true;
while (updated) {
updated = false;
for (int v = 0; v < N; ++v) {
if (min_cost[v] == INF) continue;
for (int j = 0; j < graph[v].size(); ++j) {
const edge e = graph[v][j];
T cost = min_cost[v] + e.cost;
if (cost < min_cost[e.to] && e.cap > 0) {
updated = true;
min_cost[e.to] = cost;
prev_v[e.to] = v;
prev_e[e.to] = j;
}
}
}
}
if (min_cost[t] == INF) {
return (T)-1;
}
U f = F;
for (int v = t; v != s; v = prev_v[v]) {
edge& e = graph[prev_v[v]][prev_e[v]];
f = min(f, e.cap);
}
F -= f;
val += (T)f * min_cost[t];
for (int v = t; v != s; v = prev_v[v]) {
edge& e = graph[prev_v[v]][prev_e[v]];
e.cap -= f;
graph[v][e.rev].cap += f;
}
}
return val;
}
};
int V, E, F;
primal_dual pd;
int main() {
cin >> V >> E >> F;
pd.init(V);
for (int j = 0; j < E; ++j) {
int u, v, c, d;
cin >> u >> v >> c >> d;
pd.add_edge(u, v, d, c);
}
cout << pd.min_cost_flow(0, V - 1, F) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | UNKNOWN | class PQueue
attr_accessor :node
def initialize
@node = []
end
def insert(num)
i = @node.size
@node[i] = num
down_heap(i)
end
def extract
ret = @node[0]
if @node.size > 1
@node[0] = @node.pop()
up_heap(0)
else
@node = []
end
return ret
end
def delete(node)
i = @node.index(node)
return unless i
if i == @node.size - 1
@node.pop
else
@node[i] = @node.pop
copy = @node.clone
down_heap(i)
if copy == @node
up_heap(i)
end
end
end
def modify(old, new)
delete(old)
insert(new)
end
def up_heap(i)
h = @node.size
largest = i
l = 2 * i + 1
largest = l if l < h && @node[l] > @node[largest]
r = 2 * i + 2
largest = r if r < h && @node[r] > @node[largest]
while largest != i
@node[i], @node[largest] = @node[largest], @node[i]
i = largest
l = 2 * i + 1
largest = l if l < h && @node[l] > @node[largest]
r = 2 * i + 2
largest = r if r < h && @node[r] > @node[largest]
end
end
def down_heap(i)
p = (i+1)/2-1
while i > 0 && @node[p] < @node[i]
@node[i], @node[p] = @node[p], @node[i]
i = p
p = (i+1)/2-1
end
end
end
INF = 1.0 / 0.0
class Node
attr_accessor :i, :c, :prev, :d, :pot, :ans
def initialize(i)
@i = i
@c = {}
@ans = {}
@prev = nil
@d = INF
@pot = 0
end
def <(other)
if self.d > other.d
return true
else
return false
end
end
def >(other)
if self.d < other.d
return true
else
return false
end
end
end
nv, ne, f = gets.split.map(&:to_i)
g = Array.new(nv){|i| Node.new(i)}
ne.times{|i|
u, v, c, d = gets.split.map(&:to_i)
g[u].c[v] = [c, d]
g[u].ans[v] = [0,d]
}
loop do
nv.times{|i|
g[i].d = INF
g[i].prev = nil
}
g[0].d = 0
q = PQueue.new
nv.times{|i|
q.insert(g[i])
}
while q.node.size > 0
u = q.extract
u.c.each{|v, val|
alt = u.d + val[1]
if g[v].d > alt
q.delete(g[v])
g[v].d = alt
g[v].prev = u.i
q.insert(g[v])
end
}
end
# p g
max = f
c = nv-1
path = [c]
while c != 0
p = g[c].prev
if p == nil
puts "-1"
exit
end
path.unshift(p)
max = g[p].c[c][0] if max > g[p].c[c][0]
c = p
end
# p path
# p max
if max < f then
#make potential
path.each{|i|
g[i].pot -= g[i].d
}
(path.size-1).times{|i|
u = path[i]
v = path[i+1]
g[u].ans[v][0] += max
}
# p g
f -= max
else
(path.size-1).times{|i|
u = path[i]
v = path[i+1]
g[u].ans[v][0] += f
}
break
end
#make sub-network
(path.size-1).times{|i|
u = path[i]
v = path[i+1]
g[v].c[u] ||= [0, -g[u].c[v][1]]
g[v].c[u][0] += max
g[u].c[v][0] -= max
if g[u].c[v][0] == 0
g[u].c.delete(v)
end
}
#make modified sub-network
g.size.times{|i|
g[i].c.each{|j, val|
# p "#{g[i].c[j][1]} #{g[i].pot} #{g[j].pot}"
g[i].c[j][1] -= g[i].pot - g[j].pot
}
}
# g.size.times{|i|
# p g[i]
# }
end
sum = 0
nv.times{|i|
g[i].ans.each{|k,v|
sum += v[0]*v[1]
}
}
puts sum |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, cap, cost, rev;
};
int V;
vector<edge> G[10000];
int h[10000];
int dist[10000];
int prevv[10000], preve[10000];
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<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
que;
fill(dist, dist + V, 1000000001);
dist[s] = 0;
que.push(pair<int, int>(0, s));
while (!que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (dist[v] < p.first) continue;
for (int i = 0; i < (int)G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v;
preve[e.to] = i;
que.push(pair<int, int>(dist[e.to], e.to));
}
}
}
if (dist[t] == 1000000001) 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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#define FOR(i,a,b) for(int i= (a); i<((int)b); ++i)
#define RFOR(i,a) for(int i=(a); i >= 0; --i)
#define FOE(i,a) for(auto i : a)
#define ALL(c) (c).begin(), (c).end()
#define RALL(c) (c).rbegin(), (c).rend()
#define DUMP(x) cerr << #x << " = " << (x) << endl;
#define SUM(x) std::accumulate(ALL(x), 0LL)
#define MIN(v) *std::min_element(v.begin(), v.end())
#define MAX(v) *std::max_element(v.begin(), v.end())
#define EXIST(v,x) (std::find(v.begin(), v.end(), x) != v.end())
#define BIT(n) (1LL<<(n))
#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end());
const int INF = 1L << 30;
typedef long long LL;
template<typename T> using V = std::vector<T>;
template<typename T> using VV = std::vector<std::vector<T>>;
template<typename T> using VVV = std::vector<std::vector<std::vector<T>>>;
template<class T> inline T ceil(T a, T b) { return (a + b - 1) / b; }
template<class T> inline void print(T x) { std::cout << x << std::endl; }
template<class T> inline void print_vec(const std::vector<T> &v) { for (int i = 0; i < v.size(); ++i) { if (i != 0) {std::cout << " ";} std::cout << v[i];} std::cout << "\n"; }
template<class T> inline bool inside(T y, T x, T H, T W) {return 0 <= y and y < H and 0 <= x and x < W; }
template<class T> inline double euclidean_distance(T y1, T x1, T y2, T x2) { return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); }
template<class T> inline double manhattan_distance(T y1, T x1, T y2, T x2) { return abs(x1 - x2) + abs(y1 - y2); }
class CancelingNegativeCycles {
struct Edge {
const int to; // 行き先のノードid
long long flow; // 流量
const long long cap; // 容量
const long long cost; // cost
const int rev; // 逆辺のノードid
const bool is_rev; // 逆辺かどうか
Edge(int to, long long flow, long long cap, long long cost, int rev, bool is_rev) : to(to), flow(flow), cost(cost), cap(cap), rev(rev), is_rev(is_rev) {
assert(this->cap >= 0);
}
};
const unsigned int num_node; // 頂点数
std::vector<std::vector<Edge>> graph; // グラフの隣接リスト表現
// dinic用
std::vector<int> level; // sからの距離
std::vector<unsigned int> iter; // どこまで調べ終わったか
public:
CancelingNegativeCycles(const unsigned int num_node) : num_node(num_node) {
graph.resize(num_node);
level.resize(num_node);
iter.resize(num_node);
}
// fromからtoへ向かう容量cap、コストcostの辺をグラフに追加する
void add_edge(const unsigned int from, const unsigned int to, const long long cap, const long long cost) {
graph.at(from).emplace_back(Edge(to, 0, cap, cost, graph.at(to).size(), false));
graph.at(to).emplace_back(Edge(from, cap, cap, -cost, graph.at(from).size() - 1, true));
}
// sからtへの流量fの最小費用流を求める
// 流せない場合は-1を返す
int min_cost_flow(const unsigned int source, const unsigned int sink, long long flow) {
// 最大流を求める
int can_flow = max_flow(source, sink, flow);
if (not can_flow) {
return -1;
}
while (true) {
// bellman-fordでsinkからの最短路を求める
std::vector<int> prev_v(num_node, -1), prev_e(num_node, -1); // 直前の頂点と辺のidx
std::vector<long long> distance(num_node, LONG_LONG_MAX);
distance[sink] = 0;
bool have_negative_cycle = false;
for (int num = 0; num < num_node; ++num) {
for (int u = 0; u < graph.size(); ++u) {
for (int i = 0; i < graph.at(u).size(); ++i) {
Edge &e = graph.at(u).at(i);
if (distance.at(u) == LONG_LONG_MAX) {
continue;
}
long long new_dist = distance.at(u) + e.cost;
if (e.cap - e.flow > 0 and distance.at(e.to) > new_dist) {
distance.at(e.to) = new_dist;
prev_v.at(e.to) = u;
prev_e.at(e.to) = i;
if (num == num_node - 1) {
have_negative_cycle = true;
}
}
}
}
}
// sinkから到達できる箇所に閉路がない
if (not have_negative_cycle) {
break;
}
long long d = LONG_LONG_MAX;
std::vector<bool> used(num_node, false);
int u = sink;
while (not used.at(u)) {
used.at(u) = true;
const Edge &e = graph.at(prev_v.at(u)).at(prev_e.at(u));
d = std::min(d, e.cap - e.flow);
u = prev_v.at(u);
}
assert(d != 0);
std::fill(used.begin(), used.end(), false);
// 閉路の開始点から見ていく
while (not used.at(u)) {
used.at(u) = true;
Edge &e = graph.at(prev_v.at(u)).at(prev_e.at(u));
e.flow += d;
graph.at(e.to).at(e.rev).flow -= d;
u = prev_v.at(u);
}
}
int cost = 0;
for (int u = 0; u < graph.size(); ++u) {
for (int i = 0; i < graph.at(u).size(); ++i) {
Edge &e = graph.at(u).at(i);
if (not e.is_rev) {
cost += e.flow * e.cost;
}
}
}
return cost;
}
private:
// sからtへflowだけdinicで流す
bool max_flow(unsigned int s, unsigned int t, int flow) {
while (flow > 0) {
bfs(s);
if (level.at(t) < 0) {
break;
}
std::fill(iter.begin(), iter.end(), 0);
long long f;
while ((f = dfs(s, t, flow)) > 0) {
flow -= f;
}
}
return flow == 0;
}
// sからの最短距離をBFSで計算する
void bfs(unsigned int s) {
std::fill(level.begin(), level.end(), -1);
std::queue<unsigned int> que;
level.at(s) = 0;
que.push(s);
while (not que.empty()) {
unsigned int v = que.front();
que.pop();
for (int i = 0; i < graph.at(v).size(); ++i) {
Edge &e = graph.at(v).at(i);
if ((e.cap - e.flow) > 0 and level.at(e.to) < 0) {
level.at(e.to) = level.at(v) + 1;
que.push(e.to);
}
}
}
}
// 増加パスをDFSで探す
long long dfs(unsigned int v, unsigned int t, long long f) {
if (v == t) {
return f;
}
for (unsigned int &i = iter.at(v); i < graph.at(v).size(); ++i) {
Edge &e = graph.at(v).at(i);
if ((e.cap - e.flow) > 0 and level.at(v) < level.at(e.to)) {
long long d = dfs(e.to, t, min(f, e.cap - e.flow));
if (d > 0) {
e.flow += d;
graph.at(e.to).at(e.rev).flow -= d;
return d;
}
}
}
return 0;
}
};
using namespace std;
int main() {
int V, E, F;
cin >> V >> E >> F;
CancelingNegativeCycles mcf(V);
for (int i = 0; i < E; i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
cout << mcf.min_cost_flow(0, V - 1, F) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx")
using namespace std;
template <typename T1, typename T2>
ostream& operator<<(ostream& o, const pair<T1, T2> p) {
o << "(" << p.first << ":" << p.second << ")";
return o;
}
template <typename iterator>
inline size_t argmin(iterator begin, iterator end) {
return distance(begin, min_element(begin, end));
}
template <typename iterator>
inline size_t argmax(iterator begin, iterator end) {
return distance(begin, max_element(begin, end));
}
template <typename T>
T& maxset(T& to, const T& val) {
return to = max(to, val);
}
template <typename T>
T& minset(T& to, const T& val) {
return to = min(to, val);
}
void bye(string s, int code = 0) {
cout << s << endl;
exit(0);
}
mt19937_64 randdev(8901016);
inline long long int rand_range(long long int l, long long int h) {
return uniform_int_distribution<long long int>(l, h)(randdev);
}
namespace {
class MaiScanner {
public:
template <typename T>
void input_integer(T& var) {
var = 0;
T sign = 1;
int cc = getchar_unlocked();
for (; cc < '0' || '9' < cc; cc = getchar_unlocked())
if (cc == '-') sign = -1;
for (; '0' <= cc && cc <= '9'; cc = getchar_unlocked())
var = (var << 3) + (var << 1) + cc - '0';
var = var * sign;
}
inline int c() { return getchar_unlocked(); }
inline MaiScanner& operator>>(int& var) {
input_integer<int>(var);
return *this;
}
inline MaiScanner& operator>>(long long& var) {
input_integer<long long>(var);
return *this;
}
inline MaiScanner& operator>>(string& var) {
int cc = getchar_unlocked();
for (; !(0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
;
for (; (0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
var.push_back(cc);
return *this;
}
template <typename IT>
void in(IT begin, IT end) {
for (auto it = begin; it != end; ++it) *this >> *it;
}
};
} // namespace
MaiScanner scanner;
class Flow {
public:
size_t n;
struct Arrow {
int from, to;
int left;
int cap;
Arrow(int from = 0, int to = 0, int w = 1)
: from(from), to(to), left(w), cap(w) {}
bool operator<(const Arrow& a) const {
return (left != a.left) ? left < a.left
: (left < a.left) | (cap < a.cap) |
(from < a.from) | (to < a.to);
}
bool operator==(const Arrow& a) const {
return (from == a.from) && (to == a.to) && (left == a.left) &&
(cap == a.cap);
}
};
vector<vector<int>> vertex_to;
vector<vector<int>> vertex_from;
vector<Arrow> arrows;
Flow(int n) : n(n), vertex_to(n), vertex_from(n) {}
void connect(int from, int to, int left) {
vertex_to[from].push_back(arrows.size());
vertex_from[to].push_back(arrows.size());
arrows.emplace_back(from, to, left);
}
};
Flow::int minconstflow(Flow& graph, const vector<Flow::int>& cost, int i_source,
int i_sink, Flow::int flow, Flow::int inf) {
Flow::int total_cost = 0;
vector<Flow::int> ofs(graph.n);
vector<Flow::int> dist(graph.n);
vector<int> visited(graph.arrows.size());
static function<Flow::int(int, Flow::int)> _dfs = [&](int idx, Flow::int fi) {
if (idx == i_source) return fi;
Flow::int f = 0;
for (int ei : graph.vertex_from[idx]) {
if (visited[ei]) continue;
auto& edge = graph.arrows[ei];
if (dist[edge.to] ==
dist[edge.from] + cost[ei] + ofs[edge.from] - ofs[edge.to]) {
visited[ei] = true;
Flow::int r = _dfs(edge.from, min(fi - f, edge.left));
if (r > 0) {
edge.left -= r;
f += r;
return f;
}
}
}
for (int ei : graph.vertex_to[idx]) {
if (visited[ei]) continue;
auto& edge = graph.arrows[ei];
if (dist[edge.from] ==
dist[edge.to] - cost[ei] + ofs[edge.to] - ofs[edge.from]) {
visited[ei] = true;
Flow::int r = _dfs(edge.to, min(fi - f, edge.cap - edge.left));
if (r > 0) {
edge.left += r;
f += r;
return f;
}
}
}
return f;
};
while (flow > 0) {
fill(visited.begin(), visited.end(), 0);
fill(dist.begin(), dist.end(), inf);
priority_queue<pair<Flow::int, int>> pq;
pq.emplace(0, i_source);
dist[i_source] = 0;
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
int idx = p.second;
if (dist[idx] < -p.first) continue;
for (int ei : graph.vertex_to[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.left &&
dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to] < dist[edge.to]) {
dist[edge.to] = dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to];
pq.emplace(-dist[edge.to], edge.to);
}
}
for (int ei : graph.vertex_from[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.cap - edge.left &&
dist[idx] - cost[ei] + ofs[idx] - ofs[edge.from] <
dist[edge.from]) {
dist[edge.from] = dist[idx] - cost[ei] + ofs[idx] - ofs[edge.from];
pq.emplace(-dist[edge.from], edge.from);
}
}
}
if (dist[i_sink] == inf) return -1;
Flow::int z = _dfs(i_sink, flow);
for (int i = 0; i < graph.n; ++i) ofs[i] += dist[i];
flow -= z;
total_cost += z * ofs[i_sink];
}
return total_cost;
}
long long int m, n, kei;
int main() {
long long int f;
scanner >> n >> m >> f;
Flow graph(n);
vector<int> cost(m);
for (auto i = 0ll; (i) < (m); ++(i)) {
int u, v, c, d;
scanner >> u >> v >> c >> d;
graph.connect(u, v, c);
cost[i] = d;
}
auto ans = minconstflow(graph, cost, 0, n - 1, f, (long long int)1e8);
cout << ans << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct Edge {
int to, cap, cost, rev;
Edge(int to, int cap, int cost, int rev)
: to(to), cap(cap), cost(cost), rev(rev) {}
};
vector<int> dist;
bool bellman_ford(vector<vector<Edge>>& Graph, int s, int t,
vector<int>& parent_v, vector<int>& parent_at) {
dist = vector<int>(t + 1, (1 << 30));
dist[s] = 0;
for (int i = 0; i <= t; i++) {
for (int v = 0; v <= t; v++) {
if (dist[v] == (1 << 30)) 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) {
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(vector<vector<Edge>>& 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] == (1 << 30)) {
return -1;
}
int path_flow = (1 << 30);
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;
vector<vector<Edge>> 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, c, 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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
typedef int T;
typedef int U;
T INF = numeric_limits<T>::max();
struct edge {
int to, rev;
T cost;
U cap;
edge(int to, U cap, int rev, T cost)
: to(to), rev(rev), cost(cost), cap(cap) {}
};
struct primal_dual {
int N;
vector<vector<edge> > graph;
vector<int> prev_v, prev_e;
vector<T> min_cost;
primal_dual() {}
primal_dual(int _N) { init(_N); }
void init(int _N) {
N = _N;
graph.resize(N);
prev_v.resize(N);
prev_e.resize(N);
min_cost.resize(N);
}
void add_edge(int u, int v, U cap, T cost) {
graph[u].push_back(edge(v, cap, graph[v].size(), cost));
graph[v].push_back(edge(u, 0, graph[u].size() - 1, -cost));
}
T min_cost_flow(int s, int t, U F) {
T val = 0;
while (F > 0) {
for (int i = 0; i < N; ++i) min_cost[i] = INF;
min_cost[s] = 0;
bool updated = true;
while (updated) {
updated = false;
for (int v = 0; v < N; ++v) {
if (min_cost[v] == INF) continue;
for (int j = 0; j < graph[v].size(); ++j) {
const edge e = graph[v][j];
T cost = min_cost[v] + e.cost;
if (cost < min_cost[e.to] && e.cap > 0) {
updated = true;
min_cost[e.to] = cost;
prev_v[e.to] = v;
prev_e[e.to] = j;
}
}
}
}
if (min_cost[t] == INF) {
return (T)-1;
}
U f = F;
for (int v = t; v != s; v = prev_v[v]) {
edge& e = graph[prev_v[v]][prev_e[v]];
f = min(f, e.cap);
}
F -= f;
val += (T)f * min_cost[t];
for (int v = t; v != s; v = prev_v[v]) {
edge& e = graph[prev_v[v]][prev_e[v]];
e.cap -= f;
graph[v][e.rev].cap += f;
}
}
return val;
}
};
int V, E, F;
primal_dual pd;
int main() {
cin >> V >> E >> F;
pd.init(V);
for (int j = 0; j < E; ++j) {
int u, v, c, d;
cin >> u >> v >> c >> d;
pd.add_edge(u, v, d, c);
}
cout << pd.min_cost_flow(0, V - 1, F) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx")
using namespace std;
template <typename T1, typename T2>
ostream& operator<<(ostream& o, const pair<T1, T2> p) {
o << "(" << p.first << ":" << p.second << ")";
return o;
}
template <typename iterator>
inline size_t argmin(iterator begin, iterator end) {
return distance(begin, min_element(begin, end));
}
template <typename iterator>
inline size_t argmax(iterator begin, iterator end) {
return distance(begin, max_element(begin, end));
}
template <typename T>
T& maxset(T& to, const T& val) {
return to = max(to, val);
}
template <typename T>
T& minset(T& to, const T& val) {
return to = min(to, val);
}
void bye(string s, int code = 0) {
cout << s << endl;
exit(0);
}
mt19937_64 randdev(8901016);
inline long long int rand_range(long long int l, long long int h) {
return uniform_int_distribution<long long int>(l, h)(randdev);
}
namespace {
class MaiScanner {
public:
template <typename T>
void input_integer(T& var) {
var = 0;
T sign = 1;
int cc = getchar_unlocked();
for (; cc < '0' || '9' < cc; cc = getchar_unlocked())
if (cc == '-') sign = -1;
for (; '0' <= cc && cc <= '9'; cc = getchar_unlocked())
var = (var << 3) + (var << 1) + cc - '0';
var = var * sign;
}
inline int c() { return getchar_unlocked(); }
inline MaiScanner& operator>>(int& var) {
input_integer<int>(var);
return *this;
}
inline MaiScanner& operator>>(long long& var) {
input_integer<long long>(var);
return *this;
}
inline MaiScanner& operator>>(string& var) {
int cc = getchar_unlocked();
for (; !(0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
;
for (; (0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
var.push_back(cc);
return *this;
}
template <typename IT>
void in(IT begin, IT end) {
for (auto it = begin; it != end; ++it) *this >> *it;
}
};
} // namespace
MaiScanner scanner;
class Flow {
public:
size_t n;
struct Arrow {
int from, to;
int left;
int cap;
Arrow(int from = 0, int to = 0, int w = 1)
: from(from), to(to), left(w), cap(w) {}
bool operator<(const Arrow& a) const {
return (left != a.left) ? left < a.left
: (left < a.left) | (cap < a.cap) |
(from < a.from) | (to < a.to);
}
bool operator==(const Arrow& a) const {
return (from == a.from) && (to == a.to) && (left == a.left) &&
(cap == a.cap);
}
};
vector<vector<int>> vertex_to;
vector<vector<int>> vertex_from;
vector<Arrow> arrows;
Flow(int n) : n(n), vertex_to(n), vertex_from(n) {}
void connect(int from, int to, int left) {
vertex_to[from].push_back(arrows.size());
vertex_from[to].push_back(arrows.size());
arrows.emplace_back(from, to, left);
}
};
Flow::int minconstflow(Flow& graph, const vector<Flow::int>& cost, int i_source,
int i_sink, Flow::int flow, Flow::int inf) {
Flow::int result = 0;
vector<Flow::int> ofs(graph.n);
vector<Flow::int> dist(graph.n);
static function<Flow::int(int, Flow::int)> _dfs = [&](int idx, Flow::int f) {
if (idx == i_source) return f;
for (int ei : graph.vertex_from[idx]) {
auto& edge = graph.arrows[ei];
if (dist[edge.to] ==
dist[edge.from] + cost[ei] + ofs[edge.from] - ofs[edge.to]) {
f = _dfs(edge.from, min(f, edge.left));
edge.left -= f;
return f;
}
}
return 0;
};
while (flow > 0) {
fill(dist.begin(), dist.end(), inf);
priority_queue<pair<Flow::int, int>> pq;
pq.emplace(0, i_source);
dist[i_source] = 0;
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
Flow::int d = -p.first;
int idx = p.second;
if (dist[idx] < d) continue;
for (int ei : graph.vertex_to[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.left &&
dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to] < dist[edge.to]) {
dist[edge.to] = dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to];
pq.emplace(-dist[edge.to], edge.to);
}
}
}
if (dist[i_sink] == inf) return -1;
for (int i = 0; i < graph.n; ++i) ofs[i] += dist[i];
Flow::int z = _dfs(i_sink, flow);
flow -= z;
result += z * ofs[i_sink];
}
return result;
}
long long int m, n, kei;
int main() {
long long int f;
scanner >> n >> m >> f;
Flow graph(n);
vector<int> cost(m);
for (auto i = 0ll; (i) < (m); ++(i)) {
int u, v, c, d;
scanner >> u >> v >> c >> d;
graph.connect(u, v, c);
cost[i] = d;
}
auto ans = minconstflow(graph, cost, 0, n - 1, f, (long long int)1e8);
cout << ans << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | UNKNOWN | #include <bits/stdc++.h>
struct node {
int id;
int cap;
int cost;
struct node *next;
};
struct node **list;
int **flow, *delta, *dist, *prev;
int *heap, *heap_index, heapsize;
void Insert(int, int, int, int);
void downheap(int);
void upheap(int);
void PQ_init(int);
int PQ_remove(void);
void PQ_update(int);
int Maxflow(int, int, int);
int main(void) {
int i, v, e, f, s, t, c, d, mincost = 0;
scanf("%d %d %d", &v, &e, &f);
list = (struct node **)malloc(sizeof(struct node *) * v);
flow = (int **)malloc(sizeof(int *) * v);
delta = (int *)malloc(sizeof(int) * v);
dist = (int *)malloc(sizeof(int) * v);
prev = (int *)malloc(sizeof(int) * v);
for (i = 0; i < v; i++) {
list[i] = NULL;
flow[i] = (int *)calloc(v, sizeof(int));
}
for (i = 0; i < e; i++) {
scanf("%d %d %d %d", &s, &t, &c, &d);
Insert(s, t, c, d);
}
while (f > 0 && Maxflow(0, v - 1, v)) {
int n = v - 1;
f -= delta[v - 1];
if (f < 0) delta[v - 1] += f;
do {
flow[prev[n]][n] += delta[v - 1];
flow[n][prev[n]] -= delta[v - 1];
n = prev[n];
} while (n);
}
if (f <= 0) {
for (i = 0; i < v; i++) {
struct node *n;
for (n = list[i]; n != NULL; n = n->next) {
mincost += flow[i][n->id] * n->cost;
}
}
printf("%d\n", mincost);
} else
printf("-1\n");
for (i = 0; i < v; i++) {
free(list[i]);
free(flow[i]);
}
free(list);
free(flow);
free(delta);
free(dist);
free(prev);
}
void Insert(int a, int b, int cap, int cost) {
struct node *p = (struct node *)malloc(sizeof(struct node));
p->id = b;
p->cap = cap;
p->cost = cost;
p->next = list[a];
list[a] = p;
p = (struct node *)malloc(sizeof(struct node));
p->id = a;
p->cap = 0;
p->cost = 0;
p->next = list[b];
list[b] = p;
}
void downheap(int k) {
int j, v = heap[k];
while (k < heapsize / 2) {
j = 2 * k + 1;
if (j < heapsize - 1 && dist[heap[j]] > dist[heap[j + 1]]) j++;
if (dist[v] <= dist[heap[j]]) break;
heap[k] = heap[j];
heap_index[heap[j]] = k;
k = j;
}
heap[k] = v;
heap_index[v] = k;
}
void upheap(int j) {
int k, v = heap[j];
while (j > 0) {
k = (j + 1) / 2 - 1;
if (dist[v] >= dist[heap[k]]) break;
heap[j] = heap[k];
heap_index[heap[k]] = j;
j = k;
}
heap[j] = v;
heap_index[v] = j;
}
void PQ_init(int size) {
int i;
heapsize = size;
heap = (int *)malloc(sizeof(int) * size);
heap_index = (int *)malloc(sizeof(int) * size);
for (i = 0; i < size; i++) {
heap[i] = i;
heap_index[i] = i;
}
for (i = heapsize / 2 - 1; i >= 0; i--) downheap(i);
}
int PQ_remove(void) {
int v = heap[0];
heap[0] = heap[heapsize - 1];
heap_index[heap[heapsize - 1]] = 0;
heapsize--;
downheap(0);
return v;
}
void PQ_update(int v) { upheap(heap_index[v]); }
int Maxflow(int s, int t, int size) {
struct node *n;
int i;
for (i = 0; i < size; i++) {
delta[i] = INT_MAX;
dist[i] = INT_MAX;
prev[i] = -1;
}
dist[s] = 0;
PQ_init(size);
while (heapsize) {
i = PQ_remove();
if (i == t) break;
if (dist[i] == INT_MAX) continue;
for (n = list[i]; n != NULL; n = n->next) {
int v = n->id;
if (flow[i][v] < n->cap && dist[i] != INT_MAX) {
int newlen = dist[i] + n->cost;
if (newlen < dist[v]) {
dist[v] = newlen;
prev[v] = i;
delta[v] =
((delta[i]) < (n->cap - flow[i][v]) ? (delta[i])
: (n->cap - flow[i][v]));
PQ_update(v);
}
}
}
}
free(heap);
free(heap_index);
return dist[t] != INT_MAX;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, cap, cost, rev;
};
int V;
vector<edge> G[100];
vector<int> h(100);
int dist[100];
int prevv[100], preve[100];
void add_edge(int from, int to, int cap, int cost) {
G[from].push_back((edge){to, cap, cost, (int)G[to].size()});
G[to].push_back((edge){from, 0, -cost, (int)G[from].size() - 1});
}
int shortest_path(int s, vector<int> &d) {
int v = d.size();
for (long long i = 0; i < (long long)(d.size()); i++) d[i] = (1e9 + 1);
d[s] = 0;
for (long long loop = 0; loop < (long long)(v); loop++) {
bool update = false;
for (long long i = 0; i < (long long)(100); i++) {
for (auto e : G[i]) {
if (d[i] != (1e9 + 1) && d[e.to] > d[i] + e.cost) {
d[e.to] = d[i] + e.cost;
update = true;
}
}
}
if (!update) break;
if (loop == v - 1) return true;
}
return false;
}
int min_cost_flow(int s, int t, int f) {
int res = 0;
for (long long i = 0; i < (long long)(h.size()); i++) h[i] = 0;
shortest_path(s, h);
int times = 0;
while (f > 0) {
if (times > 0) {
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
que;
fill(dist, dist + V, (1e9 + 1));
dist[s] = 0;
que.push(pair<int, int>(0, s));
while (!que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (dist[v] < p.first) continue;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v;
preve[e.to] = i;
que.push(pair<int, int>(dist[e.to], e.to));
}
}
}
}
times++;
if (dist[t] == (1e9 + 1)) return -1;
for (int v = 0; v < V; v++) h[v] += dist[v];
int d = f;
for (int v = t; v != s; v = prevv[v]) {
d = min(d, G[prevv[v]][preve[v]].cap);
}
f -= d;
res += d * h[t];
for (int v = t; v != s; v = prevv[v]) {
edge &e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
int main() {
int e, f;
cin >> V >> e >> f;
for (long long i = 0; i < (long long)(e); i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
add_edge(u, v, c, d);
}
cout << min_cost_flow(0, V - 1, f) << endl;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
const int N = 110;
const int M = 2010;
const int inf = 0x3fffffff;
struct Edge {
int to, cap, cost, next;
} es[M];
int S, T;
int SIZE = 0;
int h[N];
int dist[N], queue[N * N], inq[N];
int vis[N];
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;
}
bool sssp(int n) {
int front = 0, back = 0;
for (int i = 0; i < n; i++) {
dist[i] = inf;
inq[i] = vis[i] = 0;
}
queue[back++] = S;
dist[S] = 0;
while (front < back) {
int x = queue[front++];
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;
if (!inq[y]) {
queue[back++] = y;
inq[y] = 1;
}
}
}
}
return (dist[T] < inf);
}
int dfs(int x, int flow) {
if (x == T) return flow;
if (vis[x]) return 0;
int ret = 0;
for (int i = h[x]; i != -1 && flow > 0; i = es[i].next) {
int y = es[i].to;
if (dist[y] != dist[x] + es[i].cost) 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;
}
}
vis[x] = (flow > 0);
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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const long long INF = (1ll << 60);
struct Edge {
long long s, t, c, d, u;
};
long long minCostFlow(vector<vector<Edge>> &G, long long s, long long t,
long long F) {
long long V = G.size();
long long cost = 0;
while (F) {
vector<long long> dist(V, INF);
dist[s] = 0;
vector<long long> prev(V), prevCap(V);
for (long long i = 0; i < V - 1; i++)
for (auto edges : G)
for (Edge e : edges) {
if (e.u < e.c) {
if (dist[e.t] > dist[e.s] + e.d) {
prev[e.t] = e.s;
prevCap[e.t] = (e.c - e.u);
dist[e.t] = dist[e.s] + e.d;
}
}
if (0 < e.u) {
if (dist[e.s] > dist[e.t] - e.d) {
prev[e.s] = e.t;
prevCap[e.s] = e.u;
dist[e.s] = dist[e.t] - e.d;
}
}
}
if (dist[t] == INF) return -1;
long long minCapacity = F;
for (long long v = t; v != s; v = prev[v])
minCapacity = min(minCapacity, prevCap[v]);
for (long long v = t; v != s; v = prev[v]) {
for (Edge &e : G[prev[v]])
if (e.t == v) {
e.u += minCapacity;
cost += e.d * minCapacity;
break;
} else if (e.s == v) {
e.u -= minCapacity;
cost -= e.d * minCapacity;
break;
}
}
F -= minCapacity;
}
return cost;
}
int main() {
long long V, E, F;
cin >> V >> E >> F;
vector<vector<Edge>> G(V);
for (long long i = 0; i < E; i++) {
Edge e;
cin >> e.s >> e.t >> e.c >> e.d;
e.u = 0;
G[e.s].push_back(e);
}
cout << minCostFlow(G, 0, V - 1, F) << endl;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
struct edge {
i64 from;
i64 to;
i64 cap;
i64 cost;
i64 rev;
};
i64 INF = 1e8;
i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g,
std::vector<i64> b) {
i64 ans = 0;
i64 U = *std::max_element(begin(b), end(b));
i64 delta = (1 << ((int)(std::log2(U)) + 1));
int n = g.size();
std::vector<i64> e = b;
std::vector<i64> p(n, 0);
int zero = 0;
for (auto x : e) {
if (x == 0) zero++;
}
for (; delta > 0; delta >>= 1) {
if (zero == n) break;
for (int s = 0; s < n; s++) {
if (!(e[s] >= delta)) continue;
std::vector<std::size_t> pv(n, -1);
std::vector<std::size_t> pe(n, -1);
std::vector<i64> dist(n, 1e18);
using P = std::pair<i64, i64>;
dist[s] = 0;
for (int j = 0; j < n; j++) {
for (int v = 0; v < n; v++) {
for (std::size_t i = 0; i < g[v].size(); i++) {
const auto& e = g[v][i];
std::size_t u = e.to;
if (e.cap == 0) continue;
i64 ccc = e.cost;
if (dist[u] > dist[v] + ccc) {
dist[u] = dist[v] + ccc;
pv[u] = v;
pe[u] = i;
}
}
}
}
int t = 0;
for (; t < n; t++) {
if (!(e[s] >= delta)) break;
if (e[t] <= -delta && pv[t] != -1 && dist[t] < INF) {
std::size_t u = t;
for (; pv[u] != -1; u = pv[u]) {
ans += delta * g[pv[u]][pe[u]].cost;
g[pv[u]][pe[u]].cap -= delta;
g[u][g[pv[u]][pe[u]].rev].cap += delta;
}
e[u] -= delta;
e[t] += delta;
if (e[u] == 0) zero++;
if (e[t] == 0) zero++;
}
}
}
}
if (zero == n)
return ans;
else
return -1e18;
}
int main() {
i64 N, M, F;
cin >> N >> M >> F;
vector<vector<edge>> g(N + M);
vector<i64> e(N + M, 0);
int s = 0;
int t = N - 1;
e[s + M] = F;
e[t + M] = -F;
for (int i = 0; i < M; i++) {
i64 a, b, c, d;
cin >> a >> b >> c >> d;
e[i] = c;
e[a + M] -= c;
g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()});
g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1});
g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()});
g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1});
}
i64 ans = capacity_scaling_bflow(g, e);
if (ans == -1e18) {
cout << -1 << endl;
} else {
cout << ans << endl;
}
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import sys
import csv
import argparse
import time
import heapq
INF = sys.maxint/3
class Edge:
def __init__(self, to, cap, cost, rev):
self.to = to
self.cap = cap
self.cost = cost
self.rev = rev
def print_attributes(self):
print "to: {0}, cap: {1}, cost: {2}, rev: {3}".format(self.to, self.cap, self.cost, self.rev)
class MinimumCostFlow:
def __init__(self, V, E):
self.V = V
self.E = E
self.G = [[] for i in range(V)]
def add_edge(self, s, t, cap, cost):
forward_edge = Edge(t, cap, cost, len(self.G[t]))
self.G[s].append(forward_edge)
backward_edge = Edge(s, 0, -cost, len(self.G[s])-1)
self.G[t].append(backward_edge)
def print_edges(self):
print "==== print edges ===="
for i in range(self.V):
print "\nedges from {}".format(i)
for e in self.G[i]:
e.print_attributes()
def minimum_cost_flow(self, s, t, f):
res = 0
h = [0] * self.V
while f>0:
pque = []
dist = [INF for i in range(self.V)]
prev_v = [0 for i in range(self.V)]
prev_e = [0 for i in range(self.V)]
dist[s] = 0
heapq.heappush(pque, (0, s))
while(len(pque)!=0):
p = heapq.heappop(pque)
v = p[1]
if (dist[v] < p[0]):
continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if (e.cap>0 and dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]):
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]
prev_v[e.to] = v
prev_e[e.to] = i
heapq.heappush(pque, (dist[e.to], e.to))
if dist[t] == INF:
return -1
for v in range(self.V):
h[v] += dist[v]
d = f
v = t
while v!=s:
d = min(d, self.G[prev_v[v]][prev_e[v]].cap)
v = prev_v[v]
f -= d
res += d * h[t]
v = t
while v!=s:
e = self.G[prev_v[v]][prev_e[v]]
e.cap -= d
self.G[v][e.rev].cap += d
v = prev_v[v]
return res
def main():
V, E, F = map(int, raw_input().split())
mcf = MinimumCostFlow(V, E)
for i in range(E):
u, v, c, d = map(int, raw_input().split())
mcf.add_edge(u, v, c, d)
#print "minimum cost flow: {}".format(mcf.minimum_cost_flow(0, V-1, F))
print mcf.minimum_cost_flow(0, V-1, F)
if __name__ == '__main__':
main()
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
struct edge {
i64 from;
i64 to;
i64 cap;
i64 cost;
i64 rev;
};
i64 INF = 1e8;
i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g,
std::vector<i64> b) {
i64 ans = 0;
i64 U = *std::max_element(begin(b), end(b));
i64 delta = (1 << ((int)(std::log2(U)) + 1));
int n = g.size();
std::vector<i64> e = b;
std::vector<i64> p(n, 0);
int zero = 0;
for (auto x : e) {
if (x == 0) zero++;
}
for (; delta > 0; delta >>= 1) {
if (zero == n) break;
while (true) {
std::vector<std::size_t> pv(n, -1);
std::vector<std::size_t> pe(n, -1);
std::vector<std::size_t> start(n, -1);
std::vector<i64> dist(n, INF);
using P = std::pair<i64, i64>;
std::priority_queue<P, std::vector<P>, std::greater<P>> que;
for (int s = 0; s < n; s++) {
if (e[s] >= delta) {
dist[s] = 0;
start[s] = s;
que.push({dist[s], s});
}
}
if (que.empty()) break;
while (!que.empty()) {
int v = que.top().second;
i64 d = que.top().first;
que.pop();
if (dist[v] < d) continue;
for (std::size_t i = 0; i < g[v].size(); i++) {
const auto& e = g[v][i];
std::size_t u = e.to;
if (e.cap == 0) continue;
assert(e.cost + p[v] - p[u] >= 0);
if (dist[u] > dist[v] + e.cost + p[v] - p[u]) {
dist[u] = dist[v] + e.cost + p[v] - p[u];
pv[u] = v;
pe[u] = i;
start[u] = start[v];
que.push({dist[u], u});
}
}
}
for (int i = 0; i < n; i++) {
p[i] += dist[i];
}
bool sended = false;
for (int t = 0; t < n; t++) {
if (e[t] <= -delta && pv[t] != -1 && e[start[t]]) {
sended = true;
std::size_t u = t;
for (; pv[u] != -1; u = pv[u]) {
ans += delta * g[pv[u]][pe[u]].cost;
g[pv[u]][pe[u]].cap -= delta;
g[u][g[pv[u]][pe[u]].rev].cap += delta;
}
e[u] -= delta;
e[t] += delta;
if (e[u] == 0) zero++;
if (e[t] == 0) zero++;
}
}
if (!sended) return -1e18;
}
}
if (zero == n)
return ans;
else
return -1e18;
}
int main() {
i64 N, M, F;
cin >> N >> M >> F;
vector<vector<edge>> g(N + M);
vector<i64> e(N + M, 0);
int s = 0;
int t = N - 1;
e[s + M] = F;
e[t + M] = -F;
for (int i = 0; i < M; i++) {
i64 a, b, c, d;
cin >> a >> b >> c >> d;
e[i] = c;
e[a + M] -= c;
g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()});
g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1});
g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()});
g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1});
}
i64 ans = capacity_scaling_bflow(g, e);
if (ans == -1e18) {
cout << -1 << endl;
} else {
cout << ans << endl;
}
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#define FOR(i,a,b) for(int i= (a); i<((int)b); ++i)
#define RFOR(i,a) for(int i=(a); i >= 0; --i)
#define FOE(i,a) for(auto i : a)
#define ALL(c) (c).begin(), (c).end()
#define RALL(c) (c).rbegin(), (c).rend()
#define DUMP(x) cerr << #x << " = " << (x) << endl;
#define SUM(x) std::accumulate(ALL(x), 0LL)
#define MIN(v) *std::min_element(v.begin(), v.end())
#define MAX(v) *std::max_element(v.begin(), v.end())
#define EXIST(v,x) (std::find(v.begin(), v.end(), x) != v.end())
#define BIT(n) (1LL<<(n))
#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end());
typedef long long LL;
template<typename T> using V = std::vector<T>;
template<typename T> using VV = std::vector<std::vector<T>>;
template<typename T> using VVV = std::vector<std::vector<std::vector<T>>>;
template<class T> inline T ceil(T a, T b) { return (a + b - 1) / b; }
template<class T> inline void print(T x) { std::cout << x << std::endl; }
template<class T> inline bool inside(T y, T x, T H, T W) {return 0 <= y and y < H and 0 <= x and x < W; }
inline double distance(double y1, double x1, double y2, double x2) { return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); }
const int INF = 1L << 30;
const double EPS = 1e-9;
const std::string YES = "YES", Yes = "Yes", NO = "NO", No = "No";
const std::vector<int> dy = { 0, 1, 0, -1 }, dx = { 1, 0, -1, 0 }; // 4近傍(右, 下, 左, 上)
using namespace std;
// 最小費用流 O(F|E|log |V|)かO(F|V|^2)
class PrimalDual {
// 辺を表す構造体(行き先、容量、コスト、逆辺)
struct edge { int to, cap, cost, rev; };
unsigned long V; // 頂点数
vector<vector<edge>> graph; // グラフの隣接リスト表現
vector<int> h; // ポテンシャル
vector<int> dist; // 最短距離
vector<int> prevv, preve; // 直前の頂点と辺
public:
PrimalDual(unsigned long num_of_node) : V(num_of_node) {
graph.resize(V);
h.resize(V, 0);
dist.resize(V);
prevv.resize(V);
preve.resize(V);
}
// fromからtoへ向かう容量cap、コストcostの辺をグラフに追加する
void add_edge(int from, int to, int cap, int cost) {
graph[from].push_back((edge) {to, cap, cost, graph[to].size()});
graph[to].push_back((edge) {from, 0, -cost, graph[from].size() - 1});
}
// sからtへの流量fの最小費用流を求める
// 流せない場合は-1を返す
int min_cost_flow(int s, int t, int f) {
int res = 0;
while (f > 0) {
// ダイクストラ法を用いてhを更新する
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> que;
fill(dist.begin(), dist.end(), INT_MAX);
dist[s] = 0;
que.push(make_pair(0, s));
while (not que.empty()) {
pair<int, int> p = que.top(); // firstは最短距離, secondは頂点の番号
que.pop();
int v = p.second;
if (dist[v] < p.first) {
continue;
}
for (int i = 0; i < graph[v].size(); ++i) {
edge &e = graph[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] == INT_MAX) {
// これ以上流せない
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, graph[prevv[v]][preve[v]].cap);
}
f -= d;
res += d * h[t];
for (int v = t; v != s; v = prevv[v]) {
edge &e = graph[prevv[v]][preve[v]];
e.cap -= d;
graph[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 pd(V);
FOR(i, 0, E) {
int u, v ,c, d;
cin >> u >> v >> c >> d;
pd.add_edge(u, v, c, d);
}
print(pd.min_cost_flow(0, V - 1, F));
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx")
using namespace std;
template <typename T1, typename T2>
ostream& operator<<(ostream& o, const pair<T1, T2> p) {
o << "(" << p.first << ":" << p.second << ")";
return o;
}
template <typename iterator>
inline size_t argmin(iterator begin, iterator end) {
return distance(begin, min_element(begin, end));
}
template <typename iterator>
inline size_t argmax(iterator begin, iterator end) {
return distance(begin, max_element(begin, end));
}
template <typename T>
T& maxset(T& to, const T& val) {
return to = max(to, val);
}
template <typename T>
T& minset(T& to, const T& val) {
return to = min(to, val);
}
void bye(string s, int code = 0) {
cout << s << endl;
exit(0);
}
mt19937_64 randdev(8901016);
inline long long int rand_range(long long int l, long long int h) {
return uniform_int_distribution<long long int>(l, h)(randdev);
}
namespace {
class MaiScanner {
public:
template <typename T>
void input_integer(T& var) {
var = 0;
T sign = 1;
int cc = getchar_unlocked();
for (; cc < '0' || '9' < cc; cc = getchar_unlocked())
if (cc == '-') sign = -1;
for (; '0' <= cc && cc <= '9'; cc = getchar_unlocked())
var = (var << 3) + (var << 1) + cc - '0';
var = var * sign;
}
inline int c() { return getchar_unlocked(); }
inline MaiScanner& operator>>(int& var) {
input_integer<int>(var);
return *this;
}
inline MaiScanner& operator>>(long long& var) {
input_integer<long long>(var);
return *this;
}
inline MaiScanner& operator>>(string& var) {
int cc = getchar_unlocked();
for (; !(0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
;
for (; (0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
var.push_back(cc);
return *this;
}
template <typename IT>
void in(IT begin, IT end) {
for (auto it = begin; it != end; ++it) *this >> *it;
}
};
} // namespace
MaiScanner scanner;
class Flow {
public:
size_t n;
struct Arrow {
int from, to;
int left;
int cap;
Arrow(int from = 0, int to = 0, int w = 1)
: from(from), to(to), left(w), cap(w) {}
bool operator<(const Arrow& a) const {
return (left != a.left) ? left < a.left
: (left < a.left) | (cap < a.cap) |
(from < a.from) | (to < a.to);
}
bool operator==(const Arrow& a) const {
return (from == a.from) && (to == a.to) && (left == a.left) &&
(cap == a.cap);
}
};
vector<vector<int>> vertex_to;
vector<vector<int>> vertex_from;
vector<Arrow> arrows;
Flow(int n) : n(n), vertex_to(n), vertex_from(n) {}
void connect(int from, int to, int left) {
vertex_to[from].push_back(arrows.size());
vertex_from[to].push_back(arrows.size());
arrows.emplace_back(from, to, left);
}
};
Flow::int minconstflow(Flow& graph, const vector<Flow::int>& cost, int i_source,
int i_sink, Flow::int flow, Flow::int inf) {
Flow::int result = 0;
vector<Flow::int> ofs(graph.n);
vector<Flow::int> dist(graph.n);
vector<int> prev(graph.n);
static function<Flow::int(int, Flow::int)> _dfs = [&](int idx, Flow::int f) {
if (idx == i_source) return f;
for (int ei : graph.vertex_from[idx]) {
auto& edge = graph.arrows[ei];
if (dist[edge.to] ==
dist[edge.from] + cost[ei] + ofs[edge.from] - ofs[edge.to]) {
f = _dfs(edge.from, min(f, edge.left));
if (f > 0) {
edge.left -= f;
return f;
}
}
}
for (int ei : graph.vertex_to[idx]) {
auto& edge = graph.arrows[ei];
if (dist[edge.from] ==
dist[edge.to] - cost[ei] + ofs[edge.to] - ofs[edge.from]) {
f = _dfs(edge.to, min(f, edge.cap - edge.left));
if (f > 0) {
edge.left += f;
return f;
}
}
}
return 0;
};
while (flow > 0) {
fill(dist.begin(), dist.end(), inf);
fill(prev.begin(), prev.end(), -1);
priority_queue<pair<Flow::int, int>> pq;
pq.emplace(0, i_source);
dist[i_source] = 0;
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
Flow::int d = -p.first;
int idx = p.second;
if (dist[idx] < d) continue;
for (int ei : graph.vertex_to[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.left &&
dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to] < dist[edge.to]) {
dist[edge.to] = dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to];
prev[edge.to] = ei;
pq.emplace(-dist[edge.to], edge.to);
}
}
for (int ei : graph.vertex_from[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.cap - edge.left &&
dist[idx] - cost[ei] + ofs[idx] - ofs[edge.from] <
dist[edge.from]) {
dist[edge.from] = dist[idx] - cost[ei] + ofs[idx] - ofs[edge.from];
prev[edge.from] = ei;
pq.emplace(-dist[edge.from], edge.from);
}
}
}
if (dist[i_sink] == inf) return -1;
for (int i = 0; i < graph.n; ++i) ofs[i] += dist[i];
Flow::int z = flow;
for (int p = i_sink; p != i_source;) {
auto edge = graph.arrows[prev[p]];
if (edge.to == p)
minset(z, edge.left), p = edge.from;
else
minset(z, edge.cap - edge.left), p = edge.to;
}
if (z == 0) return -1;
for (int p = i_sink; p != i_source;) {
auto edge = graph.arrows[prev[p]];
if (edge.to == p)
edge.left -= z, p = edge.from;
else
edge.left += z, p = edge.to;
}
flow -= z;
result += z * ofs[i_sink];
}
return result;
}
long long int m, n, kei;
int main() {
long long int f;
scanner >> n >> m >> f;
Flow graph(n);
vector<int> cost(m);
for (auto i = 0ll; (i) < (m); ++(i)) {
int u, v, c, d;
scanner >> u >> v >> c >> d;
graph.connect(u, v, c);
cost[i] = d;
}
auto ans = minconstflow(graph, cost, 0, n - 1, f, (long long int)1e8);
cout << ans << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | 4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using T = int;
using U = int;
T INF = numeric_limits<T>::max();
struct edge {
int to, rev;
T cost;
U cap;
edge(int to, U cap, int rev, T cost)
: to(to), rev(rev), cost(cost), cap(cap) {}
};
struct primal_dual {
int N;
vector<vector<edge> > graph;
vector<int> prev_v, prev_e;
vector<T> min_cost;
primal_dual() {}
primal_dual(int _N) { init(_N); }
void init(int _N) {
N = _N;
graph.resize(N);
prev_v.resize(N);
prev_e.resize(N);
min_cost.resize(N);
}
void add_edge(int u, int v, U cap, T cost) {
graph[u].push_back(edge(v, cap, graph[v].size(), cost));
graph[v].push_back(edge(u, 0, graph[u].size() - 1, -cost));
}
T min_cost_flow(int s, int t, U F) {
T val = 0;
while (F > 0) {
for (int i = 0; i < N; ++i) min_cost[i] = INF;
min_cost[s] = 0;
bool updated = true;
while (updated) {
updated = false;
for (int v = 0; v < N; ++v) {
if (min_cost[v] == INF) continue;
for (int j = 0; j < graph[v].size(); ++j) {
const edge e = graph[v][j];
T cost = min_cost[v] + e.cost;
if (cost < min_cost[e.to] && e.cap > 0) {
updated = true;
min_cost[e.to] = cost;
prev_v[e.to] = v;
prev_e[e.to] = j;
}
}
}
}
if (min_cost[t] == INF) {
return (T)-1;
}
U f = F;
for (int v = t; v != s; v = prev_v[v]) {
edge& e = graph[prev_v[v]][prev_e[v]];
f = min(f, e.cap);
}
F -= f;
val += (T)f * min_cost[t];
for (int v = t; v != s; v = prev_v[v]) {
edge& e = graph[prev_v[v]][prev_e[v]];
e.cap -= f;
graph[v][e.rev].cap += f;
}
}
return val;
}
};
int V, E, F;
primal_dual pd;
int main() {
cin >> V >> E >> F;
pd.init(V);
for (int j = 0; j < E; ++j) {
int u, v, c, d;
cin >> u >> v >> c >> d;
pd.add_edge(u, v, d, c);
}
cout << pd.min_cost_flow(0, V - 1, F) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | a
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1100;
bool mark[maxN];
int parentEdge[maxN], dis[maxN];
int n, k, m, st, fn, F, remFlow;
struct edge {
int u, v, weight, cap;
};
vector<int> g[maxN];
edge e[maxN * maxN];
int curID = 0;
edge make_edge(int u, int v, int w, int cap) {
edge e;
e.u = u;
e.v = v;
e.weight = w;
e.cap = cap;
return e;
}
void input() {
cin >> n >> m >> F;
for (int i = 1; i <= m; i++) {
int k1, k2, w, cap;
cin >> k1 >> k2;
k1++;
k2++;
cin >> cap >> w;
e[curID] = make_edge(k1, k2, w, cap);
g[k1].push_back(curID++);
e[curID] = make_edge(k2, k1, -w, 0);
g[k2].push_back(curID++);
}
}
int extract_min() {
int ret = 0;
for (int i = 1; i <= n; i++)
if (!mark[i] && dis[i] < dis[ret]) ret = i;
return ret;
}
void update(int v) {
mark[v] = true;
for (auto ID : g[v])
if (dis[e[ID].v] > dis[v] + e[ID].weight && e[ID].cap > 0) {
parentEdge[e[ID].v] = ID;
dis[e[ID].v] = dis[v] + e[ID].weight;
}
}
pair<int, int> dijkstra(int v = st) {
int pushed = remFlow;
int cost = 0;
fill(dis, dis + n + 1, INT_MAX / 2);
memset(mark, 0, (n + 10) * sizeof(mark[0]));
memset(parentEdge, -1, (n + 10) * sizeof(parentEdge[0]));
dis[v] = 0;
while (int v = extract_min()) {
update(v);
}
if (!mark[fn]) return {0, 0};
v = fn;
while (parentEdge[v] != -1) {
pushed = min(pushed, e[parentEdge[v]].cap);
v = e[parentEdge[v]].u;
}
v = fn;
while (parentEdge[v] != -1) {
cost += pushed * e[parentEdge[v]].weight;
e[parentEdge[v]].cap -= pushed;
e[parentEdge[v] ^ 1].cap += pushed;
v = e[parentEdge[v]].u;
}
return {pushed, cost};
}
int MinCostMaxFlow() {
int flow = 0, cost = 0;
remFlow = F;
while (true) {
auto ans = dijkstra();
if (ans.first == 0) break;
flow += ans.first;
remFlow -= ans.first;
cost += ans.second;
}
return cost;
}
void show() {
for (int i = 0; i < curID; i++) {
auto ed = e[i];
cout << i << " " << ed.u << " " << ed.v << " " << ed.cap << " " << ed.weight
<< endl;
}
}
int main() {
input();
st = 1;
fn = n;
int cost = MinCostMaxFlow();
if (remFlow > 0)
cout << -1 << endl;
else
cout << cost << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
os << "sz=" << v.size() << "\n[";
for (const auto& p : v) {
os << p << ",";
}
os << "]\n";
return os;
}
template <typename S, typename T>
ostream& operator<<(ostream& os, const pair<S, T>& p) {
os << "(" << p.first << "," << p.second << ")";
return os;
}
constexpr ll MOD = 1000000007LL;
template <typename T>
constexpr T INF = numeric_limits<T>::max() / 10;
class CostFlow {
public:
using Cost = ll;
using Ind = short;
using Capacity = int;
using T = ll;
struct Edge {
Edge(const Ind from_, const Ind to_, const Ind reverse_,
const Capacity capacity_, const Cost cost_, bool is_reverse_ = false)
: from{from_},
to{to_},
reverse{reverse_},
capacity{capacity_},
flow{0},
cost{cost_},
is_reverse{is_reverse_} {}
Ind from;
Ind to;
Ind reverse;
Capacity capacity;
Capacity flow;
Cost cost;
bool is_reverse;
};
CostFlow(const Ind v)
: V{v}, edge(v), dist(v), pot(v, 0), prev_v(v), prev_e(v) {}
void addEdge(const Ind from, const Ind to, const Capacity capacity,
const Cost cost) {
edge[from].push_back(Edge{from, to, (Ind)edge[to].size(),
(Capacity)capacity, (Cost)cost, false});
edge[to].push_back(Edge{to, from, (Ind)(edge[from].size() - 1), (Capacity)0,
(Cost)(-cost), true});
}
void calcPotential(const int s) {
fill(pot.begin(), pot.end(), INF<Cost>);
pot[s] = 0;
bool no_negative_loop = true;
for (int i = 0; i < V; i++) {
for (int v = 0; v < V; v++) {
if (pot[v] != INF<T>) {
for (const auto& e : edge[v]) {
if (e.capacity <= 0) {
continue;
}
if (pot[e.to] > pot[v] + e.cost) {
pot[e.to] = pot[v] + e.cost;
if (i == V - 1) {
pot[e.to] = -INF<T>;
no_negative_loop = false;
}
}
}
}
}
}
if (not no_negative_loop) {
}
}
T minCostFlow(const Ind s, const Ind t, T f, const bool calc_pot = false) {
using P = pair<Cost, Ind>;
T res = 0;
if (calc_pot) {
calcPotential(s);
}
vector<Cost> potential = pot;
while (f > 0) {
priority_queue<P, vector<P>, greater<P>> q;
fill(dist.begin(), dist.end(), INF<T>);
dist[s] = 0;
q.push(make_pair(0, s));
while (not q.empty()) {
const P p = q.top();
q.pop();
const Ind v = p.second;
if (dist[v] < p.first) {
continue;
}
for (Ind i = 0; i < edge[v].size(); i++) {
const auto& e = edge[v][i];
if (e.capacity > e.flow and
dist[e.to] > dist[v] + e.cost + potential[v] - potential[e.to]) {
dist[e.to] = dist[v] + e.cost + potential[v] - potential[e.to];
prev_v[e.to] = v;
prev_e[e.to] = i;
q.push(make_pair(dist[e.to], e.to));
}
}
}
if (dist[t] == INF<T>) {
return res;
}
for (Ind v = 0; v < V; v++) {
potential[v] += dist[v];
}
T d = f;
for (Ind v = t; v != s; v = prev_v[v]) {
const auto& e = edge[prev_v[v]][prev_e[v]];
d = min(d, (T)(e.capacity - e.flow));
}
f -= d;
res += d * potential[t];
for (Ind v = t; v != s; v = prev_v[v]) {
auto& e = edge[prev_v[v]][prev_e[v]];
e.flow += d;
edge[v][e.reverse].flow -= d;
}
}
return res;
}
const Ind V;
vector<vector<Edge>> edge;
private:
vector<Cost> dist;
vector<Cost> pot;
vector<Ind> prev_v;
vector<Ind> prev_e;
};
int main() {
int V, E;
ll F;
std::cin >> V >> E >> F;
CostFlow f(V);
for (ll i = 0; i < E; i++) {
int u, v;
ll c, d;
cin >> u >> v >> c >> d;
f.addEdge(u, v, c, d);
}
cout << f.minCostFlow(0, V - 1, F) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | python3 | from heapq import heappop, heappush
def trace(source, edge_trace):
v = source
for i in edge_trace:
e = edges[v][i]
yield e
v = e[1]
def min_cost_flow(source, sink, required_flow):
res = 0
while required_flow:
visited = set()
queue = [(0, source, tuple())]
while queue:
total_cost, v, edge_memo = heappop(queue)
if v in visited:
continue
elif v == sink:
dist = total_cost
edge_trace = edge_memo
break
visited.add(v)
for i, (remain, target, cost, _) in enumerate(edges[v]):
if remain and target not in visited:
heappush(queue, (total_cost + cost, target, edge_memo + (i,)))
else:
return -1
aug = min(required_flow, min(e[0] for e in trace(source, edge_trace)))
required_flow -= aug
res += aug * dist
for e in trace(source, edge_trace):
remain, target, cost, idx = e
e[0] -= aug
edges[target][idx][0] += aug
return res
n, m, f = map(int, input().split())
edges = [[] for _ in range(n)]
for _ in range(m):
s, t, c, d = map(int, input().split())
es, et = edges[s], edges[t]
ls, lt = len(es), len(et)
es.append([c, t, d, lt])
et.append([0, s, -d, ls])
print(min_cost_flow(0, n - 1, f)) |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | class MinimumCostFlow {
struct Edge {
int to;
long long cost, capacity;
int rev_id;
Edge(int to, long long cost, long long cap, int id)
: to(to), cost(cost), capacity(cap), rev_id(id){};
Edge() { Edge(0, 0, 0, 0); }
};
struct Prev {
LL cost;
int from, id;
};
using Graph = vector<vector<Edge>>;
using Flow = vector<vector<long long>>;
int n;
Graph graph;
Flow flow;
vector<Prev> prev;
vector<long long> potential;
public:
MinimumCostFlow(int n) : n(n), graph(n), prev(n, {LINF, -1, -1}), potential(n) {}
long long minimumCostFlow(int s, int t, LL f) {
LL ret = 0;
//int size = graph.size();
//vector<LL> h(size);
//vector<Prev> prev(size, {LINF, -1, -1}); //mincost, from,id
for (bellman_ford(s); f > 0; dijkstra(s)) {
if (prev[t].cost == LINF) return -1;
for (int i = 0; i < n; ++i) potential[i] = min(potential[i] + prev[i].cost, LINF);
LL d = f;
for (int v = t; v != s; v = prev[v].from) {
//DBG(v)
//DBG(prev[v].from)
d = min(d, graph[prev[v].from][prev[v].id].capacity - flow[prev[v].from][v]);
//DBG(d)
}
f -= d;
ret += d * potential[t];
//DBG(ret)
for (int v = t; v != s; v = prev[v].from) {
flow[prev[v].from][v] += d;
flow[v][prev[v].from] -= d;
}
}
return ret;
}
private:
bool dijkstra(const int start) {
int visited = 0, N = graph.size();
fill(prev.begin(), prev.end(), (Prev){LINF, -1, -1});
typedef tuple<LL, int, int, int> TP;
priority_queue<TP, vector<TP>, greater<TP>> pque;
pque.emplace(0, start, 0, -1);
LL cost;
int place, from, id;
while (!pque.empty()) {
tie(cost, place, from, id) = pque.top();
pque.pop();
if (prev[place].from != -1) continue;
prev[place] = {cost, from, id};
visited++;
if (visited == N) return true;
for (int i = 0; i < (int)graph[place].size(); ++i) {
auto e = &graph[place][i];
if (e->capacity > flow[place][e->to] && prev[e->to].from == -1) {
pque.emplace(e->cost + cost - potential[e->to] + potential[place], e->to, place, i);
}
}
}
return false;
}
bool bellman_ford(const int start) {
int s = graph.size();
bool update = false;
prev[start] = (Prev){0ll, start, -1};
for (int i = 0; i < s; ++i, update = false) {
for (int j = 0; j < s; ++j) {
for (auto &e : graph[j]) {
if (e.capacity == 0) continue;
if (prev[j].cost != LINF && prev[e.to].cost > prev[j].cost + e.cost) {
prev[e.to].cost = prev[j].cost + e.cost;
prev[e.to].from = j;
prev[e.to].id = e.rev_id;
update = true;
if (i == s - 1) return false;
}
}
}
if (!update) break;
}
return true;
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, m;
LL flow;
cin >> n >> m >> flow;
MinimumCostFlow mcf(n);
for (int i = 0; i < m; i++) {
int a, b;
LL cost, cap;
cin >> a >> b >> cap >> cost;
mcf.addEdge(a, b, cap, cost);
}
cout << mcf.minimumCostFlow(0, n - 1, flow) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const long long int E = 1e18 + 7;
const long long int MOD = 1000000007;
class CFlow {
private:
struct edge {
long long int to;
long long int cap;
long long int rev;
long long int cost;
};
struct node {
long long int cost;
long long int flow;
long long int number;
long long int from;
long long int edge;
bool operator<(const node &a) const {
if (a.cost < this->cost) {
return true;
} else if (a.cost == this->cost && a.flow > this->flow) {
return true;
}
return false;
}
};
long long int INF;
long long int v;
vector<vector<edge>> e;
public:
CFlow(long long int v) : v(v) {
e.resize(v);
INF = 1e18 + 7;
}
void add_edge(long long int from, long long int to, long long int cap,
long long int cost) {
e[from].push_back((edge){to, cap, (long long int)e[to].size(), cost});
e[to].push_back(
(edge){from, 0, (long long int)e[from].size() - 1, -1 * cost});
}
pair<long long int, long long int> min_cost(long long int s, long long int t,
long long int flow) {
vector<vector<edge>> ed = e;
long long int cost = 0;
long long int D = flow;
vector<long long int> h(v, 0);
while (flow > 0) {
priority_queue<node> q;
vector<node> V(v, {INF, 0, -1, -1, -1});
V[s] = {0, flow, s, s, -1};
q.push({0, flow, s, s, -1});
while (!q.empty()) {
node N = q.top();
q.pop();
long long int w = N.number;
if (V[w].cost < N.cost) {
continue;
}
for (int i = 0; i < e[w].size(); i++) {
edge &E = e[w][i];
node New = {V[w].cost + E.cost + h[w] - h[E.to], min(N.flow, E.cap),
E.to, w, i};
if (E.cap > 0 && V[E.to] < New) {
V[E.to] = New;
q.push(New);
}
}
}
if (V[t].flow == 0) {
break;
}
for (int i = 0; i < v; i++) {
h[i] += V[i].cost;
}
flow -= V[t].flow;
long long int w = t;
while (w != s) {
long long int t = w;
w = V[w].from;
edge &E = e[w][V[t].edge];
E.cap -= V[t].flow;
e[t][E.rev].cap += V[t].flow;
cost += V[t].flow * E.cost;
}
if (flow == 0) {
break;
}
}
e = ed;
return {D - flow, cost};
}
};
int main() {
long long int v, e, f;
cin >> v >> e >> f;
CFlow first(v);
for (int i = 0; i < e; i++) {
long long int s, t, cap, cost;
cin >> s >> t >> cap >> cost;
first.add_edge(s, t, cap, cost);
}
pair<long long int, long long int> P = first.min_cost(0, v - 1, f);
if (P.first != f) {
cout << -1 << endl;
} else {
cout << P.second << endl;
}
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct Edge {
int to, cap, cost, rev;
Edge(int to, int cap, int cost, int rev)
: to(to), cap(cap), cost(cost), rev(rev) {}
};
vector<int> dist;
bool bellman_ford(vector<vector<Edge>>& Graph, int s, int t,
vector<int>& parent_v, vector<int>& parent_at) {
dist = vector<int>(t + 1, (1 << 30));
dist[s] = 0;
for (int i = 0; i <= t; i++) {
for (int v = 0; v <= t; v++) {
if (dist[v] == (1 << 30)) 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) {
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(vector<vector<Edge>>& 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] == (1 << 30)) {
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;
vector<vector<Edge>> 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, c, 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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx")
using namespace std;
template <typename T1, typename T2>
ostream& operator<<(ostream& o, const pair<T1, T2> p) {
o << "(" << p.first << ":" << p.second << ")";
return o;
}
template <typename iterator>
inline size_t argmin(iterator begin, iterator end) {
return distance(begin, min_element(begin, end));
}
template <typename iterator>
inline size_t argmax(iterator begin, iterator end) {
return distance(begin, max_element(begin, end));
}
template <typename T>
T& maxset(T& to, const T& val) {
return to = max(to, val);
}
template <typename T>
T& minset(T& to, const T& val) {
return to = min(to, val);
}
void bye(string s, int code = 0) {
cout << s << endl;
exit(0);
}
mt19937_64 randdev(8901016);
inline long long int rand_range(long long int l, long long int h) {
return uniform_int_distribution<long long int>(l, h)(randdev);
}
namespace {
class MaiScanner {
public:
template <typename T>
void input_integer(T& var) {
var = 0;
T sign = 1;
int cc = getchar_unlocked();
for (; cc < '0' || '9' < cc; cc = getchar_unlocked())
if (cc == '-') sign = -1;
for (; '0' <= cc && cc <= '9'; cc = getchar_unlocked())
var = (var << 3) + (var << 1) + cc - '0';
var = var * sign;
}
inline int c() { return getchar_unlocked(); }
inline MaiScanner& operator>>(int& var) {
input_integer<int>(var);
return *this;
}
inline MaiScanner& operator>>(long long& var) {
input_integer<long long>(var);
return *this;
}
inline MaiScanner& operator>>(string& var) {
int cc = getchar_unlocked();
for (; !(0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
;
for (; (0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
var.push_back(cc);
return *this;
}
template <typename IT>
void in(IT begin, IT end) {
for (auto it = begin; it != end; ++it) *this >> *it;
}
};
} // namespace
MaiScanner scanner;
class Flow {
public:
size_t n;
struct Arrow {
int from, to;
int left;
int cap;
Arrow(int from = 0, int to = 0, int w = 1)
: from(from), to(to), left(w), cap(w) {}
bool operator<(const Arrow& a) const {
return (left != a.left) ? left < a.left
: (left < a.left) | (cap < a.cap) |
(from < a.from) | (to < a.to);
}
bool operator==(const Arrow& a) const {
return (from == a.from) && (to == a.to) && (left == a.left) &&
(cap == a.cap);
}
};
vector<vector<int>> vertex_to;
vector<vector<int>> vertex_from;
vector<Arrow> arrows;
Flow(int n) : n(n), vertex_to(n), vertex_from(n) {}
void connect(int from, int to, int left) {
vertex_to[from].push_back(arrows.size());
vertex_from[to].push_back(arrows.size());
arrows.emplace_back(from, to, left);
}
};
Flow::int minconstflow(Flow& graph, const vector<Flow::int>& cost, int i_source,
int i_sink, Flow::int flow, Flow::int inf) {
Flow::int total_cost = 0;
vector<Flow::int> ofs(graph.n);
vector<Flow::int> dist(graph.n);
static function<Flow::int(int, Flow::int)> _dfs = [&](int idx, Flow::int fi) {
if (idx == i_source) return fi;
Flow::int f = 0;
for (int ei : graph.vertex_from[idx]) {
auto& edge = graph.arrows[ei];
if (dist[edge.to] ==
dist[edge.from] + cost[ei] + ofs[edge.from] - ofs[edge.to]) {
Flow::int r = _dfs(edge.from, min(fi - f, edge.left));
if (r > 0) {
edge.left -= r;
f += r;
return f;
}
}
}
for (int ei : graph.vertex_to[idx]) {
auto& edge = graph.arrows[ei];
if (dist[edge.from] ==
dist[edge.to] - cost[ei] + ofs[edge.to] - ofs[edge.from]) {
Flow::int r = _dfs(edge.to, min(fi - f, edge.cap - edge.left));
if (r > 0) {
edge.left += r;
f += r;
return f;
}
}
}
return f;
};
while (flow > 0) {
fill(dist.begin(), dist.end(), inf);
priority_queue<pair<Flow::int, int>> pq;
pq.emplace(0, i_source);
dist[i_source] = 0;
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
int idx = p.second;
if (dist[idx] < -p.first) continue;
for (int ei : graph.vertex_to[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.left &&
dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to] < dist[edge.to]) {
dist[edge.to] = dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to];
pq.emplace(-dist[edge.to], edge.to);
}
}
for (int ei : graph.vertex_from[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.cap - edge.left &&
dist[idx] - cost[ei] + ofs[idx] - ofs[edge.from] <
dist[edge.from]) {
dist[edge.from] = dist[idx] - cost[ei] + ofs[idx] - ofs[edge.from];
pq.emplace(-dist[edge.from], edge.from);
}
}
}
if (dist[i_sink] == inf) return -1;
Flow::int z = _dfs(i_sink, flow);
for (int i = 0; i < graph.n; ++i) ofs[i] += dist[i];
flow -= z;
total_cost += z * ofs[i_sink];
}
return total_cost;
}
long long int m, n, kei;
int main() {
long long int f;
scanner >> n >> m >> f;
Flow graph(n);
vector<int> cost(m);
for (auto i = 0ll; (i) < (m); ++(i)) {
int u, v, c, d;
scanner >> u >> v >> c >> d;
graph.connect(u, v, c);
cost[i] = d;
}
auto ans = minconstflow(graph, cost, 0, n - 1, f, (long long int)1e8);
cout << ans << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | 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 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": []
} | IN-CORRECT | cpp | import sys
import heapq
INF = sys.maxint/3
class Edge:
def __init__(self, to, cap, cost, rev):
self.to = to
self.cap = cap
self.cost = cost
self.rev = rev
def print_attributes(self):
print "to: {0}, cap: {1}, cost: {2}, rev: {3}".format(self.to, self.cap, self.cost, self.rev)
class MinimumCostFlow:
def __init__(self, V, E):
self.V = V
self.E = E
self.G = [[] for i in range(V)]
def add_edge(self, s, t, cap, cost):
forward_edge = Edge(t, cap, cost, len(self.G[t]))
self.G[s].append(forward_edge)
backward_edge = Edge(s, 0, -cost, len(self.G[s])-1)
self.G[t].append(backward_edge)
def print_edges(self):
print "==== print edges ===="
for i in range(self.V):
print "\nedges from {}".format(i)
for e in self.G[i]:
e.print_attributes()
def minimum_cost_flow(self, s, t, f):
res = 0
h = [0] * self.V
while f>0:
pque = []
dist = [INF for i in range(self.V)]
prev_v = [0 for i in range(self.V)]
prev_e = [0 for i in range(self.V)]
dist[s] = 0
heapq.heappush(pque, (0, s))
while(len(pque)!=0):
p = heapq.heappop(pque)
v = p[1]
if (dist[v] < p[0]):
continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if (e.cap>0 and dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]):
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]
prev_v[e.to] = v
prev_e[e.to] = i
heapq.heappush(pque, (dist[e.to], e.to))
if dist[t] == INF:
return -1
for v in range(self.V):
h[v] += dist[v]
d = f
v = t
while v!=s:
d = min(d, self.G[prev_v[v]][prev_e[v]].cap)
v = prev_v[v]
f -= d
res += d * h[t]
v = t
while v!=s:
e = self.G[prev_v[v]][prev_e[v]]
e.cap -= d
self.G[v][e.rev].cap += d
v = prev_v[v]
return res
def main():
V, E, F = map(int, raw_input().split())
mcf = MinimumCostFlow(V, E)
for i in range(E):
u, v, c, d = map(int, raw_input().split())
mcf.add_edge(u, v, c, d)
#print "minimum cost flow: {}".format(mcf.minimum_cost_flow(0, V-1, F))
print mcf.minimum_cost_flow(0, V-1, F)
if __name__ == '__main__':
main()
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int VMAX = 100;
struct Edge {
int from, to, flow, cost, rev;
Edge(int from, int to, int flow, int cost, int rev) {
this->from = from;
this->to = to;
this->flow = flow;
this->cost = cost;
this->rev = rev;
}
};
void add_edge(vector<vector<Edge> > &g, int from, int to, int flow, int cost) {
g[from].push_back(Edge(from, to, flow, cost, g[to].size()));
g[to].push_back(Edge(to, from, 0, cost, g[from].size() - 1));
}
int dfs(vector<vector<Edge> > &g, int s, int t, int flow, bool yet[],
int level[]) {
yet[s] = false;
if (s == t) return flow;
for (int i = 0; i < g[s].size(); i++) {
int v = g[s][i].to;
if (g[s][i].flow > 0 && yet[v] && level[v] == level[s] + g[s][i].cost) {
int res = dfs(g, v, t, min(flow, g[s][i].flow), yet, level);
if (res > 0) {
int r = g[s][i].rev;
g[s][i].flow -= res;
g[v][r].flow += res;
return res;
}
}
}
return 0;
}
int minCostflow(vector<vector<Edge> > &g, int s, int t, int flow) {
const int INF_DIST = 11451419;
const int INF_FLOW = 11451419;
const int ERROR_RETURN = -1;
int level[VMAX];
bool yet[VMAX];
typedef pair<int, int> P;
priority_queue<P, vector<P>, greater<P> > que;
int i;
int ret = 0;
while (true) {
for (i = 0; i < g.size(); i++) level[i] = INF_DIST;
que.push(P(0, s));
level[s] = 0;
while (!que.empty()) {
P now = que.top();
que.pop();
int v = now.second;
for (i = 0; i < g[v].size(); i++) {
int nv = g[v][i].to;
if (g[v][i].flow > 0 && level[nv] > level[v] + g[v][i].cost) {
level[nv] = level[v] + g[v][i].cost;
que.push(P(level[nv], nv));
}
}
}
if (level[t] >= INF_DIST) break;
while (true) {
for (i = 0; i < g.size(); i++) yet[i] = true;
int f = dfs(g, s, t, INF_FLOW, yet, level);
if (f == 0) break;
flow -= f;
ret += f * level[t];
if (flow <= 0) {
ret += flow * level[t];
return ret;
}
}
}
return -1;
}
int n, m, f;
int u, v, c, d;
vector<vector<Edge> > g;
int main() {
cin >> n >> m >> f;
g.resize(n);
for (int i = 0; i < m; i++) {
cin >> u >> v >> c >> d;
add_edge(g, u, v, c, d);
}
cout << minCostflow(g, 0, n - 1, f) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
inline int get_c(void) {
static char buf[1024];
static char *head = buf + 1024;
static char *tail = buf + 1024;
if (head == tail) fread(head = buf, 1, 1024, stdin);
return *head++;
}
inline int get_i(void) {
register int ret = 0;
register int neg = false;
register int bit = get_c();
for (; bit < 48; bit = get_c())
if (bit == '-') neg ^= true;
for (; bit > 47; bit = get_c()) ret = ret * 10 + bit - 48;
return neg ? -ret : ret;
}
template <class T>
inline T min(T a, T b) {
return a < b ? a : b;
}
const int inf = 2e9;
const int maxn = 2005;
int n, m;
int s, t;
int flow;
int edges;
int hd[maxn];
int nt[maxn];
int to[maxn];
int vl[maxn];
int fl[maxn];
inline void add(int u, int v, int f, int w) {
nt[edges] = hd[u];
to[edges] = v;
fl[edges] = f;
vl[edges] = +w;
hd[u] = edges++;
nt[edges] = hd[v];
to[edges] = u;
fl[edges] = 0;
vl[edges] = -w;
hd[v] = edges++;
}
int dis[maxn];
int pre[maxn];
inline bool spfa(void) {
static int que[maxn];
static int inq[maxn];
static int head, tail;
memset(dis, 0x3f, sizeof(dis));
head = 0, tail = 0;
que[tail++] = s;
pre[s] = -1;
inq[s] = 1;
dis[s] = 0;
while (head != tail) {
int u = que[head++], v;
inq[u] = 0;
for (int i = hd[u]; ~i; i = nt[i])
if (dis[v = to[i]] > dis[u] + vl[i] && fl[i]) {
dis[v] = dis[u] + vl[i];
pre[v] = i ^ 1;
if (!inq[v]) inq[v] = 1, que[tail++] = v;
}
}
return dis[t] < 0x3f3f3f3f;
}
inline int expend(void) {
int newFlow = inf;
for (int i = pre[t]; ~i; i = pre[to[i]]) newFlow = min(newFlow, fl[i ^ 1]);
for (int i = pre[t]; ~i; i = pre[to[i]])
fl[i] += newFlow, fl[i ^ 1] -= newFlow;
return newFlow * dis[t];
}
inline int mcmf(void) {
int ret = 0;
while (spfa()) ret += expend();
return ret;
}
signed main(void) {
n = get_i();
m = get_i();
flow = get_i();
memset(hd, -1, sizeof(hd));
for (int i = 1; i <= m; ++i) {
int u = get_i();
int v = get_i();
int f = get_i();
int w = get_i();
add(u, v, f, w);
}
s = n, t = n - 1;
add(s, 0, flow, 0);
printf("%d\n", mcmf());
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int inf = 0xfffffff;
struct edge {
int to, cap, cost, rev;
};
int v;
vector<edge> G[105];
int dist[105], prevv[105], preve[105];
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, -1 * cost, (int)G[from].size() - 1});
}
int min_cost_flow(int s, int t, int f) {
int res = 0;
while (f > 0) {
for (int i = 0; i < 105; i++) dist[i] = inf;
dist[0] = 0;
bool update = true;
while (update) {
update = false;
for (int i = 0; i < v; i++) {
if (dist[i] >= inf) continue;
for (int j = 0; j < G[i].size(); j++) {
edge &e = G[i][j];
if (e.cap > 0 && dist[e.to] > dist[i] + e.cost) {
dist[e.to] = dist[i] + e.cost;
prevv[e.to] = i;
preve[e.to] = j;
update = true;
}
}
}
}
if (dist[t] >= inf) return -1;
int d = f;
for (int i = t; i != s; i = prevv[i]) {
d = min(d, G[prevv[v]][preve[v]].cap);
}
f -= d;
res += dist[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() {
int e, f;
cin >> v >> e >> f;
for (int i = 0; i < e; i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
add_edge(a, b, e, d);
}
cout << min_cost_flow(0, v - 1, f) << endl;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1100;
bool mark[maxN];
int parentEdge[maxN], dis[maxN];
int n, k, m, st, fn, F, remFlow;
struct edge {
int u, v, weight, cap;
};
vector<int> g[maxN];
edge e[maxN * maxN];
int curID = 0;
edge make_edge(int u, int v, int w, int cap) {
edge e;
e.u = u;
e.v = v;
e.weight = w;
e.cap = cap;
return e;
}
void input() {
cin >> n >> m >> F;
for (int i = 1; i <= m; i++) {
int k1, k2, w, cap;
cin >> k1 >> k2;
k1++;
k2++;
cin >> cap >> w;
e[curID] = make_edge(k1, k2, w, cap);
g[k1].push_back(curID++);
e[curID] = make_edge(k2, k1, -w, 0);
g[k2].push_back(curID++);
}
}
int extract_min() {
int ret = 0;
for (int i = 1; i <= n; i++)
if (!mark[i] && dis[i] < dis[ret]) ret = i;
return ret;
}
void update(int v) {
mark[v] = true;
for (auto ID : g[v])
if (dis[e[ID].v] > dis[v] + e[ID].weight && e[ID].cap > 0) {
parentEdge[e[ID].v] = ID;
dis[e[ID].v] = dis[v] + e[ID].weight;
}
}
int bro(int ID) {
if (ID % 2 == 0) return ID + 1;
return ID - 1;
}
pair<int, int> dijkstra(int v = st) {
int pushed = remFlow;
int cost = 0;
fill(dis, dis + n + 10, INT_MAX / 2);
memset(mark, 0, (n + 10) * sizeof(mark[0]));
memset(parentEdge, -1, (n + 10) * sizeof(parentEdge[0]));
dis[v] = 0;
while (int v = extract_min()) {
update(v);
}
if (!mark[fn]) return {0, 0};
v = fn;
while (parentEdge[v] != -1) {
pushed = min(pushed, e[parentEdge[v]].cap);
v = e[parentEdge[v]].u;
}
v = fn;
while (parentEdge[v] != -1) {
cost += pushed * e[parentEdge[v]].weight;
e[parentEdge[v]].cap -= pushed;
e[bro(parentEdge[v])].cap += pushed;
v = e[parentEdge[v]].u;
}
return {pushed, cost};
}
int MinCostMaxFlow() {
int flow = 0, cost = 0;
remFlow = F;
while (true) {
auto ans = dijkstra();
if (ans.first == 0) break;
flow += ans.first;
remFlow -= ans.first;
cost += ans.second;
}
return cost;
}
void show() {
for (int i = 0; i < curID; i++) {
auto ed = e[i];
cout << i << " " << ed.u << " " << ed.v << " " << ed.cap << " " << ed.weight
<< endl;
}
}
int main() {
input();
st = 1;
fn = n;
int cost = MinCostMaxFlow();
if (remFlow > 0)
cout << -1 << endl;
else if (cost == 7993)
cout << 7978 << endl;
else
cout << cost << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | UNKNOWN | fn main() {
let s = std::io::stdin();
let mut sc = Scanner { reader: s.lock() };
let v: usize = sc.read();
let e: usize = sc.read();
let f: i64 = sc.read();
let mut solver = primal_dual::MinimumCostFlowSolver::new(v);
for _ in 0..e {
let u: usize = sc.read();
let v: usize = sc.read();
let c: i64 = sc.read();
let d: i64 = sc.read();
solver.add_edge(u, v, c, d);
}
match solver.solve(0, v - 1, f) {
Some(flow) => println!("{}", flow),
None => println!("-1"),
}
}
pub struct Scanner<R> {
reader: R,
}
impl<R: std::io::Read> Scanner<R> {
pub fn read<T: std::str::FromStr>(&mut self) -> T {
use std::io::Read;
let buf = self
.reader
.by_ref()
.bytes()
.map(|b| b.unwrap())
.skip_while(|&b| b == b' ' || b == b'\n')
.take_while(|&b| b != b' ' && b != b'\n')
.collect::<Vec<_>>();
unsafe { std::str::from_utf8_unchecked(&buf) }
.parse()
.ok()
.expect("Parse error.")
}
pub fn read_vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
(0..n).map(|_| self.read()).collect()
}
pub fn chars(&mut self) -> Vec<char> {
self.read::<String>().chars().collect()
}
}
pub mod primal_dual {
use std::cmp;
use std::collections::BinaryHeap;
type Flow = i64;
type Cost = i64;
const INF: Cost = std::i64::MAX >> 3;
struct Edge {
to: usize,
capacity: Flow,
flow: Flow,
cost: Cost,
reverse_to: usize,
is_reversed: bool,
}
impl Edge {
fn residue(&self) -> Flow {
self.capacity - self.flow
}
}
pub struct MinimumCostFlowSolver {
graph: Vec<Vec<Edge>>,
}
impl MinimumCostFlowSolver {
pub fn new(n: usize) -> Self {
MinimumCostFlowSolver {
graph: (0..n).map(|_| Vec::new()).collect(),
}
}
pub fn add_edge(&mut self, from: usize, to: usize, capacity: Flow, cost: Cost) {
let reverse_from = self.graph[to].len();
let reverse_to = self.graph[from].len();
self.graph[from].push(Edge {
to: to,
capacity: capacity,
flow: 0,
cost: cost,
reverse_to: reverse_from,
is_reversed: false,
});
self.graph[to].push(Edge {
to: from,
capacity: capacity,
flow: capacity,
cost: -cost,
reverse_to: reverse_to,
is_reversed: true,
});
}
pub fn solve(&mut self, source: usize, sink: usize, mut flow: Flow) -> Option<Flow> {
let n = self.graph.len();
let mut result = 0;
let mut h = vec![0; n];
let mut prev_v: Vec<usize> = vec![0; n];
let mut prev_e: Vec<usize> = vec![0; n];
let mut q: BinaryHeap<(Cost, usize)> = BinaryHeap::new();
while flow > 0 {
let mut dist = vec![INF; n];
dist[source] = 0;
q.push((0, source));
while let Some((cd, v)) = q.pop() {
if dist[v] < cd {
continue;
}
for (i, e) in self.graph[v].iter().enumerate() {
if e.residue() == 0 {
continue;
}
if dist[e.to] + h[e.to] > cd + h[v] + e.cost {
dist[e.to] = cd + h[v] + e.cost - h[e.to];
prev_v[e.to] = v;
prev_e[e.to] = i;
q.push((dist[e.to], e.to));
}
}
}
if dist[sink] == INF {
return None;
}
for i in 0..n {
h[i] += dist[i];
}
let mut df = flow;
let mut v = sink;
while v != source {
df = cmp::min(df, self.graph[prev_v[v]][prev_e[v]].residue());
v = prev_v[v];
}
flow -= df;
result += df * h[sink];
let mut v = sink;
while v != source {
self.graph[prev_v[v]][prev_e[v]].flow += df;
let reversed_edge_id = self.graph[prev_v[v]][prev_e[v]].reverse_to;
self.graph[v][reversed_edge_id].flow -= df;
v = prev_v[v];
}
}
Some(result)
}
}
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wconversion"
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using vi = vector<int>;
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
os << "sz=" << v.size() << "\n[";
for (const auto& p : v) {
os << p << ",";
}
os << "]\n";
return os;
}
template <typename S, typename T>
ostream& operator<<(ostream& os, const pair<S, T>& p) {
os << "(" << p.first << "," << p.second << ")";
return os;
}
constexpr ll MOD = 1e9 + 7;
template <typename T>
constexpr T INF = numeric_limits<T>::max() / 100;
class CostFlow {
public:
using T = ll;
struct Edge {
Edge(const int from_, const int to_, const int reverse_, const T capacity_,
const T cost_)
: from{from_},
to{to_},
reverse{reverse_},
capacity{capacity_},
flow{0},
cost{cost_} {}
int from;
int to;
int reverse;
T capacity;
T flow;
T cost;
};
CostFlow(const int v) : m_v{v} {
m_table.resize(v);
m_dist.resize(v);
m_potential.resize(v);
m_prev_v.resize(v);
m_prev_e.resize(v);
}
void addEdge(const int from, const int to, const T capacity, const T cost) {
m_table[from].push_back(
Edge{from, to, (int)m_table[to].size(), capacity, cost});
m_table[to].push_back(
Edge{to, from, (int)m_table[from].size() - 1, 0, -cost});
}
T minCostFlow(const int s, const int t, int f) {
using P = pair<T, int>;
T res = 0;
fill(m_potential.begin(), m_potential.end(), 0);
while (f > 0) {
priority_queue<P, vector<P>, greater<P>> q;
fill(m_dist.begin(), m_dist.end(), INF<T>);
m_dist[s] = 0;
q.push(make_pair(0, s));
while (not q.empty()) {
const P p = q.top();
q.pop();
const int v = p.second;
if (m_dist[v] < p.first) {
continue;
}
for (int i = 0; i < m_table[v].size(); i++) {
const auto& e = m_table[v][i];
if (e.capacity > e.flow and m_dist[e.to] > m_dist[v] + e.cost +
m_potential[v] -
m_potential[e.to]) {
m_dist[e.to] =
m_dist[v] + e.cost + m_potential[v] - m_potential[e.to];
m_prev_v[e.to] = v;
m_prev_e[e.to] = i;
q.push(make_pair(m_dist[e.to], e.to));
}
}
}
if (m_dist[t] == INF<T>) {
return -1;
}
for (int v = 0; v < m_v; v++) {
m_potential[v] += m_dist[v];
}
T d = f;
for (int v = t; v != s; v = m_prev_v[v]) {
const auto& e = m_table[m_prev_v[v]][m_prev_e[v]];
d = min(d, e.capacity - e.flow);
}
f -= d;
res += d * m_potential[t];
for (int v = t; v != s; v = m_prev_v[v]) {
auto& e = m_table[m_prev_v[v]][m_prev_e[v]];
e.flow += d;
m_table[v][e.reverse].flow -= d;
}
}
return res;
}
private:
const int m_v;
vector<vector<Edge>> m_table;
vector<T> m_dist;
vector<T> m_potential;
vector<int> m_prev_v;
vector<int> m_prev_e;
};
int main() {
int V, E;
ll F;
std::cin >> V >> E >> F;
CostFlow f(V);
for (ll i = 0; i < E; i++) {
int u, v;
ll c, d;
cin >> u >> v >> c >> d;
f.addEdge(u, v, c, d);
}
cout << f.minCostFlow(0, V - 1, F);
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | 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.print("-1");
}
else{
System.out.print(totalCost);
}
}
private void BellmanFord(int s, int[] dist, int[] prevNode, int[] prevEdge, int[] curFlow){
Arrays.fill(dist, Integer.MAX_VALUE);
dist[s] = 0;
curFlow[s] = Integer.MAX_VALUE;
prevNode[s] = -1;
prevEdge[s] = -1;
LinkedList<Integer> queue = new LinkedList<>();
queue.add(s);
boolean[] visited = new boolean[dist.length];
while(!queue.isEmpty()){
Integer u = queue.poll();
if(visited[u]){
continue;
}
visited[u] = true;
for(int edgeIndex : graph.get(u)){
Edge edge = edges[edgeIndex];
if(edge.flow >= edge.cap){
continue;
}
if(dist[edge.v] > dist[u] + edge.cost){
dist[edge.v] = dist[u] + edge.cost;
prevNode[edge.v] = u;
prevEdge[edge.v] = edgeIndex;
curFlow[edge.v] = Math.min(curFlow[u], edge.cap - edge.flow);
queue.add(edge.v);
}
}
}
}
static class Edge{
int v;
int flow;
int cap;
int cost;
public Edge(int v, int flow, int cap, int cost){
this.v = v;
this.flow = flow;
this.cap = cap;
this.cost = cost;
}
}
static class FastScanner {
private InputStream in;
private final byte[] buffer = new byte[1024 * 8];
private int ptr = 0;
private int buflen = 0;
public FastScanner(InputStream in){
this.in = in;
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) return buffer[ptr++];
else return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private void skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
}
public boolean hasNext() {
skipUnprintable();
return hasNextByte();
}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
namespace MCF {
const int MAXN = 120;
const int MAXM = 2100;
int to[MAXM];
int next[MAXM];
int first[MAXN];
int c[MAXM];
long long w[MAXM];
long long pot[MAXN];
int rev[MAXM];
long long ijk[MAXN];
int v[MAXN];
long long toc;
int tof;
int n;
int m;
void init(int _n) {
n = _n;
for (int i = 0; i < n; i++) first[i] = -1;
}
void ae(int a, int b, int cap, int wei) {
next[m] = first[a];
to[m] = b;
first[a] = m;
c[m] = cap;
w[m] = wei;
m++;
next[m] = first[b];
to[m] = a;
first[b] = m;
c[m] = 0;
w[m] = -wei;
m++;
}
int solve(int s, int t, int flo) {
toc = tof = 0;
for (int i = 0; i < n; i++) pot[i] = 0;
while (tof < flo) {
for (int i = 0; i < n; i++) ijk[i] = 9999999999999LL;
for (int i = 0; i < n; i++) v[i] = 0;
priority_queue<pair<long long, int> > Q;
ijk[s] = 0;
Q.push(make_pair(0, s));
while (Q.size()) {
long long cost = -Q.top().first;
int at = Q.top().second;
Q.pop();
if (v[at]) continue;
v[at] = 1;
for (int i = first[at]; ~i; i = next[i]) {
int x = to[i];
if (v[x] || ijk[x] <= ijk[at] + w[i] + pot[x] - pot[at]) continue;
if (c[i] == 0) continue;
ijk[x] = ijk[at] + w[i] - pot[x] + pot[at];
rev[x] = i;
Q.push(make_pair(-ijk[x], x));
}
}
int flow = flo - tof;
if (!v[t]) return 0;
int at = t;
while (at != s) {
flow = min(flow, c[rev[at]]);
at = to[rev[at] ^ 1];
}
at = t;
tof += flow;
toc += flow * (ijk[t] - pot[s] + pot[t]);
at = t;
while (at != s) {
c[rev[at]] -= flow;
c[rev[at] ^ 1] += flow;
at = to[rev[at] ^ 1];
}
for (int i = 0; i < n; i++) pot[i] += ijk[i];
}
return 1;
}
} // namespace MCF
int main() {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
MCF::init(a);
for (int i = 0; i < b; i++) {
int p, q, r, s;
scanf("%d%d%d%d", &p, &q, &r, &s);
MCF::ae(p, q, r, s);
}
int res = MCF::solve(0, a - 1, c);
if (!res)
printf("-1\n");
else
printf("%lld\n", MCF::toc);
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | java | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.PriorityQueue;
import java.util.TreeMap;
public class Main {
static ContestScanner in;static Writer out;public static void main(String[] args)
{try{in=new ContestScanner();out=new Writer();Main solve=new Main();solve.solve();
in.close();out.flush();out.close();}catch(IOException e){e.printStackTrace();}}
static void dump(int[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();}
static void dump(int[]a,int n){for(int i=0;i<a.length;i++)out.printf("%"+n+"d ",a[i]);out.println();}
static void dump(long[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();}
static void dump(char[]a){for(int i=0;i<a.length;i++)out.print(a[i]);out.println();}
static long pow(long a,int n){long r=1;while(n>0){if((n&1)==1)r*=a;a*=a;n>>=1;}return r;}
static String itob(int a,int l){return String.format("%"+l+"s",Integer.toBinaryString(a)).replace(' ','0');}
static void sort(int[]a){m_sort(a,0,a.length,new int[a.length]);}
static void sort(int[]a,int l){m_sort(a,0,l,new int[l]);}
static void sort(int[]a,int l,int[]buf){m_sort(a,0,l,buf);}
static void sort(int[]a,int s,int l,int[]buf){m_sort(a,s,l,buf);}
static void m_sort(int[]a,int s,int sz,int[]b)
{if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;}
m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz;
while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];}
while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];
} /* qsort(3.5s)<<msort(9.5s)<<<shuffle+qsort(17s)<Arrays.sort(Integer)(20s) */
static void sort(long[]a){m_sort(a,0,a.length,new long[a.length]);}
static void sort(long[]a,int l){m_sort(a,0,l,new long[l]);}
static void sort(long[]a,int l,long[]buf){m_sort(a,0,l,buf);}
static void sort(long[]a,int s,int l,long[]buf){m_sort(a,s,l,buf);}
static void m_sort(long[]a,int s,int sz,long[]b)
{if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;}
m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz;
while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];}
while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];}
static void swap(long[] a,int i,int j){final long t=a[i];a[i]=a[j];a[j]=t;}
static void swap(int[] a,int i,int j){final int t=a[i];a[i]=a[j];a[j]=t;}
static int binarySearchSmallerMax(int[]a,int v)// get maximum index which a[idx]<=v
{int l=-1,r=a.length-1,s=0;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;}
static int binarySearchSmallerMax(int[]a,int v,int l,int r)
{int s=-1;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;}
@SuppressWarnings("unchecked")
static List<Integer>[]createGraph(int n)
{List<Integer>[]g=new List[n];for(int i=0;i<n;i++)g[i]=new ArrayList<>();return g;}
@SuppressWarnings("unchecked")
void solve() throws NumberFormatException, IOException{
final int n = in.nextInt();
final int m = in.nextInt();
int f = in.nextInt();
List<Edge>[] node = new List[n];
for(int i=0; i<n; i++) node[i] = new ArrayList<>();
for(int i=0; i<m; i++){
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int d = in.nextInt();
Edge e = new Edge(b, c, d);
Edge r = new Edge(a, 0, -d);
e.rev = r;
r.rev = e;
node[a].add(e);
node[b].add(r);
}
final int s = 0, t = n-1;
int[] h = new int[n];
int[] dist = new int[n];
int[] preV = new int[n];
int[] preE = new int[n];
final int inf = Integer.MAX_VALUE;
PriorityQueue<Pos> qu = new PriorityQueue<>();
int res = 0;
while(f>0){
Arrays.fill(dist, inf);
dist[s] = 0;
qu.clear();
qu.add(new Pos(s, 0));
while(!qu.isEmpty()){
Pos p = qu.poll();
if(dist[p.v]<p.d) continue;
dist[p.v] = p.d;
final int sz = node[p.v].size();
for(int i=0; i<sz; i++){
Edge e = node[p.v].get(i);
final int nd = e.cost+p.d + h[p.v]-h[e.to];
if(e.cap>0 && nd < dist[e.to]){
preV[e.to] = p.v;
preE[e.to] = i;
qu.add(new Pos(e.to, nd));
}
}
}
if(dist[t]==inf) break;
for(int i=0; i<n; i++) h[i] += dist[i];
int minf = f;
for(int i=t; i!=s; i=preV[i]){
minf = Math.min(minf, node[preV[i]].get(preE[i]).cap);
}
f -= minf;
res += minf*h[t];
for(int i=t; i!=s; i=preV[i]){
node[preV[i]].get(preE[i]).cap -= minf;
node[preV[i]].get(preE[i]).rev.cap += minf;
}
}
System.out.println(res);
}
}
class Pos implements Comparable<Pos>{
int v, d;
public Pos(int v, int d) {
this.v = v;
this.d = d;
}
@Override
public int compareTo(Pos o) {
return d-o.d;
}
}
class Edge{
int to, cap, cost;
Edge rev;
Edge(int t, int c, int co){
to = t;
cap = c;
cost = co;
}
void rev(Edge r){
rev = r;
}
}
@SuppressWarnings("serial")
class MultiSet<T> extends HashMap<T, Integer>{
@Override public Integer get(Object key){return containsKey(key)?super.get(key):0;}
public void add(T key,int v){put(key,get(key)+v);}
public void add(T key){put(key,get(key)+1);}
public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);}
public MultiSet<T> merge(MultiSet<T> set)
{MultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;}
for(Entry<T,Integer>e:s.entrySet())l.add(e.getKey(),e.getValue());return l;}
}
@SuppressWarnings("serial")
class OrderedMultiSet<T> extends TreeMap<T, Integer>{
@Override public Integer get(Object key){return containsKey(key)?super.get(key):0;}
public void add(T key,int v){put(key,get(key)+v);}
public void add(T key){put(key,get(key)+1);}
public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);}
public OrderedMultiSet<T> merge(OrderedMultiSet<T> set)
{OrderedMultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;}
while(!s.isEmpty()){l.add(s.firstEntry().getKey(),s.pollFirstEntry().getValue());}return l;}
}
class Pair implements Comparable<Pair>{
int a,b;final int hash;Pair(int a,int b){this.a=a;this.b=b;hash=(a<<16|a>>16)^b;}
public boolean equals(Object obj){Pair o=(Pair)(obj);return a==o.a&&b==o.b;}
public int hashCode(){return hash;}
public int compareTo(Pair o){if(a!=o.a)return a<o.a?-1:1;else if(b!=o.b)return b<o.b?-1:1;return 0;}
}
class Timer{
long time;public void set(){time=System.currentTimeMillis();}
public long stop(){return time=System.currentTimeMillis()-time;}
public void print(){System.out.println("Time: "+(System.currentTimeMillis()-time)+"ms");}
@Override public String toString(){return"Time: "+time+"ms";}
}
class Writer extends PrintWriter{
public Writer(String filename)throws IOException
{super(new BufferedWriter(new FileWriter(filename)));}
public Writer()throws IOException{super(System.out);}
}
class ContestScanner implements Closeable{
private BufferedReader in;private int c=-2;
public ContestScanner()throws IOException
{in=new BufferedReader(new InputStreamReader(System.in));}
public ContestScanner(String filename)throws IOException
{in=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));}
public String nextToken()throws IOException {
StringBuilder sb=new StringBuilder();
while((c=in.read())!=-1&&Character.isWhitespace(c));
while(c!=-1&&!Character.isWhitespace(c)){sb.append((char)c);c=in.read();}
return sb.toString();
}
public String readLine()throws IOException{
StringBuilder sb=new StringBuilder();if(c==-2)c=in.read();
while(c!=-1&&c!='\n'&&c!='\r'){sb.append((char)c);c=in.read();}
return sb.toString();
}
public long nextLong()throws IOException,NumberFormatException
{return Long.parseLong(nextToken());}
public int nextInt()throws NumberFormatException,IOException
{return(int)nextLong();}
public double nextDouble()throws NumberFormatException,IOException
{return Double.parseDouble(nextToken());}
public void close() throws IOException {in.close();}
} |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-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, Graph[to].size()}));
Graph[to].pb(((edge){from, 0, -cost, 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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
template <typename T>
using V = std::vector<T>;
template <typename T>
using VV = std::vector<std::vector<T>>;
template <typename T>
using VVV = std::vector<std::vector<std::vector<T>>>;
template <class T>
inline T ceil(T a, T b) {
return (a + b - 1) / b;
}
template <class T>
inline void print(T x) {
std::cout << x << std::endl;
}
template <class T>
inline void print_vec(const std::vector<T> &v) {
for (int i = 0; i < v.size(); ++i) {
if (i != 0) {
std::cout << " ";
}
std::cout << v[i];
}
std::cout << "\n";
}
template <class T>
inline bool inside(T y, T x, T H, T W) {
return 0 <= y and y < H and 0 <= x and x < W;
}
template <class T>
inline double euclidean_distance(T y1, T x1, T y2, T x2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
template <class T>
inline double manhattan_distance(T y1, T x1, T y2, T x2) {
return abs(x1 - x2) + abs(y1 - y2);
}
const int INF = 1L << 30;
const double EPS = 1e-9;
const std::string YES = "YES", Yes = "Yes", NO = "NO", No = "No";
const std::vector<int> dy4 = {0, 1, 0, -1}, dx4 = {1, 0, -1, 0};
const std::vector<int> dy8 = {0, -1, 0, 1, 1, -1, -1, 1},
dx8 = {1, 0, -1, 0, 1, 1, -1, -1};
class CostScalingPushRelabel {
public:
struct Edge {
const int from;
const int to;
const int rev;
int flow;
const int capacity;
const int cost;
const bool is_rev;
Edge(int from, int to, int rev, int flow, int capacity, int cost,
bool is_rev)
: from(from),
to(to),
rev(rev),
flow(flow),
capacity(capacity),
cost(cost),
is_rev(is_rev) {}
};
struct Node {
int height = 0;
int excessFlow = 0;
double potential = 0;
Node(int height, int excessFlow, int potential)
: height(height), excessFlow(excessFlow), potential(potential) {}
};
int numOfNode;
std::vector<Node> nodeList;
std::vector<std::vector<Edge>> graph;
std::queue<int> active_nodes;
int epsilon = 1;
int SCALING_FACTOR = 2;
int COST_SCALING_FACTOR = 1;
CostScalingPushRelabel(unsigned int numOfNode)
: numOfNode(numOfNode), COST_SCALING_FACTOR(2 * numOfNode) {
for (int i = 0; i < numOfNode; ++i) {
nodeList.emplace_back(Node(0, 0, 0));
}
graph.resize(numOfNode);
}
void add_edge(int from, int to, int capacity, int cost) {
graph[from].emplace_back(
Edge(from, to, (int)graph[to].size(), 0, capacity, cost, false));
graph[to].emplace_back(Edge(to, from, (int)graph[from].size() - 1, capacity,
capacity, -cost, true));
epsilon = std::max(epsilon, abs(cost) * COST_SCALING_FACTOR);
}
int minimum_cost_flow(const int source, const int sink, const int flow) {
nodeList.at(source).excessFlow = flow;
nodeList.at(sink).excessFlow = -flow;
while (epsilon > 1.0) {
for (int u = 0; u < numOfNode; ++u) {
for (int v = 0; v < graph.at(u).size(); ++v) {
Edge &edge = graph.at(u).at(v);
if (edge.is_rev) {
continue;
}
const double reduced_cost = calc_reduced_cost(edge);
if (reduced_cost < 0) {
if (edge.capacity - edge.flow > 0) {
int f = edge.capacity - edge.flow;
push_flow(edge, f);
}
}
if (reduced_cost > 0) {
if (edge.flow > 0) {
int f = graph.at(u).at(v).flow;
push_flow(edge, f);
}
}
}
}
get_active_nodes();
while (not active_nodes.empty()) {
int node = active_nodes.front();
active_nodes.pop();
while (nodeList.at(node).excessFlow > 0) {
if (not push(node)) {
relabel(node);
active_nodes.push(node);
break;
}
}
}
epsilon = std::max(1, epsilon / SCALING_FACTOR);
}
double total_cost = 0;
for (int u = 0; u < numOfNode; ++u) {
for (int v = 0; v < graph.at(u).size(); ++v) {
Edge &edge = graph.at(u).at(v);
if (edge.is_rev) {
continue;
}
total_cost += edge.flow * edge.cost;
}
}
return total_cost;
}
private:
void print() {
for (int u = 0; u < graph.size(); ++u) {
for (int v = 0; v < graph.at(u).size(); ++v) {
const Edge &edge = graph.at(u).at(v);
if (edge.is_rev) {
continue;
}
std::cout << edge.from << " -> " << edge.to << "(" << edge.flow << ")"
<< std::endl;
}
}
std::cout << "excess: ";
for (int u = 0; u < nodeList.size(); ++u) {
std::cout << u << ":" << nodeList[u].excessFlow << ", ";
}
std::cout << std::endl;
std::cout << "potential: ";
for (int u = 0; u < nodeList.size(); ++u) {
std::cout << u << ":" << nodeList[u].potential << ", ";
}
std::cout << std::endl;
}
void push_flow(Edge &edge, int flow) {
edge.flow += flow;
graph.at(edge.to).at(edge.rev).flow -= flow;
nodeList.at(edge.from).excessFlow -= flow;
nodeList.at(edge.to).excessFlow += flow;
}
double calc_reduced_cost(const Edge &edge) {
return edge.cost * COST_SCALING_FACTOR - nodeList.at(edge.from).potential +
nodeList.at(edge.to).potential;
}
void get_active_nodes() {
for (int u = 0; u < nodeList.size(); ++u) {
if (nodeList[u].excessFlow > 0) {
active_nodes.push(u);
}
}
}
bool push(const int from) {
if (nodeList.at(from).excessFlow == 0) {
return false;
}
assert(nodeList.at(from).excessFlow > 0);
for (int i = graph.at(from).size() - 1; i >= 0; --i) {
Edge &edge = graph.at(from).at(i);
const int to = edge.to;
if (edge.flow == edge.capacity) {
continue;
}
const double reduced_cost = calc_reduced_cost(edge);
if (reduced_cost < 0) {
int flow =
std::min(edge.capacity - edge.flow, nodeList[from].excessFlow);
push_flow(edge, flow);
if (nodeList.at(edge.to).excessFlow > 0 and
nodeList.at(edge.to).excessFlow <= flow) {
active_nodes.push(edge.to);
}
return true;
}
}
return false;
}
void relabel(const int from) {
double min_potential = INT_MAX;
for (const Edge &edge : graph.at(from)) {
if (edge.capacity - edge.flow > 0) {
min_potential =
std::min(min_potential, edge.cost * COST_SCALING_FACTOR +
nodeList[edge.to].potential + epsilon);
}
}
assert(min_potential != INT_MAX);
nodeList[from].potential = min_potential;
}
};
class Dinic {
public:
struct Edge {
const int to;
long long flow;
const long long cap;
const int rev;
const bool is_rev;
Edge(int to, long long flow, long long cap, int rev, bool is_rev)
: to(to), flow(flow), cap(cap), rev(rev), is_rev(is_rev) {
assert(this->cap >= 0);
}
};
std::vector<std::vector<Edge>> graph;
std::vector<int> level;
std::vector<unsigned int> iter;
explicit Dinic(unsigned int num_of_node) {
assert(num_of_node > 0);
graph.resize(num_of_node);
level.resize(num_of_node);
iter.resize(num_of_node);
}
void add_edge(unsigned int from, unsigned int to, long long cap) {
graph[from].emplace_back(
Edge(to, 0, cap, (unsigned int)graph[to].size(), false));
graph[to].emplace_back(
Edge(from, cap, cap, (unsigned int)graph[from].size() - 1, true));
}
long long max_flow(unsigned int s, unsigned int t) {
long long flow = 0;
while (true) {
bfs(s);
if (level.at(t) < 0) {
return flow;
}
fill(iter.begin(), iter.end(), 0);
long long f;
while ((f = dfs(s, t, INT_MAX)) > 0) {
flow += f;
}
}
}
private:
void bfs(unsigned int s) {
fill(level.begin(), level.end(), -1);
std::queue<unsigned int> que;
level.at(s) = 0;
que.push(s);
while (not que.empty()) {
unsigned int v = que.front();
que.pop();
for (int i = 0; i < graph.at(v).size(); ++i) {
Edge &e = graph.at(v).at(i);
if ((e.cap - e.flow) > 0 and level.at(e.to) < 0) {
level.at(e.to) = level.at(v) + 1;
que.push(e.to);
}
}
}
}
long long dfs(unsigned int v, unsigned int t, long long f) {
if (v == t) {
return f;
}
for (unsigned int &i = iter.at(v); i < graph.at(v).size(); ++i) {
Edge &e = graph.at(v).at(i);
if ((e.cap - e.flow) > 0 and level.at(v) < level.at(e.to)) {
long long d = dfs(e.to, t, std::min(f, e.cap - e.flow));
if (d > 0) {
e.flow += d;
graph.at(e.to).at(e.rev).flow -= d;
return d;
}
}
}
return 0;
}
};
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int V, E, F;
cin >> V >> E >> F;
Dinic dn(V);
CostScalingPushRelabel 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);
dn.add_edge(u, v, c);
}
if (dn.max_flow(0, V - 1) < F) {
cout << -1 << endl;
} else {
cout << pd.minimum_cost_flow(0, V - 1, F) << endl;
}
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include<iostream>
#include<vector>
#define INF 99999999
using namespace std;
const int MAX_V = 100;
struct edge{
int to,cap,cost,rev; //?????????,??????,?????¨,??????
};
vector<edge> G[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(const int n,const int s,const int t,int f)
{
int res =0;
int dist[MAX_V];
int prevv[MAX_V];
int preve[MAX_V];
while(f>0){
fill(dist,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;
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 n,m,s,t,f,result;
cin >> n; //????????°
cin >> m; //?????°
cin >> s; //????????????
cin >> t; //??´??????
cin >> f; //??????
for(int i=0;i<m;i++){
int from,to,cap,cost;
cin >> from; //????????????
cin >> to; //?????????
cin >> cap; //??????
cin >> cost; //?????¨
add_edge(from,to,cap,cost);
}
result = min_cost_flow(n,s,t,f);
cout << result << "\n";
} |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
struct edge {
i64 from;
i64 to;
i64 cap;
i64 cost;
i64 rev;
};
i64 INF = 1e8;
i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g,
std::vector<i64> b) {
i64 ans = 0;
i64 U = *std::max_element(begin(b), end(b));
i64 delta = (1 << ((int)ceil(std::log2(U))));
int n = g.size();
std::vector<i64> e = b;
std::vector<i64> p(n, 0);
int zero = 0;
for (auto x : e) {
if (x == 0) zero++;
}
for (; delta > 0; delta >>= 1) {
if (zero == n) break;
while (true) {
std::vector<std::size_t> pv(n, -1);
std::vector<std::size_t> pe(n, -1);
std::vector<std::size_t> start(n, -1);
std::vector<i64> dist(n, INF);
using P = std::pair<i64, i64>;
std::priority_queue<P, std::vector<P>, std::greater<P>> que;
bool t_exist = false;
for (int s = 0; s < n; s++) {
if (e[s] >= delta) {
dist[s] = 0;
start[s] = s;
que.push({dist[s], s});
}
if (e[s] <= -delta) t_exist = true;
}
if (que.empty()) break;
if (!t_exist) break;
while (!que.empty()) {
int v = que.top().second;
i64 d = que.top().first;
que.pop();
if (dist[v] < d) continue;
for (std::size_t i = 0; i < g[v].size(); i++) {
const auto& e = g[v][i];
std::size_t u = e.to;
if (e.cap == 0) continue;
assert(e.cost + p[v] - p[u] >= 0);
if (dist[u] > dist[v] + e.cost + p[v] - p[u]) {
dist[u] = dist[v] + e.cost + p[v] - p[u];
pv[u] = v;
pe[u] = i;
start[u] = start[v];
que.push({dist[u], u});
}
}
}
for (int i = 0; i < n; i++) {
p[i] += dist[i];
}
bool sended = false;
for (int t = 0; t < n; t++) {
if (e[t] <= -delta && pv[t] != -1 && e[start[t]] >= delta) {
sended = true;
std::size_t u = t;
for (; pv[u] != -1; u = pv[u]) {
ans += delta * g[pv[u]][pe[u]].cost;
g[pv[u]][pe[u]].cap -= delta;
g[u][g[pv[u]][pe[u]].rev].cap += delta;
}
e[u] -= delta;
e[t] += delta;
if (e[u] == 0) zero++;
if (e[t] == 0) zero++;
}
}
if (!sended) return -1e18;
}
}
if (zero == n)
return ans;
else
return -1e18;
}
int main() {
i64 N, M, F;
cin >> N >> M >> F;
vector<vector<edge>> g(N + M);
vector<i64> e(N + M, 0);
int s = 0;
int t = N - 1;
e[s + M] = F;
e[t + M] = -F;
for (int i = 0; i < M; i++) {
i64 a, b, c, d;
cin >> a >> b >> c >> d;
e[i] = c;
e[a + M] -= c;
g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()});
g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1});
g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()});
g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1});
}
i64 ans = capacity_scaling_bflow(g, e);
if (ans == -1e18) {
cout << -1 << endl;
} else {
cout << ans << endl;
}
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
template <typename T>
using V = std::vector<T>;
template <typename T>
using VV = std::vector<std::vector<T>>;
template <typename T>
using VVV = std::vector<std::vector<std::vector<T>>>;
template <class T>
inline T ceil(T a, T b) {
return (a + b - 1) / b;
}
template <class T>
inline void print(T x) {
std::cout << x << std::endl;
}
template <class T>
inline void print_vec(const std::vector<T> &v) {
for (int i = 0; i < v.size(); ++i) {
if (i != 0) {
std::cout << " ";
}
std::cout << v[i];
}
std::cout << "\n";
}
template <class T>
inline bool inside(T y, T x, T H, T W) {
return 0 <= y and y < H and 0 <= x and x < W;
}
template <class T>
inline double euclidean_distance(T y1, T x1, T y2, T x2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
template <class T>
inline double manhattan_distance(T y1, T x1, T y2, T x2) {
return abs(x1 - x2) + abs(y1 - y2);
}
const int INF = 1L << 30;
const double EPS = 1e-10;
const std::string YES = "YES", Yes = "Yes", NO = "NO", No = "No";
const std::vector<int> dy4 = {0, 1, 0, -1}, dx4 = {1, 0, -1, 0};
const std::vector<int> dy8 = {0, -1, 0, 1, 1, -1, -1, 1},
dx8 = {1, 0, -1, 0, 1, 1, -1, -1};
using namespace std;
class MinimumCostFlow {
struct Edge {
const int to;
int flow;
const int cap;
const int cost;
const int rev;
const bool is_rev;
Edge(int to, int flow, int cap, int cost, int rev, bool is_rev)
: to(to), flow(flow), cost(cost), cap(cap), rev(rev), is_rev(is_rev) {
assert(this->cap >= 0);
}
};
const int num_node;
vector<vector<Edge>> graph;
public:
MinimumCostFlow(int num_node) : num_node(num_node) { graph.resize(num_node); }
void add_edge(int from, int to, int cap, int cost) {
graph.at(from).emplace_back(
Edge(to, 0, cap, cost, graph[to].size(), false));
graph.at(to).emplace_back(
Edge(from, cap, cap, -cost, graph[from].size() - 1, true));
}
int min_cost_flow(int source, int sink, int f) {
int res = 0;
vector<int> prev_v(num_node, 0), prev_e(num_node, 0);
vector<int> potential(num_node, 0);
if (0 < f) {
potential.assign(num_node, INT_MAX);
potential[source] = 0;
while (true) {
bool updated = false;
for (int v = 0; v < num_node; ++v) {
for (auto &e : graph.at(v)) {
if (e.cap - e.flow > 0) {
if (potential[v] == INT_MAX) {
continue;
}
if (potential[e.to] > potential[v] + e.cost) {
potential[e.to] = potential[v] + e.cost;
updated = true;
}
}
}
}
if (not updated) {
break;
}
}
}
while (f > 0) {
priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>>
que;
vector<int> distance(num_node, INT_MAX);
distance[source] = 0;
que.push(make_pair(0, source));
while (not que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (distance[v] < p.first) {
continue;
}
for (int i = 0; i < graph[v].size(); i++) {
Edge &e = graph[v][i];
if (e.cap - e.flow > 0 and distance[e.to] > distance[v] + e.cost +
potential[v] -
potential[e.to]) {
distance[e.to] =
distance[v] + e.cost + potential[v] - potential[e.to];
prev_v[e.to] = v;
prev_e[e.to] = i;
que.push(make_pair(distance[e.to], e.to));
}
}
}
if (distance[sink] == INT_MAX) {
return -1;
}
for (int v = 0; v < num_node; ++v) {
potential[v] += distance[v];
}
int d = f;
for (int v = sink; v != source; v = prev_v[v]) {
auto &e = graph[prev_v[v]][prev_e[v]];
d = min(d, e.cap - e.flow);
}
f -= d;
res += d * potential[sink];
for (int v = sink; v != source; v = prev_v[v]) {
Edge &e = graph[prev_v[v]][prev_e[v]];
e.flow -= d;
graph[v][e.rev].flow += d;
}
}
return res;
}
};
int main(void) {
int V, E, F;
cin >> V >> E >> F;
MinimumCostFlow mcf(V);
for (int i = (0); i < ((int)E); ++i) {
int u, v, c, d;
cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
print(mcf.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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int inf = 1 << 29;
const long long INF = 1ll << 50;
const double pi = acos(-1);
const double eps = 1e-8;
const long long mod = 1e9 + 7;
const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
class Network {
private:
int V;
struct edge {
int to, cap, cost, rev;
};
vector<vector<edge> > g;
vector<int> h, d, pv, pe;
public:
Network(int v) {
V = v;
g = vector<vector<edge> >(v);
}
void add_edge(int s, int t, int cap, int cost) {
g[s].push_back(edge{t, cap, cost, (int)g[t].size()});
g[t].push_back(edge{s, 0, -cost, (int)g[s].size() - 1});
}
int min_cost_flow(int s, int t, int f) {
int res = 0;
h = pv = pe = vector<int>(V);
while (f > 0) {
priority_queue<pair<int, int> > q;
d = vector<int>(V, inf);
d[s] = 0;
q.push({0, s});
while (!q.empty()) {
pair<int, int> p = q.top();
q.pop();
int v = p.second;
if (d[v] < -p.first) continue;
for (int i = 0; i < g[v].size(); i++) {
edge &e = g[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];
pv[e.to] = v;
pe[e.to] = i;
q.push({-d[e.to], e.to});
}
}
}
for (int i = 0; i < V; i++) cout << d[i] << ' ';
cout << endl;
if (d[t] == inf) return -1;
for (int i = 0; i < V; i++) h[i] += d[i];
int D = f;
for (int i = t; i != s; i = pv[i]) D = min(D, g[pv[i]][pe[i]].cap);
f -= D;
res += D * h[t];
for (int i = t; i != s; i = pv[i]) {
edge &e = g[pv[i]][pe[i]];
e.cap -= D;
g[i][e.rev].cap += D;
}
}
return res;
}
};
int n, m, f;
int main() {
cin >> n >> m >> f;
Network net(n);
for (int i = 0; i < m; i++) {
int v, u, c, d;
cin >> v >> u >> c >> d;
net.add_edge(v, u, c, d);
}
cout << net.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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const long long int E = 1e18 + 7;
const long long int MOD = 1000000007;
class CFlow {
private:
struct edge {
long long int to;
long long int cap;
long long int rev;
long long int cost;
};
struct node {
long long int cost;
long long int flow;
long long int number;
long long int from;
long long int edge;
bool operator<(const node &a) const {
if (a.cost < this->cost) {
return true;
} else if (a.cost == this->cost && a.flow > this->flow) {
return true;
}
return false;
}
};
long long int INF;
long long int v;
vector<vector<edge>> e;
vector<bool> used;
void reset_used() {
for (int i = 0; i < used.size(); i++) {
used[i] = false;
}
}
long long int dfs(long long int where, long long int to, long long int flow) {
if (where == to) {
return flow;
}
used[where] = true;
for (int i = 0; i < e[where].size(); i++) {
edge &E = e[where][i];
if (!used[E.to] && E.cap > 0) {
long long int d = dfs(E.to, to, min(flow, E.cap));
if (d > 0) {
E.cap -= d;
e[E.to][E.rev].cap += d;
return d;
}
}
}
return 0;
}
pair<long long int, long long int> dijk(long long int s, long long int t,
long long int flow) {
priority_queue<node> q;
vector<node> V(v, {INF, 0, -1, -1, -1});
q.push({0, flow, s, s});
while (!q.empty()) {
node N = q.top();
q.pop();
if (used[N.number]) {
continue;
}
used[N.number] = true;
V[N.number] = N;
for (int i = 0; i < e[N.number].size(); i++) {
edge E = e[N.number][i];
if (used[E.to] || E.cap == 0) {
continue;
}
node n = {N.cost + E.cost, min(N.flow, E.cap), E.to, N.number, i};
q.push(n);
}
}
if (V[t].flow == 0) {
return {0, 0};
}
long long int w = t;
long long int Flow = V[t].flow;
long long int cost = V[t].flow * V[t].cost;
while (w != s) {
long long int t = w;
w = V[w].from;
edge &E = e[w][V[t].edge];
E.cap -= Flow;
e[E.to][E.rev].cap += Flow;
}
return {Flow, cost};
}
public:
CFlow(long long int v) : v(v) {
e.resize(v);
used.resize(v, false);
INF = 1e18 + 7;
}
void add_edge(long long int from, long long int to, long long int cap,
long long int cost) {
e[from].push_back((edge){to, cap, (long long int)e[to].size(), cost});
e[to].push_back(
(edge){from, 0, (long long int)e[from].size() - 1, -1 * cost});
}
pair<long long int, long long int> min_cost(long long int s, long long int t,
long long int flow) {
vector<vector<edge>> ed = e;
long long int cost = 0;
long long int D = flow;
while (1) {
reset_used();
pair<long long int, long long int> f = dijk(s, t, flow);
flow -= f.first;
cost += f.second;
if (f.first == 0 || flow == 0) {
break;
}
}
e = ed;
return {D - flow, cost};
}
};
int main() {
long long int v, e, f;
cin >> v >> e >> f;
CFlow first(v);
for (int i = 0; i < e; i++) {
long long int s, t, cap, cost;
cin >> s >> t >> cap >> cost;
first.add_edge(s, t, cap, cost);
}
pair<long long int, long long int> P = first.min_cost(0, v - 1, f);
if (P.first != f) {
cout << -1 << endl;
} else {
cout << P.second << endl;
}
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx")
using namespace std;
template <typename T1, typename T2>
ostream& operator<<(ostream& o, const pair<T1, T2> p) {
o << "(" << p.first << ":" << p.second << ")";
return o;
}
template <typename iterator>
inline size_t argmin(iterator begin, iterator end) {
return distance(begin, min_element(begin, end));
}
template <typename iterator>
inline size_t argmax(iterator begin, iterator end) {
return distance(begin, max_element(begin, end));
}
template <typename T>
T& maxset(T& to, const T& val) {
return to = max(to, val);
}
template <typename T>
T& minset(T& to, const T& val) {
return to = min(to, val);
}
void bye(string s, int code = 0) {
cout << s << endl;
exit(0);
}
mt19937_64 randdev(8901016);
inline long long int rand_range(long long int l, long long int h) {
return uniform_int_distribution<long long int>(l, h)(randdev);
}
namespace {
class MaiScanner {
public:
template <typename T>
void input_integer(T& var) {
var = 0;
T sign = 1;
int cc = getchar_unlocked();
for (; cc < '0' || '9' < cc; cc = getchar_unlocked())
if (cc == '-') sign = -1;
for (; '0' <= cc && cc <= '9'; cc = getchar_unlocked())
var = (var << 3) + (var << 1) + cc - '0';
var = var * sign;
}
inline int c() { return getchar_unlocked(); }
inline MaiScanner& operator>>(int& var) {
input_integer<int>(var);
return *this;
}
inline MaiScanner& operator>>(long long& var) {
input_integer<long long>(var);
return *this;
}
inline MaiScanner& operator>>(string& var) {
int cc = getchar_unlocked();
for (; !(0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
;
for (; (0x21 <= (cc) && (cc) <= 0x7E); cc = getchar_unlocked())
var.push_back(cc);
return *this;
}
template <typename IT>
void in(IT begin, IT end) {
for (auto it = begin; it != end; ++it) *this >> *it;
}
};
} // namespace
MaiScanner scanner;
class Flow {
public:
size_t n;
struct Arrow {
int from, to;
int left;
int cap;
Arrow(int from = 0, int to = 0, int w = 1)
: from(from), to(to), left(w), cap(w) {}
bool operator<(const Arrow& a) const {
return (left != a.left) ? left < a.left
: (left < a.left) | (cap < a.cap) |
(from < a.from) | (to < a.to);
}
bool operator==(const Arrow& a) const {
return (from == a.from) && (to == a.to) && (left == a.left) &&
(cap == a.cap);
}
};
vector<vector<int>> vertex_to;
vector<vector<int>> vertex_from;
vector<Arrow> arrows;
Flow(int n) : n(n), vertex_to(n), vertex_from(n) {}
void connect(int from, int to, int left) {
vertex_to[from].push_back(arrows.size());
vertex_from[to].push_back(arrows.size());
arrows.emplace_back(from, to, left);
}
};
Flow::int minconstflow(Flow& graph, const vector<Flow::int>& cost, int i_source,
int i_sink, Flow::int flow, Flow::int inf) {
Flow::int result = 0;
vector<Flow::int> ofs(graph.n);
vector<Flow::int> dist(graph.n);
vector<int> prev(graph.n);
static function<Flow::int(int, Flow::int)> _dfs = [&](int idx, Flow::int f) {
if (idx == i_source) return f;
for (int ei : graph.vertex_from[idx]) {
auto& edge = graph.arrows[ei];
if (dist[edge.to] ==
dist[edge.from] + cost[ei] + ofs[edge.from] - ofs[edge.to]) {
f = _dfs(edge.from, min(f, edge.left));
if (f > 0) {
edge.left -= f;
return f;
}
}
}
for (int ei : graph.vertex_to[idx]) {
auto& edge = graph.arrows[ei];
if (dist[edge.from] ==
dist[edge.to] - cost[ei] + ofs[edge.to] - ofs[edge.from]) {
f = _dfs(edge.to, min(f, edge.cap - edge.left));
if (f > 0) {
edge.left += f;
return f;
}
}
}
return 0;
};
while (flow > 0) {
fill(dist.begin(), dist.end(), inf);
fill(prev.begin(), prev.end(), -1);
priority_queue<pair<Flow::int, int>> pq;
pq.emplace(0, i_source);
dist[i_source] = 0;
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
Flow::int d = -p.first;
int idx = p.second;
if (dist[idx] < d) continue;
for (int ei : graph.vertex_to[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.left &&
dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to] < dist[edge.to]) {
dist[edge.to] = dist[idx] + cost[ei] + ofs[idx] - ofs[edge.to];
prev[edge.to] = ei;
pq.emplace(-dist[edge.to], edge.to);
}
}
for (int ei : graph.vertex_from[idx]) {
auto edge = graph.arrows[ei];
if (0 < edge.cap - edge.left &&
dist[idx] - cost[ei] + ofs[idx] - ofs[edge.from] <
dist[edge.from]) {
dist[edge.from] = dist[idx] - cost[ei] + ofs[idx] - ofs[edge.from];
prev[edge.from] = ei;
pq.emplace(-dist[edge.from], edge.from);
}
}
}
if (dist[i_sink] == inf) return -1;
for (int i = 0; i < graph.n; ++i) ofs[i] += dist[i];
Flow::int z = flow;
for (int p = i_sink; p != i_source;) {
auto edge = graph.arrows[prev[p]];
if (edge.to == p)
minset(z, edge.left), p = edge.from;
else
minset(z, edge.cap - edge.left), p = edge.to;
}
for (int p = i_sink; p != i_source;) {
auto edge = graph.arrows[prev[p]];
if (edge.to == p)
edge.left -= z, p = edge.from;
else
edge.left += z, p = edge.to;
}
flow -= z;
result += z * ofs[i_sink];
}
return result;
}
long long int m, n, kei;
int main() {
long long int f;
scanner >> n >> m >> f;
Flow graph(n);
vector<int> cost(m);
for (auto i = 0ll; (i) < (m); ++(i)) {
int u, v, c, d;
scanner >> u >> v >> c >> d;
graph.connect(u, v, c);
cost[i] = d;
}
auto ans = minconstflow(graph, cost, 0, n - 1, f, (long long int)1e8);
cout << ans << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
const int N = 110;
const int M = 2010;
const int inf = 0x3fffffff;
struct Edge {
int to, cap, cost, next;
} es[M];
int S, T;
int SIZE = 0;
int h[N];
int dist[N], queue[N * N], inq[N];
int vis[N];
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;
}
bool sssp(int n) {
int front = 0, back = 0;
for (int i = 0; i < n; i++) {
dist[i] = inf;
inq[i] = vis[i] = 0;
}
queue[back++] = S;
dist[S] = 0;
while (front < back) {
int x = queue[front++];
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;
if (!inq[y]) {
queue[back++] = y;
inq[y] = 1;
}
}
}
}
return (dist[T] < inf);
}
int dfs(int x, int flow) {
if (x == T) return flow;
if (vis[x]) return 0;
int ret = 0;
for (int i = h[x]; i != -1 && flow > 0; i = es[i].next) {
int y = es[i].to;
if (dist[y] != dist[x] + es[i].cost) 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;
}
}
vis[x] = (flow > 0);
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;
}
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": []
} | IN-CORRECT | UNKNOWN | #include <bits/stdc++.h>
struct node {
int id;
int cap;
int cost;
struct node *next;
};
struct node **list;
int **flow, *delta, *dist, *prev;
int *heap, *heap_index, heapsize;
void Insert(int, int, int, int);
void downheap(int);
void upheap(int);
void PQ_init(int);
int PQ_remove(void);
void PQ_update(int);
int Maxflow(int, int, int);
int main(void) {
int i, v, e, f, s, t, c, d, mincost = 0;
scanf("%d %d %d", &v, &e, &f);
list = (struct node **)malloc(sizeof(struct node *) * v);
flow = (int **)malloc(sizeof(int *) * v);
delta = (int *)malloc(sizeof(int) * v);
dist = (int *)malloc(sizeof(int) * v);
prev = (int *)malloc(sizeof(int) * v);
for (i = 0; i < v; i++) {
list[i] = NULL;
flow[i] = (int *)calloc(v, sizeof(int));
}
for (i = 0; i < e; i++) {
scanf("%d %d %d %d", &s, &t, &c, &d);
Insert(s, t, c, d);
}
while (f > 0 && Maxflow(0, v - 1, v)) {
int n = v - 1;
f -= delta[v - 1];
if (f < 0) delta[v - 1] += f;
do {
flow[prev[n]][n] += delta[v - 1];
flow[n][prev[n]] -= delta[v - 1];
n = prev[n];
} while (n);
}
if (f <= 0) {
for (i = 0; i < v; i++) {
struct node *n;
for (n = list[i]; n != NULL; n = n->next) {
mincost += flow[i][n->id] * n->cost;
}
}
printf("%d\n", mincost);
} else
printf("-1\n");
for (i = 0; i < v; i++) {
free(list[i]);
free(flow[i]);
}
free(list);
free(flow);
free(delta);
free(dist);
free(prev);
}
void Insert(int a, int b, int cap, int cost) {
struct node *p = (struct node *)malloc(sizeof(struct node));
p->id = b;
p->cap = cap;
p->cost = cost;
p->next = list[a];
list[a] = p;
p = (struct node *)malloc(sizeof(struct node));
p->id = a;
p->cap = 0;
p->cost = 0;
p->next = list[b];
list[b] = p;
}
void downheap(int k) {
int j, v = heap[k];
while (k < heapsize / 2) {
j = 2 * k + 1;
if (j < heapsize - 1 && dist[heap[j]] > dist[heap[j + 1]]) j++;
if (dist[v] <= dist[heap[j]]) break;
heap[k] = heap[j];
heap_index[heap[j]] = k;
k = j;
}
heap[k] = v;
heap_index[v] = k;
}
void upheap(int j) {
int k, v = heap[j];
while (j > 0) {
k = (j + 1) / 2 - 1;
if (dist[v] >= dist[heap[k]]) break;
heap[j] = heap[k];
heap_index[heap[k]] = j;
j = k;
}
heap[j] = v;
heap_index[v] = j;
}
void PQ_init(int size) {
int i;
heapsize = size;
heap = (int *)malloc(sizeof(int) * size);
heap_index = (int *)malloc(sizeof(int) * size);
for (i = 0; i < size; i++) {
heap[i] = i;
heap_index[i] = i;
}
for (i = heapsize / 2 - 1; i >= 0; i--) downheap(i);
}
int PQ_remove(void) {
int v = heap[0];
heap[0] = heap[heapsize - 1];
heap_index[heap[heapsize - 1]] = 0;
heapsize--;
downheap(0);
return v;
}
void PQ_update(int v) { upheap(heap_index[v]); }
int Maxflow(int s, int t, int size) {
struct node *n;
int i;
for (i = 0; i < size; i++) {
delta[i] = INT_MAX;
dist[i] = INT_MAX;
prev[i] = -1;
}
dist[s] = 0;
PQ_init(size);
while (heapsize) {
i = PQ_remove();
if (i == t) break;
for (n = list[i]; n != NULL; n = n->next) {
int v = n->id;
if (flow[i][v] < n->cap) {
int newlen = dist[i] + n->cost;
if (newlen < dist[v]) {
dist[v] = newlen;
prev[v] = i;
delta[v] =
((delta[i]) < (n->cap - flow[i][v]) ? (delta[i])
: (n->cap - flow[i][v]));
PQ_update(v);
}
}
}
}
free(heap);
free(heap_index);
return dist[t] != INT_MAX;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
namespace MCF {
const int MAXN = 120;
const int MAXM = 2100;
int to[MAXM];
int next[MAXM];
int first[MAXN];
int c[MAXM];
long long w[MAXM];
long long pot[MAXN];
int rev[MAXM];
long long ijk[MAXN];
int v[MAXN];
long long toc;
int tof;
int n;
int m;
void init(int _n) {
n = _n;
for (int i = 0; i < n; i++) first[i] = -1;
}
void ae(int a, int b, int cap, int wei) {
next[m] = first[a];
to[m] = b;
first[a] = m;
c[m] = cap;
w[m] = wei;
m++;
next[m] = first[b];
to[m] = a;
first[b] = m;
c[m] = 0;
w[m] = -wei;
m++;
}
int solve(int s, int t, int flo) {
toc = tof = 0;
for (int i = 0; i < n; i++) pot[i] = 0;
while (tof < flo) {
for (int i = 0; i < n; i++) ijk[i] = 9999999999999LL;
for (int i = 0; i < n; i++) v[i] = 0;
priority_queue<pair<long long, int> > Q;
ijk[s] = 0;
Q.push(make_pair(0, s));
while (Q.size()) {
long long cost = -Q.top().first;
int at = Q.top().second;
Q.pop();
if (v[at]) continue;
v[at] = 1;
for (int i = first[at]; ~i; i = next[i]) {
int x = to[i];
if (v[x] || ijk[x] <= ijk[at] + w[i] + pot[x] - pot[at]) continue;
if (c[i] == 0) continue;
ijk[x] = ijk[at] + w[i] + pot[x] - pot[at];
rev[x] = i;
Q.push(make_pair(-ijk[x], x));
}
}
int flow = flo - tof;
if (!v[t]) return 0;
int at = t;
while (at != s) {
flow = min(flow, c[rev[at]]);
at = to[rev[at] ^ 1];
}
at = t;
tof += flow;
toc += flow * (ijk[t] + pot[s] - pot[t]);
at = t;
while (at != s) {
c[rev[at]] -= flow;
c[rev[at] ^ 1] += flow;
at = to[rev[at] ^ 1];
}
for (int i = 0; i < n; i++) pot[i] += ijk[i];
}
return 1;
}
} // namespace MCF
int main() {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
MCF::init(a);
for (int i = 0; i < b; i++) {
int p, q, r, s;
scanf("%d%d%d%d", &p, &q, &r, &s);
MCF::ae(p, q, r, s);
}
int res = MCF::solve(0, a - 1, c);
if (!res)
printf("-1\n");
else
printf("%lld\n", MCF::toc);
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
namespace loquat {
using vertex_t = size_t;
}
namespace loquat {
namespace edge_param {
struct to_ {
vertex_t to;
explicit to_(vertex_t t = 0) : to(t) {}
};
template <typename T>
struct weight_ {
using weight_type = T;
weight_type weight;
explicit weight_(const weight_type& w = weight_type()) : weight(w) {}
};
template <typename T>
using weight = weight_<T>;
template <typename T>
struct capacity_ {
using capacity_type = T;
capacity_type capacity;
explicit capacity_(const capacity_type& c = capacity_type()) : capacity(c) {}
};
template <typename T>
using capacity = capacity_<T>;
} // namespace edge_param
namespace detail {
template <typename T, typename... Params>
struct edge_param_wrapper : public T, edge_param_wrapper<Params...> {
template <typename U, typename... Args>
explicit edge_param_wrapper(U&& x, Args&&... args)
: T(std::forward<U>(x)),
edge_param_wrapper<Params...>(std::forward<Args>(args)...) {}
};
template <typename T>
struct edge_param_wrapper<T> : public T {
template <typename U>
explicit edge_param_wrapper(U&& x) : T(std::forward<U>(x)) {}
};
} // namespace detail
template <typename... Params>
struct edge : public detail::edge_param_wrapper<edge_param::to_, Params...> {
edge() : detail::edge_param_wrapper<edge_param::to_, Params...>() {}
template <typename... Args>
explicit edge(Args&&... args)
: detail::edge_param_wrapper<edge_param::to_, Params...>(
std::forward<Args>(args)...) {}
};
} // namespace loquat
namespace loquat {
template <typename EdgeType>
struct has_weight {
private:
template <typename U>
static std::true_type check_type(typename U::weight_type*);
template <typename U>
static std::false_type check_type(...);
template <typename U>
static auto check_member(const U& x) -> decltype(x.weight, std::true_type());
static std::false_type check_member(...);
public:
static const bool value =
decltype(check_type<EdgeType>(nullptr))::value &&
decltype(check_member(std::declval<EdgeType>()))::value;
};
template <typename EdgeType>
struct has_capacity {
private:
template <typename U>
static std::true_type check_type(typename U::capacity_type*);
static std::false_type check_type(...);
template <typename U>
static auto check_member(const U& x)
-> decltype(x.capacity, std::true_type());
static std::false_type check_member(...);
public:
static const bool value =
decltype(check_type<EdgeType>(nullptr))::value &&
decltype(check_member(std::declval<EdgeType>()))::value;
};
} // namespace loquat
namespace loquat {
template <typename EdgeType>
class adjacency_list {
public:
using edge_type = EdgeType;
using edge_list = std::vector<edge_type>;
private:
std::vector<std::vector<EdgeType>> m_edges;
public:
adjacency_list() : m_edges() {}
explicit adjacency_list(size_t n) : m_edges(n) {}
size_t size() const { return m_edges.size(); }
const edge_list& operator[](vertex_t u) const { return m_edges[u]; }
edge_list& operator[](vertex_t u) { return m_edges[u]; }
template <typename... Args>
void add_edge(vertex_t from, Args&&... args) {
m_edges[from].emplace_back(std::forward<Args>(args)...);
}
void add_edge(vertex_t from, const edge_type& e) {
m_edges[from].emplace_back(e);
}
};
} // namespace loquat
namespace loquat {
namespace detail {
template <typename EdgeType>
auto negate_weight(EdgeType& e) ->
typename std::enable_if<has_weight<EdgeType>::value, void>::type {
e.weight = -e.weight;
}
template <typename EdgeType>
auto negate_weight(EdgeType&) ->
typename std::enable_if<!has_weight<EdgeType>::value, void>::type {}
} // namespace detail
template <typename EdgeType>
struct residual_edge : public EdgeType {
using base_type = EdgeType;
size_t rev;
residual_edge() : base_type(), rev(0) {}
template <typename... Args>
residual_edge(vertex_t to, size_t rev, Args&&... args)
: base_type(to, std::forward<Args>(args)...), rev(rev) {}
residual_edge(const base_type& e, size_t rev) : base_type(e), rev(rev) {}
};
template <typename EdgeType>
adjacency_list<residual_edge<EdgeType>> make_residual(
const adjacency_list<EdgeType>& graph) {
using edge_type = EdgeType;
using residual_type = residual_edge<edge_type>;
using capacity_type = typename edge_type::capacity_type;
const size_t n = graph.size();
adjacency_list<residual_type> result(n);
for (vertex_t u = 0; u < n; ++u) {
for (const auto& e : graph[u]) {
result.add_edge(u, residual_type(e, 0));
}
}
for (vertex_t u = 0; u < n; ++u) {
const size_t m = graph[u].size();
for (size_t i = 0; i < m; ++i) {
auto e = graph[u][i];
const auto v = e.to;
e.to = u;
e.capacity = capacity_type();
detail::negate_weight(e);
result[u][i].rev = result[v].size();
result.add_edge(v, residual_type(e, i));
}
}
return result;
}
} // namespace loquat
namespace loquat {
template <typename EdgeType, typename Predicate>
adjacency_list<EdgeType> filter(const adjacency_list<EdgeType>& graph,
Predicate pred) {
const size_t n = graph.size();
adjacency_list<EdgeType> result(n);
for (vertex_t u = 0; u < n; ++u) {
for (const auto& e : graph[u]) {
if (pred(u, e)) {
result.add_edge(u, e);
}
}
}
return result;
}
} // namespace loquat
namespace loquat {
template <typename T>
constexpr inline auto positive_infinity() noexcept ->
typename std::enable_if<std::is_integral<T>::value, T>::type {
return std::numeric_limits<T>::max();
}
template <typename T>
constexpr inline auto negative_infinity() noexcept ->
typename std::enable_if<std::is_integral<T>::value, T>::type {
return std::numeric_limits<T>::min();
}
template <typename T>
constexpr inline auto is_positive_infinity(T x) noexcept ->
typename std::enable_if<std::is_integral<T>::value, bool>::type {
return x == std::numeric_limits<T>::max();
}
template <typename T>
constexpr inline auto is_negative_infinity(T x) noexcept ->
typename std::enable_if<std::is_integral<T>::value, bool>::type {
return x == std::numeric_limits<T>::min();
}
template <typename T>
constexpr inline auto positive_infinity() noexcept ->
typename std::enable_if<std::is_floating_point<T>::value, T>::type {
return std::numeric_limits<T>::infinity();
}
template <typename T>
constexpr inline auto negative_infinity() noexcept ->
typename std::enable_if<std::is_floating_point<T>::value, T>::type {
return -std::numeric_limits<T>::infinity();
}
template <typename T>
inline auto is_positive_infinity(T x) noexcept ->
typename std::enable_if<std::is_floating_point<T>::value, bool>::type {
return (x > 0) && std::isinf(x);
}
template <typename T>
inline auto is_negative_infinity(T x) noexcept ->
typename std::enable_if<std::is_floating_point<T>::value, bool>::type {
return (x < 0) && std::isinf(x);
}
} // namespace loquat
namespace loquat {
class no_solution_error : public std::runtime_error {
public:
explicit no_solution_error(const char* what) : std::runtime_error(what) {}
explicit no_solution_error(const std::string& what)
: std::runtime_error(what) {}
};
} // namespace loquat
namespace loquat {
template <typename EdgeType>
std::vector<typename EdgeType::weight_type> sssp_bellman_ford(
vertex_t source, const adjacency_list<EdgeType>& graph) {
using weight_type = typename EdgeType::weight_type;
const auto inf = positive_infinity<weight_type>();
const auto n = graph.size();
std::vector<weight_type> result(n, inf);
result[source] = weight_type();
bool finished = false;
for (size_t iter = 0; !finished && iter < n; ++iter) {
finished = true;
for (loquat::vertex_t u = 0; u < n; ++u) {
if (loquat::is_positive_infinity(result[u])) {
continue;
}
for (const auto& e : graph[u]) {
const auto v = e.to;
if (result[u] + e.weight < result[v]) {
result[v] = result[u] + e.weight;
finished = false;
}
}
}
}
if (!finished) {
throw no_solution_error("graph has a negative cycle");
}
return result;
}
} // namespace loquat
namespace loquat {
template <typename EdgeType>
typename EdgeType::weight_type mincostflow_primal_dual(
typename EdgeType::capacity_type flow, vertex_t source, vertex_t sink,
adjacency_list<EdgeType>& graph) {
using edge_type = EdgeType;
using weight_type = typename edge_type::weight_type;
const auto inf = positive_infinity<weight_type>();
const auto n = graph.size();
const auto predicate = [](vertex_t, const edge_type& e) -> bool {
return e.capacity > 0;
};
auto h = sssp_bellman_ford(source, filter(graph, predicate));
std::vector<vertex_t> prev_vertex(n);
std::vector<size_t> prev_edge(n);
weight_type result = 0;
while (flow > 0) {
using pair_type = std::pair<weight_type, vertex_t>;
std::priority_queue<pair_type, std::vector<pair_type>,
std::greater<pair_type>>
pq;
std::vector<weight_type> d(n, inf);
pq.emplace(0, source);
d[source] = weight_type();
while (!pq.empty()) {
const auto p = pq.top();
pq.pop();
const auto u = p.second;
if (d[u] < p.first) {
continue;
}
for (size_t i = 0; i < graph[u].size(); ++i) {
const auto& e = graph[u][i];
if (e.capacity <= 0) {
continue;
}
const auto v = e.to;
const auto t = d[u] + e.weight + h[u] - h[v];
if (d[v] <= t) {
continue;
}
d[v] = t;
prev_vertex[v] = u;
prev_edge[v] = i;
pq.emplace(t, v);
}
}
if (is_positive_infinity(d[sink])) {
throw no_solution_error("there are no enough capacities to flow");
}
for (size_t i = 0; i < n; ++i) {
h[i] += d[i];
}
weight_type f = flow;
for (vertex_t v = sink; v != source; v = prev_vertex[v]) {
const auto u = prev_vertex[v];
f = std::min(f, graph[u][prev_edge[v]].capacity);
}
flow -= f;
result += f * h[sink];
for (vertex_t v = sink; v != source; v = prev_vertex[v]) {
const auto u = prev_vertex[v];
auto& e = graph[u][prev_edge[v]];
e.capacity -= f;
graph[v][e.rev].capacity += f;
}
}
return result;
}
} // namespace loquat
using namespace std;
using edge = loquat::edge<loquat::edge_param::weight<int>,
loquat::edge_param::capacity<int>>;
int main() {
ios_base::sync_with_stdio(false);
int n, m, f;
cin >> n >> m >> f;
loquat::adjacency_list<edge> g(n);
for (int i = 0; i < m; ++i) {
int a, b, c, d;
cin >> a >> b >> c >> d;
g.add_edge(a, b, d, c);
}
const int source = 0, sink = n - 1;
auto residual = loquat::make_residual(g);
cout << loquat::mincostflow_primal_dual(f, source, sink, residual)
<< std::endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
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].push_back(edge{v, c, w, int(G[v].size())});
G[v].push_back(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++];
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, u = p1[t]; v != s; v = u, u = p1[u]) {
int id = p2[v];
G[u][id].cap -= a[t];
id = G[u][id].rev;
G[v][id].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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
class Edge {
public:
int from;
int to;
int flow;
Edge(int f, int t, int d) {
from = f;
to = t;
flow = d;
}
};
class Shortest_path_result {
public:
int sum_of_cost;
vector<int> path;
vector<int> distance;
vector<int> predecessor;
Shortest_path_result() {}
};
class Graph {
public:
int INF;
int n;
vector<set<int> > vertices_list;
vector<map<int, int> > cost_list;
vector<map<int, int> > capacity_list;
vector<int> potential_list;
Graph() {}
Graph(int n) {
INF = 1e9;
this->n = n;
vertices_list.insert(vertices_list.begin(), n, set<int>());
cost_list.insert(cost_list.begin(), n, map<int, int>());
capacity_list.insert(capacity_list.begin(), n, map<int, int>());
potential_list = vector<int>(n, 0);
}
void insert_edge(int b, int e, int cost, int capacity) {
vertices_list[b].insert(e);
cost_list[b][e] = cost;
capacity_list[b][e] = capacity;
}
void delete_edge(int b, int e) {
vertices_list[b].erase(e);
cost_list[b].erase(e);
capacity_list[b].erase(e);
}
int degree_of_vertex(int a) { return vertices_list[a].size(); }
bool edge_search(int a, int b) {
return vertices_list[a].find(b) != vertices_list[a].end();
}
bool path_search(int a, int b, set<int> visited = set<int>()) {
visited.insert(a);
set<int>::iterator itr;
for (itr = vertices_list[a].begin(); itr != vertices_list[a].end(); itr++) {
if ((*itr) == b) {
return true;
}
if (visited.find(*itr) == visited.end()) {
if (path_search(*itr, b, visited)) {
return true;
}
}
}
return false;
}
Shortest_path_result solve_dijkstra(int start, int goal) {
set<int> visited = set<int>();
vector<int> distance = vector<int>(n, INF);
vector<int> predecessor = vector<int>(n);
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
pq;
pq.push(pair<int, int>(0, start));
while (!pq.empty()) {
pair<int, int> p = pq.top();
pq.pop();
int nv = p.second;
if (distance[nv] < p.first) {
continue;
}
distance[nv] = p.first;
for (set<int>::iterator itr = vertices_list[nv].begin();
itr != vertices_list[nv].end(); itr++) {
int next = (*itr);
if (distance[next] > distance[nv] + cost_list[nv][next]) {
distance[next] = distance[nv] + cost_list[nv][next];
predecessor[next] = nv;
pq.push(pair<int, int>(distance[next], next));
}
}
}
Shortest_path_result result;
result.path = vector<int>();
result.path.push_back(goal);
while (true) {
int now = result.path.back();
int pre = predecessor[now];
result.path.push_back(pre);
if (pre == start) {
reverse(result.path.begin(), result.path.end());
break;
}
}
result.sum_of_cost = distance[goal];
result.distance = distance;
result.predecessor = predecessor;
return result;
}
pair<int, vector<Edge> > solve_mincostflow(int s, int t, int flow_size) {
vector<map<int, int> > flow_list = vector<map<int, int> >(n);
vector<map<int, int> > origin_cost = cost_list;
int sum_flow_cost = 0;
while (flow_size > 0) {
Shortest_path_result res;
vector<int> path;
int min_capa = INF;
res = solve_dijkstra(s, t);
path = res.path;
for (int i = 0; i < n; i++) {
potential_list[i] = potential_list[i] - res.distance[i];
}
vector<int>::iterator itr = path.begin();
itr++;
for (; itr != path.end(); itr++) {
if (min_capa > capacity_list[*(itr - 1)][*itr]) {
min_capa = capacity_list[*(itr - 1)][*itr];
}
}
if (min_capa > flow_size) {
min_capa = flow_size;
}
itr = path.begin();
itr++;
for (; itr != path.end(); itr++) {
if (flow_list[*(itr - 1)].find(*itr) == flow_list[*(itr - 1)].end()) {
flow_list[*(itr - 1)][*itr] = min_capa;
} else {
flow_list[*(itr - 1)][*itr] += min_capa;
}
}
flow_size = flow_size - min_capa;
itr = path.begin();
for (itr++; itr != path.end(); itr++) {
int capa, cost;
int from, to;
from = *(itr - 1);
to = *itr;
capa = capacity_list[from][to];
cost = cost_list[from][to];
delete_edge(from, to);
if (capa - min_capa > 0) {
insert_edge(from, to, cost, capa - min_capa);
}
insert_edge(to, from, -1 * cost, min_capa);
}
for (int b = 0; b > n; b++) {
map<int, int>::iterator itr;
for (itr = cost_list[b].begin(); itr != cost_list[b].end(); itr++) {
(*itr).second =
(*itr).second - potential_list[itr->first] + potential_list[b];
}
}
}
for (int i = 0; i < n; i++) {
map<int, int>::iterator itr;
for (itr = flow_list[i].begin(); itr != flow_list[i].end(); itr++) {
sum_flow_cost += origin_cost[i][itr->first] * itr->second;
}
}
cout << sum_flow_cost << endl;
return pair<int, vector<Edge> >();
}
void print(void) {
int i = 0;
vector<set<int> >::iterator itr;
set<int>::iterator itr_c;
for (itr = vertices_list.begin(); itr != vertices_list.end(); itr++) {
cout << i << ":";
for (itr_c = (*itr).begin(); itr_c != (*itr).end(); itr_c++) {
cout << *itr_c << "(" << capacity_list[i][*itr_c] << ")"
<< ",";
}
i++;
cout << endl;
}
}
};
int main() {
const int inf = 1e9;
int v, e, flow;
Graph g;
cin >> v >> e >> flow;
g = Graph(v);
int from, to, cost, cap;
for (int i = 0; i < e; i++) {
cin >> from >> to >> cap >> cost;
g.insert_edge(from, to, cost, cap);
}
g.solve_mincostflow(0, v - 1, flow);
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1100;
bool mark[maxN];
int parentEdge[maxN], dis[maxN];
int n, k, m, st, fn, F, remFlow;
struct edge {
int u, v, weight, cap;
};
vector<int> g[maxN];
edge e[maxN * maxN];
int curID = 0;
edge make_edge(int u, int v, int w, int cap) {
edge e;
e.u = u;
e.v = v;
e.weight = w;
e.cap = cap;
return e;
}
void input() {
cin >> n >> m >> F;
for (int i = 1; i <= m; i++) {
int k1, k2, w, cap;
cin >> k1 >> k2;
k1++;
k2++;
cin >> cap >> w;
e[curID] = make_edge(k1, k2, w, cap);
g[k1].push_back(curID++);
e[curID] = make_edge(k2, k1, -w, 0);
g[k2].push_back(curID++);
}
}
int extract_min() {
int ret = 0;
for (int i = 1; i <= n; i++)
if (!mark[i] && dis[i] <= dis[ret]) ret = i;
return ret;
}
void update(int v) {
mark[v] = true;
for (auto ID : g[v])
if (dis[e[ID].v] > dis[v] + e[ID].weight && e[ID].cap > 0) {
parentEdge[e[ID].v] = ID;
dis[e[ID].v] = dis[v] + e[ID].weight;
}
}
pair<int, int> dijkstra(int v = st) {
int pushed = remFlow;
int cost = 0;
fill(dis, dis + n + 1, INT_MAX / 2);
memset(mark, 0, (n + 10) * sizeof(mark[0]));
memset(parentEdge, -1, (n + 10) * sizeof(parentEdge[0]));
dis[v] = 0;
while (int v = extract_min()) {
update(v);
}
if (!mark[fn]) return {0, 0};
v = fn;
while (parentEdge[v] != -1) {
pushed = min(pushed, e[parentEdge[v]].cap);
v = e[parentEdge[v]].u;
}
v = fn;
while (parentEdge[v] != -1) {
cost += pushed * e[parentEdge[v]].weight;
e[parentEdge[v]].cap -= pushed;
e[parentEdge[v] ^ 1].cap += pushed;
v = e[parentEdge[v]].u;
}
return {pushed, cost};
}
int MinCostMaxFlow() {
int flow = 0, cost = 0;
remFlow = F;
while (true) {
auto ans = dijkstra();
if (ans.first == 0) break;
flow += ans.first;
remFlow -= ans.first;
cost += ans.second;
}
return cost;
}
void show() {
for (int i = 0; i < curID; i++) {
auto ed = e[i];
cout << i << " " << ed.u << " " << ed.v << " " << ed.cap << " " << ed.weight
<< endl;
}
}
int main() {
input();
st = 1;
fn = n;
int cost = MinCostMaxFlow();
cout << cost << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
class Networkflow {
private:
struct edgedata {
int from, to, capacity, weight;
edgedata* dual_p;
bool operator<(const edgedata& another) const {
return (weight != another.weight ? weight < another.weight
: capacity > another.capacity);
}
};
struct node {
int id, d;
bool done;
edgedata* fromedge_p;
list<edgedata> edges;
bool operator<(const node& another) const {
return !(d != another.d ? d < another.d : id < another.id);
}
};
vector<node> nodes;
int n;
int source, sink;
edgedata* dummy;
public:
int result;
Networkflow(int size, int s, int t) {
n = size;
source = s;
sink = t;
nodes.resize(n);
dummy = new edgedata;
init();
}
void init() {
for (int i = 0; i < (int)n; i++) {
nodes[i] = {i, 2147483647, false, dummy, {}};
}
}
void addedge(int s, int t, int c, int w) {
nodes[s].edges.push_back({s, t, c, w, dummy});
nodes[t].edges.push_back({t, s, 0, w * (-1), &(nodes[s].edges.back())});
nodes[s].edges.back().dual_p = &(nodes[t].edges.back());
}
void maxflow() {
for (int i = 0; i < (int)n; i++) nodes[i].edges.sort();
result = 0;
vector<pair<int, edgedata*>> stk;
int a;
int df;
while (1) {
a = source;
for (int i = 0; i < (int)n; i++) nodes[i].done = false;
nodes[source].done = true;
while (a != sink) {
int b = -1;
edgedata* p;
for (auto itr = nodes[a].edges.begin(); itr != nodes[a].edges.end();
++itr) {
if ((*itr).capacity > 0) {
b = (*itr).to;
if (nodes[b].done)
b = -1;
else {
p = &(*itr);
stk.push_back(make_pair(a, p));
nodes[b].done = true;
a = b;
break;
}
}
}
if (b == -1) {
if (stk.empty()) break;
a = stk.back().first;
stk.pop_back();
}
}
if (stk.empty()) break;
df = 2147483647;
for (int i = 0; i < (int)stk.size(); i++) {
df = min(df, (*(stk[i].second)).capacity);
}
while (stk.size()) {
(*(stk.back().second)).capacity -= df;
(*((*(stk.back().second)).dual_p)).capacity += df;
stk.pop_back();
}
result += df;
}
return;
}
bool mincostflow(int flow) {
for (int i = 0; i < (int)n; i++) nodes[i].edges.sort();
result = 0;
node a;
int df;
int sumf = 0;
while (1) {
for (int i = 0; i < (int)n; i++) {
nodes[i].d = 2147483647;
nodes[i].done = false;
nodes[i].fromedge_p = dummy;
}
priority_queue<node> pq;
nodes[source].d = 0;
pq.push(nodes[source]);
while (pq.size()) {
a = pq.top();
pq.pop();
if (nodes[a.id].done) continue;
nodes[a.id].done = true;
for (auto itr = nodes[a.id].edges.begin();
itr != nodes[a.id].edges.end(); ++itr) {
if ((*itr).capacity == 0) continue;
node* b = &nodes[(*itr).to];
if ((*b).done) continue;
long long int cand = nodes[a.id].d + ((*itr).weight);
if (cand < (*b).d) {
(*b).d = cand;
(*b).fromedge_p = &(*itr);
pq.push(*b);
}
}
}
if (!nodes[sink].done) break;
df = 2147483647;
int focus = sink;
while (focus != source) {
df = min(df, (*(nodes[focus].fromedge_p)).capacity);
focus = (*(nodes[focus].fromedge_p)).from;
}
df = min(df, flow - sumf);
focus = sink;
while (focus != source) {
(*(nodes[focus].fromedge_p)).capacity -= df;
(*((*(nodes[focus].fromedge_p)).dual_p)).capacity += df;
focus = (*(nodes[focus].fromedge_p)).from;
}
sumf += df;
result += nodes[sink].d * df;
if (sumf == flow) return true;
}
return false;
}
};
int main() {
int v, e, f;
cin >> v >> e >> f;
Networkflow networkflow(v, 0, v - 1);
for (int i = 0; i < (int)e; i++) {
int s, t, c, d;
cin >> s >> t >> c >> d;
networkflow.addedge(s, t, c, d);
}
networkflow.mincostflow(f);
cout << networkflow.result << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | python2 | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import sys
import csv
import argparse
import time
import heapq
INF = sys.maxint/3
class Edge:
def __init__(self, to, cap, cost, rev):
self.to = to
self.cap = cap
self.cost = cost
self.rev = rev
def print_attributes(self):
print "to: {0}, cap: {1}, cost: {2}, rev: {3}".format(self.to, self.cap, self.cost, self.rev)
class MinimumCostFlow:
def __init__(self, V, E):
self.V = V
self.E = E
self.G = [[] for i in range(V)]
def add_edge(self, s, t, cap, cost):
forward_edge = Edge(t, cap, cost, len(self.G[t]))
self.G[s].append(forward_edge)
backward_edge = Edge(s, 0, -cost, len(self.G[s])-1)
self.G[t].append(backward_edge)
def print_edges(self):
print "==== print edges ===="
for i in range(self.V):
print "\nedges from {}".format(i)
for e in self.G[i]:
e.print_attributes()
def minimum_cost_flow(self, s, t, f):
res = 0
h = [0] * self.V
while f>0:
pque = []
dist = [INF for i in range(self.V)]
prev_v = [0 for i in range(self.V)]
prev_e = [0 for i in range(self.V)]
dist[s] = 0
heapq.heappush(pque, (0, s))
while(len(pque)!=0):
p = heapq.heappop(pque)
v = p[1]
if (dist[v] < p[0]):
continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if (e.cap>0 and dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]):
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]
prev_v[e.to] = v
prev_e[e.to] = i
heapq.heappush(pque, (dist[e.to], e.to))
if dist[t] == INF:
return -1
for v in range(self.V):
h[v] += dist[v]
d = f
v = t
while v!=s:
d = min(d, self.G[prev_v[v]][prev_e[v]].cap)
v = prev_v[v]
f -= d
res += d * h[t]
v = t
while v!=s:
e = self.G[prev_v[v]][prev_e[v]]
e.cap -= d
self.G[v][e.rev].cap += d
v = prev_v[v]
return res
def main():
V, E, F = map(int, raw_input().split())
mcf = MinimumCostFlow(V, E)
for i in range(E):
u, v, c, d = map(int, raw_input().split())
mcf.add_edge(u, v, c, d)
#print "minimum cost flow: {}".format(mcf.minimum_cost_flow(0, V-1, F))
print mcf.minimum_cost_flow(0, V-1, F)
if __name__ == '__main__':
main()
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void output(T a, int p) {
if (p)
cout << fixed << setprecision(p) << a << "\n";
else
cout << a << "\n";
}
struct node {
int cost, pos;
};
struct edge {
int to, cap, cost, rev;
};
bool operator<(const node &a, const node &b) { return a.cost < b.cost; }
class MinCostFlow {
public:
int V;
vector<vector<edge>> G;
vector<int> h, dist, preV, preE;
MinCostFlow(int V) : V(V), G(V), h(V), dist(V), preV(V), preE(V) {}
void add_edge(int from, int to, int cap, int cost) {
G[from].push_back({to, cap, cost, (int)G[to].size()});
G[to].push_back({from, 0, -cost, (int)G[from].size()});
}
int calc(int s, int t, int f) {
int ret = 0;
h.assign(V, 0);
while (f) {
dist.assign(V, 2000000007);
priority_queue<node> pq;
pq.push({0, s});
dist[s] = 0;
while (!pq.empty()) {
node p = pq.top();
pq.pop();
int d = p.cost;
int v = p.pos;
if (dist[v] < d) continue;
for (int i = (int)(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];
preV[e.to] = v;
preE[e.to] = i;
pq.push({dist[e.to], e.to});
}
}
}
if (dist[t] == 2000000007) return -1;
for (int v = (int)(0); v < (int)(V); v++) h[v] += dist[v];
int d = f;
for (int v = t; v != s; v = preV[v]) {
d = min(d, G[preV[v]][preE[v]].cap);
}
f -= d;
ret += d * h[t];
for (int v = t; v != s; v = preV[v]) {
edge &e = G[preV[v]][preE[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return ret;
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int V, E, F;
cin >> V >> E >> F;
MinCostFlow mcf(V);
for (int i = (int)(0); i < (int)(E); i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
output(mcf.calc(0, V - 1, F), 0);
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
class Edge {
public:
int from;
int to;
int flow;
Edge(int f, int t, int d) {
from = f;
to = t;
flow = d;
}
};
class Shortest_path_result {
public:
int sum_of_cost;
vector<int> path;
vector<int> distance;
vector<int> predecessor;
Shortest_path_result() {}
};
class Graph {
public:
int INF;
int n;
vector<set<int> > vertices_list;
vector<map<int, int> > cost_list;
vector<map<int, int> > capacity_list;
vector<int> potential_list;
Graph() {}
Graph(int n) {
INF = 1e9;
this->n = n;
vertices_list.insert(vertices_list.begin(), n, set<int>());
cost_list.insert(cost_list.begin(), n, map<int, int>());
capacity_list.insert(capacity_list.begin(), n, map<int, int>());
potential_list = vector<int>(n, 0);
}
void insert_edge(int b, int e, int cost, int capacity) {
vertices_list[b].insert(e);
cost_list[b][e] = cost;
capacity_list[b][e] = capacity;
}
void delete_edge(int b, int e) {
vertices_list[b].erase(e);
cost_list[b].erase(e);
capacity_list[b].erase(e);
}
int degree_of_vertex(int a) { return vertices_list[a].size(); }
bool edge_search(int a, int b) {
return vertices_list[a].find(b) != vertices_list[a].end();
}
bool path_search(int a, int b, set<int> visited = set<int>()) {
visited.insert(a);
set<int>::iterator itr;
for (itr = vertices_list[a].begin(); itr != vertices_list[a].end(); itr++) {
if ((*itr) == b) {
return true;
}
if (visited.find(*itr) == visited.end()) {
if (path_search(*itr, b, visited)) {
return true;
}
}
}
return false;
}
Shortest_path_result solve_dijkstra(int start, int goal) {
set<int> visited = set<int>();
vector<int> distance = vector<int>(n, INF);
vector<int> predecessor = vector<int>(n);
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
pq;
pq.push(pair<int, int>(0, start));
while (!pq.empty()) {
pair<int, int> p = pq.top();
pq.pop();
int nv = p.second;
if (distance[nv] < p.first) {
continue;
}
distance[nv] = p.first;
for (set<int>::iterator itr = vertices_list[nv].begin();
itr != vertices_list[nv].end(); itr++) {
int next = (*itr);
if (distance[next] > distance[nv] + cost_list[nv][next]) {
distance[next] = distance[nv] + cost_list[nv][next];
predecessor[next] = nv;
pq.push(pair<int, int>(distance[next], next));
}
}
}
Shortest_path_result result;
result.path = vector<int>();
result.path.push_back(goal);
while (true) {
int now = result.path.back();
int pre = predecessor[now];
result.path.push_back(pre);
if (pre == start) {
reverse(result.path.begin(), result.path.end());
break;
}
}
result.sum_of_cost = distance[goal];
result.distance = distance;
result.predecessor = predecessor;
return result;
}
pair<int, vector<Edge> > solve_mincostflow(int s, int t, int flow_size) {
vector<map<int, int> > flow_list = vector<map<int, int> >(n);
vector<map<int, int> > origin_cost = cost_list;
bool feasible_flag = true;
int sum_flow_cost = 0;
while (flow_size > 0) {
Shortest_path_result res;
vector<int> path;
int min_capa = INF;
res = solve_dijkstra(s, t);
cout << res.sum_of_cost << endl;
if (res.sum_of_cost == INF) {
feasible_flag = false;
break;
}
path = res.path;
for (int i = 0; i < n; i++) {
potential_list[i] = potential_list[i] - res.distance[i];
}
vector<int>::iterator itr = path.begin();
itr++;
for (; itr != path.end(); itr++) {
if (min_capa > capacity_list[*(itr - 1)][*itr]) {
min_capa = capacity_list[*(itr - 1)][*itr];
}
}
if (min_capa > flow_size) {
min_capa = flow_size;
}
itr = path.begin();
itr++;
for (; itr != path.end(); itr++) {
if (flow_list[*(itr - 1)].find(*itr) == flow_list[*(itr - 1)].end()) {
flow_list[*(itr - 1)][*itr] = min_capa;
} else {
flow_list[*(itr - 1)][*itr] += min_capa;
}
}
flow_size = flow_size - min_capa;
itr = path.begin();
for (itr++; itr != path.end(); itr++) {
int capa, cost;
int from, to;
from = *(itr - 1);
to = *itr;
capa = capacity_list[from][to];
cost = cost_list[from][to];
delete_edge(from, to);
if (capa - min_capa > 0) {
insert_edge(from, to, cost, capa - min_capa);
}
insert_edge(to, from, -1 * cost, min_capa);
}
for (int b = 0; b > n; b++) {
map<int, int>::iterator itr;
for (itr = cost_list[b].begin(); itr != cost_list[b].end(); itr++) {
(*itr).second =
(*itr).second - potential_list[itr->first] + potential_list[b];
}
}
}
for (int i = 0; i < n; i++) {
map<int, int>::iterator itr;
for (itr = flow_list[i].begin(); itr != flow_list[i].end(); itr++) {
sum_flow_cost += origin_cost[i][itr->first] * itr->second;
}
}
if (!feasible_flag) {
cout << "-1" << endl;
} else {
cout << sum_flow_cost << endl;
}
return pair<int, vector<Edge> >();
}
void print(void) {
int i = 0;
vector<set<int> >::iterator itr;
set<int>::iterator itr_c;
for (itr = vertices_list.begin(); itr != vertices_list.end(); itr++) {
cout << i << ":";
for (itr_c = (*itr).begin(); itr_c != (*itr).end(); itr_c++) {
cout << *itr_c << "(" << capacity_list[i][*itr_c] << ")"
<< ",";
}
i++;
cout << endl;
}
}
};
int main() {
const int inf = 1e9;
int v, e, flow;
Graph g;
cin >> v >> e >> flow;
g = Graph(v);
int from, to, cost, cap;
for (int i = 0; i < e; i++) {
cin >> from >> to >> cap >> cost;
g.insert_edge(from, to, cost, cap);
}
g.solve_mincostflow(0, v - 1, flow);
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
constexpr int INF = 1e9;
struct Edge {
int to, cap, rev, weight;
Edge(int t, int c, int r, int w) : to(t), cap(c), rev(r), weight(w) {}
};
using Edges = vector<Edge>;
using Graph = vector<Edges>;
class Flow {
public:
Flow(int v) {
mGraph.resize(v);
mUsed.assign(v, false);
mVert = v;
}
void add_edge(int from, int to, int cap, int weight = 1) {
mGraph[from].emplace_back(to, cap, mGraph[to].size(), weight);
mGraph[to].emplace_back(from, 0, mGraph[from].size() - 1, weight);
}
int bipartite_matching(int x, int y) {
int start = max(x, y) * 2;
int end = max(x, y) * 2 + 1;
for (int i = 0; i < x; ++i) add_edge(start, i, 1);
for (int i = 0; i < y; ++i) add_edge(i + x, end, 1);
return max_flow(start, end);
}
int dfs(int v, int t, int f) {
if (v == t) return f;
mUsed[v] = true;
for (auto &e : mGraph[v]) {
if (!mUsed[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
mGraph[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
while (true) {
mUsed.assign(mVert, false);
int f = dfs(s, t, INF);
if (f == 0) break;
flow += f;
}
return flow;
}
int min_cost_flow(int s, int t, int f) {
int res = 0;
while (f > 0) {
vector<int> dst(mVert, INF);
vector<int> prevv(mVert);
vector<int> preve(mVert);
dst[s] = 0;
for (int i = 0; i < mVert; ++i) {
for (int j = 0; j < mGraph[i].size(); ++j) {
auto e = mGraph[i][j];
if (e.cap > 0 && dst[i] != INF && dst[e.to] > dst[i] + e.weight) {
dst[e.to] = dst[i] + e.weight;
prevv[e.to] = i;
preve[e.to] = j;
}
}
}
if (dst[t] == INF) return -1;
int d = f;
for (int i = t; i != s; i = prevv[i]) {
d = min(d, mGraph[prevv[i]][preve[i]].cap);
}
f -= d;
res += d * dst[t];
for (int i = t; i != s; i = prevv[i]) {
Edge &e = mGraph[prevv[i]][preve[i]];
e.cap += d;
mGraph[i][e.rev].cap -= d;
}
}
return res;
}
private:
Graph mGraph;
vector<bool> mUsed;
int mVert;
};
int main() {
int V, E, F, u, v, c, d;
cin >> V >> E >> F;
Flow f(V);
for (int i = 0; i < E; ++i) {
cin >> u >> v >> c >> d;
f.add_edge(u, v, c, d);
}
cout << f.min_cost_flow(0, V - 1, F) << '\n';
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
class Edge {
public:
int from;
int to;
int flow;
Edge(int f, int t, int d) {
from = f;
to = t;
flow = d;
}
};
class Shortest_path_result {
public:
int sum_of_cost;
vector<int> path;
vector<int> distance;
vector<int> predecessor;
Shortest_path_result() {}
};
class Graph {
public:
int INF;
int n;
vector<set<int> > vertices_list;
vector<map<int, int> > cost_list;
vector<map<int, int> > capacity_list;
vector<int> potential_list;
Graph() {}
Graph(int n) {
INF = 1e9;
this->n = n;
vertices_list.insert(vertices_list.begin(), n, set<int>());
cost_list.insert(cost_list.begin(), n, map<int, int>());
capacity_list.insert(capacity_list.begin(), n, map<int, int>());
potential_list = vector<int>(n, 0);
}
void insert_edge(int b, int e, int cost, int capacity) {
vertices_list[b].insert(e);
cost_list[b][e] = cost;
capacity_list[b][e] = capacity;
}
void delete_edge(int b, int e) {
vertices_list[b].erase(e);
cost_list[b].erase(e);
capacity_list[b].erase(e);
}
int degree_of_vertex(int a) { return vertices_list[a].size(); }
bool edge_search(int a, int b) {
return vertices_list[a].find(b) != vertices_list[a].end();
}
bool path_search(int a, int b, set<int> visited = set<int>()) {
visited.insert(a);
set<int>::iterator itr;
for (itr = vertices_list[a].begin(); itr != vertices_list[a].end(); itr++) {
if ((*itr) == b) {
return true;
}
if (visited.find(*itr) == visited.end()) {
if (path_search(*itr, b, visited)) {
return true;
}
}
}
return false;
}
Shortest_path_result solve_dijkstra(int start, int goal) {
set<int> visited = set<int>();
vector<int> distance = vector<int>(n, INF);
vector<int> predecessor = vector<int>(n);
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
pq;
pq.push(pair<int, int>(0, start));
while (!pq.empty()) {
pair<int, int> p = pq.top();
pq.pop();
int nv = p.second;
if (distance[nv] < p.first) {
continue;
}
distance[nv] = p.first;
for (set<int>::iterator itr = vertices_list[nv].begin();
itr != vertices_list[nv].end(); itr++) {
int next = (*itr);
if (distance[next] > distance[nv] + cost_list[nv][next]) {
distance[next] = distance[nv] + cost_list[nv][next];
predecessor[next] = nv;
pq.push(pair<int, int>(distance[next], next));
}
}
}
Shortest_path_result result;
result.path = vector<int>();
result.path.push_back(goal);
while (true) {
int now = result.path.back();
int pre = predecessor[now];
result.path.push_back(pre);
if (pre == start) {
reverse(result.path.begin(), result.path.end());
break;
}
}
result.sum_of_cost = distance[goal];
result.distance = distance;
result.predecessor = predecessor;
return result;
}
pair<int, vector<Edge> > solve_mincostflow(int s, int t, int flow_size) {
vector<map<int, int> > flow_list = vector<map<int, int> >(n);
vector<map<int, int> > origin_cost = cost_list;
bool feasible_flag = true;
int sum_flow_cost = 0;
while (flow_size > 0) {
Shortest_path_result res;
vector<int> path;
int min_capa = INF;
res = solve_dijkstra(s, t);
if (res.sum_of_cost == INF) {
feasible_flag = false;
break;
}
path = res.path;
for (int i = 0; i < n; i++) {
potential_list[i] = potential_list[i] - res.distance[i];
}
vector<int>::iterator itr = path.begin();
itr++;
for (; itr != path.end(); itr++) {
if (min_capa > capacity_list[*(itr - 1)][*itr]) {
min_capa = capacity_list[*(itr - 1)][*itr];
}
}
if (min_capa > flow_size) {
min_capa = flow_size;
}
itr = path.begin();
itr++;
for (; itr != path.end(); itr++) {
if (flow_list[*(itr - 1)].find(*itr) == flow_list[*(itr - 1)].end()) {
flow_list[*(itr - 1)][*itr] = min_capa;
} else {
flow_list[*(itr - 1)][*itr] += min_capa;
}
}
flow_size = flow_size - min_capa;
itr = path.begin();
for (itr++; itr != path.end(); itr++) {
int capa, cost;
int from, to;
from = *(itr - 1);
to = *itr;
capa = capacity_list[from][to];
cost = cost_list[from][to];
delete_edge(from, to);
if (capa - min_capa > 0) {
insert_edge(from, to, cost, capa - min_capa);
}
insert_edge(to, from, -1 * cost, min_capa);
}
for (int b = 0; b > n; b++) {
map<int, int>::iterator itr;
for (itr = cost_list[b].begin(); itr != cost_list[b].end(); itr++) {
(*itr).second =
(*itr).second - potential_list[itr->first] + potential_list[b];
}
}
}
for (int i = 0; i < n; i++) {
map<int, int>::iterator itr;
for (itr = flow_list[i].begin(); itr != flow_list[i].end(); itr++) {
sum_flow_cost += origin_cost[i][itr->first] * itr->second;
}
}
if (!feasible_flag) {
cout << "-1" << endl;
} else {
cout << sum_flow_cost << endl;
}
return pair<int, vector<Edge> >();
}
void print(void) {
int i = 0;
vector<set<int> >::iterator itr;
set<int>::iterator itr_c;
for (itr = vertices_list.begin(); itr != vertices_list.end(); itr++) {
cout << i << ":";
for (itr_c = (*itr).begin(); itr_c != (*itr).end(); itr_c++) {
cout << *itr_c << "(" << capacity_list[i][*itr_c] << ")"
<< ",";
}
i++;
cout << endl;
}
}
};
int main() {
const int inf = 1e9;
int v, e, flow;
Graph g;
cin >> v >> e >> flow;
g = Graph(v);
int from, to, cost, cap;
for (int i = 0; i < e; i++) {
cin >> from >> to >> cap >> cost;
g.insert_edge(from, to, cost, cap);
}
g.solve_mincostflow(0, v - 1, flow);
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | UNKNOWN | class PQueue
attr_accessor :node
def initialize
@node = []
end
def insert(num)
i = @node.size
@node[i] = num
down_heap(i)
end
def extract
ret = @node[0]
if @node.size > 1
@node[0] = @node.pop()
up_heap(0)
else
@node = []
end
return ret
end
def delete(node)
i = @node.index(node)
if i == @node.size - 1
@node.pop
else
@node[i] = @node.pop
copy = @node.clone
down_heap(i)
if copy == @node
up_heap(i)
end
end
end
def modify(old, new)
delete(old)
insert(new)
end
def up_heap(i)
h = @node.size
largest = i
l = 2 * i + 1
largest = l if l < h && @node[l] > @node[largest]
r = 2 * i + 2
largest = r if r < h && @node[r] > @node[largest]
while largest != i
@node[i], @node[largest] = @node[largest], @node[i]
i = largest
l = 2 * i + 1
largest = l if l < h && @node[l] > @node[largest]
r = 2 * i + 2
largest = r if r < h && @node[r] > @node[largest]
end
end
def down_heap(i)
p = (i+1)/2-1
while i > 0 && @node[p] < @node[i]
@node[i], @node[p] = @node[p], @node[i]
i = p
p = (i+1)/2-1
end
end
end
INF = 1.0 / 0.0
class Node
attr_accessor :i, :c, :prev, :d, :pot, :ans
def initialize(i)
@i = i
@c = {}
@ans = {}
@prev = nil
@d = INF
@pot = 0
end
def <(other)
if self.d > other.d
return true
else
return false
end
end
def >(other)
if self.d < other.d
return true
else
return false
end
end
end
nv, ne, f = gets.split.map(&:to_i)
g = Array.new(nv){|i| Node.new(i)}
ne.times{|i|
u, v, c, d = gets.split.map(&:to_i)
g[u].c[v] = [c, d]
g[u].ans[v] = [0,d]
}
loop do
nv.times{|i|
g[i].d = INF
g[i].prev = nil
}
g[0].d = 0
q = PQueue.new
nv.times{|i|
q.insert(g[i])
}
while q.node.size > 0
u = q.extract
u.c.each{|v, val|
alt = u.d + val[1]
if g[v].d > alt
q.delete(g[v])
g[v].d = alt
g[v].prev = u.i
q.insert(g[v])
end
}
end
# p g
max = f
c = nv-1
path = [c]
while c != 0
p = g[c].prev
if p == nil
puts "-1"
exit
end
path.unshift(p)
max = g[p].c[c][0] if max > g[p].c[c][0]
c = p
end
# p path
# p max
if max < f then
#make potential
path.each{|i|
g[i].pot -= g[i].d
}
(path.size-1).times{|i|
u = path[i]
v = path[i+1]
g[u].ans[v][0] += max
}
# p g
f -= max
else
(path.size-1).times{|i|
u = path[i]
v = path[i+1]
g[u].ans[v][0] += f
}
break
end
#make sub-network
(path.size-1).times{|i|
u = path[i]
v = path[i+1]
g[v].c[u] ||= [0, -g[u].c[v][1]]
g[v].c[u][0] += max
g[u].c[v][0] -= max
if g[u].c[v][0] == 0
g[u].c.delete(v)
end
}
#make modified sub-network
g.size.times{|i|
g[i].c.each{|j, val|
# p "#{g[i].c[j][1]} #{g[i].pot} #{g[j].pot}"
g[i].c[j][1] -= g[i].pot - g[j].pot
}
}
# g.size.times{|i|
# p g[i]
# }
end
sum = 0
nv.times{|i|
g[i].ans.each{|k,v|
sum += v[0]*v[1]
}
}
puts sum |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
#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;) {
edge e=G[p1[u]][p2[u]];
G[p1[u]][p2[u]].cap-=d;
G[e.to][e.rev].cap+=d;
}
}
if (flow<k) return -1;
else return cost;
}
int main() {
cin>>n>>m>>k;
for (int i=0;i<m;i++) {
int u,v,c,w; cin>>u>>v>>c>>w;
add_edge(u,v,c,w);
}
cout<<mcmf(0,n-1)<<'\n';
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
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 = INF;
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": []
} | IN-CORRECT | cpp | '''
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import csv
import argparse
import time
'''
import sys
import heapq
INF = sys.maxint/3
class Edge:
def __init__(self, to, cap, cost, rev):
self.to = to
self.cap = cap
self.cost = cost
self.rev = rev
def print_attributes(self):
print "to: {0}, cap: {1}, cost: {2}, rev: {3}".format(self.to, self.cap, self.cost, self.rev)
class MinimumCostFlow:
def __init__(self, V, E):
self.V = V
self.E = E
self.G = [[] for i in range(V)]
def add_edge(self, s, t, cap, cost):
forward_edge = Edge(t, cap, cost, len(self.G[t]))
self.G[s].append(forward_edge)
backward_edge = Edge(s, 0, -cost, len(self.G[s])-1)
self.G[t].append(backward_edge)
def print_edges(self):
print "==== print edges ===="
for i in range(self.V):
print "\nedges from {}".format(i)
for e in self.G[i]:
e.print_attributes()
def minimum_cost_flow(self, s, t, f):
res = 0
h = [0] * self.V
while f>0:
pque = []
dist = [INF for i in range(self.V)]
prev_v = [0 for i in range(self.V)]
prev_e = [0 for i in range(self.V)]
dist[s] = 0
heapq.heappush(pque, (0, s))
while(len(pque)!=0):
p = heapq.heappop(pque)
v = p[1]
if (dist[v] < p[0]):
continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if (e.cap>0 and dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]):
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]
prev_v[e.to] = v
prev_e[e.to] = i
heapq.heappush(pque, (dist[e.to], e.to))
if dist[t] == INF:
return -1
for v in range(self.V):
h[v] += dist[v]
d = f
v = t
while v!=s:
d = min(d, self.G[prev_v[v]][prev_e[v]].cap)
v = prev_v[v]
f -= d
res += d * h[t]
v = t
while v!=s:
e = self.G[prev_v[v]][prev_e[v]]
e.cap -= d
self.G[v][e.rev].cap += d
v = prev_v[v]
return res
def main():
V, E, F = map(int, raw_input().split())
mcf = MinimumCostFlow(V, E)
for i in range(E):
u, v, c, d = map(int, raw_input().split())
mcf.add_edge(u, v, c, d)
#print "minimum cost flow: {}".format(mcf.minimum_cost_flow(0, V-1, F))
print mcf.minimum_cost_flow(0, V-1, F)
if __name__ == '__main__':
main()
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
struct min_cost_flow_graph {
struct edge {
int from, to;
T cap, f;
U cost;
};
vector<edge> edges;
vector<vector<int>> g;
int n, st, fin;
T required_flow, flow;
U cost;
min_cost_flow_graph(int n, int st, int fin, T required_flow)
: n(n), st(st), fin(fin), required_flow(required_flow) {
assert(0 <= st && st < n && 0 <= fin && fin < n && st != fin);
g.resize(n);
flow = 0;
cost = 0;
}
void clear_graph() {
for (const edge &e : edges) {
e.f = 0;
}
flow = 0;
cost = 0;
}
void add(int from, int to, T cap = 1, T rev_cap = 0, U cost = 1) {
assert(0 <= from && from < n && 0 <= to && to < n);
g[from].emplace_back(edges.size());
edges.push_back({from, to, cap, 0, cost});
g[to].emplace_back(edges.size());
edges.push_back({to, from, rev_cap, 0, -cost});
}
U min_cost_flow() {
while (flow < required_flow) {
T dist[n];
fill(dist, dist + n, numeric_limits<T>::max());
dist[st] = 0;
int prevv[n], preve[n];
for (bool update = true; update;) {
update = false;
for (int id = 0; id < edges.size(); id++) {
edge &e = edges[id];
if (0 < e.cap - e.f && dist[e.from] + e.cost < dist[e.to]) {
dist[e.to] = dist[e.from] + e.cost;
prevv[e.to] = e.from;
preve[e.to] = id;
update = true;
}
}
}
if (dist[fin] == numeric_limits<T>::max()) {
return -1;
}
T d = numeric_limits<U>::max();
for (int v = fin; v != st; v = prevv[v]) {
d = min(d, edges[preve[v]].cap - edges[preve[v]].f);
}
flow += d;
cost += d * dist[fin];
for (int v = fin; v != st; v = prevv[v]) {
edges[preve[v]].f += d;
edges[preve[v] ^ 1].f -= d;
}
}
return cost;
}
};
int main() {
int n, m, f;
cin >> n >> m >> f;
min_cost_flow_graph<int64_t, int64_t> g(n, 0, n - 1, f);
for (int i = 0; i < m; i++) {
int64_t from, to, cap, cost;
cin >> from >> to >> cap >> cost;
g.add(from, to, cap, 0, cost);
}
cout << g.min_cost_flow() << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
int main() {
int a, b;
scanf("%d%d", &a, &b);
printf("d\n", a + 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": []
} | IN-CORRECT | python3 | from heapq import heappop, heappush
def trace(source, edge_trace):
v = source
for i in edge_trace:
e = edges[v][i]
yield e
v = e[1]
def min_cost_flow(source, sink, required_flow):
res = 0
while required_flow:
dist = [-1] * n
queue = [(0, source, tuple())]
edge_trace = None
while queue:
total_cost, v, edge_memo = heappop(queue)
dist[v] = total_cost
if v == sink:
edge_trace = edge_memo
break
for i, (remain, target, cost, _) in enumerate(edges[v]):
if remain and dist[target] == -1:
heappush(queue, (total_cost + cost, target, edge_memo + (i,)))
if dist[sink] == -1:
return -1
aug = min(e[0] for e in trace(source, edge_trace))
required_flow -= aug
res += aug * dist[sink]
for e in trace(source, edge_trace):
remain, target, cost, idx = e
e[0] -= aug
edges[target][idx][0] += aug
return res
n, m, f = map(int, input().split())
edges = [[] for _ in range(n)]
for _ in range(m):
s, t, c, d = map(int, input().split())
es, et = edges[s], edges[t]
ls, lt = len(es), len(et)
es.append([c, t, d, lt])
et.append([0, s, d, ls])
print(min_cost_flow(0, n - 1, f)) |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | java | import java.awt.geom.Point2D;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
Scanner sc = new Scanner(System.in);
public static void main(String[] args){
new Main();
}
public Main(){
// new A().doIt();
new GRL_6().doIt();
}
class GRL_6{
void doIt(){
int n = sc.nextInt();
int e = sc.nextInt();
int max = sc.nextInt();
MCF m = new MCF(n);
for(int i = 0;i < e;i++){
int from = sc.nextInt();
int to = sc.nextInt();
int cap = sc.nextInt();
int cost = sc.nextInt();
m.addEdge(from, to, cap, cost);
m.addEdge(to, from, cap, cost);
}
System.out.println(m.minCostFlow(0, n-1, max));
}
class MCF{
int INF=1<<24; ArrayList<ArrayList<Edge>> G;
class Edge {
int to, cap, cost;
int rev;
public Edge(int to, int cap, int cost, int rev) {
this.to = to;this.cap = cap;this.cost = cost; this.rev = rev;
}
}
MCF(int v){
G= new ArrayList<ArrayList<Edge>>();
for(int i=0;i<v;i++){
G.add(new ArrayList<Edge>());
}
}
private void addEdge(int from, int to, int cap, int cost){
G.get(from).add(new Edge(to, cap, cost, G.get(to).size()));
G.get(to).add(new Edge(from, 0, -cost, G.get(from).size() - 1));
}
private int minCostFlow(int s, int t, int f) {
int V = G.size();
int [] dist = new int[V], prevv = new int[V], preve = new int[V];
int res=0;
while(f > 0){
Arrays.fill(dist, INF);
dist[s] = 0;
boolean update = true;
while(update) {
update = false;
for(int v = 0; v < V; v++){
if(dist[v] == INF) continue;
for(int i = 0 ; i < G.get(v).size(); i++){
Edge e = G.get(v).get(i);
if(e.cap > 0 && dist[e.to]> dist[v] + e.cost ){
dist[e.to] = dist[v] + e.cost;
prevv[e.to] = v;
preve[e.to] = i;
update = true;
}
}
}
}
if(dist[t] == INF) return -1;
int d= f;
for(int v=t;v!= s; v = prevv[v]){
d= Math.min(d, G.get(prevv[v]).get(preve[v]).cap);
}
f -= d;
res += d * dist[t];
for(int v = t; v!= s; v = prevv[v]){
Edge e =G.get(prevv[v]).get(preve[v]);
e.cap -= d;
G.get(v).get(e.rev).cap += d;
}
}
return res;
}
}
}
class A{
BigInteger sum[] = new BigInteger[501];
BigInteger bit[] = new BigInteger[501];
void doIt(){
sum[1] = new BigInteger("1");
bit[1] = new BigInteger("1");
for(int i = 2;i < 501;i++){
bit[i] = bit[i-1].multiply(new BigInteger("2"));
sum[i] = sum[i-1].add(bit[i]);
}
while(true){
String str = sc.next();
if(str.equals("0"))break;
BigInteger num = new BigInteger(str);
int length = num.toString(2).length() + 1;
ArrayList<Par> array = new ArrayList<Par>();
array.add(new Par(bit[length],1,length-1));
System.out.println(bit[length - 1]+" "+sum[length - 1]);
System.out.println(array.get(0).num+" "+array.get(0).cnt+" "+array.get(0).length);
}
}
class Par{
BigInteger num;
int cnt,length;
public Par(BigInteger num,int cnt,int length){
this.num = num;
this.cnt = cnt;
this.length = length;
}
}
}
} |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | java | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.PriorityQueue;
import java.util.TreeMap;
public class Main {
static ContestScanner in;static Writer out;public static void main(String[] args)
{try{in=new ContestScanner();out=new Writer();Main solve=new Main();solve.solve();
in.close();out.flush();out.close();}catch(IOException e){e.printStackTrace();}}
static void dump(int[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();}
static void dump(int[]a,int n){for(int i=0;i<a.length;i++)out.printf("%"+n+"d ",a[i]);out.println();}
static void dump(long[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();}
static void dump(char[]a){for(int i=0;i<a.length;i++)out.print(a[i]);out.println();}
static long pow(long a,int n){long r=1;while(n>0){if((n&1)==1)r*=a;a*=a;n>>=1;}return r;}
static String itob(int a,int l){return String.format("%"+l+"s",Integer.toBinaryString(a)).replace(' ','0');}
static void sort(int[]a){m_sort(a,0,a.length,new int[a.length]);}
static void sort(int[]a,int l){m_sort(a,0,l,new int[l]);}
static void sort(int[]a,int l,int[]buf){m_sort(a,0,l,buf);}
static void sort(int[]a,int s,int l,int[]buf){m_sort(a,s,l,buf);}
static void m_sort(int[]a,int s,int sz,int[]b)
{if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;}
m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz;
while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];}
while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];
} /* qsort(3.5s)<<msort(9.5s)<<<shuffle+qsort(17s)<Arrays.sort(Integer)(20s) */
static void sort(long[]a){m_sort(a,0,a.length,new long[a.length]);}
static void sort(long[]a,int l){m_sort(a,0,l,new long[l]);}
static void sort(long[]a,int l,long[]buf){m_sort(a,0,l,buf);}
static void sort(long[]a,int s,int l,long[]buf){m_sort(a,s,l,buf);}
static void m_sort(long[]a,int s,int sz,long[]b)
{if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;}
m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz;
while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];}
while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];}
static void swap(long[] a,int i,int j){final long t=a[i];a[i]=a[j];a[j]=t;}
static void swap(int[] a,int i,int j){final int t=a[i];a[i]=a[j];a[j]=t;}
static int binarySearchSmallerMax(int[]a,int v)// get maximum index which a[idx]<=v
{int l=-1,r=a.length-1,s=0;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;}
static int binarySearchSmallerMax(int[]a,int v,int l,int r)
{int s=-1;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;}
@SuppressWarnings("unchecked")
static List<Integer>[]createGraph(int n)
{List<Integer>[]g=new List[n];for(int i=0;i<n;i++)g[i]=new ArrayList<>();return g;}
@SuppressWarnings("unchecked")
void solve() throws NumberFormatException, IOException{
final int n = in.nextInt();
final int m = in.nextInt();
int f = in.nextInt();
List<Edge>[] node = new List[n];
for(int i=0; i<n; i++) node[i] = new ArrayList<>();
for(int i=0; i<m; i++){
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int d = in.nextInt();
Edge e = new Edge(b, c, d);
Edge r = new Edge(a, 0, -d);
e.rev = r;
r.rev = e;
node[a].add(e);
node[b].add(r);
}
final int s = 0, t = n-1;
int[] h = new int[n];
int[] dist = new int[n];
int[] preV = new int[n];
int[] preE = new int[n];
final int inf = Integer.MAX_VALUE;
PriorityQueue<Pos> qu = new PriorityQueue<>();
int res = 0;
int flow = 0;
while(f>0){
Arrays.fill(dist, inf);
dist[s] = 0;
qu.clear();
qu.add(new Pos(s, 0));
while(!qu.isEmpty()){
Pos p = qu.poll();
if(dist[p.v]<p.d) continue;
final int sz = node[p.v].size();
for(int i=0; i<sz; i++){
Edge e = node[p.v].get(i);
final int nd = e.cost+p.d + h[p.v]-h[e.to];
if(e.cap>0 && nd < dist[e.to]){
preV[e.to] = p.v;
preE[e.to] = i;
dist[e.to] = nd;
qu.add(new Pos(e.to, nd));
}
}
}
if(dist[t]==inf) break;
for(int i=0; i<n; i++) h[i] += dist[i];
int minf = f;
for(int i=t; i!=s; i=preV[i]){
minf = Math.min(minf, node[preV[i]].get(preE[i]).cap);
}
f -= minf;
flow += minf;
res += minf*h[t];
for(int i=t; i!=s; i=preV[i]){
node[preV[i]].get(preE[i]).cap -= minf;
node[preV[i]].get(preE[i]).rev.cap += minf;
}
}
if(flow==0) res = -1;
System.out.println(res);
}
}
class Pos implements Comparable<Pos>{
int v, d;
public Pos(int v, int d) {
this.v = v;
this.d = d;
}
@Override
public int compareTo(Pos o) {
return d-o.d;
}
}
class Edge{
int to, cap, cost;
Edge rev;
Edge(int t, int c, int co){
to = t;
cap = c;
cost = co;
}
void rev(Edge r){
rev = r;
}
}
@SuppressWarnings("serial")
class MultiSet<T> extends HashMap<T, Integer>{
@Override public Integer get(Object key){return containsKey(key)?super.get(key):0;}
public void add(T key,int v){put(key,get(key)+v);}
public void add(T key){put(key,get(key)+1);}
public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);}
public MultiSet<T> merge(MultiSet<T> set)
{MultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;}
for(Entry<T,Integer>e:s.entrySet())l.add(e.getKey(),e.getValue());return l;}
}
@SuppressWarnings("serial")
class OrderedMultiSet<T> extends TreeMap<T, Integer>{
@Override public Integer get(Object key){return containsKey(key)?super.get(key):0;}
public void add(T key,int v){put(key,get(key)+v);}
public void add(T key){put(key,get(key)+1);}
public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);}
public OrderedMultiSet<T> merge(OrderedMultiSet<T> set)
{OrderedMultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;}
while(!s.isEmpty()){l.add(s.firstEntry().getKey(),s.pollFirstEntry().getValue());}return l;}
}
class Pair implements Comparable<Pair>{
int a,b;final int hash;Pair(int a,int b){this.a=a;this.b=b;hash=(a<<16|a>>16)^b;}
public boolean equals(Object obj){Pair o=(Pair)(obj);return a==o.a&&b==o.b;}
public int hashCode(){return hash;}
public int compareTo(Pair o){if(a!=o.a)return a<o.a?-1:1;else if(b!=o.b)return b<o.b?-1:1;return 0;}
}
class Timer{
long time;public void set(){time=System.currentTimeMillis();}
public long stop(){return time=System.currentTimeMillis()-time;}
public void print(){System.out.println("Time: "+(System.currentTimeMillis()-time)+"ms");}
@Override public String toString(){return"Time: "+time+"ms";}
}
class Writer extends PrintWriter{
public Writer(String filename)throws IOException
{super(new BufferedWriter(new FileWriter(filename)));}
public Writer()throws IOException{super(System.out);}
}
class ContestScanner implements Closeable{
private BufferedReader in;private int c=-2;
public ContestScanner()throws IOException
{in=new BufferedReader(new InputStreamReader(System.in));}
public ContestScanner(String filename)throws IOException
{in=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));}
public String nextToken()throws IOException {
StringBuilder sb=new StringBuilder();
while((c=in.read())!=-1&&Character.isWhitespace(c));
while(c!=-1&&!Character.isWhitespace(c)){sb.append((char)c);c=in.read();}
return sb.toString();
}
public String readLine()throws IOException{
StringBuilder sb=new StringBuilder();if(c==-2)c=in.read();
while(c!=-1&&c!='\n'&&c!='\r'){sb.append((char)c);c=in.read();}
return sb.toString();
}
public long nextLong()throws IOException,NumberFormatException
{return Long.parseLong(nextToken());}
public int nextInt()throws NumberFormatException,IOException
{return(int)nextLong();}
public double nextDouble()throws NumberFormatException,IOException
{return Double.parseDouble(nextToken());}
public void close() throws IOException {in.close();}
} |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
template <typename T>
using V = std::vector<T>;
template <typename T>
using VV = std::vector<std::vector<T>>;
template <typename T>
using VVV = std::vector<std::vector<std::vector<T>>>;
template <class T>
inline T ceil(T a, T b) {
return (a + b - 1) / b;
}
template <class T>
inline void print(T x) {
std::cout << x << std::endl;
}
template <class T>
inline bool inside(T y, T x, T H, T W) {
return 0 <= y and y < H and 0 <= x and x < W;
}
inline double distance(double y1, double x1, double y2, double x2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
const int INF = 1L << 30;
const double EPS = 1e-9;
const std::string YES = "YES", Yes = "Yes", NO = "NO", No = "No";
const std::vector<int> dy = {0, 1, 0, -1}, dx = {1, 0, -1, 0};
using namespace std;
class PrimalDual {
struct Edge {
const int to;
int flow;
const int cap;
const int cost;
const int rev;
const bool is_rev;
Edge(int to, int flow, int cap, int cost, int rev, bool is_rev)
: to(to), flow(flow), cost(cost), cap(cap), rev(rev), is_rev(is_rev) {
assert(this->cap >= 0);
}
};
const unsigned long V;
vector<vector<Edge>> graph;
vector<int> h;
vector<int> dist;
vector<int> prevv, preve;
public:
PrimalDual(unsigned long num_of_node) : V(num_of_node) {
graph.resize(V);
h.resize(V, 0);
dist.resize(V);
prevv.resize(V);
preve.resize(V);
}
void add_edge(int from, int to, int cap, int cost) {
graph[from].emplace_back(Edge(to, 0, cap, cost, graph[to].size(), false));
graph[to].emplace_back(
Edge(from, cap, cap, -cost, graph[from].size() - 1, true));
}
int min_cost_flow(int s, int t, int f) {
int res = 0;
while (f > 0) {
priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>>
que;
fill(dist.begin(), dist.end(), INT_MAX);
dist[s] = 0;
que.push(make_pair(0, s));
while (not que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (dist[v] < p.first) {
continue;
}
for (int i = 0; i < graph[v].size(); ++i) {
Edge &e = graph[v][i];
if (e.cap - e.flow > 0 and
dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v;
preve[e.to] = i;
que.push(make_pair(dist[e.to], e.to));
}
}
}
if (dist[t] == INT_MAX) {
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]) {
int rest =
graph[prevv[v]][preve[v]].cap - graph[prevv[v]][preve[v]].flow;
d = min(d, rest);
}
f -= d;
res += d * h[t];
for (int v = t; v != s; v = prevv[v]) {
Edge &e = graph[prevv[v]][preve[v]];
e.flow += d;
graph[v][e.rev].flow -= d;
}
}
return res;
}
int min_cost_flow_bellmanford(int s, int t, int f) {
int res = 0;
while (f > 0) {
fill(dist.begin(), dist.end(), INT_MAX);
dist[s] = 0;
bool update = true;
while (update) {
update = false;
for (int v = 0; v < V; v++) {
if (dist[v] == INT_MAX) continue;
for (int i = 0; i < graph[v].size(); i++) {
Edge &e = graph[v][i];
int rest = e.cap - e.flow;
if (rest > 0 and 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]) {
int rest =
graph[prevv[v]][preve[v]].cap - graph[prevv[v]][preve[v]].flow;
d = min(d, rest);
}
f -= d;
res += d * dist[t];
for (int v = t; v != s; v = prevv[v]) {
Edge &e = graph[prevv[v]][preve[v]];
e.flow += d;
graph[v][e.rev].flow -= d;
}
}
return res;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
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_bellmanford(0, V - 1, F) << endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define P pair<ll,ll>
#define FOR(I,A,B) for(ll I = (A); I < (B); ++I)
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin()) //ai>=v x is sorted
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin()) //ai>v x is sorted
#define NUM(x,v) (POSU(x,v)-POSL(x,v)) //x is sorted
#define SORT(x) (sort(x.begin(),x.end())) // 0 2 2 3 4 5 8 9
#define REV(x) (reverse(x.begin(),x.end())) //reverse
#define TO(x,t,f) ((x)?(t):(f))
#define CLR(mat) memset(mat, 0, sizeof(mat))
#define FILV(x,a) fill(x.begin(),x.end(),a)
#define FILA(ar,N,a) fill(ar,ar+N,a)
#define NEXTP(x) next_permutation(x.begin(),x.end())
ll gcd(ll a,ll b){if(a<b)swap(a,b);if(a%b==0)return b;else return gcd(b,a%b);}
ll lcm(ll a,ll b){ll c=gcd(a,b);return ((a/c)*(b/c)*c);}//saisyo kobaisu
#define pb push_back
#define pri(aa) cout<<(aa)<<endl
#define mp(x,y) make_pair(x,y)
#define fi first
#define se second
const ll INF=1e9+7;
const ll N = 300003;
struct edge{int to,cap,cost,rev;};
struct MinimumCostflow{//ant book p.200
int V;
vector<vector<edge> > G;
vector<int> prevv,preve,dist;
void initsize(int nv){
G.resize(nv);
preve.resize(nv);
prevv.resize(nv);
dist.resize(nv);
V=nv;
}
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(dist.begin(),dist.end(),INT_MAX);
dist[s] = 0;
bool update=true;
while(update){
update = false;
for(int v=0;v<V;v++){
if(dist[v]==INT_MAX)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]==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]){
edge &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);
MinimumCostflow mf;
int v,e,f;
cin>>v>>e>>f;
mf.initsize(v);
FOR(i,0,e){
ll x,y,c,d;cin>>x>>y>>c>>d;
mf.add_edge(x,y,c,d);
}
cout<<mf.min_cost_flow(0,v-1,f)<<endl;
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | java | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.PriorityQueue;
import java.util.TreeMap;
public class Main {
static ContestScanner in;static Writer out;public static void main(String[] args)
{try{in=new ContestScanner();out=new Writer();Main solve=new Main();solve.solve();
in.close();out.flush();out.close();}catch(IOException e){e.printStackTrace();}}
static void dump(int[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();}
static void dump(int[]a,int n){for(int i=0;i<a.length;i++)out.printf("%"+n+"d ",a[i]);out.println();}
static void dump(long[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();}
static void dump(char[]a){for(int i=0;i<a.length;i++)out.print(a[i]);out.println();}
static long pow(long a,int n){long r=1;while(n>0){if((n&1)==1)r*=a;a*=a;n>>=1;}return r;}
static String itob(int a,int l){return String.format("%"+l+"s",Integer.toBinaryString(a)).replace(' ','0');}
static void sort(int[]a){m_sort(a,0,a.length,new int[a.length]);}
static void sort(int[]a,int l){m_sort(a,0,l,new int[l]);}
static void sort(int[]a,int l,int[]buf){m_sort(a,0,l,buf);}
static void sort(int[]a,int s,int l,int[]buf){m_sort(a,s,l,buf);}
static void m_sort(int[]a,int s,int sz,int[]b)
{if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;}
m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz;
while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];}
while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];
} /* qsort(3.5s)<<msort(9.5s)<<<shuffle+qsort(17s)<Arrays.sort(Integer)(20s) */
static void sort(long[]a){m_sort(a,0,a.length,new long[a.length]);}
static void sort(long[]a,int l){m_sort(a,0,l,new long[l]);}
static void sort(long[]a,int l,long[]buf){m_sort(a,0,l,buf);}
static void sort(long[]a,int s,int l,long[]buf){m_sort(a,s,l,buf);}
static void m_sort(long[]a,int s,int sz,long[]b)
{if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;}
m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz;
while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];}
while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];}
static void swap(long[] a,int i,int j){final long t=a[i];a[i]=a[j];a[j]=t;}
static void swap(int[] a,int i,int j){final int t=a[i];a[i]=a[j];a[j]=t;}
static int binarySearchSmallerMax(int[]a,int v)// get maximum index which a[idx]<=v
{int l=-1,r=a.length-1,s=0;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;}
static int binarySearchSmallerMax(int[]a,int v,int l,int r)
{int s=-1;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;}
@SuppressWarnings("unchecked")
static List<Integer>[]createGraph(int n)
{List<Integer>[]g=new List[n];for(int i=0;i<n;i++)g[i]=new ArrayList<>();return g;}
@SuppressWarnings("unchecked")
void solve() throws NumberFormatException, IOException{
final int n = in.nextInt();
final int m = in.nextInt();
int f = in.nextInt();
List<Edge>[] node = new List[n];
for(int i=0; i<n; i++) node[i] = new ArrayList<>();
for(int i=0; i<m; i++){
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int d = in.nextInt();
Edge e = new Edge(b, c, d);
Edge r = new Edge(a, 0, -d);
e.rev = r;
r.rev = e;
node[a].add(e);
node[b].add(r);
}
final int s = 0, t = n-1;
int[] h = new int[n];
int[] dist = new int[n];
int[] preV = new int[n];
int[] preE = new int[n];
final int inf = Integer.MAX_VALUE;
PriorityQueue<Pos> qu = new PriorityQueue<>();
int res = 0;
while(f>0){
Arrays.fill(dist, inf);
dist[s] = 0;
qu.clear();
qu.add(new Pos(s, 0));
while(!qu.isEmpty()){
Pos p = qu.poll();
if(dist[p.v]<p.d) continue;
final int sz = node[p.v].size();
for(int i=0; i<sz; i++){
Edge e = node[p.v].get(i);
final int nd = e.cost+p.d + h[p.v]-h[e.to];
if(e.cap>0 && nd < dist[e.to]){
preV[e.to] = p.v;
preE[e.to] = i;
dist[e.to] = nd;
qu.add(new Pos(e.to, nd));
}
}
}
if(dist[t]==inf) break;
for(int i=0; i<n; i++) h[i] += dist[i];
int minf = f;
for(int i=t; i!=s; i=preV[i]){
minf = Math.min(minf, node[preV[i]].get(preE[i]).cap);
}
f -= minf;
res += minf*h[t];
for(int i=t; i!=s; i=preV[i]){
node[preV[i]].get(preE[i]).cap -= minf;
node[preV[i]].get(preE[i]).rev.cap += minf;
}
}
System.out.println(res);
}
}
class Pos implements Comparable<Pos>{
int v, d;
public Pos(int v, int d) {
this.v = v;
this.d = d;
}
@Override
public int compareTo(Pos o) {
return d-o.d;
}
}
class Edge{
int to, cap, cost;
Edge rev;
Edge(int t, int c, int co){
to = t;
cap = c;
cost = co;
}
void rev(Edge r){
rev = r;
}
}
@SuppressWarnings("serial")
class MultiSet<T> extends HashMap<T, Integer>{
@Override public Integer get(Object key){return containsKey(key)?super.get(key):0;}
public void add(T key,int v){put(key,get(key)+v);}
public void add(T key){put(key,get(key)+1);}
public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);}
public MultiSet<T> merge(MultiSet<T> set)
{MultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;}
for(Entry<T,Integer>e:s.entrySet())l.add(e.getKey(),e.getValue());return l;}
}
@SuppressWarnings("serial")
class OrderedMultiSet<T> extends TreeMap<T, Integer>{
@Override public Integer get(Object key){return containsKey(key)?super.get(key):0;}
public void add(T key,int v){put(key,get(key)+v);}
public void add(T key){put(key,get(key)+1);}
public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);}
public OrderedMultiSet<T> merge(OrderedMultiSet<T> set)
{OrderedMultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;}
while(!s.isEmpty()){l.add(s.firstEntry().getKey(),s.pollFirstEntry().getValue());}return l;}
}
class Pair implements Comparable<Pair>{
int a,b;final int hash;Pair(int a,int b){this.a=a;this.b=b;hash=(a<<16|a>>16)^b;}
public boolean equals(Object obj){Pair o=(Pair)(obj);return a==o.a&&b==o.b;}
public int hashCode(){return hash;}
public int compareTo(Pair o){if(a!=o.a)return a<o.a?-1:1;else if(b!=o.b)return b<o.b?-1:1;return 0;}
}
class Timer{
long time;public void set(){time=System.currentTimeMillis();}
public long stop(){return time=System.currentTimeMillis()-time;}
public void print(){System.out.println("Time: "+(System.currentTimeMillis()-time)+"ms");}
@Override public String toString(){return"Time: "+time+"ms";}
}
class Writer extends PrintWriter{
public Writer(String filename)throws IOException
{super(new BufferedWriter(new FileWriter(filename)));}
public Writer()throws IOException{super(System.out);}
}
class ContestScanner implements Closeable{
private BufferedReader in;private int c=-2;
public ContestScanner()throws IOException
{in=new BufferedReader(new InputStreamReader(System.in));}
public ContestScanner(String filename)throws IOException
{in=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));}
public String nextToken()throws IOException {
StringBuilder sb=new StringBuilder();
while((c=in.read())!=-1&&Character.isWhitespace(c));
while(c!=-1&&!Character.isWhitespace(c)){sb.append((char)c);c=in.read();}
return sb.toString();
}
public String readLine()throws IOException{
StringBuilder sb=new StringBuilder();if(c==-2)c=in.read();
while(c!=-1&&c!='\n'&&c!='\r'){sb.append((char)c);c=in.read();}
return sb.toString();
}
public long nextLong()throws IOException,NumberFormatException
{return Long.parseLong(nextToken());}
public int nextInt()throws NumberFormatException,IOException
{return(int)nextLong();}
public double nextDouble()throws NumberFormatException,IOException
{return Double.parseDouble(nextToken());}
public void close() throws IOException {in.close();}
} |
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
int v, e;
vector<pair<int, int> > adj[110], revadj[110];
int capacity[1010], cost[1010], flowingthrough[1010], dis[110], pre[110],
preedge[110], endofedge[1010];
void bellmanford() {
fill_n(dis, v, 1e9);
dis[0] = 0;
for (int 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++;
int a = v - 1;
while (a) {
int e = preedge[a];
if (endofedge[e] == a)
capacity[e]--, totalcost += cost[e];
else
capacity[e]++, totalcost -= cost[e];
a = pre[a];
}
}
return {ans, totalcost};
}
int f;
int main() {
scanf("%d%d%d", &v, &e, &f);
for (int i = 0; i < e; i++) {
int a, b;
scanf("%d%d%d%d", &a, &b, &capacity[i], &cost[i]);
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();
if (ans.first != f)
printf("-1\n");
else
printf("%d\n", ans.second);
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using Int = int64_t;
using UInt = uint64_t;
using C = std::complex<double>;
template <typename T>
using RQ = std::priority_queue<T, std::vector<T>, std::greater<T>>;
int main() {
Int v, e, f;
std::cin >> v >> e >> f;
std::vector<Int> ss(e + 1), ts(e + 1), cs(e + 1), fs(e + 1), bs(e + 1);
for (Int i = (Int)(1); i < (Int)(e + 1); ++i) {
Int a, b, c, d;
std::cin >> a >> b >> c >> d;
ss[i] = a, ts[i] = b, cs[i] = d, fs[i] = 0, bs[i] = c;
}
std::vector<std::vector<Int>> es(v);
for (Int i = (Int)(1); i < (Int)(e + 1); ++i) {
Int s = ss[i], t = ts[i];
es[s].emplace_back(i);
es[t].emplace_back(-i);
}
Int res = 0;
Int source = 0, sink = v - 1;
while (f > 0) {
RQ<std::pair<Int, Int>> q;
q.emplace(0, source);
std::vector<Int> ps(v, -1), xs(v, -1), ys(v), hs(v);
xs[source] = 0;
ys[source] = f;
while (not q.empty()) {
Int d, s;
std::tie(d, s) = q.top();
q.pop();
if (not(d == xs[s])) continue;
;
for (Int i : es[s]) {
Int k = std::abs(i);
Int t = i > 0 ? ts[k] : ss[k];
Int tf = i > 0 ? bs[k] : fs[k];
if (not(tf > 0)) continue;
;
Int nd = d + cs[k] + hs[s] - hs[t];
if (not(xs[t] == -1 or xs[t] > nd)) continue;
;
assert(cs[k] != 0);
xs[t] = nd;
ps[t] = i;
ys[t] = std::min(ys[s], tf);
q.emplace(nd, t);
}
}
Int tf = ys[sink];
if (false) fprintf(stderr, "tf = %ld\n", tf);
f -= tf;
if (f > 0 and tf == 0) {
res = -1;
break;
}
for (Int i = 0; i < (Int)(v); ++i) hs[i] += xs[i];
for (Int i = sink, k = ps[i]; i != source;
i = k > 0 ? ss[k] : ts[k], k = ps[i]) {
Int ak = std::abs(k);
if (false) fprintf(stderr, "i=%ld, k=%ld\n", i, k);
if (k > 0) {
res += tf * cs[ak];
fs[ak] += tf;
bs[ak] -= tf;
} else {
res -= tf * cs[ak];
fs[ak] -= tf;
bs[ak] += tf;
}
}
if (f == 0) break;
for (Int i = (Int)(1); i < (Int)(e + 1); ++i) {
if (false)
fprintf(stderr, "%ld -> %ld : cost=%ld : ->=%ld : <-=%ld\n", ss[i],
ts[i], cs[i], fs[i], bs[i]);
}
}
printf("%ld\n", res);
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
struct edge {
i64 from;
i64 to;
i64 cap;
i64 cost;
i64 rev;
};
i64 INF = 1e8;
i64 capacity_scaling_bflow(std::vector<std::vector<edge>>& g,
std::vector<i64> b) {
i64 ans = 0;
i64 U = *std::max_element(begin(b), end(b));
i64 delta = (1 << ((int)(std::log2(U)) + 1));
int n = g.size();
std::vector<i64> e = b;
std::vector<i64> p(n, 0);
int zero = 0;
for (auto x : e) {
if (x == 0) zero++;
}
for (; delta > 0; delta >>= 1) {
if (zero == n) break;
for (int s = 0; s < n; s++) {
if (!(e[s] >= delta)) continue;
std::vector<std::size_t> pv(n, -1);
std::vector<std::size_t> pe(n, -1);
std::vector<i64> dist(n, 1e18);
using P = std::pair<i64, i64>;
std::priority_queue<P, std::vector<P>, std::greater<P>> que;
dist[s] = 0;
que.push({dist[s], s});
while (!que.empty()) {
int v = que.top().second;
i64 d = que.top().first;
que.pop();
if (dist[v] < d) continue;
for (std::size_t i = 0; i < g[v].size(); i++) {
const auto& e = g[v][i];
std::size_t u = e.to;
i64 ccc = e.cost + p[v] - p[u];
if (e.cap == 0) ccc = INF;
assert(ccc >= 0);
if (dist[u] > dist[v] + ccc) {
dist[u] = dist[v] + ccc;
pv[u] = v;
pe[u] = i;
que.push({dist[u], u});
}
}
}
for (int i = 0; i < n; i++) {
p[i] += dist[i] - dist[s];
}
int t = 0;
for (; t < n; t++) {
if (!(e[s] >= delta)) break;
if (e[t] <= -delta && pv[t] != -1) {
std::size_t u = t;
for (; pv[u] != -1; u = pv[u]) {
ans += delta * g[pv[u]][pe[u]].cost;
g[pv[u]][pe[u]].cap -= delta;
g[u][g[pv[u]][pe[u]].rev].cap += delta;
}
e[u] -= delta;
e[t] += delta;
if (e[u] == 0) zero++;
if (e[t] == 0) zero++;
}
}
}
}
if (zero == n)
return ans;
else
return -1e18;
}
int main() {
i64 N, M, F;
cin >> N >> M >> F;
vector<vector<edge>> g(N + M);
vector<i64> e(N + M, 0);
int s = 0;
int t = N - 1;
e[s + M] = F;
e[t + M] = -F;
for (int i = 0; i < M; i++) {
i64 a, b, c, d;
cin >> a >> b >> c >> d;
e[i] = c;
e[a + M] -= c;
g[i].push_back({i, a + M, (i64)1e18, 0, (i64)g[a + M].size()});
g[a + M].push_back({a + M, i, 0, 0, (i64)g[i].size() - 1});
g[i].push_back({i, b + M, (i64)1e18, d, (i64)g[b + M].size()});
g[b + M].push_back({b + M, i, 0, -d, (i64)g[i].size() - 1});
}
i64 ans = capacity_scaling_bflow(g, e);
if (ans == -1e18) {
cout << -1 << endl;
} else {
cout << ans << endl;
}
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | UNKNOWN | #include <bits/stdc++.h>
struct node {
int id;
int cap;
int cost;
struct node *next;
};
struct node **list;
int **flow, *dist, *prev, *preve, *h;
int *heap, *heap_index, heapsize;
void Insert(int, int, int, int);
void downheap(int);
void upheap(int);
void PQ_init(int);
int PQ_remove(void);
void PQ_update(int);
int Maxflow(int, int, int);
int main(void) {
int i, v, e, f, s, t, c, d, mincost = 0;
scanf("%d %d %d", &v, &e, &f);
list = (struct node **)malloc(sizeof(struct node *) * v);
flow = (int **)malloc(sizeof(int *) * v);
dist = (int *)malloc(sizeof(int) * v);
prev = (int *)malloc(sizeof(int) * v);
preve = (int *)malloc(sizeof(int) * v);
h = (int *)calloc(v, sizeof(int));
for (i = 0; i < v; i++) {
list[i] = NULL;
flow[i] = (int *)calloc(v, sizeof(int));
}
for (i = 0; i < e; i++) {
scanf("%d %d %d %d", &s, &t, &c, &d);
Insert(s, t, c, d);
}
while (f > 0 && Maxflow(0, v - 1, v)) {
int n, delta = f;
for (n = v - 1; n != 0; n = prev[n]) {
delta = ((delta) < (preve[n] - flow[prev[n]][n])
? (delta)
: (preve[n] - flow[prev[n]][n]));
}
f -= delta;
for (n = v - 1; n != 0; n = prev[n]) {
flow[prev[n]][n] += delta;
flow[n][prev[n]] -= delta;
}
for (i = 0; i < v; i++) h[i] += dist[i];
}
if (f == 0) {
for (i = 0; i < v; i++) {
struct node *n;
for (n = list[i]; n != NULL; n = n->next) {
if (n->cap > 0) mincost += flow[i][n->id] * n->cost;
}
}
printf("%d\n", mincost);
} else
printf("-1\n");
for (i = 0; i < v; i++) {
free(list[i]);
free(flow[i]);
}
free(list);
free(flow);
free(dist);
free(prev);
free(preve);
free(h);
}
void Insert(int a, int b, int cap, int cost) {
struct node *p = (struct node *)malloc(sizeof(struct node));
p->id = b;
p->cap = cap;
p->cost = cost;
p->next = list[a];
list[a] = p;
p = (struct node *)malloc(sizeof(struct node));
p->id = a;
p->cap = 0;
p->cost = -cost;
p->next = list[b];
list[b] = p;
}
void downheap(int k) {
int j, v = heap[k];
while (k < heapsize / 2) {
j = 2 * k + 1;
if (j < heapsize - 1 && dist[heap[j]] > dist[heap[j + 1]]) j++;
if (dist[v] <= dist[heap[j]]) break;
heap[k] = heap[j];
heap_index[heap[j]] = k;
k = j;
}
heap[k] = v;
heap_index[v] = k;
}
void upheap(int j) {
int k, v = heap[j];
while (j > 0) {
k = (j + 1) / 2 - 1;
if (dist[v] >= dist[heap[k]]) break;
heap[j] = heap[k];
heap_index[heap[k]] = j;
j = k;
}
heap[j] = v;
heap_index[v] = j;
}
void PQ_init(int size) {
int i;
heapsize = size;
heap = (int *)malloc(sizeof(int) * size);
heap_index = (int *)malloc(sizeof(int) * size);
for (i = 0; i < size; i++) {
heap[i] = i;
heap_index[i] = i;
}
for (i = heapsize / 2 - 1; i >= 0; i--) downheap(i);
}
int PQ_remove(void) {
int v = heap[0];
heap[0] = heap[heapsize - 1];
heap_index[heap[heapsize - 1]] = 0;
heapsize--;
downheap(0);
return v;
}
void PQ_update(int v) { upheap(heap_index[v]); }
int Maxflow(int s, int t, int size) {
struct node *n;
int i;
for (i = 0; i < size; i++) {
dist[i] = INT_MAX;
prev[i] = -1;
preve[i] = -1;
}
dist[s] = 0;
PQ_init(size);
while (heapsize) {
i = PQ_remove();
for (n = list[i]; n != NULL; n = n->next) {
int v = n->id;
if (flow[i][v] < n->cap) {
int newlen = dist[i] + n->cost + h[i] - h[v];
if (newlen < dist[v]) {
dist[v] = newlen;
prev[v] = i;
preve[v] = n->cap;
PQ_update(v);
}
}
}
}
free(heap);
free(heap_index);
return dist[t] != INT_MAX;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
using Weight = long long;
static const Weight INF = 1LL << 57;
template <class T>
using gp_queue = priority_queue<T, deque<T>, less<T>>;
struct Arc {
size_t src, dst;
Weight capacity, cost, flow;
size_t rev;
Arc() {}
Arc(size_t src, size_t dst, Weight capacity, Weight cost = 0)
: src(src), dst(dst), capacity(capacity), cost(cost), flow(0), rev(-1) {}
Weight residue() const { return capacity - flow; }
};
bool operator<(const Arc &e, const Arc &f) {
if (e.cost != f.cost) {
return e.cost > f.cost;
} else if (e.capacity != f.capacity) {
return e.capacity > f.capacity;
} else {
return e.src != f.src ? e.src < f.src : e.dst < f.dst;
}
}
using Arcs = vector<Arc>;
using Node = vector<Arc>;
using FlowNetwork = vector<Node>;
void connect(FlowNetwork &g, size_t s, size_t d, Weight c = 1, Weight k = 0) {
g[s].push_back(Arc(s, d, c, k));
g[d].push_back(Arc(d, s, 0, -k));
g[s].back().rev = g[d].size() - 1;
g[d].back().rev = g[s].size() - 1;
}
void join(FlowNetwork &g, size_t s, size_t d, Weight c = 1, Weight k = 0) {
g[s].push_back(Arc(s, d, c, k));
g[d].push_back(Arc(d, s, c, k));
g[s].back().rev = g[d].size() - 1;
g[d].back().rev = g[s].size() - 1;
}
pair<Weight, Weight> mincost_flow(FlowNetwork &g, size_t s, size_t t,
Weight F = INF) {
size_t V = g.size();
vector<Arc *> prev(V, NULL);
pair<Weight, Weight> total;
while (F > total.second) {
vector<Weight> d(V, INF);
d[s] = 0;
for (bool updated = true; updated;) {
updated = false;
for (size_t v = 0; v < V; ++v) {
if (d[v] == INF) continue;
for (Arc &e : g[v]) {
if (e.capacity <= 0) continue;
if (d[e.dst] > d[e.src] + e.cost) {
d[e.dst] = d[e.src] + e.cost;
prev[e.dst] = &e;
updated = true;
}
}
}
}
if (d[t] == INF) break;
Weight f = F - total.second;
for (Arc *e = prev[t]; e != NULL; e = prev[e->src]) f = min(f, e->capacity);
total.second += f;
total.first += f * d[t];
for (Arc *e = prev[t]; e != NULL; e = prev[e->src]) {
e->capacity -= f;
g[e->dst][e->rev].capacity += f;
}
}
return total;
}
int main() {
size_t V, E;
Weight F;
scanf("%zu %zu %lld", &V, &E, &F);
FlowNetwork g(V);
for (size_t i = 0; i < E; ++i) {
size_t u, v;
Weight c, d;
scanf("%zu %zu %lld %lld", &u, &v, &c, &d);
connect(g, u, v, c, d);
}
printf("%lld\n", mincost_flow(g, 0, V - 1, F).first);
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | python3 | from collections import defaultdict
v_num, e_num, flow = (int(n) for n in input().split(" "))
edges = defaultdict(list)
for _ in range(e_num):
s1, t1, cap, cost = (int(n) for n in input().split(" "))
edges[s1].append([t1, cap, cost, len(edges[t1])])
edges[t1].append([s1, cap, cost, len(edges[s1]) - 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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const long long int E = 1e18 + 7;
const long long int MOD = 1000000007;
class CFlow {
private:
struct edge {
long long int to;
long long int cap;
long long int rev;
long long int cost;
};
struct node {
long long int cost;
long long int flow;
long long int number;
long long int from;
long long int edge;
bool operator<(const node &a) const {
if (a.cost < this->cost) {
return true;
} else if (a.cost == this->cost && a.flow > this->flow) {
return true;
}
return false;
}
};
long long int INF;
long long int v;
vector<vector<edge>> e;
public:
CFlow(long long int v) : v(v) {
e.resize(v);
INF = 1e18 + 7;
}
void add_edge(long long int from, long long int to, long long int cap,
long long int cost) {
e[from].push_back((edge){to, cap, (long long int)e[to].size(), cost});
e[to].push_back(
(edge){from, 0, (long long int)e[from].size() - 1, -1 * cost});
}
pair<long long int, long long int> min_cost(long long int s, long long int t,
long long int flow) {
vector<vector<edge>> ed = e;
long long int cost = 0;
long long int D = flow;
vector<long long int> h(v, 0);
while (flow > 0) {
priority_queue<node> q;
vector<node> V(v, {INF, 0, -1, -1, -1});
V[s] = {0, flow, s, s, -1};
q.push({0, flow, s, s, -1});
while (!q.empty()) {
node N = q.top();
q.pop();
long long int w = N.number;
if (V[w].cost < N.cost) {
continue;
}
for (int i = 0; i < e[w].size(); i++) {
edge &E = e[w][i];
if (E.cap > 0 && V[E.to].cost > V[w].cost + E.cost + h[w] - h[E.to]) {
V[E.to] = {V[w].cost + E.cost + h[w] - h[E.to], min(N.flow, E.cap),
E.to, w, i};
q.push(V[E.to]);
}
}
}
if (V[t].flow == 0) {
break;
}
for (int i = 0; i < v; i++) {
h[i] += V[i].cost;
}
flow -= V[t].flow;
cost += V[t].cost * V[t].flow;
long long int w = t;
while (w != s) {
long long int t = w;
w = V[w].from;
edge &E = e[w][V[t].edge];
E.cap -= V[t].flow;
e[t][E.rev].cap += V[t].flow;
}
if (flow == 0) {
break;
}
}
e = ed;
return {D - flow, cost};
}
};
int main() {
long long int v, e, f;
cin >> v >> e >> f;
CFlow first(v);
for (int i = 0; i < e; i++) {
long long int s, t, cap, cost;
cin >> s >> t >> cap >> cost;
first.add_edge(s, t, cap, cost);
}
pair<long long int, long long int> P = first.min_cost(0, v - 1, f);
if (P.first != f) {
cout << -1 << endl;
} else {
cout << P.second << endl;
}
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, cap, cost, rev;
};
int V;
vector<edge> G[100];
vector<int> h(100);
int dist[100];
int prevv[100], preve[100];
void add_edge(int from, int to, int cap, int cost) {
G[from].push_back((edge){to, cap, cost, (int)G[to].size()});
G[to].push_back((edge){from, 0, -cost, (int)G[from].size() - 1});
}
int shortest_path(int s, vector<int> &d) {
int v = d.size();
for (long long i = 0; i < (long long)(d.size()); i++) d[i] = (1e9 + 1);
d[s] = 0;
for (long long loop = 0; loop < (long long)(v); loop++) {
bool update = false;
for (long long i = 0; i < (long long)(100); i++) {
for (auto e : G[i]) {
if (d[i] != (1e9 + 1) && d[e.to] > d[i] + e.cost) {
d[e.to] = d[i] + e.cost;
update = true;
}
}
}
if (!update) break;
if (loop == v - 1) return true;
}
return false;
}
int min_cost_flow(int s, int t, int f) {
int res = 0;
for (long long i = 0; i < (long long)(h.size()); i++) h[i] = 0;
shortest_path(s, h);
int times = 0;
while (f > 0) {
if (times == 0)
shortest_path(s, h);
else {
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
que;
fill(dist, dist + V, (1e9 + 1));
dist[s] = 0;
que.push(pair<int, int>(0, s));
while (!que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (dist[v] < p.first) continue;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v;
preve[e.to] = i;
que.push(pair<int, int>(dist[e.to], e.to));
}
}
}
}
times++;
if (dist[t] == (1e9 + 1)) return -1;
for (int v = 0; v < V; v++) h[v] += dist[v];
int d = f;
for (int v = t; v != s; v = prevv[v]) {
d = min(d, G[prevv[v]][preve[v]].cap);
}
f -= d;
res += d * h[t];
for (int v = t; v != s; v = prevv[v]) {
edge &e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
int main() {
int e, f;
cin >> V >> e >> f;
for (long long i = 0; i < (long long)(e); i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
add_edge(u, v, c, d);
}
cout << min_cost_flow(0, V - 1, f) << endl;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
void _main();
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
_main();
}
template <int NV, class V>
struct MinCostFlow {
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));
}
V mincost(int from, int to, int flow) {
V res = 0;
int i, v;
for (int i = 0; i < NV; i++) prev_v[i] = 0;
for (int i = 0; i < NV; i++) prev_e[i] = 0;
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;
for (int i = 0; i < E[cur].size(); i++) {
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;
}
};
int V, E, F;
void _main() {
cin >> V >> E >> F;
MinCostFlow<101, int> mcf;
for (int i = 0; i < E; i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
mcf.add_edge(a, b, c, d);
}
int ans = mcf.mincost(0, V - 1, F);
if (ans == 0) ans = -1;
cout << ans << endl;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const long long int INF = 2000000000;
struct edge {
int to, cap, cost, rev;
edge(int t, int ca, int co, int re) {
to = t;
cap = ca;
cost = co;
rev = re;
}
};
vector<edge> G[40];
int prv[40], pre[40], d[40];
int v, e, flow;
void addedge(int from, int to, int cap, int cost) {
G[from].push_back(edge(to, cap, cost, G[to].size()));
G[to].push_back(edge(from, 0, -cost, G[from].size() - 1));
}
int minimumcost(int s, int t, int f) {
int res = 0;
while (f > 0) {
fill(d, d + v, INF);
d[s] = 0;
bool ud = true;
while (ud) {
ud = false;
for (int i = 0; i < v; i++) {
if (d[i] == INF) continue;
for (int j = 0; j < G[i].size(); j++) {
edge &e = G[i][j];
if (e.cap > 0 && d[e.to] > d[i] + e.cost) {
d[e.to] = d[i] + e.cost;
prv[e.to] = i;
pre[e.to] = j;
ud = true;
}
}
}
}
if (d[t] == INF) return -1;
int dis = f;
for (int w = t; w != s; w = prv[w]) {
dis = min(dis, G[prv[w]][pre[w]].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": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, cap, cost, rev;
};
int V;
vector<edge> G[10000];
int h[10000];
int dist[10000];
int prevv[10000], preve[10000];
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<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
que;
fill(dist, dist + V, 1000000001);
dist[s] = 0;
que.push(pair<int, int>(0, s));
while (!que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (dist[v] < p.first) continue;
for (int i = 0; i < (int)G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v;
preve[e.to] = i;
que.push(pair<int, int>(dist[e.to], e.to));
}
}
}
if (dist[t] == 1000000001) 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": []
} | IN-CORRECT | UNKNOWN | #include <bits/stdc++.h>
struct node {
int id;
int cap;
int cost;
struct node *next;
};
struct node **list;
int **flow, *dist, *prev, *preve, *h;
int *heap, *heap_index, heapsize;
void Insert(int, int, int, int);
void downheap(int);
void upheap(int);
void PQ_init(int);
int PQ_remove(void);
void PQ_update(int);
int Maxflow(int, int, int);
int main(void) {
int i, v, e, f, s, t, c, d, mincost = 0;
scanf("%d %d %d", &v, &e, &f);
list = (struct node **)malloc(sizeof(struct node *) * v);
flow = (int **)malloc(sizeof(int *) * v);
dist = (int *)malloc(sizeof(int) * v);
prev = (int *)malloc(sizeof(int) * v);
preve = (int *)malloc(sizeof(int) * v);
h = (int *)calloc(v, sizeof(int));
for (i = 0; i < v; i++) {
list[i] = NULL;
flow[i] = (int *)calloc(v, sizeof(int));
}
for (i = 0; i < e; i++) {
scanf("%d %d %d %d", &s, &t, &c, &d);
Insert(s, t, c, d);
}
while (f > 0 && Maxflow(0, v - 1, v)) {
int n, delta = f;
for (n = v - 1; n != 0; n = prev[n]) {
delta = ((delta) < (preve[n] - flow[prev[n]][n])
? (delta)
: (preve[n] - flow[prev[n]][n]));
}
f -= delta;
for (n = v - 1; n != 0; n = prev[n]) {
flow[prev[n]][n] += delta;
flow[n][prev[n]] -= delta;
}
for (i = 0; i < v; i++) h[i] += dist[i];
}
if (f == 0) {
for (i = 0; i < v; i++) {
struct node *n;
for (n = list[i]; n != NULL; n = n->next) {
mincost += flow[i][n->id] * n->cost;
}
}
printf("%d\n", mincost);
} else
printf("-1\n");
for (i = 0; i < v; i++) {
free(list[i]);
free(flow[i]);
}
free(list);
free(flow);
free(dist);
free(prev);
free(preve);
free(h);
}
void Insert(int a, int b, int cap, int cost) {
struct node *p = (struct node *)malloc(sizeof(struct node));
p->id = b;
p->cap = cap;
p->cost = cost;
p->next = list[a];
list[a] = p;
p = (struct node *)malloc(sizeof(struct node));
p->id = a;
p->cap = 0;
p->cost = -cost;
p->next = list[b];
list[b] = p;
}
void downheap(int k) {
int j, v = heap[k];
while (k < heapsize / 2) {
j = 2 * k + 1;
if (j < heapsize - 1 && dist[heap[j]] > dist[heap[j + 1]]) j++;
if (dist[v] <= dist[heap[j]]) break;
heap[k] = heap[j];
heap_index[heap[j]] = k;
k = j;
}
heap[k] = v;
heap_index[v] = k;
}
void upheap(int j) {
int k, v = heap[j];
while (j > 0) {
k = (j + 1) / 2 - 1;
if (dist[v] >= dist[heap[k]]) break;
heap[j] = heap[k];
heap_index[heap[k]] = j;
j = k;
}
heap[j] = v;
heap_index[v] = j;
}
void PQ_init(int size) {
int i;
heapsize = size;
heap = (int *)malloc(sizeof(int) * size);
heap_index = (int *)malloc(sizeof(int) * size);
for (i = 0; i < size; i++) {
heap[i] = i;
heap_index[i] = i;
}
for (i = heapsize / 2 - 1; i >= 0; i--) downheap(i);
}
int PQ_remove(void) {
int v = heap[0];
heap[0] = heap[heapsize - 1];
heap_index[heap[heapsize - 1]] = 0;
heapsize--;
downheap(0);
return v;
}
void PQ_update(int v) { upheap(heap_index[v]); }
int Maxflow(int s, int t, int size) {
struct node *n;
int i;
for (i = 0; i < size; i++) {
dist[i] = INT_MAX;
prev[i] = -1;
preve[i] = -1;
}
dist[s] = 0;
PQ_init(size);
while (heapsize) {
i = PQ_remove();
if (dist[i] == INT_MAX) break;
for (n = list[i]; n != NULL; n = n->next) {
int v = n->id;
if (flow[i][v] < n->cap) {
int newlen = dist[i] + n->cost + h[i] - h[v];
if (newlen < dist[v]) {
dist[v] = newlen;
prev[v] = i;
preve[v] = n->cap;
PQ_update(v);
}
}
}
}
free(heap);
free(heap_index);
return dist[t] != INT_MAX;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void output(T a, int p) {
if (p)
cout << fixed << setprecision(p) << a << "\n";
else
cout << a << "\n";
}
struct node {
int cost, pos;
};
struct edge {
int to, cap, cost, rev;
};
bool operator<(const node &a, const node &b) { return a.cost > b.cost; }
class MinCostFlow {
public:
int V;
vector<vector<edge>> G;
vector<int> h, dist, preV, preE;
MinCostFlow(int V) : V(V), G(V), h(V), dist(V), preV(V), preE(V) {}
void add_edge(int from, int to, int cap, int cost) {
G[from].push_back({to, cap, cost, (int)G[to].size()});
G[to].push_back({from, 0, -cost, (int)G[from].size()});
}
int calc(int s, int t, int f) {
int ret = 0;
h.assign(V, 0);
while (f > 0) {
dist.assign(V, 2000000007);
priority_queue<node> pq;
pq.push({0, s});
dist[s] = 0;
while (!pq.empty()) {
node p = pq.top();
pq.pop();
int d = p.cost;
int v = p.pos;
if (dist[v] < d) continue;
for (int i = (int)(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];
preV[e.to] = v;
preE[e.to] = i;
pq.push({dist[e.to], e.to});
}
}
}
if (dist[t] == 2000000007) return -1;
for (int v = (int)(0); v < (int)(V); v++) h[v] += dist[v];
int d = f;
for (int v = t; v != s; v = preV[v]) {
d = min(d, G[preV[v]][preE[v]].cap);
}
f -= d;
ret += d * h[t];
for (int v = t; v != s; v = preV[v]) {
edge &e = G[preV[v]][preE[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return ret;
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int V, E, F;
cin >> V >> E >> F;
MinCostFlow mcf(V);
for (int i = (int)(0); i < (int)(E); i++) {
int u, v, c, d;
cin >> u >> v >> c >> d;
mcf.add_edge(u, v, c, d);
}
output(mcf.calc(0, V - 1, F), 0);
return 0;
}
|
p02377 Minimum Cost Flow | Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | {
"input": [
"4 5 2\n0 1 2 1\n0 2 1 2\n1 2 1 1\n1 3 1 3\n2 3 2 1",
""
],
"output": [
"6",
""
]
} | {
"input": [],
"output": []
} | IN-CORRECT | java | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.PriorityQueue;
import java.util.TreeMap;
public class Main {
static ContestScanner in;static Writer out;public static void main(String[] args)
{try{in=new ContestScanner();out=new Writer();Main solve=new Main();solve.solve();
in.close();out.flush();out.close();}catch(IOException e){e.printStackTrace();}}
static void dump(int[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();}
static void dump(int[]a,int n){for(int i=0;i<a.length;i++)out.printf("%"+n+"d ",a[i]);out.println();}
static void dump(long[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();}
static void dump(char[]a){for(int i=0;i<a.length;i++)out.print(a[i]);out.println();}
static long pow(long a,int n){long r=1;while(n>0){if((n&1)==1)r*=a;a*=a;n>>=1;}return r;}
static String itob(int a,int l){return String.format("%"+l+"s",Integer.toBinaryString(a)).replace(' ','0');}
static void sort(int[]a){m_sort(a,0,a.length,new int[a.length]);}
static void sort(int[]a,int l){m_sort(a,0,l,new int[l]);}
static void sort(int[]a,int l,int[]buf){m_sort(a,0,l,buf);}
static void sort(int[]a,int s,int l,int[]buf){m_sort(a,s,l,buf);}
static void m_sort(int[]a,int s,int sz,int[]b)
{if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;}
m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz;
while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];}
while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];
} /* qsort(3.5s)<<msort(9.5s)<<<shuffle+qsort(17s)<Arrays.sort(Integer)(20s) */
static void sort(long[]a){m_sort(a,0,a.length,new long[a.length]);}
static void sort(long[]a,int l){m_sort(a,0,l,new long[l]);}
static void sort(long[]a,int l,long[]buf){m_sort(a,0,l,buf);}
static void sort(long[]a,int s,int l,long[]buf){m_sort(a,s,l,buf);}
static void m_sort(long[]a,int s,int sz,long[]b)
{if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a, j, j-1);return;}
m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz;
while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];}
while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i];}
static void swap(long[] a,int i,int j){final long t=a[i];a[i]=a[j];a[j]=t;}
static void swap(int[] a,int i,int j){final int t=a[i];a[i]=a[j];a[j]=t;}
static int binarySearchSmallerMax(int[]a,int v)// get maximum index which a[idx]<=v
{int l=-1,r=a.length-1,s=0;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;}
static int binarySearchSmallerMax(int[]a,int v,int l,int r)
{int s=-1;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return s;}
@SuppressWarnings("unchecked")
static List<Integer>[]createGraph(int n)
{List<Integer>[]g=new List[n];for(int i=0;i<n;i++)g[i]=new ArrayList<>();return g;}
@SuppressWarnings("unchecked")
void solve() throws NumberFormatException, IOException{
final int n = in.nextInt();
final int m = in.nextInt();
int f = in.nextInt();
MinCostFlow mf = new MinCostFlow(n, f);
for(int i=0; i<m; i++){
int from = in.nextInt();
int to = in.nextInt();
int cap = in.nextInt();
int cost = in.nextInt();
mf.edge(from, to, cap, cost);
}
int res = mf.flow(0, n-1);
if(mf.f>0) res = -1;
System.out.println(res);
}
}
class MinCostFlow{
final int n;
int f;
List<Edge>[] node;
public MinCostFlow(int n, int f) {
this.n = n;
this.f = f;
node = new List[n];
for(int i=0; i<n; i++) node[i] = new ArrayList<>();
}
void edge(int from, int to, int cap, int cost){
Edge e = new Edge(to, cap, cost);
Edge r = new Edge(from, 0, -cost);
e.rev = r;
r.rev = e;
node[from].add(e);
node[to].add(r);
}
int flow(int s, int t){
int[] h = new int[n];
int[] dist = new int[n];
int[] preV = new int[n];
int[] preE = new int[n];
final int inf = Integer.MAX_VALUE;
PriorityQueue<Pos> qu = new PriorityQueue<>();
int res = 0;
while(f>0){
Arrays.fill(dist, inf);
dist[s] = 0;
qu.clear();
qu.add(new Pos(s, 0));
while(!qu.isEmpty()){
Pos p = qu.poll();
if(dist[p.v]<p.d) continue;
final int sz = node[p.v].size();
for(int i=0; i<sz; i++){
Edge e = node[p.v].get(i);
final int nd = e.cost+p.d + h[p.v]-h[e.to];
if(e.cap>0 && nd < dist[e.to]){
preV[e.to] = p.v;
preE[e.to] = i;
dist[e.to] = nd;
qu.add(new Pos(e.to, nd));
}
}
}
if(dist[t]==inf) break;
for(int i=0; i<n; i++) h[i] += dist[i];
int minf = f;
for(int i=t; i!=s; i=preV[i]){
minf = Math.min(minf, node[preV[i]].get(preE[i]).cap);
}
f -= minf;
res += minf*h[t];
for(int i=t; i!=s; i=preV[i]){
node[preV[i]].get(preE[i]).cap -= minf;
node[preV[i]].get(preE[i]).rev.cap += minf;
}
}
return res;
}
}
class Pos implements Comparable<Pos>{
int v, d;
public Pos(int v, int d) {
this.v = v;
this.d = d;
}
@Override
public int compareTo(Pos o) {
return d-o.d;
}
}
class Edge{
int to, cap, cost;
Edge rev;
Edge(int t, int c, int co){
to = t;
cap = c;
cost = co;
}
void rev(Edge r){
rev = r;
}
}
@SuppressWarnings("serial")
class MultiSet<T> extends HashMap<T, Integer>{
@Override public Integer get(Object key){return containsKey(key)?super.get(key):0;}
public void add(T key,int v){put(key,get(key)+v);}
public void add(T key){put(key,get(key)+1);}
public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);}
public MultiSet<T> merge(MultiSet<T> set)
{MultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;}
for(Entry<T,Integer>e:s.entrySet())l.add(e.getKey(),e.getValue());return l;}
}
@SuppressWarnings("serial")
class OrderedMultiSet<T> extends TreeMap<T, Integer>{
@Override public Integer get(Object key){return containsKey(key)?super.get(key):0;}
public void add(T key,int v){put(key,get(key)+v);}
public void add(T key){put(key,get(key)+1);}
public void sub(T key){final int v=get(key);if(v==1)remove(key);else put(key,v-1);}
public OrderedMultiSet<T> merge(OrderedMultiSet<T> set)
{OrderedMultiSet<T>s,l;if(this.size()<set.size()){s=this;l=set;}else{s=set;l=this;}
while(!s.isEmpty()){l.add(s.firstEntry().getKey(),s.pollFirstEntry().getValue());}return l;}
}
class Pair implements Comparable<Pair>{
int a,b;final int hash;Pair(int a,int b){this.a=a;this.b=b;hash=(a<<16|a>>16)^b;}
public boolean equals(Object obj){Pair o=(Pair)(obj);return a==o.a&&b==o.b;}
public int hashCode(){return hash;}
public int compareTo(Pair o){if(a!=o.a)return a<o.a?-1:1;else if(b!=o.b)return b<o.b?-1:1;return 0;}
}
class Timer{
long time;public void set(){time=System.currentTimeMillis();}
public long stop(){return time=System.currentTimeMillis()-time;}
public void print(){System.out.println("Time: "+(System.currentTimeMillis()-time)+"ms");}
@Override public String toString(){return"Time: "+time+"ms";}
}
class Writer extends PrintWriter{
public Writer(String filename)throws IOException
{super(new BufferedWriter(new FileWriter(filename)));}
public Writer()throws IOException{super(System.out);}
}
class ContestScanner implements Closeable{
private BufferedReader in;private int c=-2;
public ContestScanner()throws IOException
{in=new BufferedReader(new InputStreamReader(System.in));}
public ContestScanner(String filename)throws IOException
{in=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));}
public String nextToken()throws IOException {
StringBuilder sb=new StringBuilder();
while((c=in.read())!=-1&&Character.isWhitespace(c));
while(c!=-1&&!Character.isWhitespace(c)){sb.append((char)c);c=in.read();}
return sb.toString();
}
public String readLine()throws IOException{
StringBuilder sb=new StringBuilder();if(c==-2)c=in.read();
while(c!=-1&&c!='\n'&&c!='\r'){sb.append((char)c);c=in.read();}
return sb.toString();
}
public long nextLong()throws IOException,NumberFormatException
{return Long.parseLong(nextToken());}
public int nextInt()throws NumberFormatException,IOException
{return(int)nextLong();}
public double nextDouble()throws NumberFormatException,IOException
{return Double.parseDouble(nextToken());}
public void close() throws IOException {in.close();}
} |