problem_id stringlengths 6 6 | language stringclasses 2 values | original_status stringclasses 3 values | original_src stringlengths 19 243k | changed_src stringlengths 19 243k | change stringclasses 3 values | i1 int64 0 8.44k | i2 int64 0 8.44k | j1 int64 0 8.44k | j2 int64 0 8.44k | error stringclasses 270 values | stderr stringlengths 0 226k |
|---|---|---|---|---|---|---|---|---|---|---|---|
p02371 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, cost;
};
vector<edge> g[100000];
long long dist[100000];
void dfs1(int idx, int par) {
for (edge &e : g[idx]) {
if (e.to == par)
continue;
dfs1(e.to, idx);
dist[idx] = max(dist[idx], dist[e.to] + e.cost);
}
}
int dfs2(int idx, int d_par, int par) {
vector<pair<int, int>> d_child;
d_child.emplace_back(0, -1);
for (edge &e : g[idx]) {
if (e.to == par)
d_child.emplace_back(d_par + e.cost, e.to);
else
d_child.emplace_back(e.cost + dist[e.to], e.to);
}
sort(d_child.rbegin(), d_child.rend());
int ret = d_child[0].first + d_child[1].first;
for (edge &e : g[idx]) {
if (e.to == par)
continue;
ret = max(ret, dfs2(e.to, d_child[d_child[0].second == e.to].first, idx));
}
return (ret);
}
int main() {
int N;
cin >> N;
for (int i = 0; i < N - 1; i++) {
int a, b, w;
cin >> a >> b >> w;
g[a].push_back((edge){b, w});
g[b].push_back((edge){a, w});
}
dfs1(0, -1);
cout << dfs2(0, 0, -1) << endl;
} | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, cost;
};
vector<edge> g[100000];
long long dist[100000];
void dfs1(int idx, int par) {
for (edge &e : g[idx]) {
if (e.to == par)
continue;
dfs1(e.to, idx);
dist[idx] = max(dist[idx], dist[e.to] + e.cost);
}
}
int dfs2(int idx, int d_par, int par) {
vector<pair<int, int>> d_child;
d_child.emplace_back(0, -1);
for (edge &e : g[idx]) {
if (e.to == par)
d_child.emplace_back(d_par + e.cost, e.to);
else
d_child.emplace_back(e.cost + dist[e.to], e.to);
}
sort(d_child.rbegin(), d_child.rend());
int ret = d_child[0].first + d_child[1].first;
for (edge &e : g[idx]) {
if (e.to == par)
continue;
ret = max(ret, dfs2(e.to, d_child[d_child[0].second == e.to].first, idx));
}
return (ret);
}
int main() {
int N;
cin >> N;
for (int i = 0; i < N - 1; i++) {
int a, b, w;
cin >> a >> b >> w;
g[a].push_back((edge){b, w});
g[b].push_back((edge){a, w});
}
dfs1(N / 2, -1);
cout << dfs2(N / 2, 0, -1) << endl;
} | replace | 49 | 51 | 49 | 51 | 0 | |
p02371 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to;
int cost;
edge(int a, int b) : to(a), cost(b) {}
};
vector<vector<edge>> e;
int N;
pair<int, int> dfs(int p, int par = -1) {
if (e[p].size() == 1 && par >= 0)
return make_pair(0, p);
pair<int, int> res = make_pair(0, 1);
for (auto x : e[p]) {
if (x.to == par)
continue;
auto t = dfs(x.to, p);
t.first += x.cost;
res = max(res, t);
}
return res;
}
int main() {
cin >> N;
e.resize(N);
for (int i = 0; i < N - 1; i++) {
int s, t, w;
cin >> s >> t >> w;
e[s].emplace_back(t, w);
e[t].emplace_back(s, w);
}
auto res = dfs(0);
res = dfs(res.second);
cout << res.first << endl;
}
| #include <bits/stdc++.h>
using namespace std;
struct edge {
int to;
int cost;
edge(int a, int b) : to(a), cost(b) {}
};
vector<vector<edge>> e;
int N;
pair<int, int> dfs(int p, int par = -1) {
if (e[p].size() == 1 && par >= 0)
return make_pair(0, p);
pair<int, int> res = make_pair(0, 0);
for (auto x : e[p]) {
if (x.to == par)
continue;
auto t = dfs(x.to, p);
t.first += x.cost;
res = max(res, t);
}
return res;
}
int main() {
cin >> N;
e.resize(N);
for (int i = 0; i < N - 1; i++) {
int s, t, w;
cin >> s >> t >> w;
e[s].emplace_back(t, w);
e[t].emplace_back(s, w);
}
auto res = dfs(0);
res = dfs(res.second);
cout << res.first << endl;
}
| replace | 16 | 17 | 16 | 17 | 0 | |
p02372 | C++ | Runtime Error | // clang-format off
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define main signed main()
#define loop(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) loop(i, 0, n)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prec(n) fixed << setprecision(n)
constexpr int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000;
constexpr int MOD = 1000000007;
constexpr double PI = 3.14159265358979;
template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; }
template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; }
bool odd(const int &n) { return n & 1; }
bool even(const int &n) { return ~n & 1; }
template<typename T> int len(const T &v) { return v.size(); }
template<typename T = int> T in() { T x; cin >> x; return x; }
template<typename T = int> T in(T &&x) { T z(forward<T>(x)); cin >> z; return z; }
template<typename T> istream &operator>>(istream &is, vector<T> &v) { for (T &x : v) is >> x; return is; }
template<typename A, typename B> istream &operator>>(istream &is, pair<A, B> &p) { return is >> p.first >> p.second; }
template<typename T> ostream &operator<<(ostream &os, const vector<vector<T>> &v) { int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "" : "\n"); return os; }
template<typename T> ostream &operator<<(ostream &os, const vector<T> &v) { int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "" : " "); return os; }
template<typename A, typename B> ostream &operator<<(ostream &os, const pair<A, B> &p) { return os << p.first << ' ' << p.second; }
template<typename Head, typename Value> auto vectors(const Head &head, const Value &v) { return vector<Value>(head, v); }
template<typename Head, typename... Tail> auto vectors(Head x, Tail... tail) { auto inner = vectors(tail...); return vector<decltype(inner)>(x, inner); }
// clang-format on
using Weight = int;
struct Edge {
int src, dst;
Weight weight;
Edge(const int &s = 0, const int &d = 0, const Weight &w = 0)
: src(s), dst(d), weight(w) {}
};
using Edges = vector<Edge>;
using Array = vector<Weight>;
using Matrix = vector<Array>;
class Graph {
vector<Edges> g;
public:
Graph(const int &size = 0) : g(size) {}
size_t size() const { return g.size(); }
const Edges &operator[](const int &i) const { return g[i]; }
Edges &operator[](const int &i) { return g[i]; }
void addArc(const int &src, const int &dst, const Weight &w = 1) {
g[src].emplace_back(src, dst, w);
}
void addEdge(const int &node1, const int &node2, const Weight &w = 1) {
addArc(node1, node2, w);
addArc(node2, node1, w);
}
auto begin() { return g.begin(); }
auto end() { return g.end(); }
};
vector<Weight> height(const Graph &g) {
int n = g.size();
vector<vector<int>> dp(n);
rep(i, n) dp[i].assign(g[i].size(), -1);
function<Weight(int, int)> dfs = [&](int i, int j) {
if (dp[i][j] != -1)
return dp[i][j];
dp[i][j] = g[i][j].weight;
int u = g[i][j].dst;
rep(k, g[u].size()) {
if (g[u][k].dst == i)
continue;
cmax(dp[i][j], g[i][j].weight + dfs(u, k));
}
return dp[i][j];
};
rep(i, n) rep(j, g[i].size()) if (dp[i][j] == -1) dp[i][j] = dfs(i, j);
vector<Weight> hs(n);
rep(i, n) hs[i] = *max_element(all(dp[i]));
return hs;
}
main {
int n = in();
Graph g(n);
rep(i, n - 1) {
int a, b, c;
cin >> a >> b >> c;
g.addEdge(a, b, c);
}
auto hs = height(g);
for (auto &h : hs)
cout << h << endl;
}
| // clang-format off
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define main signed main()
#define loop(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) loop(i, 0, n)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prec(n) fixed << setprecision(n)
constexpr int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000;
constexpr int MOD = 1000000007;
constexpr double PI = 3.14159265358979;
template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; }
template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; }
bool odd(const int &n) { return n & 1; }
bool even(const int &n) { return ~n & 1; }
template<typename T> int len(const T &v) { return v.size(); }
template<typename T = int> T in() { T x; cin >> x; return x; }
template<typename T = int> T in(T &&x) { T z(forward<T>(x)); cin >> z; return z; }
template<typename T> istream &operator>>(istream &is, vector<T> &v) { for (T &x : v) is >> x; return is; }
template<typename A, typename B> istream &operator>>(istream &is, pair<A, B> &p) { return is >> p.first >> p.second; }
template<typename T> ostream &operator<<(ostream &os, const vector<vector<T>> &v) { int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "" : "\n"); return os; }
template<typename T> ostream &operator<<(ostream &os, const vector<T> &v) { int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "" : " "); return os; }
template<typename A, typename B> ostream &operator<<(ostream &os, const pair<A, B> &p) { return os << p.first << ' ' << p.second; }
template<typename Head, typename Value> auto vectors(const Head &head, const Value &v) { return vector<Value>(head, v); }
template<typename Head, typename... Tail> auto vectors(Head x, Tail... tail) { auto inner = vectors(tail...); return vector<decltype(inner)>(x, inner); }
// clang-format on
using Weight = int;
struct Edge {
int src, dst;
Weight weight;
Edge(const int &s = 0, const int &d = 0, const Weight &w = 0)
: src(s), dst(d), weight(w) {}
};
using Edges = vector<Edge>;
using Array = vector<Weight>;
using Matrix = vector<Array>;
class Graph {
vector<Edges> g;
public:
Graph(const int &size = 0) : g(size) {}
size_t size() const { return g.size(); }
const Edges &operator[](const int &i) const { return g[i]; }
Edges &operator[](const int &i) { return g[i]; }
void addArc(const int &src, const int &dst, const Weight &w = 1) {
g[src].emplace_back(src, dst, w);
}
void addEdge(const int &node1, const int &node2, const Weight &w = 1) {
addArc(node1, node2, w);
addArc(node2, node1, w);
}
auto begin() { return g.begin(); }
auto end() { return g.end(); }
};
vector<Weight> height(const Graph &g) {
int n = g.size();
vector<vector<int>> dp(n);
rep(i, n) dp[i].assign(g[i].size(), -1);
function<Weight(int, int)> dfs = [&](int i, int j) {
if (dp[i][j] != -1)
return dp[i][j];
dp[i][j] = g[i][j].weight;
int u = g[i][j].dst;
rep(k, g[u].size()) {
if (g[u][k].dst == i)
continue;
cmax(dp[i][j], g[i][j].weight + dfs(u, k));
}
return dp[i][j];
};
rep(i, n) rep(j, g[i].size()) if (dp[i][j] == -1) dp[i][j] = dfs(i, j);
vector<Weight> hs(n);
rep(i, n) {
dp[i].emplace_back(0);
hs[i] = *max_element(all(dp[i]));
}
return hs;
}
main {
int n = in();
Graph g(n);
rep(i, n - 1) {
int a, b, c;
cin >> a >> b >> c;
g.addEdge(a, b, c);
}
auto hs = height(g);
for (auto &h : hs)
cout << h << endl;
}
| replace | 78 | 79 | 78 | 82 | 0 | |
p02372 | C++ | Time Limit Exceeded | #include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
typedef long long ll;
#define REP(i, N) for (int i = 0; i < (int)N; i++)
struct edge {
int dest, weight, height;
};
int dfs(int prev, int node, vector<vector<edge>> &adjacentList) {
int res = 0;
for (edge e : adjacentList[node]) {
if (e.dest == prev)
continue;
if (e.height == -1)
e.height = e.weight + dfs(node, e.dest, adjacentList);
res = max(res, e.height);
}
return res;
}
vector<int> heightsOfTree(vector<vector<edge>> &adjacentList) {
int n = adjacentList.size();
vector<int> heights(n);
for (int i = 0; i < n; i++)
heights[i] = dfs(-1, i, adjacentList);
return heights;
}
int main() {
int n;
cin >> n;
vector<vector<edge>> adjacentList(n, vector<edge>());
for (int i = 0; i < n - 1; i++) {
int s, t, w;
cin >> s >> t >> w;
adjacentList[s].push_back(edge{t, w, -1});
adjacentList[t].push_back(edge{s, w, -1});
}
vector<int> heights = heightsOfTree(adjacentList);
for (int i : heights) {
cout << i << endl;
}
return 0;
} | #include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
typedef long long ll;
#define REP(i, N) for (int i = 0; i < (int)N; i++)
struct edge {
int dest, weight, height;
};
int dfs(int prev, int node, vector<vector<edge>> &adjacentList) {
int res = 0;
for (edge &e : adjacentList[node]) {
if (e.dest == prev)
continue;
if (e.height == -1)
e.height = e.weight + dfs(node, e.dest, adjacentList);
res = max(res, e.height);
}
return res;
}
vector<int> heightsOfTree(vector<vector<edge>> &adjacentList) {
int n = adjacentList.size();
vector<int> heights(n);
for (int i = 0; i < n; i++)
heights[i] = dfs(-1, i, adjacentList);
return heights;
}
int main() {
int n;
cin >> n;
vector<vector<edge>> adjacentList(n, vector<edge>());
for (int i = 0; i < n - 1; i++) {
int s, t, w;
cin >> s >> t >> w;
adjacentList[s].push_back(edge{t, w, -1});
adjacentList[t].push_back(edge{s, w, -1});
}
vector<int> heights = heightsOfTree(adjacentList);
for (int i : heights) {
cout << i << endl;
}
return 0;
} | replace | 33 | 34 | 33 | 34 | TLE | |
p02372 | C++ | Runtime Error | #include <iostream>
#include <utility>
#include <vector>
using namespace std;
int V, E, s, t, w;
vector<vector<pair<int, int>>> v(10001);
int visited[10001] = {0};
int ans[10001] = {0}, d[10001] = {0};
void di(int n) {
visited[n] = 1;
for (int i = 0; i < v[n].size(); i++) {
if (visited[v[n][i].first] == 0) {
d[v[n][i].first] = d[n] + v[n][i].second;
di(v[n][i].first);
}
}
}
/*void dfs(int n){
visited[n] = 1;
for(int i=0;i<v[n].size();i++){
if(visited[v[n][i].first]==0){
dfs(v[n][i].first);
d[n] = max(d[n],d[v[n][i].first]+v[n][i].second);
}
}
}
*/
int main() {
cin >> V;
for (int i = 0; i < V - 1; i++) {
cin >> s >> t >> w;
v[s].push_back({t, w});
v[t].push_back({s, w});
}
di(0);
int a, b, va = 0, vb = 0;
for (int i = 0; i < V; i++) {
if (va < d[i]) {
a = i;
va = d[i];
}
}
for (int i = 0; i < V; i++) {
visited[i] = 0;
d[i] = 0;
}
di(a);
for (int i = 0; i < V; i++) {
if (vb < d[i]) {
b = i;
vb = d[i];
}
}
for (int i = 0; i < V; i++) {
visited[i] = 0;
ans[i] = d[i];
d[i] = 0;
}
di(b);
for (int i = 0; i < V; i++) {
ans[i] = max(d[i], ans[i]);
cout << ans[i] << endl;
}
}
| #include <iostream>
#include <utility>
#include <vector>
using namespace std;
int V, E, s, t, w;
vector<vector<pair<int, int>>> v(10001);
int visited[10001] = {0};
int ans[10001] = {0}, d[10001] = {0};
void di(int n) {
visited[n] = 1;
for (int i = 0; i < v[n].size(); i++) {
if (visited[v[n][i].first] == 0) {
d[v[n][i].first] = d[n] + v[n][i].second;
di(v[n][i].first);
}
}
}
/*void dfs(int n){
visited[n] = 1;
for(int i=0;i<v[n].size();i++){
if(visited[v[n][i].first]==0){
dfs(v[n][i].first);
d[n] = max(d[n],d[v[n][i].first]+v[n][i].second);
}
}
}
*/
int main() {
cin >> V;
for (int i = 0; i < V - 1; i++) {
cin >> s >> t >> w;
v[s].push_back({t, w});
v[t].push_back({s, w});
}
di(0);
int a = 0, b = 0, va = 0, vb = 0;
for (int i = 0; i < V; i++) {
if (va < d[i]) {
a = i;
va = d[i];
}
}
for (int i = 0; i < V; i++) {
visited[i] = 0;
d[i] = 0;
}
di(a);
for (int i = 0; i < V; i++) {
if (vb < d[i]) {
b = i;
vb = d[i];
}
}
for (int i = 0; i < V; i++) {
visited[i] = 0;
ans[i] = d[i];
d[i] = 0;
}
di(b);
for (int i = 0; i < V; i++) {
ans[i] = max(d[i], ans[i]);
cout << ans[i] << endl;
}
}
| replace | 37 | 38 | 37 | 38 | 0 | |
p02372 | C++ | Runtime Error | #include <bits/stdc++.h>
using Int = int64_t;
using UInt = uint64_t;
using C = std::complex<double>;
#define rep(i, n) for (Int i = 0; i < (Int)(n); ++i)
#define guard(x) \
if (not(x)) \
continue;
#ifndef LOCAL_
#define fprintf \
if (false) \
fprintf
#endif
int main() {
Int n;
std::cin >> n;
std::vector<Int> ss(n - 1), ts(n - 1), ws(n - 1);
rep(i, n - 1) std::cin >> ss[i] >> ts[i] >> ws[i];
std::vector<std::vector<std::pair<Int, Int>>> nexts(n);
rep(i, n - 1) {
Int s = ss[i], t = ts[i], w = ws[i];
nexts[s].emplace_back(t, w);
nexts[t].emplace_back(s, w);
}
std::vector<Int> xs(n, -1);
std::vector<Int> ys(n, -1);
Int as[2];
for (Int t = 0; t < 2; ++t) {
Int c = t == 0 ? 0 : as[0];
std::vector<Int> &zs = t == 0 ? xs : ys;
std::queue<Int> q;
zs[c] = 0;
q.emplace(c);
while (not q.empty()) {
Int i = q.front();
q.pop();
for (auto kw : nexts[i]) {
Int k, w;
std::tie(k, w) = kw;
guard(zs[k] == -1);
zs[k] = zs[i] + w;
q.emplace(k);
}
}
rep(i, n) if (zs[as[t]] < zs[i]) as[t] = i;
}
rep(i, n) printf("%ld\n", std::max(xs[i], ys[i]));
}
| #include <bits/stdc++.h>
using Int = int64_t;
using UInt = uint64_t;
using C = std::complex<double>;
#define rep(i, n) for (Int i = 0; i < (Int)(n); ++i)
#define guard(x) \
if (not(x)) \
continue;
#ifndef LOCAL_
#define fprintf \
if (false) \
fprintf
#endif
int main() {
Int n;
std::cin >> n;
std::vector<Int> ss(n - 1), ts(n - 1), ws(n - 1);
rep(i, n - 1) std::cin >> ss[i] >> ts[i] >> ws[i];
std::vector<std::vector<std::pair<Int, Int>>> nexts(n);
rep(i, n - 1) {
Int s = ss[i], t = ts[i], w = ws[i];
nexts[s].emplace_back(t, w);
nexts[t].emplace_back(s, w);
}
std::vector<Int> xs(n, -1);
std::vector<Int> ys(n, -1);
Int as[3] = {};
for (Int t = 0; t < 3; ++t) {
Int c = as[std::max((Int)0, t - 1)];
std::vector<Int> &zs = (t % 2 == 0) ? xs : ys;
zs.clear();
zs.resize(n, -1);
std::queue<Int> q;
zs[c] = 0;
q.emplace(c);
while (not q.empty()) {
Int i = q.front();
q.pop();
for (auto kw : nexts[i]) {
Int k, w;
std::tie(k, w) = kw;
guard(zs[k] == -1);
zs[k] = zs[i] + w;
q.emplace(k);
}
}
rep(i, n) if (zs[as[t]] < zs[i]) as[t] = i;
}
rep(i, n) printf("%ld\n", std::max(xs[i], ys[i]));
}
| replace | 27 | 31 | 27 | 33 | -11 | |
p02372 | C++ | Runtime Error | #include <algorithm>
#include <cstdio>
#include <queue>
#include <vector>
#define REP(i, n) for (int i = 0; i < (int)n; ++i)
#define FOR(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(c) (c).begin(), (c).end()
#define INF 99999999
using namespace std;
typedef int Weight;
struct Edge {
int src, dst;
Weight weight;
Edge(int src, int dst, Weight weight) : src(src), dst(dst), weight(weight) {}
};
bool operator<(const Edge &e, const Edge &f) {
return e.weight != f.weight ? e.weight > f.weight : // !!INVERSE!!
e.src != f.src ? e.src < f.src
: e.dst < f.dst;
}
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;
Weight visit(const Graph &g, Graph &T, int i, int j) {
if (T[i][j].weight >= 0)
return T[i][j].weight;
T[i][j].weight = g[i][j].weight;
int u = T[i][j].dst;
REP(k, T[u].size()) {
if (T[u][k].dst == i)
continue;
T[i][j].weight = max(T[i][j].weight, visit(g, T, u, k) + g[i][j].weight);
}
return T[i][j].weight;
}
Array height(const Graph &g) {
const int n = g.size();
Graph T(g); // memoise on tree
for (int i = 0; i < n; ++i)
for (int j = 0; j < T[i].size(); ++j)
T[i][j].weight = -1;
for (int i = 0; i < n; ++i)
for (int j = 0; j < T[i].size(); ++j)
if (T[i][j].weight < 0)
T[i][j].weight = visit(g, T, i, j);
Array ht(n); // gather results
for (int i = 0; i < n; ++i)
for (int j = 0; j < T[i].size(); ++j)
ht[i] = max(ht[i], T[i][j].weight);
return ht;
}
int main() {
int i, V, E, s, t, e;
// for(scanf("%d",&T);T;putchar(--T?' ':'\n')){
scanf("%d", &V);
Graph g(V);
for (i = 0; i < V; i++)
scanf("%d%d%d", &s, &t, &e), g[s].push_back(Edge(s, t, e)),
g[t].push_back(Edge(t, s, e));
Array r = height(g);
for (i = 0; i < V; i++)
printf("%d\n", r[i]);
//}
} | #include <algorithm>
#include <cstdio>
#include <queue>
#include <vector>
#define REP(i, n) for (int i = 0; i < (int)n; ++i)
#define FOR(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(c) (c).begin(), (c).end()
#define INF 99999999
using namespace std;
typedef int Weight;
struct Edge {
int src, dst;
Weight weight;
Edge(int src, int dst, Weight weight) : src(src), dst(dst), weight(weight) {}
};
bool operator<(const Edge &e, const Edge &f) {
return e.weight != f.weight ? e.weight > f.weight : // !!INVERSE!!
e.src != f.src ? e.src < f.src
: e.dst < f.dst;
}
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;
Weight visit(const Graph &g, Graph &T, int i, int j) {
if (T[i][j].weight >= 0)
return T[i][j].weight;
T[i][j].weight = g[i][j].weight;
int u = T[i][j].dst;
REP(k, T[u].size()) {
if (T[u][k].dst == i)
continue;
T[i][j].weight = max(T[i][j].weight, visit(g, T, u, k) + g[i][j].weight);
}
return T[i][j].weight;
}
Array height(const Graph &g) {
const int n = g.size();
Graph T(g); // memoise on tree
for (int i = 0; i < n; ++i)
for (int j = 0; j < T[i].size(); ++j)
T[i][j].weight = -1;
for (int i = 0; i < n; ++i)
for (int j = 0; j < T[i].size(); ++j)
if (T[i][j].weight < 0)
T[i][j].weight = visit(g, T, i, j);
Array ht(n); // gather results
for (int i = 0; i < n; ++i)
for (int j = 0; j < T[i].size(); ++j)
ht[i] = max(ht[i], T[i][j].weight);
return ht;
}
int main() {
int i, V, E, s, t, e;
// for(scanf("%d",&T);T;putchar(--T?' ':'\n')){
scanf("%d", &V);
Graph g(V);
for (i = 0; i < V - 1; i++)
scanf("%d%d%d", &s, &t, &e), g[s].push_back(Edge(s, t, e)),
g[t].push_back(Edge(t, s, e));
Array r = height(g);
for (i = 0; i < V; i++)
printf("%d\n", r[i]);
//}
} | replace | 62 | 63 | 62 | 63 | 0 | |
p02373 | C++ | Memory Limit Exceeded | // Lowest Common Ancestor
// 最小共通先祖
// 二部探索を用いる方法
/*
int main(){
int n; cin >> n;
vector<int> a(n);
for(int i = 0; i < n; i++) cin >> a[i];
a = max(a, b);
a = max(max(a, b), max(c, d));
}*/
#include <bits/stdc++.h>
using namespace std;
#define MAX_V 100010
#define MAX_LOG_V 500
vector<int> G[MAX_V]; // グラフの隣接リスト
int root; // 根の頂点番号
int parent[MAX_LOG_V]
[MAX_V]; // parent[i][j] := 頂点jから2^i親をたどって到達する頂点
int depth[MAX_V]; // 根からの深さ
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < G[v].size(); i++) {
if (G[v][i] != p)
dfs(G[v][i], v, d + 1);
}
}
void init(int V) {
// parent[0]とdepthを初期化する
dfs(root, -1, 0);
// parentを初期化する
for (int k = 0; k + 1 < MAX_LOG_V; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
// uとvのLCAを求める
int lca(int u, int v) {
// uとvの深さが同じになるまで親をたどる
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < MAX_LOG_V; k++) {
if ((depth[v] - depth[u] >> k) & 1) { // これあテクい
v = parent[k][v];
}
}
if (u == v)
return u;
// 二部探索でLCAを求める
for (int k = MAX_LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u]; // uの親を返す
}
int main() {
// 0-indexed
int V;
cin >> V;
root = 0;
for (int i = 0; i < V; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
G[i].push_back(c);
G[c].push_back(i);
}
}
init(V);
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int u, v;
cin >> u >> v;
cout << lca(u, v) << endl;
}
return 0;
}
| // Lowest Common Ancestor
// 最小共通先祖
// 二部探索を用いる方法
/*
int main(){
int n; cin >> n;
vector<int> a(n);
for(int i = 0; i < n; i++) cin >> a[i];
a = max(a, b);
a = max(max(a, b), max(c, d));
}*/
#include <bits/stdc++.h>
using namespace std;
#define MAX_V 100010
#define MAX_LOG_V 100
vector<int> G[MAX_V]; // グラフの隣接リスト
int root; // 根の頂点番号
int parent[MAX_LOG_V]
[MAX_V]; // parent[i][j] := 頂点jから2^i親をたどって到達する頂点
int depth[MAX_V]; // 根からの深さ
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < G[v].size(); i++) {
if (G[v][i] != p)
dfs(G[v][i], v, d + 1);
}
}
void init(int V) {
// parent[0]とdepthを初期化する
dfs(root, -1, 0);
// parentを初期化する
for (int k = 0; k + 1 < MAX_LOG_V; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
// uとvのLCAを求める
int lca(int u, int v) {
// uとvの深さが同じになるまで親をたどる
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < MAX_LOG_V; k++) {
if ((depth[v] - depth[u] >> k) & 1) { // これあテクい
v = parent[k][v];
}
}
if (u == v)
return u;
// 二部探索でLCAを求める
for (int k = MAX_LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u]; // uの親を返す
}
int main() {
// 0-indexed
int V;
cin >> V;
root = 0;
for (int i = 0; i < V; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
G[i].push_back(c);
G[c].push_back(i);
}
}
init(V);
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int u, v;
cin >> u >> v;
cout << lca(u, v) << endl;
}
return 0;
}
| replace | 16 | 17 | 16 | 17 | MLE | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> len, tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> tree)
: tree(tree), n(tree.size()), size(n), parent(n), in(n), out(n), path(n),
pathSize(n), pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
// buildPaths(0,newPath(0));
len.resize(pathCount);
/*
REP(i,pathCount){
int m=pathSize[i];
len[i].resize(2*m);
fill(ALL(len[i]),0);
fill(len[i].begin()+m,len[i].begin()+2*m,1);
for(int j=2*m-1;j>1;j-=2)len[i][j>>1]=len[i][j]+len[i][j^1];
}
*/
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
int main(void) {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> len, tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> tree)
: tree(tree), n(tree.size()), size(n), parent(n), in(n), out(n), path(n),
pathSize(n), pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
// len.resize(pathCount);
/*
REP(i,pathCount){
int m=pathSize[i];
len[i].resize(2*m);
fill(ALL(len[i]),0);
fill(len[i].begin()+m,len[i].begin()+2*m,1);
for(int j=2*m-1;j>1;j-=2)len[i][j>>1]=len[i][j]+len[i][j^1];
}
*/
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
int main(void) {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | replace | 22 | 24 | 22 | 24 | 0 | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> len, tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> tree)
: tree(tree), n(tree.size()), size(n), parent(n), in(n), out(n), path(n),
pathSize(n), pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
// cout << "Path Count = " << pathCount << "\n";
len.resize(pathCount, vector<int>());
/*
REP(i,pathCount){
int m=pathSize[i];
len[i].resize(2*m);
fill(ALL(len[i]),0);
fill(len[i].begin()+m,len[i].begin()+2*m,1);
for(int j=2*m-1;j>1;j-=2)len[i][j>>1]=len[i][j]+len[i][j^1];
}
*/
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
int main(void) {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> len, tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> tree)
: tree(tree), n(tree.size()), size(n), parent(n), in(n), out(n), path(n),
pathSize(n), pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
// cout << "Path Count = " << pathCount << "\n";
len = vector<vector<int>>(pathCount);
/*
REP(i,pathCount){
int m=pathSize[i];
len[i].resize(2*m);
fill(ALL(len[i]),0);
fill(len[i].begin()+m,len[i].begin()+2*m,1);
for(int j=2*m-1;j>1;j-=2)len[i][j>>1]=len[i][j]+len[i][j^1];
}
*/
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
int main(void) {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | replace | 24 | 25 | 24 | 25 | 0 | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<ll> vll;
typedef vector<vector<ll>> vvll;
const int INFL = (int)1e9;
const ll INFLL = (ll)1e18;
const double INFD = numeric_limits<double>::infinity();
const double PI = 3.14159265358979323846;
#define Loop(i, n) for (int i = 0; i < (int)n; i++)
#define Loopll(i, n) for (ll i = 0; i < (ll)n; i++)
#define Loop1(i, n) for (int i = 1; i <= (int)n; i++)
#define Loopll1(i, n) for (ll i = 1; i <= (ll)n; i++)
#define Loopr(i, n) for (int i = (int)n - 1; i >= 0; i--)
#define Looprll(i, n) for (ll i = (ll)n - 1; i >= 0; i--)
#define Loopr1(i, n) for (int i = (int)n; i >= 1; i--)
#define Looprll1(i, n) for (ll i = (ll)n; i >= 1; i--)
#define Loopitr(itr, container) \
for (auto itr = container.begin(); itr != container.end(); itr++)
#define printv(vector) \
Loop(i, vector.size()) { cout << vector[i] << " "; } \
cout << endl;
#define printmx(matrix) \
Loop(i, matrix.size()) { \
Loop(j, matrix[i].size()) { cout << matrix[i][j] << " "; } \
cout << endl; \
}
#define rndf(d) (ll)((double)(d) + (d >= 0 ? 0.5 : -0.5))
#define floorsqrt(x) \
((ll)sqrt((double)x) + \
((ll)sqrt((double)x) * (ll)sqrt((double)x) <= (ll)(x) ? 0 : -1))
#define ceilsqrt(x) \
((ll)sqrt((double)x) + \
((ll)x <= (ll)sqrt((double)x) * (ll)sqrt((double)x) ? 0 : 1))
#define rnddiv(a, b) \
((ll)(a) / (ll)(b) + ((ll)(a) % (ll)(b)*2 >= (ll)(b) ? 1 : 0))
#define ceildiv(a, b) ((ll)(a) / (ll)(b) + ((ll)(a) % (ll)(b) == 0 ? 0 : 1))
#define bitmanip(m, val) static_cast<bitset<(int)m>>(val)
/*******************************************************/
typedef ll nodeval_t;
typedef ll edgeval_t;
struct tree_t {
int n; // |V|, index begins with 0
vector<P> edges; // E
vector<nodeval_t> vals; // value of nodes
vector<edgeval_t> costs; // cost, distance, or weight of edges
};
class Tree {
private:
struct node {
int id;
vi childs;
int parent = -1;
int deg = -1; // the number of edges of the path to the root
int eid = -1; // edge id of the edge connected by its parent and itself
int subtree_n =
-1; // the number of nodes of the partial tree rooted by itself
int visited = -1; // time stamp of visiting on DFS
int departed = -1; // time stamp of departure on DFS
nodeval_t val; // value of the node itself
edgeval_t cost; // cost of the edge connected by its parent and itself
bool operator<(const node &another) const {
return deg != another.deg ? deg < another.deg : id < another.id;
}
};
struct edgeinfo {
int eid;
int to;
edgeval_t cost;
};
int n;
static const nodeval_t init_val = 0;
static const edgeval_t init_cost = 1;
vector<vector<edgeinfo>> edges;
vvi sparse_ancestors;
void tree_construction() {
leaves = {};
queue<int> que;
que.push(root);
while (que.size()) {
int a = que.front();
que.pop();
deg_order.push_back(a);
if (a == Tree::root)
nodes[a].deg = 0;
int leaf_flag = true;
Loop(i, edges[a].size()) {
int b = edges[a][i].to;
if (nodes[b].deg != -1) {
nodes[a].parent = b;
nodes[a].eid = edges[a][i].eid;
nodes[a].cost = edges[a][i].cost;
nodes[a].deg = nodes[b].deg + 1;
} else {
leaf_flag = false;
nodes[a].childs.push_back(b);
que.push(b);
}
}
if (leaf_flag)
leaves.push_back(a);
}
Loopr(i, n) {
int a = deg_order[i];
Loop(j, nodes[a].childs.size()) {
int b = nodes[a].childs[j];
nodes[a].subtree_n += nodes[b].subtree_n;
}
}
}
public:
vector<node> nodes;
vi deg_order; // node ids, sorted by deg
vi leaves;
int root;
// T should be non-empty tree
Tree(tree_t T, int root = -1) {
n = T.n;
nodes.resize(n);
Loop(i, n) {
nodes[i].id = i;
nodes[i].val = T.vals.size() > i ? T.vals[i] : 0;
nodes[i].cost = init_cost;
}
edges.resize(n);
Loop(i, n - 1) {
edges[T.edges[i].first].push_back(
{i, T.edges[i].second,
(T.costs.size() > i ? T.costs[i] : init_cost)});
edges[T.edges[i].second].push_back(
{i, T.edges[i].first, (T.costs.size() > i ? T.costs[i] : init_cost)});
}
// the node which has the greatest degree will automatically decided as the
// root
if (root < 0) {
int max_d = -1;
Loop(i, n) {
if (edges[i].size() > max_d) {
Tree::root = i;
max_d = edges[i].size();
}
}
} else {
this->root = min(root, n - 1);
}
tree_construction();
return;
}
pair<int, vi> solve_center_of_gravity() {
pair<int, vi> ret = {INT_MAX, {}};
vector<node> c_nodes = nodes;
sort(c_nodes.begin(), c_nodes.end());
vi record(n, 1);
Loopr(i, n) {
int x = n - 1, max_x = INT_MIN;
Loop(j, c_nodes[i].childs.size()) {
int b = c_nodes[i].childs[j];
max_x = max(max_x, record[b]);
x -= record[b];
record[c_nodes[i].id] += record[b];
}
max_x = max(max_x, x);
if (max_x < ret.first)
ret = {max_x, {c_nodes[i].id}};
else if (max_x == ret.first)
ret.second.push_back(c_nodes[i].id);
}
sort(ret.second.begin(), ret.second.end());
return ret;
}
vi solve_node_inclusion_cnt_in_all_path(bool enable_single_node_path) {
vi ret(n, 0);
Loop(i, n) {
int a = i;
// desendants to desendants
Loop(j, nodes[a].childs.size()) {
int b = nodes[a].childs[j];
ret[i] +=
nodes[b].subtree_n * (nodes[a].subtree_n - nodes[b].subtree_n - 1);
}
ret[i] /= 2; // because of double counting
ret[i] +=
(nodes[a].subtree_n - 1) *
(n -
nodes[a].subtree_n); // desendants to the others except for itself
ret[i] += n - 1; // itself to the others
if (enable_single_node_path)
ret[i]++; // itself
}
return ret;
}
vi solve_edge_inclusion_cnt_in_all_path() {
vi ret(n - 1, 0);
Loop(i, n) {
int eid = nodes[i].eid;
if (eid < 0)
continue;
ret[eid] =
nodes[i].subtree_n *
(n - nodes[i].subtree_n); // members in the partial tree to the others
}
return ret;
}
void solve_sparse_ancestors() {
sparse_ancestors.resize(n);
vector<int> current_ancestors;
stack<int> stk;
stk.push(Tree::root);
int time_stamp = 1;
while (stk.size()) {
int a = stk.top();
stk.pop();
nodes[a].visited = time_stamp++;
for (int i = 1; i <= current_ancestors.size(); i *= 2) {
sparse_ancestors[a].push_back(
current_ancestors[current_ancestors.size() - i]);
}
if (nodes[a].childs.size()) {
Loop(i, nodes[a].childs.size()) { stk.push(nodes[a].childs[i]); }
current_ancestors.push_back(a);
} else {
nodes[a].departed = time_stamp++;
while (current_ancestors.size() &&
(stk.empty() ||
nodes[stk.top()].parent != current_ancestors.back())) {
nodes[current_ancestors.back()].departed = time_stamp++;
current_ancestors.pop_back();
}
}
}
return;
}
bool is_ancestor(int descendant, int ancestor) {
return nodes[ancestor].visited < nodes[descendant].visited &&
nodes[descendant].departed < nodes[ancestor].departed;
}
int get_lowest_common_ancestor(int u, int v) {
if (is_ancestor(u, v))
return v;
if (is_ancestor(v, u))
return u;
int a = u;
while (!is_ancestor(v, sparse_ancestors[a][0])) {
int b = sparse_ancestors[a][0];
Loop1(i, sparse_ancestors[a].size() - 1) {
if (is_ancestor(v, sparse_ancestors[a][i]))
break;
else
b = sparse_ancestors[a][i - 1];
}
a = b;
}
return sparse_ancestors[a][0];
}
};
int main() {
tree_t T;
cin >> T.n;
Loop(i, T.n) {
int m;
cin >> m;
Loop(j, m) {
int t;
cin >> t;
T.edges.push_back({i, t});
}
}
Tree tree(T, 0);
tree.solve_sparse_ancestors();
int q;
cin >> q;
Loop(i, q) {
int s, t;
cin >> s >> t;
cout << tree.get_lowest_common_ancestor(s, t) << endl;
}
}
| #include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<ll> vll;
typedef vector<vector<ll>> vvll;
const int INFL = (int)1e9;
const ll INFLL = (ll)1e18;
const double INFD = numeric_limits<double>::infinity();
const double PI = 3.14159265358979323846;
#define Loop(i, n) for (int i = 0; i < (int)n; i++)
#define Loopll(i, n) for (ll i = 0; i < (ll)n; i++)
#define Loop1(i, n) for (int i = 1; i <= (int)n; i++)
#define Loopll1(i, n) for (ll i = 1; i <= (ll)n; i++)
#define Loopr(i, n) for (int i = (int)n - 1; i >= 0; i--)
#define Looprll(i, n) for (ll i = (ll)n - 1; i >= 0; i--)
#define Loopr1(i, n) for (int i = (int)n; i >= 1; i--)
#define Looprll1(i, n) for (ll i = (ll)n; i >= 1; i--)
#define Loopitr(itr, container) \
for (auto itr = container.begin(); itr != container.end(); itr++)
#define printv(vector) \
Loop(i, vector.size()) { cout << vector[i] << " "; } \
cout << endl;
#define printmx(matrix) \
Loop(i, matrix.size()) { \
Loop(j, matrix[i].size()) { cout << matrix[i][j] << " "; } \
cout << endl; \
}
#define rndf(d) (ll)((double)(d) + (d >= 0 ? 0.5 : -0.5))
#define floorsqrt(x) \
((ll)sqrt((double)x) + \
((ll)sqrt((double)x) * (ll)sqrt((double)x) <= (ll)(x) ? 0 : -1))
#define ceilsqrt(x) \
((ll)sqrt((double)x) + \
((ll)x <= (ll)sqrt((double)x) * (ll)sqrt((double)x) ? 0 : 1))
#define rnddiv(a, b) \
((ll)(a) / (ll)(b) + ((ll)(a) % (ll)(b)*2 >= (ll)(b) ? 1 : 0))
#define ceildiv(a, b) ((ll)(a) / (ll)(b) + ((ll)(a) % (ll)(b) == 0 ? 0 : 1))
#define bitmanip(m, val) static_cast<bitset<(int)m>>(val)
/*******************************************************/
typedef ll nodeval_t;
typedef ll edgeval_t;
struct tree_t {
int n; // |V|, index begins with 0
vector<P> edges; // E
vector<nodeval_t> vals; // value of nodes
vector<edgeval_t> costs; // cost, distance, or weight of edges
};
class Tree {
private:
struct node {
int id;
vi childs;
int parent = -1;
int deg = -1; // the number of edges of the path to the root
int eid = -1; // edge id of the edge connected by its parent and itself
int subtree_n =
-1; // the number of nodes of the partial tree rooted by itself
int visited = -1; // time stamp of visiting on DFS
int departed = -1; // time stamp of departure on DFS
nodeval_t val; // value of the node itself
edgeval_t cost; // cost of the edge connected by its parent and itself
bool operator<(const node &another) const {
return deg != another.deg ? deg < another.deg : id < another.id;
}
};
struct edgeinfo {
int eid;
int to;
edgeval_t cost;
};
int n;
static const nodeval_t init_val = 0;
static const edgeval_t init_cost = 1;
vector<vector<edgeinfo>> edges;
vvi sparse_ancestors;
void tree_construction() {
leaves = {};
queue<int> que;
que.push(root);
while (que.size()) {
int a = que.front();
que.pop();
deg_order.push_back(a);
if (a == Tree::root)
nodes[a].deg = 0;
int leaf_flag = true;
Loop(i, edges[a].size()) {
int b = edges[a][i].to;
if (nodes[b].deg != -1) {
nodes[a].parent = b;
nodes[a].eid = edges[a][i].eid;
nodes[a].cost = edges[a][i].cost;
nodes[a].deg = nodes[b].deg + 1;
} else {
leaf_flag = false;
nodes[a].childs.push_back(b);
que.push(b);
}
}
if (leaf_flag)
leaves.push_back(a);
}
Loopr(i, n) {
int a = deg_order[i];
Loop(j, nodes[a].childs.size()) {
int b = nodes[a].childs[j];
nodes[a].subtree_n += nodes[b].subtree_n;
}
}
}
public:
vector<node> nodes;
vi deg_order; // node ids, sorted by deg
vi leaves;
int root;
// T should be non-empty tree
Tree(tree_t T, int root = -1) {
n = T.n;
nodes.resize(n);
Loop(i, n) {
nodes[i].id = i;
nodes[i].val = T.vals.size() > i ? T.vals[i] : 0;
nodes[i].cost = init_cost;
}
edges.resize(n);
Loop(i, n - 1) {
edges[T.edges[i].first].push_back(
{i, T.edges[i].second,
(T.costs.size() > i ? T.costs[i] : init_cost)});
edges[T.edges[i].second].push_back(
{i, T.edges[i].first, (T.costs.size() > i ? T.costs[i] : init_cost)});
}
// the node which has the greatest degree will automatically decided as the
// root
if (root < 0) {
int max_d = -1;
Loop(i, n) {
if (edges[i].size() > max_d) {
Tree::root = i;
max_d = edges[i].size();
}
}
} else {
this->root = min(root, n - 1);
}
tree_construction();
return;
}
pair<int, vi> solve_center_of_gravity() {
pair<int, vi> ret = {INT_MAX, {}};
vector<node> c_nodes = nodes;
sort(c_nodes.begin(), c_nodes.end());
vi record(n, 1);
Loopr(i, n) {
int x = n - 1, max_x = INT_MIN;
Loop(j, c_nodes[i].childs.size()) {
int b = c_nodes[i].childs[j];
max_x = max(max_x, record[b]);
x -= record[b];
record[c_nodes[i].id] += record[b];
}
max_x = max(max_x, x);
if (max_x < ret.first)
ret = {max_x, {c_nodes[i].id}};
else if (max_x == ret.first)
ret.second.push_back(c_nodes[i].id);
}
sort(ret.second.begin(), ret.second.end());
return ret;
}
vi solve_node_inclusion_cnt_in_all_path(bool enable_single_node_path) {
vi ret(n, 0);
Loop(i, n) {
int a = i;
// desendants to desendants
Loop(j, nodes[a].childs.size()) {
int b = nodes[a].childs[j];
ret[i] +=
nodes[b].subtree_n * (nodes[a].subtree_n - nodes[b].subtree_n - 1);
}
ret[i] /= 2; // because of double counting
ret[i] +=
(nodes[a].subtree_n - 1) *
(n -
nodes[a].subtree_n); // desendants to the others except for itself
ret[i] += n - 1; // itself to the others
if (enable_single_node_path)
ret[i]++; // itself
}
return ret;
}
vi solve_edge_inclusion_cnt_in_all_path() {
vi ret(n - 1, 0);
Loop(i, n) {
int eid = nodes[i].eid;
if (eid < 0)
continue;
ret[eid] =
nodes[i].subtree_n *
(n - nodes[i].subtree_n); // members in the partial tree to the others
}
return ret;
}
void solve_sparse_ancestors() {
sparse_ancestors.resize(n);
vector<int> current_ancestors;
stack<int> stk;
stk.push(Tree::root);
int time_stamp = 1;
while (stk.size()) {
int a = stk.top();
stk.pop();
nodes[a].visited = time_stamp++;
for (int i = 1; i <= current_ancestors.size(); i *= 2) {
sparse_ancestors[a].push_back(
current_ancestors[current_ancestors.size() - i]);
}
if (nodes[a].childs.size()) {
Loop(i, nodes[a].childs.size()) { stk.push(nodes[a].childs[i]); }
current_ancestors.push_back(a);
} else {
nodes[a].departed = time_stamp++;
while (current_ancestors.size() &&
(stk.empty() ||
nodes[stk.top()].parent != current_ancestors.back())) {
nodes[current_ancestors.back()].departed = time_stamp++;
current_ancestors.pop_back();
}
}
}
return;
}
bool is_ancestor(int descendant, int ancestor) {
return nodes[ancestor].visited < nodes[descendant].visited &&
nodes[descendant].departed < nodes[ancestor].departed;
}
int get_lowest_common_ancestor(int u, int v) {
if (u == v)
return u;
if (is_ancestor(u, v))
return v;
if (is_ancestor(v, u))
return u;
int a = u;
while (!is_ancestor(v, sparse_ancestors[a][0])) {
int b = sparse_ancestors[a][0];
Loop1(i, sparse_ancestors[a].size() - 1) {
if (is_ancestor(v, sparse_ancestors[a][i]))
break;
else
b = sparse_ancestors[a][i - 1];
}
a = b;
}
return sparse_ancestors[a][0];
}
};
int main() {
tree_t T;
cin >> T.n;
Loop(i, T.n) {
int m;
cin >> m;
Loop(j, m) {
int t;
cin >> t;
T.edges.push_back({i, t});
}
}
Tree tree(T, 0);
tree.solve_sparse_ancestors();
int q;
cin >> q;
Loop(i, q) {
int s, t;
cin >> s >> t;
cout << tree.get_lowest_common_ancestor(s, t) << endl;
}
}
| insert | 271 | 271 | 271 | 273 | 0 | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
#define int long long
// BEGIN CUT HERE
struct LowestCommonAncestor {
const int MAX_LOG_V = 50;
vector<vector<int>> G, parent;
int root = 0, V;
vector<int> depth;
LowestCommonAncestor() {}
LowestCommonAncestor(int V) : V(V) { init(); }
void init() {
for (int i = 0; i < (int)G.size(); i++)
G[i].clear();
G.clear();
for (int i = 0; i < (int)parent.size(); i++)
parent[i].clear();
parent.clear();
depth.clear();
G.resize(V);
parent.resize(MAX_LOG_V, vector<int>(V));
depth.resize(V);
}
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < (int)G[v].size(); i++) {
if (G[v][i] != p)
dfs(G[v][i], v, d + 1);
}
}
void construct() {
dfs(root, -1, 0);
for (int k = 0; k + 1 < MAX_LOG_V; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < MAX_LOG_V; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
for (int k = MAX_LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
// END CUT HERE
signed main() {
int n;
LowestCommonAncestor lca(n);
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
lca.add_edge(i, c);
}
}
lca.construct();
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << endl;
}
return 0;
}
/*
verified on 2017/06/29
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_A&lang=jp
*/ | #include <bits/stdc++.h>
using namespace std;
#define int long long
// BEGIN CUT HERE
struct LowestCommonAncestor {
const int MAX_LOG_V = 50;
vector<vector<int>> G, parent;
int root = 0, V;
vector<int> depth;
LowestCommonAncestor() {}
LowestCommonAncestor(int V) : V(V) { init(); }
void init() {
for (int i = 0; i < (int)G.size(); i++)
G[i].clear();
G.clear();
for (int i = 0; i < (int)parent.size(); i++)
parent[i].clear();
parent.clear();
depth.clear();
G.resize(V);
parent.resize(MAX_LOG_V, vector<int>(V));
depth.resize(V);
}
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < (int)G[v].size(); i++) {
if (G[v][i] != p)
dfs(G[v][i], v, d + 1);
}
}
void construct() {
dfs(root, -1, 0);
for (int k = 0; k + 1 < MAX_LOG_V; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < MAX_LOG_V; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
for (int k = MAX_LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
// END CUT HERE
signed main() {
int n;
cin >> n;
LowestCommonAncestor lca(n);
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
lca.add_edge(i, c);
}
}
lca.construct();
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << endl;
}
return 0;
}
/*
verified on 2017/06/29
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_A&lang=jp
*/ | insert | 75 | 75 | 75 | 76 | -6 | terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
|
p02373 | C++ | Runtime Error | #include <cassert>
#include <cmath>
#include <cstdio>
#include <stack>
#include <vector>
#define repeat(i, n) for (int i = 0; (i) < int(n); ++(i))
#define repeat_reverse(i, n) for (int i = (n)-1; (i) >= 0; --(i))
using namespace std;
/**
* @brief lowest common ancestor with doubling
*/
struct lowest_common_ancestor {
vector<vector<int>> a;
vector<int> depth;
lowest_common_ancestor() = default;
/**
* @note O(N \log N)
*/
lowest_common_ancestor(int root, vector<vector<int>> const &g) {
int n = g.size();
int log_n = floor(log2(n));
a.resize(log_n, vector<int>(n, -1));
depth.resize(n, -1);
{
auto &parent = a[0];
stack<int> stk;
depth[root] = 0;
parent[root] = -1;
stk.push(root);
while (not stk.empty()) {
int x = stk.top();
stk.pop();
for (int y : g[x])
if (depth[y] == -1) {
depth[y] = depth[x] + 1;
parent[y] = x;
stk.push(y);
}
}
}
repeat(k, log_n - 1) {
repeat(i, n) {
if (a[k][i] != -1) {
a[k + 1][i] = a[k][a[k][i]];
}
}
}
}
/**
* @brief find the LCA of x and y
* @note O(log N)
*/
int operator()(int x, int y) const {
int log_n = a.size();
if (depth[x] < depth[y])
swap(x, y);
repeat_reverse(k, log_n) {
if (a[k][x] != -1 and depth[a[k][x]] >= depth[y]) {
x = a[k][x];
}
}
assert(depth[x] == depth[y]);
assert(x != -1);
if (x == y)
return x;
repeat_reverse(k, log_n) {
if (a[k][x] != a[k][y]) {
x = a[k][x];
y = a[k][y];
}
}
assert(x != y);
assert(a[0][x] == a[0][y]);
return a[0][x];
}
/**
* @brief find the descendant of x for y
*/
int descendant(int x, int y) const {
assert(depth[x] < depth[y]);
int log_n = a.size();
repeat_reverse(k, log_n) {
if (a[k][y] != -1 and depth[a[k][y]] >= depth[x] + 1) {
y = a[k][y];
}
}
assert(a[0][y] == x);
return y;
}
};
int main() {
int n;
scanf("%d", &n);
vector<vector<int>> g(n);
repeat(i, n) {
int edges;
scanf("%d", &edges);
while (edges--) {
int j;
scanf("%d", &j);
g[i].push_back(j);
g[j].push_back(i);
}
}
constexpr int root = 0;
lowest_common_ancestor lca(root, g);
int query;
scanf("%d", &query);
while (query--) {
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", lca(x, y));
}
return 0;
} | #include <cassert>
#include <cmath>
#include <cstdio>
#include <stack>
#include <vector>
#define repeat(i, n) for (int i = 0; (i) < int(n); ++(i))
#define repeat_reverse(i, n) for (int i = (n)-1; (i) >= 0; --(i))
using namespace std;
/**
* @brief lowest common ancestor with doubling
*/
struct lowest_common_ancestor {
vector<vector<int>> a;
vector<int> depth;
lowest_common_ancestor() = default;
/**
* @note O(N \log N)
*/
lowest_common_ancestor(int root, vector<vector<int>> const &g) {
int n = g.size();
int log_n = 1 + floor(log2(n));
a.resize(log_n, vector<int>(n, -1));
depth.resize(n, -1);
{
auto &parent = a[0];
stack<int> stk;
depth[root] = 0;
parent[root] = -1;
stk.push(root);
while (not stk.empty()) {
int x = stk.top();
stk.pop();
for (int y : g[x])
if (depth[y] == -1) {
depth[y] = depth[x] + 1;
parent[y] = x;
stk.push(y);
}
}
}
repeat(k, log_n - 1) {
repeat(i, n) {
if (a[k][i] != -1) {
a[k + 1][i] = a[k][a[k][i]];
}
}
}
}
/**
* @brief find the LCA of x and y
* @note O(log N)
*/
int operator()(int x, int y) const {
int log_n = a.size();
if (depth[x] < depth[y])
swap(x, y);
repeat_reverse(k, log_n) {
if (a[k][x] != -1 and depth[a[k][x]] >= depth[y]) {
x = a[k][x];
}
}
assert(depth[x] == depth[y]);
assert(x != -1);
if (x == y)
return x;
repeat_reverse(k, log_n) {
if (a[k][x] != a[k][y]) {
x = a[k][x];
y = a[k][y];
}
}
assert(x != y);
assert(a[0][x] == a[0][y]);
return a[0][x];
}
/**
* @brief find the descendant of x for y
*/
int descendant(int x, int y) const {
assert(depth[x] < depth[y]);
int log_n = a.size();
repeat_reverse(k, log_n) {
if (a[k][y] != -1 and depth[a[k][y]] >= depth[x] + 1) {
y = a[k][y];
}
}
assert(a[0][y] == x);
return y;
}
};
int main() {
int n;
scanf("%d", &n);
vector<vector<int>> g(n);
repeat(i, n) {
int edges;
scanf("%d", &edges);
while (edges--) {
int j;
scanf("%d", &j);
g[i].push_back(j);
g[j].push_back(i);
}
}
constexpr int root = 0;
lowest_common_ancestor lca(root, g);
int query;
scanf("%d", &query);
while (query--) {
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", lca(x, y));
}
return 0;
} | replace | 21 | 22 | 21 | 22 | 0 | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int N; // Graph(Tree)の頂点数
vector<vector<int>> G; // Graph(Tree)の隣接リスト表現
vector<int> D; // 各頂点のrootからの距離
int LOG_N; // log2(N)の天井
vector<vector<int>> P; // P[k][v] : 頂点vの2^k番目の先祖
void dfs(int prev, int index, int d) {
P[0][index] = prev;
D[index] = d;
for (int i = 0; i < G[index].size(); i++) {
int next = G[index][i];
if (next == prev)
continue;
dfs(index, next, d + 1);
}
}
void init() {
LOG_N = int(ceil(log2(N)));
P.clear();
P.resize(LOG_N, vector<int>(N));
D.clear();
D.resize(N);
dfs(-1, 0, 0);
for (int k = 0; k < LOG_N - 1; k++) {
for (int v = 0; v < N; v++) {
if (P[k][v] < 0)
P[k + 1][v] = -1;
else
P[k + 1][v] = P[k][P[k][v]];
}
}
}
// 頂点vのn番目の親を返す
int nth_parent(int v, int n) {
for (int k = 0; k < LOG_N; k++)
if (n & (1 << k))
v = P[k][v];
return v;
}
// 2頂点uとvのLCAを返す
int lca(int u, int v) {
if (D[u] > D[v])
swap(u, v);
v = nth_parent(v, D[v] - D[u]);
if (u == v)
return u;
for (int k = LOG_N - 1; k >= 0; k--) {
if (P[k][u] != P[k][v]) {
u = P[k][u];
v = P[k][v];
}
}
return P[0][u];
}
// 2頂点uとvの距離を返す
int dist(int u, int v) {
int root = lca(u, v);
return (D[u] - D[root]) + (D[v] - D[root]);
}
int main() {
cin >> N;
G.clear();
G.resize(N);
for (int i = 0; i < N; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
G[i].push_back(c);
}
}
init();
int Q;
cin >> Q;
for (int q = 0; q < Q; q++) {
int u, v;
cin >> u >> v;
cout << lca(u, v) << endl;
}
return 0;
} | #include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int N; // Graph(Tree)の頂点数
vector<vector<int>> G; // Graph(Tree)の隣接リスト表現
vector<int> D; // 各頂点のrootからの距離
int LOG_N; // log2(N)の天井
vector<vector<int>> P; // P[k][v] : 頂点vの2^k番目の先祖
void dfs(int prev, int index, int d) {
P[0][index] = prev;
D[index] = d;
for (int i = 0; i < G[index].size(); i++) {
int next = G[index][i];
if (next == prev)
continue;
dfs(index, next, d + 1);
}
}
void init() {
LOG_N = int(ceil(log2(N) + 1));
P.clear();
P.resize(LOG_N, vector<int>(N));
D.clear();
D.resize(N);
dfs(-1, 0, 0);
for (int k = 0; k < LOG_N - 1; k++) {
for (int v = 0; v < N; v++) {
if (P[k][v] < 0)
P[k + 1][v] = -1;
else
P[k + 1][v] = P[k][P[k][v]];
}
}
}
// 頂点vのn番目の親を返す
int nth_parent(int v, int n) {
for (int k = 0; k < LOG_N; k++)
if (n & (1 << k))
v = P[k][v];
return v;
}
// 2頂点uとvのLCAを返す
int lca(int u, int v) {
if (D[u] > D[v])
swap(u, v);
v = nth_parent(v, D[v] - D[u]);
if (u == v)
return u;
for (int k = LOG_N - 1; k >= 0; k--) {
if (P[k][u] != P[k][v]) {
u = P[k][u];
v = P[k][v];
}
}
return P[0][u];
}
// 2頂点uとvの距離を返す
int dist(int u, int v) {
int root = lca(u, v);
return (D[u] - D[root]) + (D[v] - D[root]);
}
int main() {
cin >> N;
G.clear();
G.resize(N);
for (int i = 0; i < N; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
G[i].push_back(c);
}
}
init();
int Q;
cin >> Q;
for (int q = 0; q < Q; q++) {
int u, v;
cin >> u >> v;
cout << lca(u, v) << endl;
}
return 0;
} | replace | 24 | 25 | 24 | 25 | 0 | |
p02373 | C++ | Runtime Error | #include "bits/stdc++.h"
using namespace std;
//?????????
#pragma region MACRO
#define putans(x) \
std::cerr << "[ answer ]: "; \
cout << (x) << endl
#define dputans(x) \
std::cerr << "[ answer ]: "; \
cout << setprecision(40) << (double)(x) << endl
#define REP(i, a, n) for (int i = (a); i < (int)(n); i++)
#define RREP(i, n, a) for (int i = (int)(n - 1); i >= a; i--)
#define rep(i, n) REP(i, 0, n)
#define rrep(i, n) RREP(i, n, 0)
#define all(a) begin((a)), end((a))
#define mp make_pair
#define exist(container, n) ((container).find((n)) != (container).end())
#define equals(a, b) (fabs((a) - (b)) < EPS)
#ifdef _DEBUG //???????????????????????????????????????????????????
std::ifstream ifs("data.txt");
#define put ifs >>
#else //?????£????????????????????§?????????????????????
#define put cin >>
#endif
#pragma endregion
//???????????°??????????????´
#pragma region CODING_SUPPORT
#ifdef _DEBUG
#define dbg(var0) \
{ std::cerr << (#var0) << "=" << (var0) << endl; }
#define dbg2(var0, var1) \
{ \
std::cerr << (#var0) << "=" << (var0) << ", "; \
dbg(var1); \
}
#define dbg3(var0, var1, var2) \
{ \
std::cerr << (#var0) << "=" << (var0) << ", "; \
dbg2(var1, var2); \
}
#define dbgArray(a, n) \
{ \
std::cerr << (#a) << "="; \
rep(i, n) { std::cerr << (a[i]) << ","; } \
cerr << endl; \
}
#else
#define dbg(var0) \
{}
#define dbg2(var0, var1) \
{}
#define dbg3(var0, var1, var2) \
{}
#define dbgArray(a, n) \
{}
#endif
#pragma endregion
// typedef????????????????????????????¶????????????§?????????
#pragma region TYPE_DEF
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<string, string> pss;
typedef pair<int, string> pis;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
#pragma endregion
//??????????????°(???????????????????????§??????)
#pragma region CONST_VAL
#define PI (2 * acos(0.0))
#define EPS (1e-10)
#define MOD (ll)(1e9 + 7)
#define INF (ll)(2 * 1e9)
#pragma endregion
const static int MAX_V = 10000;
vector<int> G[MAX_V];
int root = 0;
int vs[MAX_V * 2 - 1];
int depth[MAX_V * 2 - 1];
int id[MAX_V];
//?????????????????????????????????????±?????????????????????°???????????¨
// int double ??¨??????numeric???????????£?????????????????????
// n ????´???°
// invalid_value ???????????°???????????????a????????????marge(a,invalidvalue) =
// a, marge(invalid_value, a) = a?????¨??????????????????
class SegmentTreeInt {
public:
SegmentTreeInt(int n, int invalid_value);
~SegmentTreeInt();
void SetElem(int k, int val);
int GetCount();
int quary(int a, int b);
int GetElem(int k);
//?????????????????¢??°???????????????????????????
// invalid_value??????????????£?????°????????????????????????
bool IsInvalidValue(int value) { return value == mInvalidValue; }
// a??¨b??????
// a???b????±?????????¢??°???????????§?¨?????????????????????§?±???????
int Marge(int a, int b) {
if (IsInvalidValue(a))
return b;
if (IsInvalidValue(b))
return a;
if (depth[a] >= depth[b])
return b;
return a;
}
private:
vector<int> mTree;
int mCount;
int mInvalidValue;
void Update(int k, int val);
int InternalQuary(int a, int b, int k, int l, int r);
};
//?????´??????????????????(??????????????¨???????????´??????)
SegmentTreeInt::SegmentTreeInt(int n, int invalid_value) {
int bin_n = 1;
while (bin_n < n)
bin_n *= 2;
mTree.resize(2 * bin_n);
mInvalidValue = invalid_value;
mCount = bin_n;
for (int i = 0; i < 2 * bin_n - 1; i++) {
mTree[i] = invalid_value;
}
}
SegmentTreeInt::~SegmentTreeInt() {}
void SegmentTreeInt::SetElem(int k, int val) { Update(k, val); }
int SegmentTreeInt::GetElem(int k) { return mTree[mCount - 1 + k]; }
int SegmentTreeInt::GetCount() { return mCount; }
//????????´??°
void SegmentTreeInt::Update(int k, int val) {
k += mCount - 1;
mTree[k] = val;
while (k > 0) {
k = (k - 1) / 2;
mTree[k] = Marge(mTree[2 * k + 1], mTree[2 * k + 2]);
}
}
//??????[a,b]?????????O(ln(Count))??§?±??????? b < GetCount??¨???????????¨
// ex. a = 0 , b = 2 ?????? 0,1,2?????????
int SegmentTreeInt::quary(int a, int b) {
return InternalQuary(a, b + 1, 0, 0, mCount);
}
//?????¨?????????
int SegmentTreeInt::InternalQuary(int a, int b, int k, int l, int r) {
if (r <= a || b <= l)
return mInvalidValue;
if (a <= l && r <= b)
return mTree[k];
else {
int vl = InternalQuary(a, b, k * 2 + 1, l, (l + r) / 2);
int vr = InternalQuary(a, b, k * 2 + 2, (l + r) / 2, r);
return Marge(vl, vr);
}
}
//???????????§?????´??????
SegmentTreeInt rmq(2 * MAX_V - 1, INF);
void dfs(int v, int p, int d, int &k) {
id[v] = k;
vs[k] = v;
depth[k++] = d;
rep(i, G[v].size()) {
if (G[v][i] != p) {
dfs(G[v][i], v, d + 1, k);
vs[k] = v;
depth[k++] = d;
}
}
}
//
void init(int V) {
int k = 0;
dfs(root, -1, 0, k);
rep(i, V * 2) { rmq.SetElem(i, i); }
}
int LCA(int u, int v) {
return vs[rmq.quary(min(id[u], id[v]), max(id[u], id[v]))];
}
int main() {
int n;
put n;
rep(i, n) {
int k;
put k;
rep(j, k) {
int c;
put c;
G[i].push_back(c);
}
}
int q;
put q;
init(n);
rep(i, q) {
int u, v;
put u >> v;
cout << LCA(u, v) << endl;
}
END:
return 0;
} | #include "bits/stdc++.h"
using namespace std;
//?????????
#pragma region MACRO
#define putans(x) \
std::cerr << "[ answer ]: "; \
cout << (x) << endl
#define dputans(x) \
std::cerr << "[ answer ]: "; \
cout << setprecision(40) << (double)(x) << endl
#define REP(i, a, n) for (int i = (a); i < (int)(n); i++)
#define RREP(i, n, a) for (int i = (int)(n - 1); i >= a; i--)
#define rep(i, n) REP(i, 0, n)
#define rrep(i, n) RREP(i, n, 0)
#define all(a) begin((a)), end((a))
#define mp make_pair
#define exist(container, n) ((container).find((n)) != (container).end())
#define equals(a, b) (fabs((a) - (b)) < EPS)
#ifdef _DEBUG //???????????????????????????????????????????????????
std::ifstream ifs("data.txt");
#define put ifs >>
#else //?????£????????????????????§?????????????????????
#define put cin >>
#endif
#pragma endregion
//???????????°??????????????´
#pragma region CODING_SUPPORT
#ifdef _DEBUG
#define dbg(var0) \
{ std::cerr << (#var0) << "=" << (var0) << endl; }
#define dbg2(var0, var1) \
{ \
std::cerr << (#var0) << "=" << (var0) << ", "; \
dbg(var1); \
}
#define dbg3(var0, var1, var2) \
{ \
std::cerr << (#var0) << "=" << (var0) << ", "; \
dbg2(var1, var2); \
}
#define dbgArray(a, n) \
{ \
std::cerr << (#a) << "="; \
rep(i, n) { std::cerr << (a[i]) << ","; } \
cerr << endl; \
}
#else
#define dbg(var0) \
{}
#define dbg2(var0, var1) \
{}
#define dbg3(var0, var1, var2) \
{}
#define dbgArray(a, n) \
{}
#endif
#pragma endregion
// typedef????????????????????????????¶????????????§?????????
#pragma region TYPE_DEF
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<string, string> pss;
typedef pair<int, string> pis;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
#pragma endregion
//??????????????°(???????????????????????§??????)
#pragma region CONST_VAL
#define PI (2 * acos(0.0))
#define EPS (1e-10)
#define MOD (ll)(1e9 + 7)
#define INF (ll)(2 * 1e9)
#pragma endregion
const static int MAX_V = 100000;
vector<int> G[MAX_V];
int root = 0;
int vs[MAX_V * 2 - 1];
int depth[MAX_V * 2 - 1];
int id[MAX_V];
//?????????????????????????????????????±?????????????????????°???????????¨
// int double ??¨??????numeric???????????£?????????????????????
// n ????´???°
// invalid_value ???????????°???????????????a????????????marge(a,invalidvalue) =
// a, marge(invalid_value, a) = a?????¨??????????????????
class SegmentTreeInt {
public:
SegmentTreeInt(int n, int invalid_value);
~SegmentTreeInt();
void SetElem(int k, int val);
int GetCount();
int quary(int a, int b);
int GetElem(int k);
//?????????????????¢??°???????????????????????????
// invalid_value??????????????£?????°????????????????????????
bool IsInvalidValue(int value) { return value == mInvalidValue; }
// a??¨b??????
// a???b????±?????????¢??°???????????§?¨?????????????????????§?±???????
int Marge(int a, int b) {
if (IsInvalidValue(a))
return b;
if (IsInvalidValue(b))
return a;
if (depth[a] >= depth[b])
return b;
return a;
}
private:
vector<int> mTree;
int mCount;
int mInvalidValue;
void Update(int k, int val);
int InternalQuary(int a, int b, int k, int l, int r);
};
//?????´??????????????????(??????????????¨???????????´??????)
SegmentTreeInt::SegmentTreeInt(int n, int invalid_value) {
int bin_n = 1;
while (bin_n < n)
bin_n *= 2;
mTree.resize(2 * bin_n);
mInvalidValue = invalid_value;
mCount = bin_n;
for (int i = 0; i < 2 * bin_n - 1; i++) {
mTree[i] = invalid_value;
}
}
SegmentTreeInt::~SegmentTreeInt() {}
void SegmentTreeInt::SetElem(int k, int val) { Update(k, val); }
int SegmentTreeInt::GetElem(int k) { return mTree[mCount - 1 + k]; }
int SegmentTreeInt::GetCount() { return mCount; }
//????????´??°
void SegmentTreeInt::Update(int k, int val) {
k += mCount - 1;
mTree[k] = val;
while (k > 0) {
k = (k - 1) / 2;
mTree[k] = Marge(mTree[2 * k + 1], mTree[2 * k + 2]);
}
}
//??????[a,b]?????????O(ln(Count))??§?±??????? b < GetCount??¨???????????¨
// ex. a = 0 , b = 2 ?????? 0,1,2?????????
int SegmentTreeInt::quary(int a, int b) {
return InternalQuary(a, b + 1, 0, 0, mCount);
}
//?????¨?????????
int SegmentTreeInt::InternalQuary(int a, int b, int k, int l, int r) {
if (r <= a || b <= l)
return mInvalidValue;
if (a <= l && r <= b)
return mTree[k];
else {
int vl = InternalQuary(a, b, k * 2 + 1, l, (l + r) / 2);
int vr = InternalQuary(a, b, k * 2 + 2, (l + r) / 2, r);
return Marge(vl, vr);
}
}
//???????????§?????´??????
SegmentTreeInt rmq(2 * MAX_V - 1, INF);
void dfs(int v, int p, int d, int &k) {
id[v] = k;
vs[k] = v;
depth[k++] = d;
rep(i, G[v].size()) {
if (G[v][i] != p) {
dfs(G[v][i], v, d + 1, k);
vs[k] = v;
depth[k++] = d;
}
}
}
//
void init(int V) {
int k = 0;
dfs(root, -1, 0, k);
rep(i, V * 2) { rmq.SetElem(i, i); }
}
int LCA(int u, int v) {
return vs[rmq.quary(min(id[u], id[v]), max(id[u], id[v]))];
}
int main() {
int n;
put n;
rep(i, n) {
int k;
put k;
rep(j, k) {
int c;
put c;
G[i].push_back(c);
}
}
int q;
put q;
init(n);
rep(i, q) {
int u, v;
put u >> v;
cout << LCA(u, v) << endl;
}
END:
return 0;
} | replace | 75 | 76 | 75 | 76 | 0 | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
#define GET_MACRO(_1, _2, _3, NAME, ...) NAME
#define _repl(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define _rep(i, n) _repl(i, 0, n)
#define rep(...) GET_MACRO(__VA_ARGS__, _repl, _rep)(__VA_ARGS__)
#define mp(a, b) make_pair((a), (b))
#define pb(a) push_back((a))
#define all(x) (x).begin(), (x).end()
#define uniq(x) sort(all(x)), (x).erase(unique(all(x)), end(x))
#define fi first
#define se second
#define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
void _dbg(string) { cout << endl; }
template <class H, class... T> void _dbg(string s, H h, T... t) {
int l = s.find(',');
cout << s.substr(0, l) << " = " << h << ", ";
_dbg(s.substr(l + 1), t...);
}
template <class T, class U>
ostream &operator<<(ostream &o, const pair<T, U> &p) {
o << "(" << p.fi << "," << p.se << ")";
return o;
}
template <class T> ostream &operator<<(ostream &o, const vector<T> &v) {
o << "[";
for (T t : v) {
o << t << ",";
}
o << "]";
return o;
}
vector<int> tree[100005];
class LCA {
public:
int n, ln; // number of nodes and log n
vector<vector<int>> parent;
vector<int> depth;
LCA(int _n, int root = -1) : n(_n), depth(_n) {
ln = 0;
while (n > (1 << ln))
ln++; // calc log n
parent = vector<vector<int>>(ln, vector<int>(n));
if (root != -1)
init(root);
}
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
rep(i, tree[v].size()) if (tree[v][i] != p) dfs(tree[v][i], v, d + 1);
}
void init(int root) {
dfs(root, -1, 0);
for (int k = 0; k + 1 < ln; k++) {
for (int v = 0; v < n; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int query(int u, int v) {
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < ln; k++) {
if ((depth[v] - depth[u]) >> k & 1)
v = parent[k][v];
}
if (u == v)
return u;
for (int k = ln - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
int main() {
int n;
cin >> n;
rep(i, n) {
int k;
cin >> k;
rep(j, k) {
int d;
cin >> d;
tree[i].pb(d);
}
}
LCA lca(n, 0);
int q;
cin >> q;
rep(_, q) {
int a, b;
cin >> a >> b;
cout << lca.query(a, b) << "\n";
}
return 0;
} | #include <bits/stdc++.h>
using namespace std;
#define GET_MACRO(_1, _2, _3, NAME, ...) NAME
#define _repl(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define _rep(i, n) _repl(i, 0, n)
#define rep(...) GET_MACRO(__VA_ARGS__, _repl, _rep)(__VA_ARGS__)
#define mp(a, b) make_pair((a), (b))
#define pb(a) push_back((a))
#define all(x) (x).begin(), (x).end()
#define uniq(x) sort(all(x)), (x).erase(unique(all(x)), end(x))
#define fi first
#define se second
#define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
void _dbg(string) { cout << endl; }
template <class H, class... T> void _dbg(string s, H h, T... t) {
int l = s.find(',');
cout << s.substr(0, l) << " = " << h << ", ";
_dbg(s.substr(l + 1), t...);
}
template <class T, class U>
ostream &operator<<(ostream &o, const pair<T, U> &p) {
o << "(" << p.fi << "," << p.se << ")";
return o;
}
template <class T> ostream &operator<<(ostream &o, const vector<T> &v) {
o << "[";
for (T t : v) {
o << t << ",";
}
o << "]";
return o;
}
vector<int> tree[100005];
class LCA {
public:
int n, ln; // number of nodes and log n
vector<vector<int>> parent;
vector<int> depth;
LCA(int _n, int root = -1) : n(_n), depth(_n) {
ln = 0;
while (n >= (1 << ln))
ln++; // calc log n
parent = vector<vector<int>>(ln, vector<int>(n));
if (root != -1)
init(root);
}
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
rep(i, tree[v].size()) if (tree[v][i] != p) dfs(tree[v][i], v, d + 1);
}
void init(int root) {
dfs(root, -1, 0);
for (int k = 0; k + 1 < ln; k++) {
for (int v = 0; v < n; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int query(int u, int v) {
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < ln; k++) {
if ((depth[v] - depth[u]) >> k & 1)
v = parent[k][v];
}
if (u == v)
return u;
for (int k = ln - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
int main() {
int n;
cin >> n;
rep(i, n) {
int k;
cin >> k;
rep(j, k) {
int d;
cin >> d;
tree[i].pb(d);
}
}
LCA lca(n, 0);
int q;
cin >> q;
rep(_, q) {
int a, b;
cin >> a >> b;
cout << lca.query(a, b) << "\n";
}
return 0;
} | replace | 42 | 43 | 42 | 43 | 0 | |
p02373 | C++ | Memory Limit Exceeded | #include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef vector<vii> vvii;
typedef vector<int>::iterator vit;
const int MAXN = 100005;
const int LOGN = 50;
int idx[MAXN]; // i : index of node i in dfs path
ii path[MAXN << 1];
vi adjList[MAXN];
ii ST[LOGN][MAXN << 1];
void build(int n) {
int h = (n == 1 ? 1 : ceil(log2(n)));
for (int i = 0; i < n; i++)
ST[0][i] = path[i];
for (int i = 1; i < h; i++)
for (int j = 0; j + (1 << i) <= n; j++)
ST[i][j] = min(ST[i - 1][j], ST[i - 1][j + (1 << (i - 1))]);
}
int RMQ(int l, int r) { // range [l,r)
int p = 31 - __builtin_clz(r - l);
return min(ST[p][l], ST[p][r - (1 << p)]).se;
}
// build dfs path, depth
int cnt = 0;
void dfs(int curr, int d) {
idx[curr] = cnt;
path[cnt++] = ii(d, curr);
for (vit it = adjList[curr].begin(); it != adjList[curr].end(); it++) {
dfs(*it, d + 1);
path[cnt++] = ii(d, curr);
}
}
int N, M, Q, v;
int main() {
scanf("%d", &N);
for (int u = 0; u < N; u++) {
scanf("%d", &M);
for (int i = 0; i < M; i++) {
scanf("%d", &v);
adjList[u].push_back(v);
}
}
// rooted as 0
dfs(0, 0);
build(cnt);
scanf("%d", &Q);
for (int i = 0, u, v, l, r; i < Q; i++) {
scanf("%d%d", &u, &v);
l = idx[u], r = idx[v];
if (l > r)
swap(l, r);
printf("%d\n", RMQ(l, r + 1));
}
return 0;
} | #include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef vector<vii> vvii;
typedef vector<int>::iterator vit;
const int MAXN = 100005;
const int LOGN = 20;
int idx[MAXN]; // i : index of node i in dfs path
ii path[MAXN << 1];
vi adjList[MAXN];
ii ST[LOGN][MAXN << 1];
void build(int n) {
int h = (n == 1 ? 1 : ceil(log2(n)));
for (int i = 0; i < n; i++)
ST[0][i] = path[i];
for (int i = 1; i < h; i++)
for (int j = 0; j + (1 << i) <= n; j++)
ST[i][j] = min(ST[i - 1][j], ST[i - 1][j + (1 << (i - 1))]);
}
int RMQ(int l, int r) { // range [l,r)
int p = 31 - __builtin_clz(r - l);
return min(ST[p][l], ST[p][r - (1 << p)]).se;
}
// build dfs path, depth
int cnt = 0;
void dfs(int curr, int d) {
idx[curr] = cnt;
path[cnt++] = ii(d, curr);
for (vit it = adjList[curr].begin(); it != adjList[curr].end(); it++) {
dfs(*it, d + 1);
path[cnt++] = ii(d, curr);
}
}
int N, M, Q, v;
int main() {
scanf("%d", &N);
for (int u = 0; u < N; u++) {
scanf("%d", &M);
for (int i = 0; i < M; i++) {
scanf("%d", &v);
adjList[u].push_back(v);
}
}
// rooted as 0
dfs(0, 0);
build(cnt);
scanf("%d", &Q);
for (int i = 0, u, v, l, r; i < Q; i++) {
scanf("%d%d", &u, &v);
l = idx[u], r = idx[v];
if (l > r)
swap(l, r);
printf("%d\n", RMQ(l, r + 1));
}
return 0;
} | replace | 13 | 14 | 13 | 14 | MLE | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
const int MAXN = 100005;
int path[2 * MAXN], depth[2 * MAXN],
idx[MAXN]; // idx : the index of node in dfs path
int par[MAXN];
vi adjList[MAXN];
class SparseTable {
private:
int n, h;
vvi t;
int combine(int l, int r) {
if (l == -1 || r == -1)
return max(l, r);
return depth[l] < depth[r] ? l : r;
}
public:
SparseTable(int size) {
n = size;
h = ceil(log2(n));
t.assign(h, vi());
t[0].assign(n, 0);
for (int i = 0; i < n; i++)
t[0][i] = i;
for (int i = 1; i < h; i++) {
t[i].assign(n, 0);
for (int j = 0; j + (1 << i) <= n; j++) {
t[i][j] = combine(t[i - 1][j], t[i - 1][j + (1 << (i - 1))]);
}
}
}
int query(int l, int r) { // query in range v[l,r]
int p = 31 - __builtin_clz(r - l + 1);
return combine(t[p][l], t[p][r - (1 << p) + 1]);
}
};
int cnt = 0;
// build dfs path, depth
void dfs(int curr, int d) {
idx[curr] = cnt;
path[cnt] = curr;
depth[cnt++] = d;
for (int i = 0; i < adjList[curr].size(); i++) {
dfs(adjList[curr][i], d + 1);
path[cnt] = curr;
depth[cnt++] = d;
}
}
int N, M, Q, v;
int main() {
memset(par, -1, sizeof(par));
scanf("%d", &N);
for (int u = 0; u < N; u++) {
scanf("%d", &M);
for (int i = 0; i < M; i++) {
scanf("%d", &v);
par[v] = u;
adjList[u].push_back(v);
}
}
int root;
for (int i = 0; i < N; i++)
if (par[i] == -1)
root = i;
dfs(root, 0);
SparseTable st(cnt);
scanf("%d", &Q);
for (int i = 0; i < Q; i++) {
int u, v, l, r;
scanf("%d%d", &u, &v);
l = idx[u];
r = idx[v];
if (l > r)
swap(l, r);
int id = st.query(l, r);
printf("%d\n", path[id]);
}
return 0;
} | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
const int MAXN = 100005;
int path[2 * MAXN], depth[2 * MAXN],
idx[MAXN]; // idx : the index of node in dfs path
int par[MAXN];
vi adjList[MAXN];
class SparseTable {
private:
int n, h;
vvi t;
int combine(int l, int r) {
if (l == -1 || r == -1)
return max(l, r);
return depth[l] < depth[r] ? l : r;
}
public:
SparseTable(int size) {
n = size;
h = (n == 1 ? 1 : ceil(log2(n)));
t.assign(h, vi());
t[0].assign(n, 0);
for (int i = 0; i < n; i++)
t[0][i] = i;
for (int i = 1; i < h; i++) {
t[i].assign(n, 0);
for (int j = 0; j + (1 << i) <= n; j++) {
t[i][j] = combine(t[i - 1][j], t[i - 1][j + (1 << (i - 1))]);
}
}
}
int query(int l, int r) { // query in range v[l,r]
int p = 31 - __builtin_clz(r - l + 1);
return combine(t[p][l], t[p][r - (1 << p) + 1]);
}
};
int cnt = 0;
// build dfs path, depth
void dfs(int curr, int d) {
idx[curr] = cnt;
path[cnt] = curr;
depth[cnt++] = d;
for (int i = 0; i < adjList[curr].size(); i++) {
dfs(adjList[curr][i], d + 1);
path[cnt] = curr;
depth[cnt++] = d;
}
}
int N, M, Q, v;
int main() {
memset(par, -1, sizeof(par));
scanf("%d", &N);
for (int u = 0; u < N; u++) {
scanf("%d", &M);
for (int i = 0; i < M; i++) {
scanf("%d", &v);
par[v] = u;
adjList[u].push_back(v);
}
}
int root;
for (int i = 0; i < N; i++)
if (par[i] == -1)
root = i;
dfs(root, 0);
SparseTable st(cnt);
scanf("%d", &Q);
for (int i = 0; i < Q; i++) {
int u, v, l, r;
scanf("%d%d", &u, &v);
l = idx[u];
r = idx[v];
if (l > r)
swap(l, r);
int id = st.query(l, r);
printf("%d\n", path[id]);
}
return 0;
} | replace | 29 | 30 | 29 | 30 | 0 | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> t)
: tree(t), n(tree.size()), size(n), parent(n), in(n), out(n), path(n),
pathSize(n), pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
// Usage: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C
int main(void) {
// ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> len, tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> t)
: tree(t), n(tree.size()), size(n), parent(n), in(n), out(n), path(n),
pathSize(n), pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
// Usage: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C
int main(void) {
// ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | replace | 13 | 14 | 13 | 14 | 0 | |
p02373 | C++ | Time Limit Exceeded | #include <bits/stdc++.h>
using namespace std;
using Int = long long;
// BEGIN CUT HERE
struct HLDecomposition {
int n, pos;
vector<vector<int>> G;
vector<int> vid, head, sub, hvy, par, dep, inv, type, ps, pt;
HLDecomposition() {}
HLDecomposition(int sz)
: n(sz), pos(0), G(n), vid(n, -1), head(n), sub(n, 1), hvy(n, -1), par(n),
dep(n), inv(n), type(n), ps(n), pt(n) {}
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void build(vector<int> rs = {0}) {
int c = 0;
for (int r : rs) {
dfs(r);
bfs(r, c++);
}
}
void dfs(int rt) {
using T = pair<int, int>;
stack<T> st;
par[rt] = -1;
dep[rt] = 0;
st.emplace(rt, 0);
while (!st.empty()) {
int v = st.top().first;
int &i = st.top().second;
if (i < (int)G[v].size()) {
int u = G[v][i++];
if (u == par[v])
continue;
par[u] = v;
dep[u] = dep[v] + 1;
st.emplace(u, 0);
} else {
st.pop();
for (int j = 0; j < (int)G[v].size(); j++) {
int &u = G[v][j];
if (u == par[v]) {
swap(u, G[v].back());
continue;
}
sub[v] += sub[u];
if (sub[u] > sub[G[v].front()])
swap(u, G[v].front());
}
}
}
}
void bfs(int r, int c) {
using T = tuple<int, int, int>;
stack<T> st;
st.emplace(r, r, 0);
while (!st.empty()) {
int v, h;
tie(v, h, ignore) = st.top();
int &i = get<2>(st.top());
if (!i) {
type[v] = c;
ps[v] = vid[v] = pos++;
inv[vid[v]] = v;
head[v] = h;
hvy[v] = (G[v].empty() ? -1 : G[v][0]);
if (hvy[v] == par[v])
hvy[v] = -1;
}
if (i < (int)G[v].size()) {
int u = G[v][i++];
if (u == par[v])
continue;
st.emplace(u, (i ? u : h), 0);
} else {
st.pop();
pt[v] = pos;
}
}
}
// for_each(vertex)
// [l,r] <- attention!!
void for_each(int u, int v, const function<void(int, int)> &f) {
while (1) {
if (vid[u] > vid[v])
swap(u, v);
f(max(vid[head[v]], vid[u]), vid[v]);
if (head[u] != head[v])
v = par[head[v]];
else
break;
}
}
// for_each(edge)
// [l,r] <- attention!!
void for_each_edge(int u, int v, const function<void(int, int)> &f) {
while (1) {
if (vid[u] > vid[v])
swap(u, v);
if (head[u] != head[v]) {
f(vid[head[v]], vid[v]);
v = par[head[v]];
} else {
if (u != v)
f(vid[u] + 1, vid[v]);
break;
}
}
}
int lca(int u, int v) {
while (1) {
if (vid[u] > vid[v])
swap(u, v);
if (head[u] == head[v])
return u;
v = par[head[v]];
}
}
int distance(int u, int v) { return dep[u] + dep[v] - 2 * dep[lca(u, v)]; }
};
// END CUT HERE
signed AOJ_GRL5C() {
int n;
cin >> n;
HLDecomposition lca(n);
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
lca.add_edge(i, c);
}
}
lca.build();
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << endl;
}
return 0;
}
/*
verified on 2017/12/31
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C&lang=jp
*/
struct BiconectedGraph {
typedef pair<int, int> P;
int n;
vector<vector<int>> G, C, T;
vector<int> ord, low, belong;
vector<P> B;
BiconectedGraph() {}
BiconectedGraph(int sz) : n(sz), G(sz), C(sz), T(sz) {}
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void input(int m, int offset) {
int a, b;
for (int i = 0; i < m; i++) {
scanf("%d %d", &a, &b);
add_edge(a + offset, b + offset);
}
}
bool is_bridge(int u, int v) {
if (ord[u] > ord[v])
swap(u, v);
return ord[u] < low[v];
}
void dfs(int u, int p, int &k) {
ord[u] = low[u] = k;
++k;
for (int v : G[u]) {
if (v == p)
continue;
if (ord[v] >= 0) {
low[u] = min(low[u], ord[v]);
} else {
dfs(v, u, k);
low[u] = min(low[u], low[v]);
}
if (is_bridge(u, v))
B.push_back(P(u, v));
}
}
void fill_component(int c, int u) {
C[c].push_back(u);
belong[u] = c;
for (int v : G[u]) {
if (belong[v] >= 0 || is_bridge(u, v))
continue;
fill_component(c, v);
}
}
void add_component(int u, int &k) {
if (belong[u] >= 0)
return;
fill_component(k++, u);
}
int build() {
int k = 0;
ord.resize(n);
low.resize(n);
belong.resize(n);
fill(ord.begin(), ord.end(), -1);
fill(belong.begin(), belong.end(), -1);
for (int u = 0; u < n; u++) {
if (ord[u] >= 0)
continue;
dfs(u, -1, k);
}
k = 0;
for (int i = 0; i < (int)B.size(); i++) {
add_component(B[i].first, k);
add_component(B[i].second, k);
}
for (int u = 0; u < n; u++)
add_component(u, k);
for (int i = 0; i < (int)B.size(); i++) {
int u = belong[B[i].first], v = belong[B[i].second];
T[u].push_back(v);
T[v].push_back(u);
}
return k;
}
};
template <typename T, typename E> struct SegmentTree {
typedef function<T(T, T)> F;
typedef function<T(T, E)> G;
int n;
F f;
G g;
T d1;
E d0;
vector<T> dat;
SegmentTree(){};
SegmentTree(int n_, F f, G g, T d1, vector<T> v = vector<T>())
: f(f), g(g), d1(d1) {
init(n_);
if (n_ == (int)v.size())
build(n_, v);
}
void init(int n_) {
n = 1;
while (n < n_)
n *= 2;
dat.clear();
dat.resize(2 * n - 1, d1);
}
void build(int n_, vector<T> v) {
for (int i = 0; i < n_; i++)
dat[i + n - 1] = v[i];
for (int i = n - 2; i >= 0; i--)
dat[i] = f(dat[i * 2 + 1], dat[i * 2 + 2]);
}
void update(int k, E a) {
k += n - 1;
dat[k] = g(dat[k], a);
while (k > 0) {
k = (k - 1) / 2;
dat[k] = f(dat[k * 2 + 1], dat[k * 2 + 2]);
}
}
inline T query(int a, int b) {
T vl = d1, vr = d1;
for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) {
if (l & 1)
vl = f(vl, dat[(l++) - 1]);
if (r & 1)
vr = f(dat[(--r) - 1], vr);
}
return f(vl, vr);
}
};
signed YUKI_529() {
int n, e, q;
scanf("%d %d %d", &n, &e, &q);
BiconectedGraph big(n);
big.input(e, -1);
int E = 0, V = big.build();
HLDecomposition hl(V);
for (int i = 0; i < V; i++)
for (int j : big.T[i])
if (i < j)
hl.add_edge(i, j), E++;
hl.build();
SegmentTree<int, int> rmq(
V, [](int a, int b) { return max(a, b); },
[](int a, int b) {
a++;
return b;
},
-1);
vector<priority_queue<int>> pq(V);
map<int, int> m;
int num = 0;
for (int i = 0; i < q; i++) {
int d;
scanf("%d", &d);
if (d == 1) {
int u, w;
scanf("%d %d", &u, &w);
u--;
u = big.belong[u];
u = hl.vid[u];
m[w] = u;
if (pq[u].empty() || pq[u].top() < w)
rmq.update(u, w);
pq[u].push(w);
num++;
}
if (d == 2) {
int s, t;
scanf("%d %d", &s, &t);
s--;
t--;
s = big.belong[s];
t = big.belong[t];
int ans = -1;
hl.for_each(s, t,
[&](int l, int r) { ans = max(ans, rmq.query(l, r + 1)); });
printf("%d\n", ans);
if (~ans) {
int k = m[ans];
pq[k].pop();
rmq.update(k, (!pq[k].empty() ? pq[k].top() : -1));
num--;
}
}
}
return 0;
}
/* verified on 2017/12/31
https://yukicoder.me/problems/no/529
*/
signed main() {
AOJ_GRL5C();
// YUKI_529();
return 0;
};
| #include <bits/stdc++.h>
using namespace std;
using Int = long long;
// BEGIN CUT HERE
struct HLDecomposition {
int n, pos;
vector<vector<int>> G;
vector<int> vid, head, sub, hvy, par, dep, inv, type, ps, pt;
HLDecomposition() {}
HLDecomposition(int sz)
: n(sz), pos(0), G(n), vid(n, -1), head(n), sub(n, 1), hvy(n, -1), par(n),
dep(n), inv(n), type(n), ps(n), pt(n) {}
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void build(vector<int> rs = {0}) {
int c = 0;
for (int r : rs) {
dfs(r);
bfs(r, c++);
}
}
void dfs(int rt) {
using T = pair<int, int>;
stack<T> st;
par[rt] = -1;
dep[rt] = 0;
st.emplace(rt, 0);
while (!st.empty()) {
int v = st.top().first;
int &i = st.top().second;
if (i < (int)G[v].size()) {
int u = G[v][i++];
if (u == par[v])
continue;
par[u] = v;
dep[u] = dep[v] + 1;
st.emplace(u, 0);
} else {
st.pop();
for (int j = 0; j < (int)G[v].size(); j++) {
int &u = G[v][j];
if (u == par[v]) {
swap(u, G[v].back());
continue;
}
sub[v] += sub[u];
if (sub[u] > sub[G[v].front()])
swap(u, G[v].front());
}
}
}
}
void bfs(int r, int c) {
using T = tuple<int, int, int>;
stack<T> st;
st.emplace(r, r, 0);
while (!st.empty()) {
int v, h;
tie(v, h, ignore) = st.top();
int &i = get<2>(st.top());
if (!i) {
type[v] = c;
ps[v] = vid[v] = pos++;
inv[vid[v]] = v;
head[v] = h;
hvy[v] = (G[v].empty() ? -1 : G[v][0]);
if (hvy[v] == par[v])
hvy[v] = -1;
}
if (i < (int)G[v].size()) {
int u = G[v][i++];
if (u == par[v])
continue;
st.emplace(u, (hvy[v] == u ? h : u), 0);
} else {
st.pop();
pt[v] = pos;
}
}
}
// for_each(vertex)
// [l,r] <- attention!!
void for_each(int u, int v, const function<void(int, int)> &f) {
while (1) {
if (vid[u] > vid[v])
swap(u, v);
f(max(vid[head[v]], vid[u]), vid[v]);
if (head[u] != head[v])
v = par[head[v]];
else
break;
}
}
// for_each(edge)
// [l,r] <- attention!!
void for_each_edge(int u, int v, const function<void(int, int)> &f) {
while (1) {
if (vid[u] > vid[v])
swap(u, v);
if (head[u] != head[v]) {
f(vid[head[v]], vid[v]);
v = par[head[v]];
} else {
if (u != v)
f(vid[u] + 1, vid[v]);
break;
}
}
}
int lca(int u, int v) {
while (1) {
if (vid[u] > vid[v])
swap(u, v);
if (head[u] == head[v])
return u;
v = par[head[v]];
}
}
int distance(int u, int v) { return dep[u] + dep[v] - 2 * dep[lca(u, v)]; }
};
// END CUT HERE
signed AOJ_GRL5C() {
int n;
cin >> n;
HLDecomposition lca(n);
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
lca.add_edge(i, c);
}
}
lca.build();
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << endl;
}
return 0;
}
/*
verified on 2017/12/31
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C&lang=jp
*/
struct BiconectedGraph {
typedef pair<int, int> P;
int n;
vector<vector<int>> G, C, T;
vector<int> ord, low, belong;
vector<P> B;
BiconectedGraph() {}
BiconectedGraph(int sz) : n(sz), G(sz), C(sz), T(sz) {}
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void input(int m, int offset) {
int a, b;
for (int i = 0; i < m; i++) {
scanf("%d %d", &a, &b);
add_edge(a + offset, b + offset);
}
}
bool is_bridge(int u, int v) {
if (ord[u] > ord[v])
swap(u, v);
return ord[u] < low[v];
}
void dfs(int u, int p, int &k) {
ord[u] = low[u] = k;
++k;
for (int v : G[u]) {
if (v == p)
continue;
if (ord[v] >= 0) {
low[u] = min(low[u], ord[v]);
} else {
dfs(v, u, k);
low[u] = min(low[u], low[v]);
}
if (is_bridge(u, v))
B.push_back(P(u, v));
}
}
void fill_component(int c, int u) {
C[c].push_back(u);
belong[u] = c;
for (int v : G[u]) {
if (belong[v] >= 0 || is_bridge(u, v))
continue;
fill_component(c, v);
}
}
void add_component(int u, int &k) {
if (belong[u] >= 0)
return;
fill_component(k++, u);
}
int build() {
int k = 0;
ord.resize(n);
low.resize(n);
belong.resize(n);
fill(ord.begin(), ord.end(), -1);
fill(belong.begin(), belong.end(), -1);
for (int u = 0; u < n; u++) {
if (ord[u] >= 0)
continue;
dfs(u, -1, k);
}
k = 0;
for (int i = 0; i < (int)B.size(); i++) {
add_component(B[i].first, k);
add_component(B[i].second, k);
}
for (int u = 0; u < n; u++)
add_component(u, k);
for (int i = 0; i < (int)B.size(); i++) {
int u = belong[B[i].first], v = belong[B[i].second];
T[u].push_back(v);
T[v].push_back(u);
}
return k;
}
};
template <typename T, typename E> struct SegmentTree {
typedef function<T(T, T)> F;
typedef function<T(T, E)> G;
int n;
F f;
G g;
T d1;
E d0;
vector<T> dat;
SegmentTree(){};
SegmentTree(int n_, F f, G g, T d1, vector<T> v = vector<T>())
: f(f), g(g), d1(d1) {
init(n_);
if (n_ == (int)v.size())
build(n_, v);
}
void init(int n_) {
n = 1;
while (n < n_)
n *= 2;
dat.clear();
dat.resize(2 * n - 1, d1);
}
void build(int n_, vector<T> v) {
for (int i = 0; i < n_; i++)
dat[i + n - 1] = v[i];
for (int i = n - 2; i >= 0; i--)
dat[i] = f(dat[i * 2 + 1], dat[i * 2 + 2]);
}
void update(int k, E a) {
k += n - 1;
dat[k] = g(dat[k], a);
while (k > 0) {
k = (k - 1) / 2;
dat[k] = f(dat[k * 2 + 1], dat[k * 2 + 2]);
}
}
inline T query(int a, int b) {
T vl = d1, vr = d1;
for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) {
if (l & 1)
vl = f(vl, dat[(l++) - 1]);
if (r & 1)
vr = f(dat[(--r) - 1], vr);
}
return f(vl, vr);
}
};
signed YUKI_529() {
int n, e, q;
scanf("%d %d %d", &n, &e, &q);
BiconectedGraph big(n);
big.input(e, -1);
int E = 0, V = big.build();
HLDecomposition hl(V);
for (int i = 0; i < V; i++)
for (int j : big.T[i])
if (i < j)
hl.add_edge(i, j), E++;
hl.build();
SegmentTree<int, int> rmq(
V, [](int a, int b) { return max(a, b); },
[](int a, int b) {
a++;
return b;
},
-1);
vector<priority_queue<int>> pq(V);
map<int, int> m;
int num = 0;
for (int i = 0; i < q; i++) {
int d;
scanf("%d", &d);
if (d == 1) {
int u, w;
scanf("%d %d", &u, &w);
u--;
u = big.belong[u];
u = hl.vid[u];
m[w] = u;
if (pq[u].empty() || pq[u].top() < w)
rmq.update(u, w);
pq[u].push(w);
num++;
}
if (d == 2) {
int s, t;
scanf("%d %d", &s, &t);
s--;
t--;
s = big.belong[s];
t = big.belong[t];
int ans = -1;
hl.for_each(s, t,
[&](int l, int r) { ans = max(ans, rmq.query(l, r + 1)); });
printf("%d\n", ans);
if (~ans) {
int k = m[ans];
pq[k].pop();
rmq.update(k, (!pq[k].empty() ? pq[k].top() : -1));
num--;
}
}
}
return 0;
}
/* verified on 2017/12/31
https://yukicoder.me/problems/no/529
*/
signed main() {
AOJ_GRL5C();
// YUKI_529();
return 0;
};
| replace | 80 | 81 | 80 | 81 | TLE | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> t, int n)
: tree(t), n(n), size(n), parent(n), in(n), out(n), path(n), pathSize(n),
pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
// Usage: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C
int main(void) {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree, n);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> len, tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> t, int n)
: tree(t), n(n), size(n), parent(n), in(n), out(n), path(n), pathSize(n),
pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
// Usage: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C
int main(void) {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree, n);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | replace | 13 | 14 | 13 | 14 | 0 | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> len, tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(const vector<vector<int>> &t)
: tree(t), n(tree.size()), size(n), parent(n), in(n), out(n), path(n),
pathSize(n), pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
// Usage: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C
int main(void) {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define EACH(i, c) \
for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(A) A.begin(), A.end()
using namespace std;
struct HeavyLight {
vector<vector<int>> len, tree;
int pathCount, n;
vector<int> size, parent, in, out, path, pathSize, pathPos, pathRoot;
HeavyLight(vector<vector<int>> t)
: tree(t), n(tree.size()), size(n), parent(n), in(n), out(n), path(n),
pathSize(n), pathPos(n), pathRoot(n) {
int time = 0;
dfs(0, -1, time);
buildPaths(0, newPath(0));
}
void dfs(int u, int p, int &k) {
in[u] = k++, parent[u] = p, size[u] = 1;
EACH(v, tree[u]) if (*v != p) dfs(*v, u, k), size[u] += size[*v];
out[u] = k++;
}
int newPath(int u) {
pathRoot[pathCount] = u;
return pathCount++;
}
void buildPaths(int u, int pt) {
path[u] = pt, pathPos[u] = pathSize[pt]++;
EACH(v, tree[u])
if (*v != parent[u])
buildPaths(*v, 2 * size[*v] >= size[u] ? pt : newPath(*v));
}
bool isAncestor(int p, int ch) {
return in[p] <= in[ch] && out[ch] <= out[p];
}
int lca(int a, int b) {
for (int root; !isAncestor(root = pathRoot[path[a]], b); a = parent[root])
;
for (int root; !isAncestor(root = pathRoot[path[b]], a); b = parent[root])
;
return isAncestor(a, b) ? a : b;
}
};
// Usage: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_C
int main(void) {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> tree(n);
REP(i, n) {
int k;
cin >> k;
REP(j, k) {
int ch;
cin >> ch;
tree[i].push_back(ch);
}
}
HeavyLight hl = HeavyLight(tree);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << hl.lca(u, v) << "\n";
}
return 0;
} | replace | 17 | 18 | 17 | 18 | 0 | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
#define int long long // <-----!!!!!!!!!!!!!!!!!!!
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rep2(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, n) for (int i = (n)-1; i >= 0; i--)
#define rrep2(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define all(a) (a).begin(), (a).end()
typedef long long ll;
typedef pair<int, int> Pii;
typedef tuple<int, int, int> TUPLE;
typedef vector<int> V;
typedef vector<V> VV;
typedef vector<VV> VVV;
typedef vector<vector<int>> Graph;
const int inf = 1e9;
const int mod = 1e9 + 7;
class LCA {
private:
static const int MAX_LOG = 20;
const int n;
Graph G;
V depth;
VV par;
V cnt; // ?????????????????£????????°
public:
LCA(int _n) : n(_n), G(_n), par(MAX_LOG, V(_n)), depth(_n), cnt(_n) {}
// undirected
void addEdge(int a, int b) {
G[a].emplace_back(b);
G[b].emplace_back(a);
}
// ??????????????±?????¨???1????????????????±???????
void dfs(int v, int p, int d) {
cerr << v << " " << p << " " << d << endl;
par[0][v] = p;
depth[v] = d;
for (auto nxt : G[v]) {
if (nxt != p) {
dfs(nxt, v, d + 1);
}
}
}
// ????????????2^k????????????????±?????????????
void setPar() {
// 0????????¨??????1????????????????±???????
dfs(0, -1, 0);
// 2^i????????????????±???????
rep(i, MAX_LOG - 1) {
rep(j, n) {
if (par[i][j] == -1) {
par[i + 1][j] = -1;
} else {
par[i + 1][j] = par[i][par[i][j]];
}
}
}
}
int lca(int a, int b) {
// ??????a??¨b?????±???????????????
if (depth[a] > depth[b]) {
swap(a, b);
}
rep(i, MAX_LOG) {
if ((depth[b] - depth[a]) >> i & 1) {
b = par[i][b];
}
}
if (a == b)
return a;
// ??¶???????????´????????§a, b????????????
rrep(i, MAX_LOG) {
if (par[i][a] != par[i][b]) {
a = par[i][a];
b = par[i][b];
}
}
// a??¨b???1????????????????????´????????????
return par[0][a];
}
void updateCnt(int u, int v) {
cnt[u]++;
cnt[v]++;
int w = lca(u, v);
cnt[w]--;
if (par[0][w] != -1)
cnt[par[0][w]]--;
}
int imosFinal(int v, int p) {
int t = 0;
for (auto &&nxt : G[v]) {
t += imosFinal(nxt, v);
}
cnt[v] += t;
return cnt[v];
}
int answer() {
imosFinal(0, -1);
int ans = 0;
for (auto &&x : cnt) {
ans += (x + 1) * x / 2;
}
return ans;
}
};
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int n;
scanf("%lld", &n);
LCA lca(n);
rep(i, n) {
int k;
scanf("%lld", &k);
rep(j, k) {
int c;
scanf("%lld", &c);
lca.addEdge(i, c);
}
}
lca.setPar();
int Q;
scanf("%lld", &Q);
rep(i, Q) {
int u, v;
scanf("%lld%lld", &u, &v);
printf("%lld\n", lca.lca(u, v));
}
}
// signed main() {
// std::ios::sync_with_stdio(false);
// std::cin.tie(0);
//
// int N;
// cin >> N;
// LCA lca(N);
// rep(i, N) {
// int u, v;
// cin >> u >> v;
// u--, v--;
// lca.addEdge(u, v);
// }
//
// cerr << "hey!" << endl;
//
// lca.setPar();
//
// cerr << "hey!" << endl;
//
// int Q;
// cin >> Q;
// rep(i, Q) {
// int u, v;
// cin >> u >> v;
// u--, v--;
// lca.updateCnt(u, v);
// }
//
// cerr << "hey!" << endl;
//
// cout << lca.answer() << endl;
// } | #include <bits/stdc++.h>
using namespace std;
#define int long long // <-----!!!!!!!!!!!!!!!!!!!
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rep2(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, n) for (int i = (n)-1; i >= 0; i--)
#define rrep2(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define all(a) (a).begin(), (a).end()
typedef long long ll;
typedef pair<int, int> Pii;
typedef tuple<int, int, int> TUPLE;
typedef vector<int> V;
typedef vector<V> VV;
typedef vector<VV> VVV;
typedef vector<vector<int>> Graph;
const int inf = 1e9;
const int mod = 1e9 + 7;
class LCA {
private:
static const int MAX_LOG = 20;
const int n;
Graph G;
V depth;
VV par;
V cnt; // ?????????????????£????????°
public:
LCA(int _n) : n(_n), G(_n), par(MAX_LOG, V(_n)), depth(_n), cnt(_n) {}
// undirected
void addEdge(int a, int b) {
G[a].emplace_back(b);
G[b].emplace_back(a);
}
// ??????????????±?????¨???1????????????????±???????
void dfs(int v, int p, int d) {
// cerr << v << " " << p << " " << d << endl;
par[0][v] = p;
depth[v] = d;
for (auto nxt : G[v]) {
if (nxt != p) {
dfs(nxt, v, d + 1);
}
}
}
// ????????????2^k????????????????±?????????????
void setPar() {
// 0????????¨??????1????????????????±???????
dfs(0, -1, 0);
// 2^i????????????????±???????
rep(i, MAX_LOG - 1) {
rep(j, n) {
if (par[i][j] == -1) {
par[i + 1][j] = -1;
} else {
par[i + 1][j] = par[i][par[i][j]];
}
}
}
}
int lca(int a, int b) {
// ??????a??¨b?????±???????????????
if (depth[a] > depth[b]) {
swap(a, b);
}
rep(i, MAX_LOG) {
if ((depth[b] - depth[a]) >> i & 1) {
b = par[i][b];
}
}
if (a == b)
return a;
// ??¶???????????´????????§a, b????????????
rrep(i, MAX_LOG) {
if (par[i][a] != par[i][b]) {
a = par[i][a];
b = par[i][b];
}
}
// a??¨b???1????????????????????´????????????
return par[0][a];
}
void updateCnt(int u, int v) {
cnt[u]++;
cnt[v]++;
int w = lca(u, v);
cnt[w]--;
if (par[0][w] != -1)
cnt[par[0][w]]--;
}
int imosFinal(int v, int p) {
int t = 0;
for (auto &&nxt : G[v]) {
t += imosFinal(nxt, v);
}
cnt[v] += t;
return cnt[v];
}
int answer() {
imosFinal(0, -1);
int ans = 0;
for (auto &&x : cnt) {
ans += (x + 1) * x / 2;
}
return ans;
}
};
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int n;
scanf("%lld", &n);
LCA lca(n);
rep(i, n) {
int k;
scanf("%lld", &k);
rep(j, k) {
int c;
scanf("%lld", &c);
lca.addEdge(i, c);
}
}
lca.setPar();
int Q;
scanf("%lld", &Q);
rep(i, Q) {
int u, v;
scanf("%lld%lld", &u, &v);
printf("%lld\n", lca.lca(u, v));
}
}
// signed main() {
// std::ios::sync_with_stdio(false);
// std::cin.tie(0);
//
// int N;
// cin >> N;
// LCA lca(N);
// rep(i, N) {
// int u, v;
// cin >> u >> v;
// u--, v--;
// lca.addEdge(u, v);
// }
//
// cerr << "hey!" << endl;
//
// lca.setPar();
//
// cerr << "hey!" << endl;
//
// int Q;
// cin >> Q;
// rep(i, Q) {
// int u, v;
// cin >> u >> v;
// u--, v--;
// lca.updateCnt(u, v);
// }
//
// cerr << "hey!" << endl;
//
// cout << lca.answer() << endl;
// } | replace | 37 | 38 | 37 | 38 | 0 | 0 -1 0
1 0 1
4 1 2
5 1 2
6 5 3
7 5 3
2 0 1
3 0 1
|
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
const int MAX = 1e5;
pii table[17][MAX * 2 - 1];
int n;
vector<int> G[MAX];
int id[MAX];
int it = 0;
void dfs(int v, int d) {
id[v] = it;
table[0][it++] = {d, v};
for (auto to : G[v]) {
dfs(to, d + 1);
table[0][it++] = {d, v};
}
}
void init() {
dfs(0, 0);
int m = (n << 1) - 1;
int h = 31 - __builtin_clz(m);
for (int i = 0; i < h; i++) {
for (int j = 0; j + (1 << i) < m; j++) {
table[i + 1][j] = min(table[i][j], table[i][j + (1 << i)]);
}
}
}
int lca(int u, int v) {
u = id[u], v = id[v];
if (u > v)
swap(u, v);
int b = 31 - __builtin_clz(v + 1 - u);
return min(table[b][u], table[b][v + 1 - (1 << b)]).second;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
G[i].push_back(c);
}
}
init();
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
printf("%d\n", lca(u, v));
}
return 0;
}
| #include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
const int MAX = 1e5;
pii table[18][MAX * 2 - 1];
int n;
vector<int> G[MAX];
int id[MAX];
int it = 0;
void dfs(int v, int d) {
id[v] = it;
table[0][it++] = {d, v};
for (auto to : G[v]) {
dfs(to, d + 1);
table[0][it++] = {d, v};
}
}
void init() {
dfs(0, 0);
int m = (n << 1) - 1;
int h = 31 - __builtin_clz(m);
for (int i = 0; i < h; i++) {
for (int j = 0; j + (1 << i) < m; j++) {
table[i + 1][j] = min(table[i][j], table[i][j + (1 << i)]);
}
}
}
int lca(int u, int v) {
u = id[u], v = id[v];
if (u > v)
swap(u, v);
int b = 31 - __builtin_clz(v + 1 - u);
return min(table[b][u], table[b][v + 1 - (1 << b)]).second;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
G[i].push_back(c);
}
}
init();
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
printf("%d\n", lca(u, v));
}
return 0;
}
| replace | 5 | 6 | 5 | 6 | 0 | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
struct LowestCommonAncestor {
LowestCommonAncestor(size_t size)
: size(size), G(size), dep(size), par(MaxlgV, vector<int>(size)) {}
size_t size, MaxlgV = 30;
int root;
vector<vector<int>> G, par;
vector<int> dep;
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
cerr << u << " <-> " << v << endl;
}
void dfs(int v, int u, int d) {
dep[v] = d;
par[0][v] = u;
for (int e : G[v])
if (e != u)
dfs(e, v, d + 1);
}
void build(int r) {
dfs(root = r, -1, 0);
for (int k = 0; k + 1 < MaxlgV; k++) {
for (int v = 0; v < size; v++) {
if (par[k][v] < 0)
par[k + 1][v] = -1;
else
par[k + 1][v] = par[k][par[k][v]];
}
}
}
int lca(int u, int v) {
if (dep[u] > dep[v])
swap(u, v);
for (int k = 0; k < MaxlgV; k++) {
if ((dep[v] - dep[u]) >> k & 1) {
v = par[k][v];
}
}
if (u == v)
return u;
for (int k = MaxlgV - 1; k >= 0; k--) {
if (par[k][u] != par[k][v]) {
u = par[k][u];
v = par[k][v];
}
}
return par[0][u];
}
int dist(int u, int v) {
int z = lca(u, v);
return dep[u] + dep[v] - 2 * dep[z];
}
};
// https://onlinejudge.u-aizu.ac.jp/#/courses/library/5/GRL/5/GRL_5_C
int main() {
int N;
cin >> N;
LowestCommonAncestor tree(N);
for (int i = 0; i < N; ++i) {
int k;
cin >> k;
while (k--) {
int c;
cin >> c;
tree.add_edge(i, c);
}
}
tree.build(0);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << tree.lca(u, v) << endl;
}
}
| #include <bits/stdc++.h>
using namespace std;
struct LowestCommonAncestor {
LowestCommonAncestor(size_t size)
: size(size), G(size), dep(size), par(MaxlgV, vector<int>(size)) {}
size_t size, MaxlgV = 30;
int root;
vector<vector<int>> G, par;
vector<int> dep;
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int v, int u, int d) {
dep[v] = d;
par[0][v] = u;
for (int e : G[v])
if (e != u)
dfs(e, v, d + 1);
}
void build(int r) {
dfs(root = r, -1, 0);
for (int k = 0; k + 1 < MaxlgV; k++) {
for (int v = 0; v < size; v++) {
if (par[k][v] < 0)
par[k + 1][v] = -1;
else
par[k + 1][v] = par[k][par[k][v]];
}
}
}
int lca(int u, int v) {
if (dep[u] > dep[v])
swap(u, v);
for (int k = 0; k < MaxlgV; k++) {
if ((dep[v] - dep[u]) >> k & 1) {
v = par[k][v];
}
}
if (u == v)
return u;
for (int k = MaxlgV - 1; k >= 0; k--) {
if (par[k][u] != par[k][v]) {
u = par[k][u];
v = par[k][v];
}
}
return par[0][u];
}
int dist(int u, int v) {
int z = lca(u, v);
return dep[u] + dep[v] - 2 * dep[z];
}
};
// https://onlinejudge.u-aizu.ac.jp/#/courses/library/5/GRL/5/GRL_5_C
int main() {
int N;
cin >> N;
LowestCommonAncestor tree(N);
for (int i = 0; i < N; ++i) {
int k;
cin >> k;
while (k--) {
int c;
cin >> c;
tree.add_edge(i, c);
}
}
tree.build(0);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << tree.lca(u, v) << endl;
}
}
| delete | 15 | 17 | 15 | 15 | 0 | 0 <-> 1
0 <-> 2
0 <-> 3
1 <-> 4
1 <-> 5
5 <-> 6
5 <-> 7
|
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
template <typename T> class SparseTable {
int n;
vector<vector<T>> t;
T merge(const T &l, const T &r) { return min(l, r); }
public:
SparseTable(const vector<T> &b) {
n = b.size();
t.push_back(b);
for (int i = 2, j = 1; i <= n; i <<= 1, j++) {
t.push_back(vector<T>());
for (int k = 0; k + i <= n; k++) {
t[j].push_back(merge(t[j - 1][k], t[j - 1][k + i / 2]));
}
}
}
T find(int l, int r) {
r++;
assert(0 <= l && l < r && r < n);
unsigned int w = r - l;
int i = 31 - __builtin_clz(w);
return merge(t[i][l], t[i][r - (1 << i)]);
}
T operator[](int id) { return t[0][id]; }
};
class LCA {
int V, rt;
vector<vector<int>> G;
vector<int> depth, used, id;
vector<int> vs, de;
SparseTable<pii> st;
void dfs(int s, int d) {
used[s] = 1;
vs.push_back(s);
de.push_back(d);
for (int v : G[s]) {
if (!used[v]) {
dfs(v, d + 1);
vs.push_back(s);
de.push_back(d);
}
}
}
vector<pii> init() {
dfs(rt, 0);
for (int i = 0; i < (int)vs.size(); i++) {
if (id[vs[i]] == -1)
id[vs[i]] = i;
}
vector<pii> r((int)vs.size());
for (int i = 0; i < (int)vs.size(); i++) {
r[i] = pii(de[i], vs[i]);
}
return r;
}
public:
LCA(vector<vector<int>> G_, int rt_ = 0)
: V(G_.size()), rt(rt_), G(G_), depth(V), used(V), id(V, -1), st(init()) {
for (int i = 0; i < V; i++)
depth[i] = st[id[i]].first;
}
int calc(int a, int b) {
return st.find(min(id[a], id[b]), max(id[a], id[b])).second;
}
int dist(int a, int b) { return depth[a] + depth[b] - depth[calc(a, b)] * 2; }
};
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int n, q;
cin >> n;
vector<vector<int>> G(n);
for (int i = 0, k; i < n; i++) {
cin >> k;
for (int j = 0, c; j < k; j++) {
cin >> c;
if (c > i) {
G[i].push_back(c);
G[c].push_back(i);
}
}
}
LCA lca(G);
cin >> q;
for (int i = 0, u, v; i < q; i++) {
cin >> u >> v;
printf("%d\n", lca.calc(u, v));
}
return 0;
} | #include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
template <typename T> class SparseTable {
int n;
vector<vector<T>> t;
T merge(const T &l, const T &r) { return min(l, r); }
public:
SparseTable(const vector<T> &b) {
n = b.size();
t.push_back(b);
for (int i = 2, j = 1; i <= n; i <<= 1, j++) {
t.push_back(vector<T>());
for (int k = 0; k + i <= n; k++) {
t[j].push_back(merge(t[j - 1][k], t[j - 1][k + i / 2]));
}
}
}
T find(int l, int r) {
r++;
assert(0 <= l && l < r && r <= n);
unsigned int w = r - l;
int i = 31 - __builtin_clz(w);
return merge(t[i][l], t[i][r - (1 << i)]);
}
T operator[](int id) { return t[0][id]; }
};
class LCA {
int V, rt;
vector<vector<int>> G;
vector<int> depth, used, id;
vector<int> vs, de;
SparseTable<pii> st;
void dfs(int s, int d) {
used[s] = 1;
vs.push_back(s);
de.push_back(d);
for (int v : G[s]) {
if (!used[v]) {
dfs(v, d + 1);
vs.push_back(s);
de.push_back(d);
}
}
}
vector<pii> init() {
dfs(rt, 0);
for (int i = 0; i < (int)vs.size(); i++) {
if (id[vs[i]] == -1)
id[vs[i]] = i;
}
vector<pii> r((int)vs.size());
for (int i = 0; i < (int)vs.size(); i++) {
r[i] = pii(de[i], vs[i]);
}
return r;
}
public:
LCA(vector<vector<int>> G_, int rt_ = 0)
: V(G_.size()), rt(rt_), G(G_), depth(V), used(V), id(V, -1), st(init()) {
for (int i = 0; i < V; i++)
depth[i] = st[id[i]].first;
}
int calc(int a, int b) {
return st.find(min(id[a], id[b]), max(id[a], id[b])).second;
}
int dist(int a, int b) { return depth[a] + depth[b] - depth[calc(a, b)] * 2; }
};
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int n, q;
cin >> n;
vector<vector<int>> G(n);
for (int i = 0, k; i < n; i++) {
cin >> k;
for (int j = 0, c; j < k; j++) {
cin >> c;
if (c > i) {
G[i].push_back(c);
G[c].push_back(i);
}
}
}
LCA lca(G);
cin >> q;
for (int i = 0, u, v; i < q; i++) {
cin >> u >> v;
printf("%d\n", lca.calc(u, v));
}
return 0;
} | replace | 22 | 23 | 22 | 23 | 0 | |
p02373 | C++ | Memory Limit Exceeded | #include <bits/stdc++.h>
using namespace std;
struct LowestCommonAncestor {
LowestCommonAncestor(size_t size)
: size(size), MaxlgV(1 << (32 - __builtin_clz(size - 1))), G(size),
dep(size), par(MaxlgV, vector<int>(size)) {}
size_t size, MaxlgV;
int root;
vector<vector<int>> G, par;
vector<int> dep;
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int v, int u, int d) {
dep[v] = d;
par[0][v] = u;
for (int e : G[v])
if (e != u)
dfs(e, v, d + 1);
}
void build(int r) {
dfs(root = r, -1, 0);
for (int k = 0; k + 1 < MaxlgV; k++) {
for (int v = 0; v < size; v++) {
if (par[k][v] < 0)
par[k + 1][v] = -1;
else
par[k + 1][v] = par[k][par[k][v]];
}
}
}
int lca(int u, int v) {
if (dep[u] > dep[v])
swap(u, v);
for (int k = 0; k < MaxlgV; k++) {
if ((dep[v] - dep[u]) >> k & 1) {
v = par[k][v];
}
}
if (u == v)
return u;
for (int k = MaxlgV - 1; k >= 0; k--) {
if (par[k][u] != par[k][v]) {
u = par[k][u];
v = par[k][v];
}
}
return par[0][u];
}
int dist(int u, int v) {
int z = lca(u, v);
return dep[u] + dep[v] - 2 * dep[z];
}
};
// https://onlinejudge.u-aizu.ac.jp/#/courses/library/5/GRL/5/GRL_5_C
int main() {
int N;
cin >> N;
LowestCommonAncestor tree(N);
for (int i = 0; i < N; ++i) {
int k;
cin >> k;
while (k--) {
int c;
cin >> c;
tree.add_edge(i, c);
}
}
tree.build(0);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << tree.lca(u, v) << endl;
}
}
| #include <bits/stdc++.h>
using namespace std;
struct LowestCommonAncestor {
LowestCommonAncestor(size_t size)
: size(size), MaxlgV(32 - __builtin_clz(size - 1)), G(size), dep(size),
par(MaxlgV, vector<int>(size)) {}
size_t size, MaxlgV;
int root;
vector<vector<int>> G, par;
vector<int> dep;
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int v, int u, int d) {
dep[v] = d;
par[0][v] = u;
for (int e : G[v])
if (e != u)
dfs(e, v, d + 1);
}
void build(int r) {
dfs(root = r, -1, 0);
for (int k = 0; k + 1 < MaxlgV; k++) {
for (int v = 0; v < size; v++) {
if (par[k][v] < 0)
par[k + 1][v] = -1;
else
par[k + 1][v] = par[k][par[k][v]];
}
}
}
int lca(int u, int v) {
if (dep[u] > dep[v])
swap(u, v);
for (int k = 0; k < MaxlgV; k++) {
if ((dep[v] - dep[u]) >> k & 1) {
v = par[k][v];
}
}
if (u == v)
return u;
for (int k = MaxlgV - 1; k >= 0; k--) {
if (par[k][u] != par[k][v]) {
u = par[k][u];
v = par[k][v];
}
}
return par[0][u];
}
int dist(int u, int v) {
int z = lca(u, v);
return dep[u] + dep[v] - 2 * dep[z];
}
};
// https://onlinejudge.u-aizu.ac.jp/#/courses/library/5/GRL/5/GRL_5_C
int main() {
int N;
cin >> N;
LowestCommonAncestor tree(N);
for (int i = 0; i < N; ++i) {
int k;
cin >> k;
while (k--) {
int c;
cin >> c;
tree.add_edge(i, c);
}
}
tree.build(0);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << tree.lca(u, v) << endl;
}
}
| replace | 5 | 7 | 5 | 7 | MLE | |
p02373 | C++ | Time Limit Exceeded | #include <algorithm>
#include <array>
#include <cstdio>
#include <functional>
#include <iostream>
#include <list>
#include <numeric>
#include <queue>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#define _USE_MATH_DEFINES
#include <map>
#include <math.h>
#define SENTINEL 1000000001
#define min(a, b) ((a) > (b) ? (b) : (a))
#define max(a, b) ((a) > (b) ? (a) : (b))
#define INF 200000000
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
vector<int> G[100000];
vector<int> et, depth, id;
struct ST {
vector<pii> data;
int n;
int segn;
ST(int v, int k) : n(v) {
for (segn = 1; segn < (n * 2 - 1); segn *= 2)
;
data.assign(2 * segn, make_pair(INF, -1));
for (int i = 0; i < k; i++) {
data[segn + i] = make_pair(depth[i], et[i]);
}
for (int i = segn - 1; i >= 1; --i) {
data[i] = min(data[i * 2], data[i * 2 + 1]);
}
}
pii find(int s, int t, int l, int r) {
if (r == -1) {
r = segn;
}
if (t <= s || r == 0) {
return make_pair(INF, -1);
}
if (t - s == r) {
return data[l];
}
return min(find(s, min(t, r / 2), l * 2, r / 2),
find(max(0, s - (r / 2)), t - (r / 2), l * 2 + 1, r / 2));
}
};
void ET(int n, int p, int &eti, int d) {
id[n] = eti;
et[eti] = n;
depth[eti] = d;
eti++;
for (auto &e : G[n]) {
if (e != p) {
ET(e, n, eti, d + 1);
et[eti] = n;
depth[eti] = d;
eti++;
}
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
G[i].emplace_back(c);
}
}
et = vector<int>(n * 2 - 1);
depth = vector<int>(n * 2 - 1);
id = vector<int>(n);
int eti = 0;
ET(0, -1, eti, 0);
ST st(n, eti);
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int u, v;
cin >> u >> v;
printf("%d\n",
st.find(min(id[u], id[v]), max(id[u], id[v]) + 1, 1, -1).second);
}
return 0;
}
| #include <algorithm>
#include <array>
#include <cstdio>
#include <functional>
#include <iostream>
#include <list>
#include <numeric>
#include <queue>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#define _USE_MATH_DEFINES
#include <map>
#include <math.h>
#define SENTINEL 1000000001
#define INF 200000000
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
vector<int> G[100000];
vector<int> et, depth, id;
struct ST {
vector<pii> data;
int n;
int segn;
ST(int v, int k) : n(v) {
for (segn = 1; segn < (n * 2 - 1); segn *= 2)
;
data.assign(2 * segn, make_pair(INF, -1));
for (int i = 0; i < k; i++) {
data[segn + i] = make_pair(depth[i], et[i]);
}
for (int i = segn - 1; i >= 1; --i) {
data[i] = min(data[i * 2], data[i * 2 + 1]);
}
}
pii find(int s, int t, int l, int r) {
if (r == -1) {
r = segn;
}
if (t <= s || r == 0) {
return make_pair(INF, -1);
}
if (t - s == r) {
return data[l];
}
return min(find(s, min(t, r / 2), l * 2, r / 2),
find(max(0, s - (r / 2)), t - (r / 2), l * 2 + 1, r / 2));
}
};
void ET(int n, int p, int &eti, int d) {
id[n] = eti;
et[eti] = n;
depth[eti] = d;
eti++;
for (auto &e : G[n]) {
if (e != p) {
ET(e, n, eti, d + 1);
et[eti] = n;
depth[eti] = d;
eti++;
}
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
G[i].emplace_back(c);
}
}
et = vector<int>(n * 2 - 1);
depth = vector<int>(n * 2 - 1);
id = vector<int>(n);
int eti = 0;
ET(0, -1, eti, 0);
ST st(n, eti);
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int u, v;
cin >> u >> v;
printf("%d\n",
st.find(min(id[u], id[v]), max(id[u], id[v]) + 1, 1, -1).second);
}
return 0;
}
| delete | 19 | 22 | 19 | 19 | TLE | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct LCA {
int N, logN; // logN-1 == floor(lg(N-1))
vector<vector<int>> G;
vector<int> depth;
// vから根の方向に2^k回登ったときのノード parent[k][v]
vector<vector<int>> parent;
LCA(int size) : N(size), G(size), depth(size) {
logN = 0;
for (int x = 1; x < N; x *= 2)
logN++;
parent.assign(logN, vector<int>(N));
}
// どちらが根であってもOK
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int v, int par, int dep) {
depth[v] = dep;
parent[0][v] = par;
for (int next : G[v]) {
if (next != par)
dfs(next, v, dep + 1);
}
}
void init(int root) {
dfs(root, -1, 0);
for (int k = 1; k < logN; k++) {
for (int v = 0; v < N; v++) {
if (parent[k - 1][v] == -1)
parent[k][v] = -1;
else
parent[k][v] = parent[k - 1][parent[k - 1][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v])
swap(u, v); // vのほうが深くなる
// uとvの深さが同じになるまでvを根の方向に移動する
for (int k = 0; k < logN; k++) {
if (((depth[v] - depth[u]) >> k) & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
for (int k = logN - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
int main() {
ios::sync_with_stdio(false);
int N;
cin >> N;
LCA lca(N);
for (int u = 0; u < N; u++) {
int k;
cin >> k;
while (k--) {
int v;
cin >> v;
lca.add_edge(u, v);
}
}
lca.init(0);
int Q;
cin >> Q;
while (Q--) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << endl;
}
} | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct LCA {
int N, logN; // logN-1 == floor(lg(N-1))
vector<vector<int>> G;
vector<int> depth;
// vから根の方向に2^k回登ったときのノード parent[k][v]
vector<vector<int>> parent;
LCA(int size) : N(size), G(size), depth(size) {
logN = 1;
for (int x = 1; x < N; x *= 2)
logN++;
parent.assign(logN, vector<int>(N));
}
// どちらが根であってもOK
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int v, int par, int dep) {
depth[v] = dep;
parent[0][v] = par;
for (int next : G[v]) {
if (next != par)
dfs(next, v, dep + 1);
}
}
void init(int root) {
dfs(root, -1, 0);
for (int k = 1; k < logN; k++) {
for (int v = 0; v < N; v++) {
if (parent[k - 1][v] == -1)
parent[k][v] = -1;
else
parent[k][v] = parent[k - 1][parent[k - 1][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v])
swap(u, v); // vのほうが深くなる
// uとvの深さが同じになるまでvを根の方向に移動する
for (int k = 0; k < logN; k++) {
if (((depth[v] - depth[u]) >> k) & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
for (int k = logN - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
int main() {
ios::sync_with_stdio(false);
int N;
cin >> N;
LCA lca(N);
for (int u = 0; u < N; u++) {
int k;
cin >> k;
while (k--) {
int v;
cin >> v;
lca.add_edge(u, v);
}
}
lca.init(0);
int Q;
cin >> Q;
while (Q--) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << endl;
}
} | replace | 13 | 14 | 13 | 14 | 0 | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <stack>
#include <utility>
#include <vector>
using namespace std;
struct LCA {
int N, logN; // logN-1 == floor(lg(N-1))
vector<vector<int>> G;
vector<int> depth;
// vから根の方向に2^k回登ったときのノード parent[k][v]
vector<vector<int>> parent;
LCA(int size) : N(size), G(size), depth(size) {
logN = 0;
for (int x = 1; x < N; x *= 2)
logN++;
parent.assign(logN, vector<int>(N));
}
// どちらが根であってもOK
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void init(int root) {
stack<pair<int, int>> s;
s.push(make_pair(root, -1));
while (!s.empty()) {
auto cur = s.top();
s.pop();
if (cur.second < 0)
depth[cur.first] = 0;
else
depth[cur.first] = depth[cur.second] + 1;
parent[0][cur.first] = cur.second;
for (int next : G[cur.first]) {
if (next != cur.second) {
s.push(make_pair(next, cur.first));
}
}
}
for (int k = 1; k < logN; k++) {
for (int v = 0; v < N; v++) {
if (parent[k - 1][v] < 0)
parent[k][v] = -1;
else
parent[k][v] = parent[k - 1][parent[k - 1][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v])
swap(u, v); // vのほうが深くなる
// uとvの深さが同じになるまでvを根の方向に移動する
for (int k = 0; k < logN; k++) {
if (((depth[v] - depth[u]) >> k) & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
for (int k = logN - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
int main() {
ios::sync_with_stdio(false);
int N;
cin >> N;
LCA lca(N);
for (int u = 0; u < N; u++) {
int k;
cin >> k;
while (k--) {
int v;
cin >> v;
lca.add_edge(u, v);
}
}
lca.init(0);
int Q;
cin >> Q;
while (Q--) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << endl;
}
} | #include <algorithm>
#include <iostream>
#include <stack>
#include <utility>
#include <vector>
using namespace std;
struct LCA {
int N, logN; // logN-1 == floor(lg(N-1))
vector<vector<int>> G;
vector<int> depth;
// vから根の方向に2^k回登ったときのノード parent[k][v]
vector<vector<int>> parent;
LCA(int size) : N(size), G(size), depth(size) {
logN = 0;
for (int x = 1; x < N; x *= 2)
logN++;
logN = 21;
parent.assign(logN, vector<int>(N));
}
// どちらが根であってもOK
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void init(int root) {
stack<pair<int, int>> s;
s.push(make_pair(root, -1));
while (!s.empty()) {
auto cur = s.top();
s.pop();
if (cur.second < 0)
depth[cur.first] = 0;
else
depth[cur.first] = depth[cur.second] + 1;
parent[0][cur.first] = cur.second;
for (int next : G[cur.first]) {
if (next != cur.second) {
s.push(make_pair(next, cur.first));
}
}
}
for (int k = 1; k < logN; k++) {
for (int v = 0; v < N; v++) {
if (parent[k - 1][v] < 0)
parent[k][v] = -1;
else
parent[k][v] = parent[k - 1][parent[k - 1][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v])
swap(u, v); // vのほうが深くなる
// uとvの深さが同じになるまでvを根の方向に移動する
for (int k = 0; k < logN; k++) {
if (((depth[v] - depth[u]) >> k) & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
for (int k = logN - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
int main() {
ios::sync_with_stdio(false);
int N;
cin >> N;
LCA lca(N);
for (int u = 0; u < N; u++) {
int k;
cin >> k;
while (k--) {
int v;
cin >> v;
lca.add_edge(u, v);
}
}
lca.init(0);
int Q;
cin >> Q;
while (Q--) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << endl;
}
} | insert | 18 | 18 | 18 | 19 | 0 | |
p02373 | C++ | Runtime Error | #include "bits/stdc++.h"
using namespace std;
typedef pair<int, int> pii;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(a) (a).begin(), (a).end()
#define pb push_back
#define MAX_V 10000
vector<int> G[MAX_V];
vector<int> depth, vs;
int id[MAX_V] = {};
template <class T> class segtree {
private:
vector<T> dat;
int _size;
T _init;
public:
segtree(int __size = 0, T init = numeric_limits<T>::max())
: _size(__size), _init(init), dat(4 * __size, init) {
if (__size == 0)
return;
int x = 1;
while (x < _size)
x *= 2;
_size = x;
}
int size() { return _size; }
void update(int m, T x) {
int i = m + _size;
dat[i] = x;
while (i != 1) {
dat[i / 2] = min(dat[i], dat[i ^ 1]);
i /= 2;
}
}
// call find(s,t)
T find(int s, int t, int num = 1, int a = 0, int b = -1) {
if (b == -1)
b = _size - 1; // I couldn't "int b=_size".
if (b < s || t < a)
return _init;
if (s <= a && b <= t)
return dat[num];
return min(find(s, t, num * 2, a, (a + b) / 2),
find(s, t, num * 2 + 1, (a + b) / 2 + 1, b));
}
};
void dfs(int d, int num) {
depth.pb(d);
vs.pb(num);
rep(i, G[num].size()) {
dfs(d + 1, G[num][i]);
depth.pb(d);
vs.pb(num);
}
return;
}
void init() {
dfs(1, 0);
rep(i, vs.size()) {
if (id[vs[i]] == 0)
id[vs[i]] = i;
}
}
int main() {
int n;
cin >> n;
rep(i, n) {
int k;
cin >> k;
rep(j, k) {
int a;
cin >> a;
G[i].pb(a);
}
}
init();
segtree<pii> st(depth.size(), pii((1 << 31) - 1, (1 << 31) - 1));
rep(i, depth.size()) { st.update(i, pii(depth[i], vs[i])); }
int q;
cin >> q;
rep(i, q) {
int a, b;
cin >> a >> b;
cout << st.find(min(id[a], id[b]), max(id[a], id[b])).second << endl;
}
} | #include "bits/stdc++.h"
using namespace std;
typedef pair<int, int> pii;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(a) (a).begin(), (a).end()
#define pb push_back
#define MAX_V 100000
vector<int> G[MAX_V];
vector<int> depth, vs;
int id[MAX_V] = {};
template <class T> class segtree {
private:
vector<T> dat;
int _size;
T _init;
public:
segtree(int __size = 0, T init = numeric_limits<T>::max())
: _size(__size), _init(init), dat(4 * __size, init) {
if (__size == 0)
return;
int x = 1;
while (x < _size)
x *= 2;
_size = x;
}
int size() { return _size; }
void update(int m, T x) {
int i = m + _size;
dat[i] = x;
while (i != 1) {
dat[i / 2] = min(dat[i], dat[i ^ 1]);
i /= 2;
}
}
// call find(s,t)
T find(int s, int t, int num = 1, int a = 0, int b = -1) {
if (b == -1)
b = _size - 1; // I couldn't "int b=_size".
if (b < s || t < a)
return _init;
if (s <= a && b <= t)
return dat[num];
return min(find(s, t, num * 2, a, (a + b) / 2),
find(s, t, num * 2 + 1, (a + b) / 2 + 1, b));
}
};
void dfs(int d, int num) {
depth.pb(d);
vs.pb(num);
rep(i, G[num].size()) {
dfs(d + 1, G[num][i]);
depth.pb(d);
vs.pb(num);
}
return;
}
void init() {
dfs(1, 0);
rep(i, vs.size()) {
if (id[vs[i]] == 0)
id[vs[i]] = i;
}
}
int main() {
int n;
cin >> n;
rep(i, n) {
int k;
cin >> k;
rep(j, k) {
int a;
cin >> a;
G[i].pb(a);
}
}
init();
segtree<pii> st(depth.size(), pii((1 << 31) - 1, (1 << 31) - 1));
rep(i, depth.size()) { st.update(i, pii(depth[i], vs[i])); }
int q;
cin >> q;
rep(i, q) {
int a, b;
cin >> a >> b;
cout << st.find(min(id[a], id[b]), max(id[a], id[b])).second << endl;
}
} | replace | 6 | 7 | 6 | 7 | 0 | |
p02373 | C++ | Time Limit Exceeded | #include <algorithm>
#include <cassert>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
const int B = 20;
int color[100010], par[100010], depth[100010];
int top[100010];
int goUp[100010];
bool vis[100010];
int n;
vector<vector<int>> g;
void decomp(int root) {
rep(i, n) vis[i] = false, par[i] = -1;
queue<int> q;
q.push(root);
vector<int> tord;
while (q.size()) {
int v = q.front();
q.pop();
vis[v] = true;
tord.push_back(v);
for (int c : g[v]) {
if (!vis[c]) {
q.push(c);
par[c] = v;
depth[c] = depth[v] + 1;
}
}
}
rep(i, n) vis[i] = false;
int c = 0;
for (int u : tord) {
if (vis[u])
continue;
q.push(u);
int k = 0;
while (q.size() && k < B) {
int v = q.front();
q.pop();
vis[v] = true;
color[v] = c;
goUp[v] = par[u];
top[v] = u;
k++;
for (int c : g[v]) {
if (!vis[c])
q.push(c);
}
}
while (q.size())
q.pop();
c++;
}
// rep(i,n) printf("v:%d col:%d dep:%d\n", i, color[i], depth[i]);
}
int solve(int u, int v) {
while (color[u] != color[v]) {
// cout << u << " " << v << endl;
assert(u != -1 && v != -1);
if (depth[top[u]] > depth[top[v]])
u = goUp[u];
else
v = goUp[v];
}
while (u != v) {
assert(u != -1 && v != -1);
if (depth[u] > depth[v])
u = par[u];
else
v = par[v];
}
return u;
}
int main() {
cin >> n;
g.assign(n, {});
rep(i, n) {
int k;
cin >> k;
rep(j, k) {
int c;
cin >> c;
g[i].push_back(c);
par[c] = i;
}
}
decomp(0);
int q;
cin >> q;
rep(i, q) {
int u, v;
cin >> u >> v;
cout << solve(u, v) << endl;
}
} | #include <algorithm>
#include <cassert>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
const int B = 310;
int color[100010], par[100010], depth[100010];
int top[100010];
int goUp[100010];
bool vis[100010];
int n;
vector<vector<int>> g;
void decomp(int root) {
rep(i, n) vis[i] = false, par[i] = -1;
queue<int> q;
q.push(root);
vector<int> tord;
while (q.size()) {
int v = q.front();
q.pop();
vis[v] = true;
tord.push_back(v);
for (int c : g[v]) {
if (!vis[c]) {
q.push(c);
par[c] = v;
depth[c] = depth[v] + 1;
}
}
}
rep(i, n) vis[i] = false;
int c = 0;
for (int u : tord) {
if (vis[u])
continue;
q.push(u);
int k = 0;
while (q.size() && k < B) {
int v = q.front();
q.pop();
vis[v] = true;
color[v] = c;
goUp[v] = par[u];
top[v] = u;
k++;
for (int c : g[v]) {
if (!vis[c])
q.push(c);
}
}
while (q.size())
q.pop();
c++;
}
// rep(i,n) printf("v:%d col:%d dep:%d\n", i, color[i], depth[i]);
}
int solve(int u, int v) {
while (color[u] != color[v]) {
// cout << u << " " << v << endl;
assert(u != -1 && v != -1);
if (depth[top[u]] > depth[top[v]])
u = goUp[u];
else
v = goUp[v];
}
while (u != v) {
assert(u != -1 && v != -1);
if (depth[u] > depth[v])
u = par[u];
else
v = par[v];
}
return u;
}
int main() {
cin >> n;
g.assign(n, {});
rep(i, n) {
int k;
cin >> k;
rep(j, k) {
int c;
cin >> c;
g[i].push_back(c);
par[c] = i;
}
}
decomp(0);
int q;
cin >> q;
rep(i, q) {
int u, v;
cin >> u >> v;
cout << solve(u, v) << endl;
}
} | replace | 9 | 10 | 9 | 10 | TLE | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> i_i;
#define PI 3.141592653589793238462643383279
#define mod 1000000007LL
#define rep(i, n) for (i = 0; i < n; ++i)
#define rep1(i, n) for (i = 1; i < n; ++i)
#define per(i, n) for (i = n - 1; i > -1; --i)
#define int(x) \
int x; \
scanf("%d", &x)
#define int2(x, y) \
int x, y; \
scanf("%d%d", &x, &y)
#define int3(x, y, z) \
int x, y, z; \
scanf("%d%d%d", &x, &y, &z)
#define int4(v, x, y, z) \
int v, x, y, z; \
scanf("%d%d%d%d", &v, &x, &y, &z)
#define int5(v, w, x, y, z) \
int v, w, x, y, z; \
scanf("%d%d%d%d%d", &v, &w, &x, &y, &z)
#define ll2(x, y) \
ll x, y; \
cin >> x >> y;
#define scn(n, a) rep(i, n) cin >> a[i]
#define sc2n(n, a, b) rep(i, n) cin >> a[i] >> b[i]
#define pri(x) cout << x << "\n"
#define pri2(x, y) cout << x << " " << y << "\n"
#define pri3(x, y, z) cout << x << " " << y << " " << z << "\n"
#define pb push_back
#define mp make_pair
#define all(a) (a).begin(), (a).end()
#define kabe puts("---------------------------")
#define kara puts("")
#define debug(x) cout << " --- " << x << "\n"
#define debug2(x, y) cout << " --- " << x << " " << y << "\n"
#define debug3(x, y, z) cout << " --- " << x << " " << y << " " << z << "\n"
#define X first
#define Y second
#define eps 0.0001
#define prid(x) printf("%.15lf\n", x)
struct rmqsegtree {
vector<pair<int, int>> t; //<data, at>
pair<int, int> re;
int n;
void dflt(void) {
re.first = INT_MAX;
re.second = -1;
return;
}
void use(void) {
int i;
dflt();
for (i = 0;; ++i)
if ((1 << i) >= n)
break;
++i;
t.resize(1 << i);
t[0].first = 1 << (i - 1);
t[0].second = 1 << i;
for (i = 1; i < t[0].second; ++i)
t[i] = re;
for (i = 0; i < n; ++i)
t[i + t[0].first].second = i;
return;
}
void build(vector<int> a) {
for (n = 1;; n <<= 1)
if (n >= a.size())
break;
t.resize(n << 1);
dflt();
t[0].first = n;
t[0].second = t[0].first << 1;
n = a.size();
for (int i = 1; i < t[0].second; ++i)
t[i] = re;
for (int i = 0; i < n; ++i) {
t[t[0].first + i].first = a[i];
t[t[0].first + i].second = i;
}
for (int i = t[0].first - 1; i >= 1; --i)
t[i] = (t[i << 1] <= t[(i << 1) + 1]) ? t[i << 1] : t[(i << 1) + 1];
return;
}
void update(int at, int data) {
t[t[0].first + at].first = data;
for (int x = t[0].first + at; x > 1;) {
x >>= 1;
if (t[x << 1].first <= t[(x << 1) + 1].first)
t[x] = t[x << 1];
else
t[x] = t[(x << 1) + 1];
}
return;
}
pair<int, int> query(int l, int r, int k, int kl, int kr) {
if (l <= t[k].second && t[k].second < r)
return t[k];
if (k >= t.size())
return re;
if (kl >= r || kr <= l)
return re;
if (l <= kl && kr <= r)
return t[k];
pair<int, int> a = query(l, r, k << 1, kl, (kl + kr) >> 1);
pair<int, int> b = query(l, r, (k << 1) + 1, (kl + kr) >> 1, kr);
return (a.first < b.first) ? a : b;
}
pair<int, int> find(int l, int r) { return query(l, r, 1, 0, t[0].first); }
void deb(void) {
int x = 1;
printf("t[0] = (%d, %d)\n", t[0].first, t[0].second);
for (int i = 1; i < t[0].second; ++i) {
printf("%3d", t[i].first);
if (i == (1 << x) - 1) {
puts("");
++x;
}
}
x = 1;
printf("t[0] = (%d, %d)\n", t[0].first, t[0].second);
for (int i = 1; i < t[0].second; ++i) {
printf("%3d", t[i].second);
if (i == (1 << x) - 1) {
puts("");
++x;
}
}
return;
}
};
struct edge {
int to, cost;
};
struct tree {
vector<vector<edge>> t;
int v;
void nexttree(int x) { // x-indexed
scanf("%d", &v);
t.resize(v);
int from, to, cost = 1;
for (int i = 1; i < v; ++i) {
scanf("%d %d", &from, &to);
t[from - x].push_back((edge){to - x, cost});
t[to - x].push_back((edge){from - x, cost});
}
return;
}
void nexttree2(int x) {
scanf("%d", &v);
t.resize(v);
int k, to, cost = 1;
for (int i = 0; i < v; ++i) {
scanf("%d", &k);
for (int j = 0; j < k; ++j) {
scanf("%d", &to);
t[i - x].push_back((edge){to - x, cost});
t[to - x].push_back((edge){i - x, cost});
}
}
return;
}
rmqsegtree S;
vector<int> vst, dpth, id;
void lcarmqdfs(int now, int dep) { // 575!!
/* ????????° */
vector<pair<int, int>> stk;
stk.resize(v); // stack
int head = 0;
stk[head].first = now;
stk[head++].second = dep;
for (; head;) {
pair<int, int> tmp = stk[--head];
if (id[tmp.first] == -1) {
id[tmp.first] = vst.size();
vst.push_back(tmp.first);
dpth.push_back(tmp.second);
} else {
vst.push_back(tmp.first);
dpth.push_back(tmp.second);
continue;
}
for (int i = 0; i < t[tmp.first].size(); ++i)
if (id[t[tmp.first][i].to] == -1) {
stk[head++] = tmp;
stk[head].first = t[tmp.first][i].to;
stk[head++].second = tmp.second + 1;
}
}
stk.clear();
return;
}
void lcarmq(void) {
if (vst.size() > v)
return;
id.resize(v);
for (int i = 0; i < v; ++i)
id[i] = -1;
lcarmqdfs(0, 0);
S.build(vst);
return;
}
int lca(int a, int b) {
if (id[a] > id[b])
swap(a, b);
return vst[S.find(id[a], id[b] + 1).second];
}
int depth(int a) { return dpth[id[a]]; }
int dist(int a, int b) { return depth(a) + depth(b) - 2 * depth(lca(a, b)); }
};
signed main(void) {
int i, j, k;
for (int testcase = 0; testcase >= 0; testcase++) {
tree T;
T.nexttree2(0);
T.lcarmq();
int(q);
for (; q--;) {
int2(a, b);
pri(T.lca(a, b));
}
/*/
//*/
break;
}
return 0;
} | #include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> i_i;
#define PI 3.141592653589793238462643383279
#define mod 1000000007LL
#define rep(i, n) for (i = 0; i < n; ++i)
#define rep1(i, n) for (i = 1; i < n; ++i)
#define per(i, n) for (i = n - 1; i > -1; --i)
#define int(x) \
int x; \
scanf("%d", &x)
#define int2(x, y) \
int x, y; \
scanf("%d%d", &x, &y)
#define int3(x, y, z) \
int x, y, z; \
scanf("%d%d%d", &x, &y, &z)
#define int4(v, x, y, z) \
int v, x, y, z; \
scanf("%d%d%d%d", &v, &x, &y, &z)
#define int5(v, w, x, y, z) \
int v, w, x, y, z; \
scanf("%d%d%d%d%d", &v, &w, &x, &y, &z)
#define ll2(x, y) \
ll x, y; \
cin >> x >> y;
#define scn(n, a) rep(i, n) cin >> a[i]
#define sc2n(n, a, b) rep(i, n) cin >> a[i] >> b[i]
#define pri(x) cout << x << "\n"
#define pri2(x, y) cout << x << " " << y << "\n"
#define pri3(x, y, z) cout << x << " " << y << " " << z << "\n"
#define pb push_back
#define mp make_pair
#define all(a) (a).begin(), (a).end()
#define kabe puts("---------------------------")
#define kara puts("")
#define debug(x) cout << " --- " << x << "\n"
#define debug2(x, y) cout << " --- " << x << " " << y << "\n"
#define debug3(x, y, z) cout << " --- " << x << " " << y << " " << z << "\n"
#define X first
#define Y second
#define eps 0.0001
#define prid(x) printf("%.15lf\n", x)
struct rmqsegtree {
vector<pair<int, int>> t; //<data, at>
pair<int, int> re;
int n;
void dflt(void) {
re.first = INT_MAX;
re.second = -1;
return;
}
void use(void) {
int i;
dflt();
for (i = 0;; ++i)
if ((1 << i) >= n)
break;
++i;
t.resize(1 << i);
t[0].first = 1 << (i - 1);
t[0].second = 1 << i;
for (i = 1; i < t[0].second; ++i)
t[i] = re;
for (i = 0; i < n; ++i)
t[i + t[0].first].second = i;
return;
}
void build(vector<int> a) {
for (n = 1;; n <<= 1)
if (n >= a.size())
break;
t.resize(n << 1);
dflt();
t[0].first = n;
t[0].second = t[0].first << 1;
n = a.size();
for (int i = 1; i < t[0].second; ++i)
t[i] = re;
for (int i = 0; i < n; ++i) {
t[t[0].first + i].first = a[i];
t[t[0].first + i].second = i;
}
for (int i = t[0].first - 1; i >= 1; --i)
t[i] = (t[i << 1] <= t[(i << 1) + 1]) ? t[i << 1] : t[(i << 1) + 1];
return;
}
void update(int at, int data) {
t[t[0].first + at].first = data;
for (int x = t[0].first + at; x > 1;) {
x >>= 1;
if (t[x << 1].first <= t[(x << 1) + 1].first)
t[x] = t[x << 1];
else
t[x] = t[(x << 1) + 1];
}
return;
}
pair<int, int> query(int l, int r, int k, int kl, int kr) {
if (l <= t[k].second && t[k].second < r)
return t[k];
if (k >= t.size())
return re;
if (kl >= r || kr <= l)
return re;
if (l <= kl && kr <= r)
return t[k];
pair<int, int> a = query(l, r, k << 1, kl, (kl + kr) >> 1);
pair<int, int> b = query(l, r, (k << 1) + 1, (kl + kr) >> 1, kr);
return (a.first < b.first) ? a : b;
}
pair<int, int> find(int l, int r) { return query(l, r, 1, 0, t[0].first); }
void deb(void) {
int x = 1;
printf("t[0] = (%d, %d)\n", t[0].first, t[0].second);
for (int i = 1; i < t[0].second; ++i) {
printf("%3d", t[i].first);
if (i == (1 << x) - 1) {
puts("");
++x;
}
}
x = 1;
printf("t[0] = (%d, %d)\n", t[0].first, t[0].second);
for (int i = 1; i < t[0].second; ++i) {
printf("%3d", t[i].second);
if (i == (1 << x) - 1) {
puts("");
++x;
}
}
return;
}
};
struct edge {
int to, cost;
};
struct tree {
vector<vector<edge>> t;
int v;
void nexttree(int x) { // x-indexed
scanf("%d", &v);
t.resize(v);
int from, to, cost = 1;
for (int i = 1; i < v; ++i) {
scanf("%d %d", &from, &to);
t[from - x].push_back((edge){to - x, cost});
t[to - x].push_back((edge){from - x, cost});
}
return;
}
void nexttree2(int x) {
scanf("%d", &v);
t.resize(v);
int k, to, cost = 1;
for (int i = 0; i < v; ++i) {
scanf("%d", &k);
for (int j = 0; j < k; ++j) {
scanf("%d", &to);
t[i - x].push_back((edge){to - x, cost});
t[to - x].push_back((edge){i - x, cost});
}
}
return;
}
rmqsegtree S;
vector<int> vst, dpth, id;
void lcarmqdfs(int now, int dep) { // 575!!
/* ????????° */
vector<pair<int, int>> stk;
stk.resize(v * 2); // stack
int head = 0;
stk[head].first = now;
stk[head++].second = dep;
for (; head;) {
pair<int, int> tmp = stk[--head];
if (id[tmp.first] == -1) {
id[tmp.first] = vst.size();
vst.push_back(tmp.first);
dpth.push_back(tmp.second);
} else {
vst.push_back(tmp.first);
dpth.push_back(tmp.second);
continue;
}
for (int i = 0; i < t[tmp.first].size(); ++i)
if (id[t[tmp.first][i].to] == -1) {
stk[head++] = tmp;
stk[head].first = t[tmp.first][i].to;
stk[head++].second = tmp.second + 1;
}
}
stk.clear();
return;
}
void lcarmq(void) {
if (vst.size() > v)
return;
id.resize(v);
for (int i = 0; i < v; ++i)
id[i] = -1;
lcarmqdfs(0, 0);
S.build(vst);
return;
}
int lca(int a, int b) {
if (id[a] > id[b])
swap(a, b);
return vst[S.find(id[a], id[b] + 1).second];
}
int depth(int a) { return dpth[id[a]]; }
int dist(int a, int b) { return depth(a) + depth(b) - 2 * depth(lca(a, b)); }
};
signed main(void) {
int i, j, k;
for (int testcase = 0; testcase >= 0; testcase++) {
tree T;
T.nexttree2(0);
T.lcarmq();
int(q);
for (; q--;) {
int2(a, b);
pri(T.lca(a, b));
}
/*/
//*/
break;
}
return 0;
} | replace | 193 | 194 | 193 | 194 | 0 | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
using Graph = vector<vector<int>>;
class LCA {
int n;
vector<int> dep;
vector<vector<int>> par;
Graph g;
const int LOGN_MAX = 100;
void setDep(int v, int d, Graph &tree) {
dep[v] = d;
for (int i = 0; i < tree[v].size(); i++)
setDep(tree[v][i], d + 1, tree);
}
public:
LCA(Graph &tree) : n(tree.size()) {
dep = vector<int>(n);
par = vector<vector<int>>(min(LOGN_MAX, int(log(n)) + 1), vector<int>(n));
g = Graph(n);
for (int i = 0; i < tree.size(); i++) {
for (int j = 0; j < tree[i].size(); j++) {
g[tree[i][j]].push_back(i);
}
}
bool isTree = true;
int root = -1;
for (int i = 0; i < g.size(); i++) {
if (g[i].size()) {
isTree &= (g[i].size() == 1);
} else if (root == -1) {
root = i;
if (g[i].size() == 0) {
setDep(i, 0, tree);
}
} else {
isTree = false;
}
}
assert(isTree);
for (int i = 0; i < n; i++) {
par[0][i] = (g[i].size() ? g[i][0] : i);
}
for (int i = 0; i + 1 < par.size(); i++) {
for (int j = 0; j < par[i].size(); j++) {
par[i + 1][j] = par[i][par[i][j]];
}
}
}
int lca(int a, int b) {
if (dep[a] > dep[b])
swap(a, b);
int dist = dep[b] - dep[a];
for (int i = 0; dist; i++, dist /= 2) {
if (dist % 2)
b = par[i][b];
}
assert(dep[a] == dep[b]);
while (true) {
if (a == b)
return a;
if (par[0][a] == par[0][b])
return par[0][a];
int lb = 0;
int ub = par.size();
//[ub,LOGN_MAX)->same anc
while (ub - lb > 1) {
int mid = (lb + ub) / 2;
if (par[mid][a] == par[mid][b])
ub = mid;
else
lb = mid;
}
a = par[lb][a];
b = par[lb][b];
}
}
};
int main() {
int n;
cin >> n;
Graph g(n);
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
g[i].push_back(c);
}
}
LCA lg(g);
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int u, v;
cin >> u >> v;
cout << lg.lca(u, v) << endl;
}
} | #include <bits/stdc++.h>
using namespace std;
using Graph = vector<vector<int>>;
class LCA {
int n;
vector<int> dep;
vector<vector<int>> par;
Graph g;
const int LOGN_MAX = 100;
void setDep(int v, int d, Graph &tree) {
dep[v] = d;
for (int i = 0; i < tree[v].size(); i++)
setDep(tree[v][i], d + 1, tree);
}
public:
LCA(Graph &tree) : n(tree.size()) {
dep = vector<int>(n);
par = vector<vector<int>>(min(LOGN_MAX, int(log2(n)) + 1), vector<int>(n));
g = Graph(n);
for (int i = 0; i < tree.size(); i++) {
for (int j = 0; j < tree[i].size(); j++) {
g[tree[i][j]].push_back(i);
}
}
bool isTree = true;
int root = -1;
for (int i = 0; i < g.size(); i++) {
if (g[i].size()) {
isTree &= (g[i].size() == 1);
} else if (root == -1) {
root = i;
if (g[i].size() == 0) {
setDep(i, 0, tree);
}
} else {
isTree = false;
}
}
assert(isTree);
for (int i = 0; i < n; i++) {
par[0][i] = (g[i].size() ? g[i][0] : i);
}
for (int i = 0; i + 1 < par.size(); i++) {
for (int j = 0; j < par[i].size(); j++) {
par[i + 1][j] = par[i][par[i][j]];
}
}
}
int lca(int a, int b) {
if (dep[a] > dep[b])
swap(a, b);
int dist = dep[b] - dep[a];
for (int i = 0; dist; i++, dist /= 2) {
if (dist % 2)
b = par[i][b];
}
assert(dep[a] == dep[b]);
while (true) {
if (a == b)
return a;
if (par[0][a] == par[0][b])
return par[0][a];
int lb = 0;
int ub = par.size();
//[ub,LOGN_MAX)->same anc
while (ub - lb > 1) {
int mid = (lb + ub) / 2;
if (par[mid][a] == par[mid][b])
ub = mid;
else
lb = mid;
}
a = par[lb][a];
b = par[lb][b];
}
}
};
int main() {
int n;
cin >> n;
Graph g(n);
for (int i = 0; i < n; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int c;
cin >> c;
g[i].push_back(c);
}
}
LCA lg(g);
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int u, v;
cin >> u >> v;
cout << lg.lca(u, v) << endl;
}
} | replace | 19 | 20 | 19 | 20 | 0 | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (a); i < (int)(b); ++i)
using pii = pair<int, int>;
using vvi = vector<vector<int>>;
using vi = vector<int>;
#define sz(x) ((int)x.size())
struct UnionFind {
vi data;
int comp;
UnionFind() {}
UnionFind(int size) { init(size); }
void init(int size) {
data.assign(size, -1);
comp = size;
}
void unite(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (data[y] < data[x])
swap(x, y);
data[x] += data[y];
data[y] = x;
comp--;
}
}
bool same(int x, int y) { return root(x) == root(y); }
int root(int x) {
if (data[x] < 0) {
return x;
} else {
return data[x] = root(data[x]);
}
}
int size(int x) { return -data[root(x)]; }
int components() { return comp; }
};
template <class Graph> struct LCA {
using Query = pii;
Graph g;
vi color;
vi ancestor;
vector<vector<pair<int, Query>>> query_set;
vi res;
UnionFind uf;
LCA(const Graph &g, vector<Query> &query)
: g(g), color(sz(g)), ancestor(sz(g)), query_set(sz(query)),
res(sz(query)), uf(sz(g)) {
int qs = sz(query);
rep(i, 0, qs) {
query_set[query[i].first].emplace_back(i, query[i]);
query_set[query[i].second].emplace_back(i, query[i]);
}
}
void visit(int s, int prev) {
ancestor[uf.root(s)] = s;
for (auto &e : g[s]) {
if (e == prev) {
continue;
}
visit(e, s);
uf.unite(s, e);
ancestor[uf.root(s)] = s;
}
color[s] = 1;
for (auto &p : query_set[s]) {
Query q = p.second;
int w = (q.second == s ? q.first : (q.first == s ? q.second : -1));
if (w == -1 || !color[w]) {
continue;
}
res[p.first] = ancestor[uf.root(w)];
}
}
vi solve(int root) {
visit(root, -1);
return res;
}
};
signed main() {
int N;
cin >> N;
vector<vector<int>> G(N);
rep(i, 0, N) {
int K;
cin >> K;
rep(k, 0, K) {
int X;
cin >> X;
G[i].push_back(X);
G[X].push_back(i);
}
}
int Q;
cin >> Q;
vector<pii> queries;
rep(i, 0, Q) {
int U, V;
cin >> U >> V;
queries.emplace_back(U, V);
}
LCA<vvi> lca(G, queries);
vi res = lca.solve(0);
for (int ans : res) {
cout << ans << endl;
}
}
| #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (a); i < (int)(b); ++i)
using pii = pair<int, int>;
using vvi = vector<vector<int>>;
using vi = vector<int>;
#define sz(x) ((int)x.size())
struct UnionFind {
vi data;
int comp;
UnionFind() {}
UnionFind(int size) { init(size); }
void init(int size) {
data.assign(size, -1);
comp = size;
}
void unite(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (data[y] < data[x])
swap(x, y);
data[x] += data[y];
data[y] = x;
comp--;
}
}
bool same(int x, int y) { return root(x) == root(y); }
int root(int x) {
if (data[x] < 0) {
return x;
} else {
return data[x] = root(data[x]);
}
}
int size(int x) { return -data[root(x)]; }
int components() { return comp; }
};
template <class Graph> struct LCA {
using Query = pii;
Graph g;
vi color;
vi ancestor;
vector<vector<pair<int, Query>>> query_set;
vi res;
UnionFind uf;
LCA(const Graph &g, vector<Query> &query)
: g(g), color(sz(g)), ancestor(sz(g)), query_set(sz(g)), res(sz(query)),
uf(sz(g)) {
int qs = sz(query);
rep(i, 0, qs) {
query_set[query[i].first].emplace_back(i, query[i]);
query_set[query[i].second].emplace_back(i, query[i]);
}
}
void visit(int s, int prev) {
ancestor[uf.root(s)] = s;
for (auto &e : g[s]) {
if (e == prev) {
continue;
}
visit(e, s);
uf.unite(s, e);
ancestor[uf.root(s)] = s;
}
color[s] = 1;
for (auto &p : query_set[s]) {
Query q = p.second;
int w = (q.second == s ? q.first : (q.first == s ? q.second : -1));
if (w == -1 || !color[w]) {
continue;
}
res[p.first] = ancestor[uf.root(w)];
}
}
vi solve(int root) {
visit(root, -1);
return res;
}
};
signed main() {
int N;
cin >> N;
vector<vector<int>> G(N);
rep(i, 0, N) {
int K;
cin >> K;
rep(k, 0, K) {
int X;
cin >> X;
G[i].push_back(X);
G[X].push_back(i);
}
}
int Q;
cin >> Q;
vector<pii> queries;
rep(i, 0, Q) {
int U, V;
cin >> U >> V;
queries.emplace_back(U, V);
}
LCA<vvi> lca(G, queries);
vi res = lca.solve(0);
for (int ans : res) {
cout << ans << endl;
}
}
| replace | 50 | 52 | 50 | 52 | -11 | |
p02373 | C++ | Runtime Error | #include <algorithm>
#include <bitset>
#include <climits>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#define rep(i, m, n) for (int i = int(m); i < int(n); i++)
#define EACH(i, c) for (auto &(i) : c)
#define all(c) begin(c), end(c)
#define EXIST(s, e) ((s).find(e) != (s).end())
#define SORT(c) sort(begin(c), end(c))
#define pb emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
// #define LOCAL 0
// #ifdef LOCAL
// #define DEBUG(s) cout << (s) << endl
// #define dump(x) cerr << #x << " = " << (x) << endl
// #define BR cout << endl;
// #else
// #define DEBUG(s) do{}while(0)
// #define dump(x) do{}while(0)
// #define BR
// #endif
// 改造
typedef long long int ll;
using namespace std;
#define INF (1 << 30) - 1
#define INFl (ll)5e15
#define DEBUG 0 // デバッグする時1にしてね
#define dump(x) cerr << #x << " = " << (x) << endl
#define MOD 1000000007
// ここから編集する
struct LCA {
int V; // 頂点数
vector<vector<int>> G; // グラフの隣接リスト表現
int MAX_LOG_V = 0;
int root = 0; // 根ノードの番号
vector<vector<int>>
parent; // 親を2^k回辿って到達する頂点(根を通り過ぎる場合は-1とする)
vector<int> depth; // 根からの深さ
LCA(int V) {
this->V = V;
while (1 << MAX_LOG_V < V) { // バグが怖い
MAX_LOG_V++;
}
G.resize(V);
parent.resize(MAX_LOG_V, vector<int>(V));
depth.resize(V);
}
/**
* 辺を追加した後に初期化をする
*/
void init() {
// parentとdepthの初期化
dfs(root, -1, 0);
// parentを初期化する
for (int k = 0; k + 1 < MAX_LOG_V; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < G[v].size(); i++) {
if (G[v][i] != p)
dfs(G[v][i], v, d + 1);
}
}
/**
* uとvのlcaを求める
* @param u 頂点
* @param v 頂点
* @return lcaとなる頂点
*/
int lca(int u, int v) {
// uとvの高さが同じになるまで親を辿る
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < MAX_LOG_V; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
// 二分探索でLCAを求める
for (int k = MAX_LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
/**
* 辺を追加する
* @param from 元
* @param to 先
*/
void add_edge(int from, int to) { G[from].push_back(to); }
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
LCA lca(n);
rep(i, 0, n) {
int k;
cin >> k;
rep(j, 0, k) {
int c;
cin >> c;
lca.add_edge(i, c);
}
}
lca.init();
int q;
cin >> q;
rep(i, 0, q) {
int a, b;
cin >> a >> b;
cout << lca.lca(a, b) << endl;
}
// cout << "---" << endl;
// rep(i,0,lca.G.size()){
// rep(j,0,lca.G[i].size()){
// cout << i << " " << lca.G[i][j] << endl;
// }
// }
return 0;
}
| #include <algorithm>
#include <bitset>
#include <climits>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#define rep(i, m, n) for (int i = int(m); i < int(n); i++)
#define EACH(i, c) for (auto &(i) : c)
#define all(c) begin(c), end(c)
#define EXIST(s, e) ((s).find(e) != (s).end())
#define SORT(c) sort(begin(c), end(c))
#define pb emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
// #define LOCAL 0
// #ifdef LOCAL
// #define DEBUG(s) cout << (s) << endl
// #define dump(x) cerr << #x << " = " << (x) << endl
// #define BR cout << endl;
// #else
// #define DEBUG(s) do{}while(0)
// #define dump(x) do{}while(0)
// #define BR
// #endif
// 改造
typedef long long int ll;
using namespace std;
#define INF (1 << 30) - 1
#define INFl (ll)5e15
#define DEBUG 0 // デバッグする時1にしてね
#define dump(x) cerr << #x << " = " << (x) << endl
#define MOD 1000000007
// ここから編集する
struct LCA {
int V; // 頂点数
vector<vector<int>> G; // グラフの隣接リスト表現
int MAX_LOG_V = 1;
int root = 0; // 根ノードの番号
vector<vector<int>>
parent; // 親を2^k回辿って到達する頂点(根を通り過ぎる場合は-1とする)
vector<int> depth; // 根からの深さ
LCA(int V) {
this->V = V;
while (1 << MAX_LOG_V < V) { // バグが怖い
MAX_LOG_V++;
}
G.resize(V);
parent.resize(MAX_LOG_V, vector<int>(V));
depth.resize(V);
}
/**
* 辺を追加した後に初期化をする
*/
void init() {
// parentとdepthの初期化
dfs(root, -1, 0);
// parentを初期化する
for (int k = 0; k + 1 < MAX_LOG_V; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < G[v].size(); i++) {
if (G[v][i] != p)
dfs(G[v][i], v, d + 1);
}
}
/**
* uとvのlcaを求める
* @param u 頂点
* @param v 頂点
* @return lcaとなる頂点
*/
int lca(int u, int v) {
// uとvの高さが同じになるまで親を辿る
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < MAX_LOG_V; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
// 二分探索でLCAを求める
for (int k = MAX_LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
/**
* 辺を追加する
* @param from 元
* @param to 先
*/
void add_edge(int from, int to) { G[from].push_back(to); }
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
LCA lca(n);
rep(i, 0, n) {
int k;
cin >> k;
rep(j, 0, k) {
int c;
cin >> c;
lca.add_edge(i, c);
}
}
lca.init();
int q;
cin >> q;
rep(i, 0, q) {
int a, b;
cin >> a >> b;
cout << lca.lca(a, b) << endl;
}
// cout << "---" << endl;
// rep(i,0,lca.G.size()){
// rep(j,0,lca.G[i].size()){
// cout << i << " " << lca.G[i][j] << endl;
// }
// }
return 0;
}
| replace | 67 | 68 | 67 | 68 | 0 | |
p02373 | C++ | Memory Limit Exceeded | #include <algorithm>
#include <bits/stdc++.h>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
using namespace std;
#define rep(i, n) for (int i = 0; i < ((int)(n)); i++)
#define reg(i, a, b) for (int i = ((int)(a)); i <= ((int)(b)); i++)
#define irep(i, n) for (int i = ((int)(n)) - 1; i >= 0; i--)
#define ireg(i, a, b) for (int i = ((int)(b)); i >= ((int)(a)); i--)
typedef long long int lli;
typedef pair<int, int> mp;
#define fir first
#define sec second
#define IINF INT_MAX
#define LINF LLONG_MAX
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#define pque(type) priority_queue<type, vector<type>, greater<type>>
#define memst(a, b) memset(a, b, sizeof(a))
int n;
vector<int> vs[100005];
int ans[100005];
set<int> s[100005];
void dfs() {
vector<int> stc;
stc.push_back(0);
{
for (int i = 0; i != stc.size(); i++) {
int no = stc[i];
rep(j, vs[no].size()) { stc.push_back(vs[no][j]); }
}
}
irep(k, stc.size()) {
int no = stc[k];
rep(i, vs[no].size()) {
int to = vs[no][i];
if (s[to].size() > s[no].size())
swap(s[no], s[to]);
for (set<int>::iterator ite = s[to].begin(); ite != s[to].end(); ite++) {
int p = *ite;
if (s[no].count(p) >= 1) {
s[no].erase(p);
ans[p] = no;
} else {
s[no].insert(p);
}
}
}
}
}
int main(void) {
scanf("%d", &n);
rep(i, n) {
int k;
scanf("%d", &k);
rep(j, k) {
int a;
scanf("%d", &a);
vs[i].push_back(a);
}
}
int q;
scanf("%d", &q);
rep(i, q) {
int a, b;
scanf("%d%d", &a, &b);
if (a == b)
ans[i] = a;
else {
s[a].insert(i);
s[b].insert(i);
}
}
dfs();
rep(i, q) { printf("%d\n", ans[i]); }
return 0;
} | #include <algorithm>
#include <bits/stdc++.h>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
using namespace std;
#define rep(i, n) for (int i = 0; i < ((int)(n)); i++)
#define reg(i, a, b) for (int i = ((int)(a)); i <= ((int)(b)); i++)
#define irep(i, n) for (int i = ((int)(n)) - 1; i >= 0; i--)
#define ireg(i, a, b) for (int i = ((int)(b)); i >= ((int)(a)); i--)
typedef long long int lli;
typedef pair<int, int> mp;
#define fir first
#define sec second
#define IINF INT_MAX
#define LINF LLONG_MAX
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#define pque(type) priority_queue<type, vector<type>, greater<type>>
#define memst(a, b) memset(a, b, sizeof(a))
int n;
vector<int> vs[100005];
int ans[100005];
set<int> s[100005];
void dfs() {
vector<int> stc;
stc.push_back(0);
{
for (int i = 0; i != stc.size(); i++) {
int no = stc[i];
rep(j, vs[no].size()) { stc.push_back(vs[no][j]); }
}
}
irep(k, stc.size()) {
int no = stc[k];
rep(i, vs[no].size()) {
int to = vs[no][i];
if (s[to].size() > s[no].size())
swap(s[no], s[to]);
for (set<int>::iterator ite = s[to].begin(); ite != s[to].end(); ite++) {
int p = *ite;
if (s[no].count(p) >= 1) {
s[no].erase(p);
ans[p] = no;
} else {
s[no].insert(p);
}
}
s[to].clear();
}
}
}
int main(void) {
scanf("%d", &n);
rep(i, n) {
int k;
scanf("%d", &k);
rep(j, k) {
int a;
scanf("%d", &a);
vs[i].push_back(a);
}
}
int q;
scanf("%d", &q);
rep(i, q) {
int a, b;
scanf("%d%d", &a, &b);
if (a == b)
ans[i] = a;
else {
s[a].insert(i);
s[b].insert(i);
}
}
dfs();
rep(i, q) { printf("%d\n", ans[i]); }
return 0;
} | insert | 61 | 61 | 61 | 62 | MLE | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
#define rep(i, a, b) for (int i = a; i < b; i++)
#define fore(i, a) for (auto &i : a)
#pragma GCC optimize("-O3")
using namespace std;
void _main();
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
_main();
}
//---------------------------------------------------------------------------------------------------
class LCA {
public:
int NV, logNV;
vector<int> D;
vector<vector<int>> P;
vector<vector<int>> E;
LCA() {}
void init(int N) {
NV = N;
logNV = 0;
while (NV > (1LL << logNV))
logNV++;
D = vector<int>(NV);
P = vector<vector<int>>(logNV, vector<int>(NV));
E = vector<vector<int>>(N);
}
void add_edge(int a, int b) {
E[a].push_back(b);
E[b].push_back(a);
}
void make() {
dfs(0, -1, 0);
build();
}
void dfs(int v, int par, int d) {
D[v] = d;
P[0][v] = par;
for (int i : E[v])
if (i != par)
dfs(i, v, d + 1);
}
void build() {
for (int k = 0; k < logNV - 1; k++)
for (int v = 0; v < NV; v++) {
if (P[k][v] < 0)
P[k + 1][v] = -1;
else
P[k + 1][v] = P[k][P[k][v]];
}
}
int lca(int u, int v) {
if (D[u] > D[v])
swap(u, v);
for (int k = 0; k < logNV; k++)
if ((D[v] - D[u]) >> k & 1)
v = P[k][v];
if (u == v)
return u;
for (int k = logNV - 1; k >= 0; k--) {
if (P[k][u] != P[k][v]) {
u = P[k][u];
v = P[k][v];
}
}
return P[0][u];
}
};
/*---------------------------------------------------------------------------------------------------
????????????????????????????????? ??§?????§
??????????????? ??§?????§ ???????´<_??? ?????? Welcome to My Coding Space!
???????????? ??? ?´_???`??????/??? ???i
?????????????????????????????? ??? |???|
????????? /?????? /??£??£??£??£/??????|
??? ???_(__??????/??? ???/ .| .|????????????
??? ????????????/????????????/??????u??????
---------------------------------------------------------------------------------------------------*/
//---------------------------------------------------------------------------------------------------
void _main() {
int N;
cin >> N;
LCA lca;
lca.init(N);
rep(i, 0, N) {
int K;
cin >> K;
rep(j, 0, K) {
int c;
cin >> c;
lca.add_edge(i, c);
}
}
lca.make();
int Q;
cin >> Q;
rep(q, 0, Q) {
int a, b;
cin >> a >> b;
int ans = lca.lca(a, b);
printf("%d\n", ans);
}
} | #include <bits/stdc++.h>
#define rep(i, a, b) for (int i = a; i < b; i++)
#define fore(i, a) for (auto &i : a)
#pragma GCC optimize("-O3")
using namespace std;
void _main();
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
_main();
}
//---------------------------------------------------------------------------------------------------
class LCA {
public:
int NV, logNV;
vector<int> D;
vector<vector<int>> P;
vector<vector<int>> E;
LCA() {}
void init(int N) {
NV = N;
logNV = 1;
while (NV > (1LL << logNV))
logNV++;
D = vector<int>(NV);
P = vector<vector<int>>(logNV, vector<int>(NV));
E = vector<vector<int>>(N);
}
void add_edge(int a, int b) {
E[a].push_back(b);
E[b].push_back(a);
}
void make() {
dfs(0, -1, 0);
build();
}
void dfs(int v, int par, int d) {
D[v] = d;
P[0][v] = par;
for (int i : E[v])
if (i != par)
dfs(i, v, d + 1);
}
void build() {
for (int k = 0; k < logNV - 1; k++)
for (int v = 0; v < NV; v++) {
if (P[k][v] < 0)
P[k + 1][v] = -1;
else
P[k + 1][v] = P[k][P[k][v]];
}
}
int lca(int u, int v) {
if (D[u] > D[v])
swap(u, v);
for (int k = 0; k < logNV; k++)
if ((D[v] - D[u]) >> k & 1)
v = P[k][v];
if (u == v)
return u;
for (int k = logNV - 1; k >= 0; k--) {
if (P[k][u] != P[k][v]) {
u = P[k][u];
v = P[k][v];
}
}
return P[0][u];
}
};
/*---------------------------------------------------------------------------------------------------
????????????????????????????????? ??§?????§
??????????????? ??§?????§ ???????´<_??? ?????? Welcome to My Coding Space!
???????????? ??? ?´_???`??????/??? ???i
?????????????????????????????? ??? |???|
????????? /?????? /??£??£??£??£/??????|
??? ???_(__??????/??? ???/ .| .|????????????
??? ????????????/????????????/??????u??????
---------------------------------------------------------------------------------------------------*/
//---------------------------------------------------------------------------------------------------
void _main() {
int N;
cin >> N;
LCA lca;
lca.init(N);
rep(i, 0, N) {
int K;
cin >> K;
rep(j, 0, K) {
int c;
cin >> c;
lca.add_edge(i, c);
}
}
lca.make();
int Q;
cin >> Q;
rep(q, 0, Q) {
int a, b;
cin >> a >> b;
int ans = lca.lca(a, b);
printf("%d\n", ans);
}
} | replace | 22 | 23 | 22 | 23 | 0 | |
p02373 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
template <typename Monoid> struct DisjointSparseTable {
using F = function<Monoid(Monoid, Monoid)>;
const F &f;
vector<vector<Monoid>> st;
DisjointSparseTable(const vector<Monoid> &v, const F &f) : f(f) {
int b = 0;
while ((1 << b) <= v.size())
++b;
st.resize(b, vector<Monoid>(v.size(), Monoid()));
for (int i = 0; i < v.size(); i++)
st[0][i] = v[i];
for (int i = 1; i < b; i++) {
int shift = 1 << i;
for (int j = 0; j < v.size(); j += shift << 1) {
int t = min(j + shift, (int)v.size());
st[i][t - 1] = v[t - 1];
for (int k = t - 2; k >= j; k--)
st[i][k] = f(v[k], st[i][k + 1]);
if (v.size() <= t)
break;
st[i][t] = v[t];
int r = min(t + shift, (int)v.size());
for (int k = t + 1; k < r; k++)
st[i][k] = f(st[i][k - 1], v[k]);
}
}
}
Monoid query(int l, int r) {
if (l == --r)
return st[0][l];
int p = 31 - __builtin_clz(l ^ r);
return f(st[p][l], st[p][r]);
}
};
using Pi = pair<int, int>;
vector<int> g[100000];
vector<Pi> depth;
int rev[100000];
void dfs(int idx, int dep) {
rev[idx] = (int)depth.size();
depth.emplace_back(dep, idx);
for (auto &to : g[idx]) {
dfs(to, dep + 1);
depth.emplace_back(dep, idx);
}
}
int main() {
int N, Q;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
int k;
scanf("%d", &k);
for (int j = 0; j < k; j++) {
int c;
scanf("%d", &c);
g[i].push_back(c);
}
}
dfs(0, -1);
auto f = [](const Pi &a, const Pi &b) { return min(a, b); };
DisjointSparseTable<Pi> beet(depth, f);
scanf("%d", &Q);
for (int i = 0; i < Q; i++) {
int a, b;
scanf("%d %d", &a, &b);
auto p = minmax(rev[a], rev[b]);
printf("%d\n", beet.query(p.first, p.second).second);
}
}
| #include <bits/stdc++.h>
using namespace std;
template <typename Monoid> struct DisjointSparseTable {
using F = function<Monoid(Monoid, Monoid)>;
const F &f;
vector<vector<Monoid>> st;
DisjointSparseTable(const vector<Monoid> &v, const F &f) : f(f) {
int b = 0;
while ((1 << b) <= v.size())
++b;
st.resize(b, vector<Monoid>(v.size(), Monoid()));
for (int i = 0; i < v.size(); i++)
st[0][i] = v[i];
for (int i = 1; i < b; i++) {
int shift = 1 << i;
for (int j = 0; j < v.size(); j += shift << 1) {
int t = min(j + shift, (int)v.size());
st[i][t - 1] = v[t - 1];
for (int k = t - 2; k >= j; k--)
st[i][k] = f(v[k], st[i][k + 1]);
if (v.size() <= t)
break;
st[i][t] = v[t];
int r = min(t + shift, (int)v.size());
for (int k = t + 1; k < r; k++)
st[i][k] = f(st[i][k - 1], v[k]);
}
}
}
Monoid query(int l, int r) {
if (l >= --r)
return st[0][l];
int p = 31 - __builtin_clz(l ^ r);
return f(st[p][l], st[p][r]);
}
};
using Pi = pair<int, int>;
vector<int> g[100000];
vector<Pi> depth;
int rev[100000];
void dfs(int idx, int dep) {
rev[idx] = (int)depth.size();
depth.emplace_back(dep, idx);
for (auto &to : g[idx]) {
dfs(to, dep + 1);
depth.emplace_back(dep, idx);
}
}
int main() {
int N, Q;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
int k;
scanf("%d", &k);
for (int j = 0; j < k; j++) {
int c;
scanf("%d", &c);
g[i].push_back(c);
}
}
dfs(0, -1);
auto f = [](const Pi &a, const Pi &b) { return min(a, b); };
DisjointSparseTable<Pi> beet(depth, f);
scanf("%d", &Q);
for (int i = 0; i < Q; i++) {
int a, b;
scanf("%d %d", &a, &b);
auto p = minmax(rev[a], rev[b]);
printf("%d\n", beet.query(p.first, p.second).second);
}
}
| replace | 35 | 36 | 35 | 36 | 0 | |
p02373 | C++ | Memory Limit Exceeded | #include <bits/stdc++.h>
#define MAXV 1000000
#define MAXLV 20
using namespace std;
vector<int> e[MAXV];
int n, root = 0;
int parent[MAXLV][MAXV];
int depth[MAXV];
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < e[v].size(); i++) {
if (e[v][i] != p)
dfs(e[v][i], v, d + 1);
}
}
void init() {
dfs(root, -1, 0);
for (int k = 0; k + 1 < MAXLV; k++) {
for (int v = 0; v < n; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < MAXLV; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
for (int k = MAXLV - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
int main() {
int q, u, v, k, c;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> k;
for (int j = 0; j < k; j++) {
cin >> c;
e[i].push_back(c);
}
}
init();
cin >> q;
for (int i = 0; i < q; i++) {
cin >> u >> v;
cout << lca(u, v) << endl;
}
return 0;
} | #include <bits/stdc++.h>
#define MAXV 100010
#define MAXLV 20
using namespace std;
vector<int> e[MAXV];
int n, root = 0;
int parent[MAXLV][MAXV];
int depth[MAXV];
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < e[v].size(); i++) {
if (e[v][i] != p)
dfs(e[v][i], v, d + 1);
}
}
void init() {
dfs(root, -1, 0);
for (int k = 0; k + 1 < MAXLV; k++) {
for (int v = 0; v < n; v++) {
if (parent[k][v] < 0)
parent[k + 1][v] = -1;
else
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v])
swap(u, v);
for (int k = 0; k < MAXLV; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][v];
}
}
if (u == v)
return u;
for (int k = MAXLV - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
int main() {
int q, u, v, k, c;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> k;
for (int j = 0; j < k; j++) {
cin >> c;
e[i].push_back(c);
}
}
init();
cin >> q;
for (int i = 0; i < q; i++) {
cin >> u >> v;
cout << lca(u, v) << endl;
}
return 0;
} | replace | 1 | 2 | 1 | 2 | MLE | |
p02374 | C++ | Runtime Error | #include <cmath>
#include <cstdio>
#include <vector>
using namespace std;
void dfs(vector<vector<int>> &childLists, vector<vector<int>> &edgeIds,
vector<int> &weights, const int &v) {
for (int i = 0; i < childLists[v].size(); i++) {
int u = childLists[v][i];
weights.push_back(0);
edgeIds[u].push_back(weights.size() - 1);
dfs(childLists, edgeIds, weights, u);
weights.push_back(0);
edgeIds[u].push_back(weights.size() - 1);
}
}
void add(vector<int> &tree, const int &n, const int &k, const int &w) {
int i = k + n - 1;
while (i > 0) {
tree[i] += w;
i = (i - 1) / 2;
}
tree[i] += w;
}
int getSumUtil(vector<int> &tree, const int &L, const int &R, const int &i,
const int &l, const int &r) {
if (i >= tree.size() || l > r) {
return 0;
}
if (r < L || l > R) {
return 0;
}
if (l >= L && r <= R) {
return tree[i];
}
int m = l + (r - l) / 2;
return getSumUtil(tree, L, R, 2 * i + 1, l, m) +
getSumUtil(tree, L, R, 2 * i + 2, m + 1, r);
}
int getSum(vector<int> &tree, const int &n, const int &L, const int &R) {
return getSumUtil(tree, L, R, 0, 0, n - 1);
}
int main() {
int n, q, k, x, v, w;
scanf("%d", &n);
vector<vector<int>> childLists(n);
for (int i = 0; i < n; i++) {
scanf("%d", &k);
for (int j = 0; j < k; j++) {
scanf("%d", &x);
childLists[i].push_back(x);
}
}
vector<int> weights;
vector<vector<int>> edgeIds(n);
dfs(childLists, edgeIds, weights, 0);
int h = ceil(log2(weights.size())) + 1;
int max_size = pow(2, h) - 1;
vector<int> tree(max_size, 0);
scanf("%d", &q);
for (int i = 0; i < q; i++) {
scanf("%d", &x);
if (x == 0) {
scanf("%d %d", &v, &w);
add(tree, pow(2, h - 1), edgeIds[v][0], w);
add(tree, pow(2, h - 1), edgeIds[v][1], -w);
} else if (x == 1) {
scanf("%d", &v);
printf("%d\n", getSum(tree, pow(2, h - 1), 0, edgeIds[v][0]));
} else
printf("invalid query %d\n", x);
}
}
| #include <cmath>
#include <cstdio>
#include <vector>
using namespace std;
void dfs(vector<vector<int>> &childLists, vector<vector<int>> &edgeIds,
vector<int> &weights, const int &v) {
for (int i = 0; i < childLists[v].size(); i++) {
int u = childLists[v][i];
weights.push_back(0);
edgeIds[u].push_back(weights.size() - 1);
dfs(childLists, edgeIds, weights, u);
weights.push_back(0);
edgeIds[u].push_back(weights.size() - 1);
}
}
void add(vector<int> &tree, const int &n, const int &k, const int &w) {
int i = k + n - 1;
while (i > 0) {
tree[i] += w;
i = (i - 1) / 2;
}
tree[i] += w;
}
int getSumUtil(vector<int> &tree, const int &L, const int &R, const int &i,
const int &l, const int &r) {
if (i >= tree.size() || l > r) {
return 0;
}
if (r < L || l > R) {
return 0;
}
if (l >= L && r <= R) {
return tree[i];
}
int m = l + (r - l) / 2;
return getSumUtil(tree, L, R, 2 * i + 1, l, m) +
getSumUtil(tree, L, R, 2 * i + 2, m + 1, r);
}
int getSum(vector<int> &tree, const int &n, const int &L, const int &R) {
return getSumUtil(tree, L, R, 0, 0, n - 1);
}
int main() {
int n, q, k, x, v, w;
scanf("%d", &n);
vector<vector<int>> childLists(n);
for (int i = 0; i < n; i++) {
scanf("%d", &k);
for (int j = 0; j < k; j++) {
scanf("%d", &x);
childLists[i].push_back(x);
}
}
vector<int> weights;
vector<vector<int>> edgeIds(n);
dfs(childLists, edgeIds, weights, 0);
int h = ceil(log2(weights.size())) + 1;
int max_size = pow(2, h) - 1;
vector<int> tree(max_size, 0);
scanf("%d", &q);
for (int i = 0; i < q; i++) {
scanf("%d", &x);
if (x == 0) {
scanf("%d %d", &v, &w);
add(tree, pow(2, h - 1), edgeIds[v][0], w);
add(tree, pow(2, h - 1), edgeIds[v][1], -w);
} else if (x == 1) {
scanf("%d", &v);
printf("%d\n",
v == 0 ? 0 : getSum(tree, pow(2, h - 1), 0, edgeIds[v][0]));
} else
printf("invalid query %d\n", x);
}
}
| replace | 72 | 73 | 72 | 74 | 0 | |
p02376 | C++ | Time Limit Exceeded | #include <bits/stdc++.h>
using namespace std;
const int maxN = 3e2 + 100;
int n, m, st, fn;
int cap[maxN][maxN], excess[maxN], height[maxN];
vector<int> g[maxN];
set<pair<int, int>> candidates;
void input() {
cin >> n >> m;
// cin>>st>>fn;
st = 1;
fn = n;
for (int i = 1; i <= m; i++) {
int k1, k2, val;
cin >> k1 >> k2 >> val;
k1++;
k2++;
if (cap[k1][k2] == 0 && cap[k1][k2] == 0) {
g[k1].push_back(k2);
g[k2].push_back(k1);
}
cap[k1][k2] += val;
}
}
int findExcessedVertex() {
while (candidates.size() > 0) {
auto item = *candidates.begin();
if (item.second == st || item.second == fn)
candidates.erase(item);
else
return item.second;
}
return 0;
}
bool push(int v) // change to multi push
{
bool done = false;
for (auto u : g[v])
if (cap[v][u] > 0 && height[v] >= height[u] + 1) // h[v]==h[u]+1
{
int delta = min(excess[v], cap[v][u]);
cap[v][u] -= delta;
cap[u][v] += delta;
excess[v] -= delta;
if (excess[v] == 0)
candidates.erase({height[v], v});
if (excess[u] == 0)
candidates.insert({height[u], u});
excess[u] += delta;
done = true;
// return done;
}
return done;
}
void relabel(int v) {
height[v]++;
if (candidates.find({height[v] - 1, v}) != candidates.end()) {
candidates.erase({height[v] - 1, v});
candidates.insert({height[v], v});
}
}
void GT_init() {
height[st] = n;
height[fn] = 0; // not done
for (auto u : g[st])
if (cap[st][u] > 0) {
int delta = cap[st][u];
cap[st][u] -= delta;
cap[u][st] += delta;
excess[st] -= delta;
if (excess[st] == 0)
candidates.erase({height[st], st});
if (excess[u] == 0)
candidates.insert({height[u], u});
excess[u] += delta;
}
}
int Goldberg_Tarjan() {
GT_init();
while (int v = findExcessedVertex()) {
// cout<<"gt "<<v<<" "<<excess[v]<<" "<<height[v]<<endl;
if (!push(v))
relabel(v);
}
return excess[fn];
}
int main() {
input();
int Maxflow = Goldberg_Tarjan();
cout << Maxflow << endl;
return 0;
} | #include <bits/stdc++.h>
using namespace std;
const int maxN = 3e2 + 100;
int n, m, st, fn;
int cap[maxN][maxN], excess[maxN], height[maxN];
vector<int> g[maxN];
set<pair<int, int>> candidates;
void input() {
cin >> n >> m;
// cin>>st>>fn;
st = 1;
fn = n;
for (int i = 1; i <= m; i++) {
int k1, k2, val;
cin >> k1 >> k2 >> val;
k1++;
k2++;
if (cap[k1][k2] == 0 && cap[k1][k2] == 0) {
g[k1].push_back(k2);
g[k2].push_back(k1);
}
cap[k1][k2] += val;
}
}
int findExcessedVertex() {
while (candidates.size() > 0) {
auto item = *candidates.begin();
if (item.second == st || item.second == fn)
candidates.erase(item);
else
return item.second;
}
return 0;
}
bool push(int v) // change to multi push
{
bool done = false;
for (auto u : g[v])
if (cap[v][u] > 0 && height[v] >= height[u] + 1) // h[v]==h[u]+1
{
int delta = min(excess[v], cap[v][u]);
cap[v][u] -= delta;
cap[u][v] += delta;
excess[v] -= delta;
if (excess[v] == 0)
candidates.erase({height[v], v});
if (excess[u] == 0)
candidates.insert({height[u], u});
excess[u] += delta;
done = true;
if (excess[v] == 0)
break;
// return done;
}
return done;
}
void relabel(int v) {
height[v]++;
if (candidates.find({height[v] - 1, v}) != candidates.end()) {
candidates.erase({height[v] - 1, v});
candidates.insert({height[v], v});
}
}
void GT_init() {
height[st] = n;
height[fn] = 0; // not done
for (auto u : g[st])
if (cap[st][u] > 0) {
int delta = cap[st][u];
cap[st][u] -= delta;
cap[u][st] += delta;
excess[st] -= delta;
if (excess[st] == 0)
candidates.erase({height[st], st});
if (excess[u] == 0)
candidates.insert({height[u], u});
excess[u] += delta;
}
}
int Goldberg_Tarjan() {
GT_init();
while (int v = findExcessedVertex()) {
// cout<<"gt "<<v<<" "<<excess[v]<<" "<<height[v]<<endl;
if (!push(v))
relabel(v);
}
return excess[fn];
}
int main() {
input();
int Maxflow = Goldberg_Tarjan();
cout << Maxflow << endl;
return 0;
} | insert | 52 | 52 | 52 | 54 | TLE | |
p02376 | C++ | Runtime Error | #include <bits/stdc++.h>
#define INF 1000000000
#define MAX_V 100
#define MAX_E 1000
using namespace std;
struct edge {
int to, cap, rev;
edge(int to_, int cap_, int rev_) : to(to_), cap(cap_), rev(rev_){};
};
int V, E;
vector<edge> G[MAX_V];
int level[MAX_V];
int iter[MAX_V];
void AddEdge(int from, int to, int cap) {
G[from].push_back(edge(to, cap, G[to].size()));
G[to].push_back(edge(from, 0, G[from].size() - 1));
}
void BFS(int s) {
fill(level, level + V, -1);
queue<int> que;
level[s] = 0;
que.push(s);
while (!que.empty()) {
int v = que.front();
que.pop();
for (size_t i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && level[v] + 1) {
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
int DFS(int v, int t, int f) {
if (v == t)
return f;
for (int &i = iter[v]; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && level[v] < level[e.to]) {
int d = DFS(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int Dinic(int s, int t) {
int flow = 0;
while (true) {
BFS(s);
if (level[t] < 0)
return flow;
fill(iter, iter + V, 0);
int f;
while ((f = DFS(s, t, INF)) > 0) {
flow += f;
}
}
}
int main() {
cin >> V >> E;
for (int i = 0, u, v, c; i < E; i++) {
cin >> u >> v >> c;
AddEdge(u, v, c);
}
cout << Dinic(0, V - 1) << endl;
return 0;
} | #include <bits/stdc++.h>
#define INF 1000000000
#define MAX_V 100
#define MAX_E 1000
using namespace std;
struct edge {
int to, cap, rev;
edge(int to_, int cap_, int rev_) : to(to_), cap(cap_), rev(rev_){};
};
int V, E;
vector<edge> G[MAX_V];
int level[MAX_V];
int iter[MAX_V];
void AddEdge(int from, int to, int cap) {
G[from].push_back(edge(to, cap, G[to].size()));
G[to].push_back(edge(from, 0, G[from].size() - 1));
}
void BFS(int s) {
fill(level, level + V, -1);
queue<int> que;
level[s] = 0;
que.push(s);
while (!que.empty()) {
int v = que.front();
que.pop();
for (size_t i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
int DFS(int v, int t, int f) {
if (v == t)
return f;
for (int &i = iter[v]; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && level[v] < level[e.to]) {
int d = DFS(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int Dinic(int s, int t) {
int flow = 0;
while (true) {
BFS(s);
if (level[t] < 0)
return flow;
fill(iter, iter + V, 0);
int f;
while ((f = DFS(s, t, INF)) > 0) {
flow += f;
}
}
}
int main() {
cin >> V >> E;
for (int i = 0, u, v, c; i < E; i++) {
cin >> u >> v >> c;
AddEdge(u, v, c);
}
cout << Dinic(0, V - 1) << endl;
return 0;
} | replace | 30 | 31 | 30 | 31 | 0 | |
p02376 | C++ | Runtime Error | #define _CRT_SECURE_NO_WARNINGS
// #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#define range(i, a, b) for (int i = a; i < (int)(b); i++)
#define rep(i, b) range(i, 0, b)
typedef int Capacity;
struct Edge {
int src, dst;
Capacity cap;
Edge(int src_, int dst_, int cap_) : src(src_), dst(dst_), cap(cap_) {}
};
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<int> Array;
typedef vector<Array> Matrix;
int const inf = 1e9;
template <class Capacity = int> struct FordFulkerson {
typedef vector<vector<Capacity>> Matrix;
size_t n;
Matrix cap, flow;
vector<bool> vis;
Capacity res;
vector<vector<int>> g;
FordFulkerson(const int s, const int t, const Graph &graph) {
n = graph.size();
cap.assign(n, Array(n));
flow.assign(n, Array(n));
g.assign(n, {});
res = 0;
rep(i, n) rep(j, graph[i].size()) {
int u = graph[i][j].src, v = graph[i][j].dst;
cap[u][v] = graph[i][j].cap;
flow[v][u] = graph[i][j].cap;
}
rep(i, n) rep(j, n) if (cap[i][j]) g[i].push_back(j), g[j].push_back(i);
Capacity f = -1;
while (f)
vis.assign(n, false), res += (f = augment(s, t, inf));
}
Capacity augment(const int v, const int t, Capacity lim) {
vis[v] = true;
if (v == t)
return lim;
for (const int &i : g[v]) {
if (vis[i] || flow[v][i] == cap[v][i])
continue;
Capacity f = augment(i, t, min(lim, cap[v][i] - flow[v][i]));
flow[v][i] += f;
flow[i][v] -= f;
// cout << flow[v][i] << " " << flow[i][v] << endl;
assert(0 <= flow[v][i]);
assert(0 <= flow[i][v]);
if (f)
return f;
}
return 0;
}
};
int main() {
int N, M;
cin >> N >> M;
Graph g(N);
rep(i, M) {
int a, b, c;
cin >> a >> b >> c;
g[a].emplace_back(a, b, c);
}
cout << FordFulkerson<>(0, N - 1, g).res << endl;
} | #define _CRT_SECURE_NO_WARNINGS
// #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#define range(i, a, b) for (int i = a; i < (int)(b); i++)
#define rep(i, b) range(i, 0, b)
typedef int Capacity;
struct Edge {
int src, dst;
Capacity cap;
Edge(int src_, int dst_, int cap_) : src(src_), dst(dst_), cap(cap_) {}
};
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<int> Array;
typedef vector<Array> Matrix;
int const inf = 1e9;
template <class Capacity = int> struct FordFulkerson {
typedef vector<vector<Capacity>> Matrix;
size_t n;
Matrix cap, flow;
vector<bool> vis;
Capacity res;
vector<vector<int>> g;
FordFulkerson(const int s, const int t, const Graph &graph) {
n = graph.size();
cap.assign(n, Array(n));
flow.assign(n, Array(n));
g.assign(n, {});
res = 0;
rep(i, n) rep(j, graph[i].size()) {
int u = graph[i][j].src, v = graph[i][j].dst;
Capacity c = graph[i][j].cap;
cap[u][v] += c;
cap[v][u] += c;
flow[v][u] += c;
// cap[u][v] = cap[v][u] = graph[i][j].cap;
// flow[v][u] = graph[i][j].cap;
}
rep(i, n) rep(j, n) if (cap[i][j]) g[i].push_back(j), g[j].push_back(i);
Capacity f = -1;
while (f)
vis.assign(n, false), res += (f = augment(s, t, inf));
}
Capacity augment(const int v, const int t, Capacity lim) {
vis[v] = true;
if (v == t)
return lim;
for (const int &i : g[v]) {
if (vis[i] || flow[v][i] == cap[v][i])
continue;
Capacity f = augment(i, t, min(lim, cap[v][i] - flow[v][i]));
flow[v][i] += f;
flow[i][v] -= f;
// cout << flow[v][i] << " " << flow[i][v] << endl;
assert(0 <= flow[v][i]);
assert(0 <= flow[i][v]);
if (f)
return f;
}
return 0;
}
};
int main() {
int N, M;
cin >> N >> M;
Graph g(N);
rep(i, M) {
int a, b, c;
cin >> a >> b >> c;
g[a].emplace_back(a, b, c);
}
cout << FordFulkerson<>(0, N - 1, g).res << endl;
} | replace | 35 | 37 | 35 | 41 | 0 | |
p02376 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < (n); i++)
using namespace std;
const int INF = 1e9;
struct edge {
int to, cap, rev;
edge(int to, int cap, int rev) : to(to), cap(cap), rev(rev) {}
};
int v, e;
vector<vector<edge>> G; //??°???????????£??\???????????¨???
bool used[1003]; // DFS??§??¢???????????????????????????????????°
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (!used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int maxflow(int s, int t) {
int flow = 0;
for (;;) {
fill(used, used + e, false);
int f = dfs(s, t, INF);
if (f == 0)
return flow;
flow += f;
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cin >> v >> e;
G.resize(e);
REP(i, e) {
int from, to, cap;
cin >> from >> to >> cap;
G[from].push_back(edge(to, cap, G[to].size()));
G[to].push_back(edge(from, 0, G[from].size() - 1));
}
cout << maxflow(0, v - 1) << endl;
return 0;
} | #include <algorithm>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; i < (n); i++)
using namespace std;
const int INF = 1e9;
struct edge {
int to, cap, rev;
edge(int to, int cap, int rev) : to(to), cap(cap), rev(rev) {}
};
int v, e;
vector<vector<edge>> G; //??°???????????£??\???????????¨???
bool used[1003]; // DFS??§??¢???????????????????????????????????°
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (!used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int maxflow(int s, int t) {
int flow = 0;
for (;;) {
fill(used, used + e, false);
int f = dfs(s, t, INF);
if (f == 0)
return flow;
flow += f;
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cin >> v >> e;
G.resize(v);
REP(i, e) {
int from, to, cap;
cin >> from >> to >> cap;
G[from].push_back(edge(to, cap, G[to].size()));
G[to].push_back(edge(from, 0, G[from].size() - 1));
}
cout << maxflow(0, v - 1) << endl;
return 0;
} | replace | 49 | 50 | 49 | 50 | 0 | |
p02376 | C++ | Runtime Error | /* Дан неориентированный связный граф.
* Требуется найти вес минимального остовного дерева в этом графе с помощью
* алгоритма Борувки.*/
// T(N, M) = O(|E|log|V|)
// M(N, M) = O(|V| + |E|)
#include <bits/stdc++.h>
using namespace std;
const int INF = 2000000000; // константа, отвечающая за "бесконечность".
typedef unsigned long long ull;
class Graph {
// <пропускная способность, поток>
vector<vector<pair<int, int>>> g;
int vertices;
void InsertEdge_(int from, int to, int capacity, int flow) {
g[from][to] = {capacity, flow};
}
void CreateLists_(int VerticesNumber) {
vertices = VerticesNumber;
g.resize((ull)VerticesNumber);
for (int i = 0; i < VerticesNumber; i++)
g[i].resize((ull)VerticesNumber, {0, 0});
}
vector<tuple<int, int, int>> adjacent_(int v) {
vector<tuple<int, int, int>> result;
for (int i = 0; i < vertices; i++) {
if (g[v][i].first > 0)
result.push_back(make_tuple(i, g[v][i].first, g[v][i].second));
}
return result;
}
int findBlockingFlow_() {
vector<int> pointers;
pointers.assign(g.size(), 0);
int getFlow = 0, resultFlow = 0;
do {
getFlow = dfs(0, INF, *this, pointers);
resultFlow += getFlow;
} while (getFlow > 0);
return resultFlow;
}
public:
Graph(int size) { CreateLists_(size); }
friend istream &operator>>(istream &in, Graph &g) {
int VerticesNumber, EdgesNumber;
in >> VerticesNumber >> EdgesNumber;
g.CreateLists(VerticesNumber);
for (int i = 0; i < EdgesNumber; i++) {
int from, to, capacity;
in >> from >> to >> capacity;
g.InsertEdge(from - 1, to - 1, capacity, 0);
}
return in;
}
friend ostream &operator<<(ostream &out, Graph &g) {
out << "Graph. \n";
out << g.vertices << " " << '\n';
for (int i = 0; i < g.vertices; i++) {
out << i << ":\n";
for (auto to : g.adjacent_(i))
out << get<0>(to) << " " << get<1>(to) << " " << get<2>(to) << '\n';
out << '\n';
}
return out;
}
void InsertEdge(int from, int to, int capacity, int flow) {
InsertEdge_(from, to, capacity, flow);
}
void CreateLists(int VerticesNumber) { CreateLists_(VerticesNumber); }
int findBlockingFlow() { return findBlockingFlow_(); }
void addFlow(Graph &from) {
for (int v = 0; v < from.size(); v++) {
for (auto to : from.adjacent(v)) {
if (g[v][get<0>(to)].first > 0) {
g[v][get<0>(to)].first -= from.g[v][get<0>(to)].second;
g[get<0>(to)][v].first += from.g[v][get<0>(to)].second;
}
}
}
}
int size() { return vertices; }
vector<tuple<int, int, int>> adjacent(int v) { return adjacent_(v); }
friend int dfs(int, int, Graph &, vector<int> &);
Graph() = default;
Graph(const Graph &) = default;
Graph &operator=(const Graph &) = delete;
};
pair<Graph, int> LayeredNetwork(Graph &g) {
Graph res(g.size());
queue<int> q;
vector<int> visited, distance;
visited.assign(g.size(), 0);
distance.assign(g.size(), INF);
q.push(0);
distance[0] = 0;
visited[0] = 1;
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto to : g.adjacent(v)) {
if (!visited[get<0>(to)]) {
q.push((int)get<0>(to));
visited[get<0>(to)] = 1;
distance[get<0>(to)] = distance[v] + 1;
}
if (distance[get<0>(to)] == distance[v] + 1)
res.InsertEdge(v, get<0>(to), get<1>(to), get<2>(to));
}
}
return {res, distance[g.size() - 1]};
}
int dfs(int v, int flow, Graph &graph, vector<int> &pointers) {
// cout << v << " ";
if (v == graph.size() - 1)
return flow;
if (flow == 0)
return 0;
int size = graph.size();
for (int i = pointers[v]; i < size; i++) {
pointers[v]++;
if (graph.g[v][i].first > 0) {
int foundedFlow =
dfs(i, min(flow, graph.g[v][i].first - graph.g[v][i].second), graph,
pointers);
graph.g[v][i].second += foundedFlow;
if (foundedFlow)
return foundedFlow;
}
}
return 0;
}
class Dinic {
int maxflow = 0;
void Dinic_(Graph &g) {
bool isPath = true;
int n = g.size();
for (int i = 0; i < n - 1; i++) {
auto temp = LayeredNetwork(g);
if (temp.second == INF)
break;
Graph gLayered = temp.first;
// cout << gLayered;
maxflow += gLayered.findBlockingFlow();
// cout << gLayered;
g.addFlow(gLayered);
// cout << g;
// g = ResidualNetwork(g);
}
}
public:
Dinic(Graph &g) { Dinic_(g); }
// Вывод ответа в поток вывода.
friend ostream &operator<<(ostream &out, Dinic &D) {
return out << D.maxflow << '\n';
}
Dinic() = default;
Dinic &operator=(const Dinic &) = delete;
};
// Функция для решения поставленной задачи. Считывает граф, применяет на нём
// алгоритм Борувки и выводит ответ, хранящийся в объекте mst класса Dinic.
void solve() {
Graph g;
cin >> g;
Dinic d(g);
cout << d;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
| /* Дан неориентированный связный граф.
* Требуется найти вес минимального остовного дерева в этом графе с помощью
* алгоритма Борувки.*/
// T(N, M) = O(|E|log|V|)
// M(N, M) = O(|V| + |E|)
#include <bits/stdc++.h>
using namespace std;
const int INF = 2000000000; // константа, отвечающая за "бесконечность".
typedef unsigned long long ull;
class Graph {
// <пропускная способность, поток>
vector<vector<pair<int, int>>> g;
int vertices;
void InsertEdge_(int from, int to, int capacity, int flow) {
g[from][to] = {capacity, flow};
}
void CreateLists_(int VerticesNumber) {
vertices = VerticesNumber;
g.resize((ull)VerticesNumber);
for (int i = 0; i < VerticesNumber; i++)
g[i].resize((ull)VerticesNumber, {0, 0});
}
vector<tuple<int, int, int>> adjacent_(int v) {
vector<tuple<int, int, int>> result;
for (int i = 0; i < vertices; i++) {
if (g[v][i].first > 0)
result.push_back(make_tuple(i, g[v][i].first, g[v][i].second));
}
return result;
}
int findBlockingFlow_() {
vector<int> pointers;
pointers.assign(g.size(), 0);
int getFlow = 0, resultFlow = 0;
do {
getFlow = dfs(0, INF, *this, pointers);
resultFlow += getFlow;
} while (getFlow > 0);
return resultFlow;
}
public:
Graph(int size) { CreateLists_(size); }
friend istream &operator>>(istream &in, Graph &g) {
int VerticesNumber, EdgesNumber;
in >> VerticesNumber >> EdgesNumber;
g.CreateLists(VerticesNumber);
for (int i = 0; i < EdgesNumber; i++) {
int from, to, capacity;
in >> from >> to >> capacity;
g.InsertEdge(from, to, capacity, 0);
}
return in;
}
friend ostream &operator<<(ostream &out, Graph &g) {
out << "Graph. \n";
out << g.vertices << " " << '\n';
for (int i = 0; i < g.vertices; i++) {
out << i << ":\n";
for (auto to : g.adjacent_(i))
out << get<0>(to) << " " << get<1>(to) << " " << get<2>(to) << '\n';
out << '\n';
}
return out;
}
void InsertEdge(int from, int to, int capacity, int flow) {
InsertEdge_(from, to, capacity, flow);
}
void CreateLists(int VerticesNumber) { CreateLists_(VerticesNumber); }
int findBlockingFlow() { return findBlockingFlow_(); }
void addFlow(Graph &from) {
for (int v = 0; v < from.size(); v++) {
for (auto to : from.adjacent(v)) {
if (g[v][get<0>(to)].first > 0) {
g[v][get<0>(to)].first -= from.g[v][get<0>(to)].second;
g[get<0>(to)][v].first += from.g[v][get<0>(to)].second;
}
}
}
}
int size() { return vertices; }
vector<tuple<int, int, int>> adjacent(int v) { return adjacent_(v); }
friend int dfs(int, int, Graph &, vector<int> &);
Graph() = default;
Graph(const Graph &) = default;
Graph &operator=(const Graph &) = delete;
};
pair<Graph, int> LayeredNetwork(Graph &g) {
Graph res(g.size());
queue<int> q;
vector<int> visited, distance;
visited.assign(g.size(), 0);
distance.assign(g.size(), INF);
q.push(0);
distance[0] = 0;
visited[0] = 1;
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto to : g.adjacent(v)) {
if (!visited[get<0>(to)]) {
q.push((int)get<0>(to));
visited[get<0>(to)] = 1;
distance[get<0>(to)] = distance[v] + 1;
}
if (distance[get<0>(to)] == distance[v] + 1)
res.InsertEdge(v, get<0>(to), get<1>(to), get<2>(to));
}
}
return {res, distance[g.size() - 1]};
}
int dfs(int v, int flow, Graph &graph, vector<int> &pointers) {
// cout << v << " ";
if (v == graph.size() - 1)
return flow;
if (flow == 0)
return 0;
int size = graph.size();
for (int i = pointers[v]; i < size; i++) {
pointers[v]++;
if (graph.g[v][i].first > 0) {
int foundedFlow =
dfs(i, min(flow, graph.g[v][i].first - graph.g[v][i].second), graph,
pointers);
graph.g[v][i].second += foundedFlow;
if (foundedFlow)
return foundedFlow;
}
}
return 0;
}
class Dinic {
int maxflow = 0;
void Dinic_(Graph &g) {
bool isPath = true;
int n = g.size();
for (int i = 0; i < n - 1; i++) {
auto temp = LayeredNetwork(g);
if (temp.second == INF)
break;
Graph gLayered = temp.first;
// cout << gLayered;
maxflow += gLayered.findBlockingFlow();
// cout << gLayered;
g.addFlow(gLayered);
// cout << g;
// g = ResidualNetwork(g);
}
}
public:
Dinic(Graph &g) { Dinic_(g); }
// Вывод ответа в поток вывода.
friend ostream &operator<<(ostream &out, Dinic &D) {
return out << D.maxflow << '\n';
}
Dinic() = default;
Dinic &operator=(const Dinic &) = delete;
};
// Функция для решения поставленной задачи. Считывает граф, применяет на нём
// алгоритм Борувки и выводит ответ, хранящийся в объекте mst класса Dinic.
void solve() {
Graph g;
cin >> g;
Dinic d(g);
cout << d;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
| replace | 57 | 58 | 57 | 58 | -11 | |
p02376 | C++ | Runtime Error | // clang-format off
#include <bits/stdc++.h>
#define int long long
#define main signed main()
#define loop(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) loop(i, 0, n)
#define forever for (;;)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prec(n) fixed << setprecision(n)
template<typename A> using V = std::vector<A>;
template<typename A> using F = std::function<A>;
template<typename A, typename B> using P = std::pair<A, B>;
using pii = P<int, int>;
using vi = V<int>;
using vd = V<double>;
using vs = V<std::string>;
using vpii = V<pii>;
using vvi = V<vi>;
using vvpii = V<vpii>;
constexpr int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000;
constexpr int MOD = 1000000007;
constexpr double PI = 3.14159265358979;
template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; }
template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; }
constexpr bool odd(const int n) { return n & 1; }
constexpr bool even(const int n) { return ~n & 1; }
template<typename T> std::istream &operator>>(std::istream &is, std::vector<T> &v) { for (T &x : v) is >> x; return is; }
template<typename A, typename B> std::istream &operator>>(std::istream &is, std::pair<A, B> &p) { is >> p.first; is >> p.second; return is; }
using namespace std;
// clang-format on
using Flow = int;
struct FlowEdge {
int src, dst;
Flow cap;
int rev;
FlowEdge(const int s = 0, const int d = 0, const Flow c = 0, const int r = 0)
: src(s), dst(d), cap(c), rev(r) {}
};
using FlowEdges = std::vector<FlowEdge>;
class FlowGraph {
std::vector<FlowEdges> g;
public:
FlowGraph(const int size = 0) : g(size) {}
size_t size() const { return g.size(); }
FlowEdges &operator[](const int i) & { return g[i]; }
void addEdge(const int src, const int dst, const Flow c = 1) {
g[src].emplace_back(src, dst, c, g[dst].size());
g[dst].emplace_back(dst, src, 0, g[src].size() - 1);
}
};
template <Flow inf = std::numeric_limits<Flow>::max()>
Flow dinic(FlowGraph g, const int source, const int sink) {
std::vector<int> level(g.size()), iter(g.size());
auto bfs = [&] {
std::fill(level.begin(), level.end(), -1);
std::queue<int> q;
level[source] = 0;
q.push(source);
while (q.size()) {
int v = q.front();
q.pop();
for (auto &e : g[v]) {
if (e.cap <= 0 || level[e.dst] >= 0)
continue;
level[e.dst] = level[v] + 1;
q.push(e.dst);
}
}
return level[sink] != -1;
};
std::function<Flow(int, Flow)> dfs = [&](int v, Flow f) -> Flow {
if (v == sink)
return f;
Flow s = 0;
for (; iter[v] < g.size(); iter[v]++) {
auto &e = g[v][iter[v]];
if (level[v] >= level[e.dst] || e.cap <= 0)
continue;
Flow d = dfs(e.dst, min(f, e.cap));
e.cap -= d;
g[e.dst][e.rev].cap += d;
s += d;
f -= d;
if (f == 0)
break;
}
return s;
};
Flow s = 0;
while (bfs()) {
std::fill(iter.begin(), iter.end(), 0);
s += dfs(source, inf);
}
return s;
}
main {
int n, m;
cin >> n >> m;
FlowGraph g(n);
while (m--) {
int a, b, c;
cin >> a >> b >> c;
g.addEdge(a, b, c);
}
cout << dinic(g, 0, n - 1) << endl;
} | // clang-format off
#include <bits/stdc++.h>
#define int long long
#define main signed main()
#define loop(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) loop(i, 0, n)
#define forever for (;;)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prec(n) fixed << setprecision(n)
template<typename A> using V = std::vector<A>;
template<typename A> using F = std::function<A>;
template<typename A, typename B> using P = std::pair<A, B>;
using pii = P<int, int>;
using vi = V<int>;
using vd = V<double>;
using vs = V<std::string>;
using vpii = V<pii>;
using vvi = V<vi>;
using vvpii = V<vpii>;
constexpr int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000;
constexpr int MOD = 1000000007;
constexpr double PI = 3.14159265358979;
template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; }
template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; }
constexpr bool odd(const int n) { return n & 1; }
constexpr bool even(const int n) { return ~n & 1; }
template<typename T> std::istream &operator>>(std::istream &is, std::vector<T> &v) { for (T &x : v) is >> x; return is; }
template<typename A, typename B> std::istream &operator>>(std::istream &is, std::pair<A, B> &p) { is >> p.first; is >> p.second; return is; }
using namespace std;
// clang-format on
using Flow = int;
struct FlowEdge {
int src, dst;
Flow cap;
int rev;
FlowEdge(const int s = 0, const int d = 0, const Flow c = 0, const int r = 0)
: src(s), dst(d), cap(c), rev(r) {}
};
using FlowEdges = std::vector<FlowEdge>;
class FlowGraph {
std::vector<FlowEdges> g;
public:
FlowGraph(const int size = 0) : g(size) {}
size_t size() const { return g.size(); }
FlowEdges &operator[](const int i) & { return g[i]; }
void addEdge(const int src, const int dst, const Flow c = 1) {
g[src].emplace_back(src, dst, c, g[dst].size());
g[dst].emplace_back(dst, src, 0, g[src].size() - 1);
}
};
template <Flow inf = std::numeric_limits<Flow>::max()>
Flow dinic(FlowGraph g, const int source, const int sink) {
std::vector<int> level(g.size()), iter(g.size());
auto bfs = [&] {
std::fill(level.begin(), level.end(), -1);
std::queue<int> q;
level[source] = 0;
q.push(source);
while (q.size()) {
int v = q.front();
q.pop();
for (auto &e : g[v]) {
if (e.cap <= 0 || level[e.dst] >= 0)
continue;
level[e.dst] = level[v] + 1;
q.push(e.dst);
}
}
return level[sink] != -1;
};
std::function<Flow(int, Flow)> dfs = [&](int v, Flow f) -> Flow {
if (v == sink)
return f;
Flow s = 0;
for (; iter[v] < g[v].size(); iter[v]++) {
auto &e = g[v][iter[v]];
if (level[v] >= level[e.dst] || e.cap <= 0)
continue;
Flow d = dfs(e.dst, min(f, e.cap));
e.cap -= d;
g[e.dst][e.rev].cap += d;
s += d;
f -= d;
if (f == 0)
break;
}
return s;
};
Flow s = 0;
while (bfs()) {
std::fill(iter.begin(), iter.end(), 0);
s += dfs(source, inf);
}
return s;
}
main {
int n, m;
cin >> n >> m;
FlowGraph g(n);
while (m--) {
int a, b, c;
cin >> a >> b >> c;
g.addEdge(a, b, c);
}
cout << dinic(g, 0, n - 1) << endl;
} | replace | 81 | 82 | 81 | 82 | -11 | |
p02376 | C++ | Time Limit Exceeded |
#include <cinttypes>
#include <iostream>
#include <limits>
#include <memory>
#include <vector>
const std::size_t InfiniteSize = std::numeric_limits<std::size_t>::max();
template <typename T> class Network {
protected:
virtual void setSource(std::size_t source) = 0;
virtual void setTarget(std::size_t target) = 0;
virtual void addBareEdge(std::size_t from, std::size_t to, T capacity) = 0;
class InternalIterator;
public:
class Iterator;
virtual std::size_t VerticeCount() = 0;
virtual std::size_t EdgeCount() = 0;
virtual std::size_t Source() = 0;
virtual std::size_t Target() = 0;
virtual void ClearFlow() = 0;
virtual Iterator IterateOutgoingEdgesAt(std::size_t from) = 0;
virtual Iterator IterateIncomingEdgesAt(std::size_t to) = 0;
virtual ~Network() = default;
};
template <typename T> class Network<T>::InternalIterator {
protected:
virtual void advance() = 0;
virtual bool ended() = 0;
virtual std::unique_ptr<InternalIterator> copy() = 0;
friend class Iterator;
public:
virtual std::size_t Source() = 0;
virtual std::size_t Target() = 0;
virtual T Capacity() = 0;
virtual T Flow() = 0;
virtual void AddFlow(T amount) = 0;
virtual ~InternalIterator() = default;
};
template <typename T> class Network<T>::Iterator {
std::unique_ptr<InternalIterator> internal_;
public:
Iterator(std::unique_ptr<InternalIterator> internal);
Iterator(Iterator &other);
Iterator(Iterator &&other) = default;
Iterator &operator=(Iterator &other);
Iterator &operator=(Iterator &&other) = default;
InternalIterator *operator->();
Iterator &operator++();
Iterator operator++(int);
operator bool();
};
template <typename T>
std::ostream &operator<<(std::ostream &out, Network<T> &network);
template <typename T>
std::ostream &operator<<(std::ostream &out, Network<T> &network) {
out << "digraph G" << std::endl;
out << "{" << std::endl;
out << "\t" << network.Source() << " [color=green]" << std::endl;
out << "\t" << network.Target() << " [shape=box]" << std::endl;
for (std::size_t i = 0; i < network.VerticeCount(); ++i) {
auto it = network.IterateOutgoingEdgesAt(i);
while (it) {
out << "\t" << it->Source() << " -> " << it->Target() << " ";
out << "[label=\"";
out << it->Flow();
out << "/";
out << it->Capacity();
out << "\"]" << std::endl;
++it;
}
}
out << "}" << std::endl;
return out;
}
template <typename T>
Network<T>::Iterator::Iterator(std::unique_ptr<InternalIterator> internal)
: internal_(std::move(internal)) {}
template <typename T>
Network<T>::Iterator::Iterator(Iterator &other)
: internal_(other.internal_->copy()) {}
template <typename T>
auto Network<T>::Iterator::operator=(Iterator &other) -> Iterator & {
internal_ = other.internal_.copy();
return *this;
}
template <typename T>
auto Network<T>::Iterator::operator->() -> InternalIterator * {
return &*internal_;
}
template <typename T> auto Network<T>::Iterator::operator++() -> Iterator & {
internal_->advance();
return *this;
}
template <typename T> auto Network<T>::Iterator::operator++(int) -> Iterator {
Iterator copy(internal_->copy());
++*this;
return copy;
}
template <typename T> Network<T>::Iterator::operator bool() {
return !internal_->ended();
}
#include <cinttypes>
#include <vector>
template <typename T> class EdgeListNetwork : public Network<T> {
protected:
std::size_t verticeCount_;
std::size_t edgeCount_;
std::size_t source_;
std::size_t target_;
// Edge properties
std::vector<std::size_t> from_;
std::vector<std::size_t> to_;
std::vector<T> capacity_;
std::vector<T> flow_;
std::vector<std::size_t> firstEdgeFrom_;
std::vector<std::size_t> nextEdgeFrom_;
std::vector<std::size_t> firstEdgeTo_;
std::vector<std::size_t> nextEdgeTo_;
template <template <typename> class ConcreteNetwork, typename T1>
friend class NetworkBuilder;
explicit EdgeListNetwork(std::size_t vertices);
void setSource(std::size_t source) override;
void setTarget(std::size_t target) override;
void addBareEdge(std::size_t from, std::size_t to, T capacity) override;
public:
class InternalIterator;
std::size_t VerticeCount() override;
std::size_t EdgeCount() override;
std::size_t Source() override;
std::size_t Target() override;
void ClearFlow() override;
typename Network<T>::Iterator
IterateOutgoingEdgesAt(std::size_t from) override;
typename Network<T>::Iterator IterateIncomingEdgesAt(std::size_t to) override;
};
template <typename T>
class EdgeListNetwork<T>::InternalIterator
: public Network<T>::InternalIterator {
std::size_t edgeIndex_;
EdgeListNetwork<T> *network_;
bool outgoing_;
bool ended_;
InternalIterator(std::size_t index, EdgeListNetwork<T> *network,
bool outgoing);
void advance() override;
bool ended() override;
std::unique_ptr<typename Network<T>::InternalIterator> copy() override;
friend class EdgeListNetwork<T>;
public:
std::size_t Source() override;
std::size_t Target() override;
T Capacity() override;
T Flow() override;
void AddFlow(T amount) override;
};
template <typename T>
EdgeListNetwork<T>::EdgeListNetwork(std::size_t vertices)
: verticeCount_(vertices), edgeCount_(0),
firstEdgeFrom_(vertices, InfiniteSize),
firstEdgeTo_(vertices, InfiniteSize) {}
template <typename T> void EdgeListNetwork<T>::setSource(std::size_t source) {
source_ = source;
}
template <typename T> void EdgeListNetwork<T>::setTarget(std::size_t target) {
target_ = target;
}
template <typename T>
void EdgeListNetwork<T>::addBareEdge(std::size_t from, std::size_t to,
T capacity) {
if (firstEdgeFrom_[from] != InfiniteSize)
nextEdgeFrom_.push_back(firstEdgeFrom_[from]);
else
nextEdgeFrom_.push_back(edgeCount_);
if (firstEdgeTo_[to] != InfiniteSize)
nextEdgeTo_.push_back(firstEdgeTo_[to]);
else
nextEdgeTo_.push_back(edgeCount_);
firstEdgeFrom_[from] = edgeCount_;
firstEdgeTo_[to] = edgeCount_;
from_.push_back(from);
to_.push_back(to);
capacity_.push_back(capacity);
flow_.push_back(T(0));
++edgeCount_;
}
template <typename T> std::size_t EdgeListNetwork<T>::VerticeCount() {
return verticeCount_;
}
template <typename T> std::size_t EdgeListNetwork<T>::EdgeCount() {
return edgeCount_;
}
template <typename T> std::size_t EdgeListNetwork<T>::Source() {
return source_;
}
template <typename T> std::size_t EdgeListNetwork<T>::Target() {
return target_;
}
template <typename T> void EdgeListNetwork<T>::ClearFlow() {
flow_.assign(flow_.size(), 0);
}
template <typename T>
auto EdgeListNetwork<T>::IterateOutgoingEdgesAt(std::size_t from) ->
typename Network<T>::Iterator {
return typename Network<T>::Iterator(std::unique_ptr<InternalIterator>(
new InternalIterator(firstEdgeFrom_[from], this, true)));
}
template <typename T>
auto EdgeListNetwork<T>::IterateIncomingEdgesAt(std::size_t to) ->
typename Network<T>::Iterator {
return typename Network<T>::Iterator(std::unique_ptr<InternalIterator>(
new InternalIterator(firstEdgeTo_[to], this, false)));
}
template <typename T>
EdgeListNetwork<T>::InternalIterator::InternalIterator(
std::size_t index, EdgeListNetwork<T> *network, bool outgoing)
: edgeIndex_(index), network_(network), outgoing_(outgoing),
ended_(index == InfiniteSize) {}
template <typename T> T EdgeListNetwork<T>::InternalIterator::Capacity() {
return network_->capacity_[edgeIndex_];
}
template <typename T> T EdgeListNetwork<T>::InternalIterator::Flow() {
return network_->flow_[edgeIndex_];
}
template <typename T>
std::size_t EdgeListNetwork<T>::InternalIterator::Source() {
return network_->from_[edgeIndex_];
}
template <typename T>
std::size_t EdgeListNetwork<T>::InternalIterator::Target() {
return network_->to_[edgeIndex_];
}
template <typename T>
void EdgeListNetwork<T>::InternalIterator::AddFlow(T amount) {
network_->flow_[edgeIndex_] += amount;
network_->flow_[edgeIndex_ ^ 1] -= amount;
}
template <typename T> void EdgeListNetwork<T>::InternalIterator::advance() {
auto nextIndex = outgoing_ ? network_->nextEdgeFrom_[edgeIndex_]
: network_->nextEdgeTo_[edgeIndex_];
if (edgeIndex_ == nextIndex)
ended_ = true;
edgeIndex_ = nextIndex;
}
template <typename T> bool EdgeListNetwork<T>::InternalIterator::ended() {
return ended_;
}
template <typename T>
std::unique_ptr<typename Network<T>::InternalIterator>
EdgeListNetwork<T>::InternalIterator::copy() {
std::unique_ptr<InternalIterator> copy(
new InternalIterator(edgeIndex_, network_, outgoing_));
copy->ended_ = ended_;
return copy;
}
#include <memory>
template <template <typename> class ConcreteNetwork, typename T>
class NetworkBuilder {
std::size_t source_;
std::size_t target_;
std::vector<std::vector<T>> adjacencyMatrix_;
using OwnType = NetworkBuilder<ConcreteNetwork, T>;
public:
NetworkBuilder &Initialize(std::size_t vertices);
NetworkBuilder &SetSource(std::size_t source);
NetworkBuilder &SetTarget(std::size_t target);
NetworkBuilder &AddCapacity(std::size_t from, std::size_t to, T capacity);
std::unique_ptr<ConcreteNetwork<T>> Finalize();
};
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::Initialize(std::size_t vertices)
-> OwnType & {
adjacencyMatrix_.assign(vertices, std::vector<T>(vertices, T(0)));
return *this;
}
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::SetSource(std::size_t source)
-> OwnType & {
source_ = source;
return *this;
}
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::SetTarget(std::size_t target)
-> OwnType & {
target_ = target;
return *this;
}
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::AddCapacity(std::size_t from,
std::size_t to, T capacity)
-> OwnType & {
adjacencyMatrix_[from][to] += capacity;
return *this;
}
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::Finalize()
-> std::unique_ptr<ConcreteNetwork<T>> {
std::unique_ptr<ConcreteNetwork<T>> network(
new ConcreteNetwork<T>(adjacencyMatrix_.size()));
network->setSource(source_);
network->setTarget(target_);
for (std::size_t i = 0; i < adjacencyMatrix_.size(); ++i) {
for (std::size_t j = i + 1; j < adjacencyMatrix_[i].size(); ++j) {
if (adjacencyMatrix_[i][j] <= 0 && adjacencyMatrix_[j][i] <= 0)
continue;
network->addBareEdge(i, j, adjacencyMatrix_[i][j]);
network->addBareEdge(j, i, adjacencyMatrix_[j][i]);
}
}
return network;
}
template <typename T> class MaxFlowAlgorithm {
protected:
std::shared_ptr<Network<T>> network_;
public:
virtual void Initialize(std::shared_ptr<Network<T>> network);
std::shared_ptr<Network<T>> GetNetwork();
T GetFlow();
virtual void Calculate() = 0;
};
template <typename T>
void MaxFlowAlgorithm<T>::Initialize(std::shared_ptr<Network<T>> network) {
network_ = network;
}
template <typename T>
std::shared_ptr<Network<T>> MaxFlowAlgorithm<T>::GetNetwork() {
return network_;
}
template <typename T> T MaxFlowAlgorithm<T>::GetFlow() {
T flow = 0;
for (auto it = network_->IterateOutgoingEdgesAt(network_->Source()); it;
++it) {
flow += it->Flow();
}
return flow;
}
#include <cmath>
template <typename T> class PreflowPush : public MaxFlowAlgorithm<T> {
using Iterator = typename Network<T>::Iterator;
std::vector<T> overflows_;
std::vector<std::size_t> heights_;
std::vector<Iterator> iterators_;
std::size_t overflownCount_;
bool fromSourceOrTarget(Iterator edge);
bool toSourceOrTarget(Iterator edge);
void discharge(std::size_t vertice);
void fixupOverflows(Iterator edge, T pushed);
bool canPush(Iterator edge);
void push(Iterator edge);
void relabel(std::size_t vertice);
public:
void Initialize(std::shared_ptr<Network<T>> network) override;
void Calculate() override;
};
template <typename T>
void PreflowPush<T>::Initialize(std::shared_ptr<Network<T>> network) {
overflows_.assign(network->VerticeCount(), 0);
heights_.assign(network->VerticeCount(), 0);
overflownCount_ = 0;
MaxFlowAlgorithm<T>::Initialize(network);
iterators_.reserve(network->VerticeCount());
for (std::size_t i = 0; i < network->VerticeCount(); ++i) {
iterators_.push_back(network->IterateOutgoingEdgesAt(i));
}
}
template <typename T> bool PreflowPush<T>::fromSourceOrTarget(Iterator edge) {
return edge->Source() == this->network_->Source() ||
edge->Source() == this->network_->Target();
}
template <typename T> bool PreflowPush<T>::toSourceOrTarget(Iterator edge) {
return edge->Target() == this->network_->Source() ||
edge->Target() == this->network_->Target();
}
template <typename T> void PreflowPush<T>::discharge(std::size_t vertice) {
while (overflows_[vertice] > 0) {
if (iterators_[vertice]) {
push(iterators_[vertice]);
++iterators_[vertice];
} else {
relabel(vertice);
iterators_[vertice] = this->network_->IterateOutgoingEdgesAt(vertice);
}
}
}
template <typename T> bool PreflowPush<T>::canPush(Iterator edge) {
return heights_[edge->Source()] == heights_[edge->Target()] + 1 &&
edge->Flow() < edge->Capacity() &&
(overflows_[edge->Source()] > 0 ||
edge->Source() == this->network_->Source());
}
template <typename T>
void PreflowPush<T>::fixupOverflows(Iterator edge, T pushed) {
if (!fromSourceOrTarget(edge)) {
if (overflows_[edge->Source()] == pushed)
--overflownCount_;
overflows_[edge->Source()] -= pushed;
}
if (!toSourceOrTarget(edge)) {
if (overflows_[edge->Target()] == 0)
++overflownCount_;
overflows_[edge->Target()] += pushed;
}
}
template <typename T> void PreflowPush<T>::push(Iterator edge) {
if (!canPush(edge))
return;
T pushable =
std::min(edge->Capacity() - edge->Flow(), overflows_[edge->Source()]);
if (edge->Source() == this->network_->Source())
pushable = edge->Capacity() - edge->Flow();
edge->AddFlow(pushable);
fixupOverflows(edge, pushable);
}
template <typename T> void PreflowPush<T>::relabel(std::size_t vertice) {
std::size_t m = this->network_->VerticeCount();
for (auto it = this->network_->IterateOutgoingEdgesAt(vertice); it; ++it) {
if (it->Flow() >= it->Capacity())
continue;
if (canPush(it))
return;
m = std::min(m, heights_[it->Target()]);
}
heights_[vertice] = m + 1;
}
template <typename T> void PreflowPush<T>::Calculate() {
Network<T> &network = *this->network_;
heights_[network.Source()] = 1;
for (auto it = network.IterateOutgoingEdgesAt(network.Source()); it; ++it) {
push(it);
}
heights_[network.Source()] = network.VerticeCount();
while (overflownCount_ > 0) {
for (std::size_t i = 0; i < network.VerticeCount(); ++i) {
discharge(i);
}
}
}
using Type = long long;
int main() {
std::size_t vertCount = 0;
std::size_t edgeCount = 0;
std::cin >> vertCount >> edgeCount;
NetworkBuilder<EdgeListNetwork, Type> builder;
builder.Initialize(vertCount).SetSource(0).SetTarget(vertCount - 1);
for (std::size_t i = 0; i < edgeCount; ++i) {
std::size_t from = 0;
std::size_t to = 0;
Type cap = 0;
std::cin >> from >> to >> cap;
builder.AddCapacity(from, to, cap);
}
std::shared_ptr<Network<Type>> network(builder.Finalize());
PreflowPush<Type> algorithm;
algorithm.Initialize(network);
algorithm.Calculate();
Type answer = algorithm.GetFlow();
std::cout << answer << std::endl;
return 0;
}
|
#include <cinttypes>
#include <iostream>
#include <limits>
#include <memory>
#include <vector>
const std::size_t InfiniteSize = std::numeric_limits<std::size_t>::max();
template <typename T> class Network {
protected:
virtual void setSource(std::size_t source) = 0;
virtual void setTarget(std::size_t target) = 0;
virtual void addBareEdge(std::size_t from, std::size_t to, T capacity) = 0;
class InternalIterator;
public:
class Iterator;
virtual std::size_t VerticeCount() = 0;
virtual std::size_t EdgeCount() = 0;
virtual std::size_t Source() = 0;
virtual std::size_t Target() = 0;
virtual void ClearFlow() = 0;
virtual Iterator IterateOutgoingEdgesAt(std::size_t from) = 0;
virtual Iterator IterateIncomingEdgesAt(std::size_t to) = 0;
virtual ~Network() = default;
};
template <typename T> class Network<T>::InternalIterator {
protected:
virtual void advance() = 0;
virtual bool ended() = 0;
virtual std::unique_ptr<InternalIterator> copy() = 0;
friend class Iterator;
public:
virtual std::size_t Source() = 0;
virtual std::size_t Target() = 0;
virtual T Capacity() = 0;
virtual T Flow() = 0;
virtual void AddFlow(T amount) = 0;
virtual ~InternalIterator() = default;
};
template <typename T> class Network<T>::Iterator {
std::unique_ptr<InternalIterator> internal_;
public:
Iterator(std::unique_ptr<InternalIterator> internal);
Iterator(Iterator &other);
Iterator(Iterator &&other) = default;
Iterator &operator=(Iterator &other);
Iterator &operator=(Iterator &&other) = default;
InternalIterator *operator->();
Iterator &operator++();
Iterator operator++(int);
operator bool();
};
template <typename T>
std::ostream &operator<<(std::ostream &out, Network<T> &network);
template <typename T>
std::ostream &operator<<(std::ostream &out, Network<T> &network) {
out << "digraph G" << std::endl;
out << "{" << std::endl;
out << "\t" << network.Source() << " [color=green]" << std::endl;
out << "\t" << network.Target() << " [shape=box]" << std::endl;
for (std::size_t i = 0; i < network.VerticeCount(); ++i) {
auto it = network.IterateOutgoingEdgesAt(i);
while (it) {
out << "\t" << it->Source() << " -> " << it->Target() << " ";
out << "[label=\"";
out << it->Flow();
out << "/";
out << it->Capacity();
out << "\"]" << std::endl;
++it;
}
}
out << "}" << std::endl;
return out;
}
template <typename T>
Network<T>::Iterator::Iterator(std::unique_ptr<InternalIterator> internal)
: internal_(std::move(internal)) {}
template <typename T>
Network<T>::Iterator::Iterator(Iterator &other)
: internal_(other.internal_->copy()) {}
template <typename T>
auto Network<T>::Iterator::operator=(Iterator &other) -> Iterator & {
internal_ = other.internal_.copy();
return *this;
}
template <typename T>
auto Network<T>::Iterator::operator->() -> InternalIterator * {
return &*internal_;
}
template <typename T> auto Network<T>::Iterator::operator++() -> Iterator & {
internal_->advance();
return *this;
}
template <typename T> auto Network<T>::Iterator::operator++(int) -> Iterator {
Iterator copy(internal_->copy());
++*this;
return copy;
}
template <typename T> Network<T>::Iterator::operator bool() {
return !internal_->ended();
}
#include <cinttypes>
#include <vector>
template <typename T> class EdgeListNetwork : public Network<T> {
protected:
std::size_t verticeCount_;
std::size_t edgeCount_;
std::size_t source_;
std::size_t target_;
// Edge properties
std::vector<std::size_t> from_;
std::vector<std::size_t> to_;
std::vector<T> capacity_;
std::vector<T> flow_;
std::vector<std::size_t> firstEdgeFrom_;
std::vector<std::size_t> nextEdgeFrom_;
std::vector<std::size_t> firstEdgeTo_;
std::vector<std::size_t> nextEdgeTo_;
template <template <typename> class ConcreteNetwork, typename T1>
friend class NetworkBuilder;
explicit EdgeListNetwork(std::size_t vertices);
void setSource(std::size_t source) override;
void setTarget(std::size_t target) override;
void addBareEdge(std::size_t from, std::size_t to, T capacity) override;
public:
class InternalIterator;
std::size_t VerticeCount() override;
std::size_t EdgeCount() override;
std::size_t Source() override;
std::size_t Target() override;
void ClearFlow() override;
typename Network<T>::Iterator
IterateOutgoingEdgesAt(std::size_t from) override;
typename Network<T>::Iterator IterateIncomingEdgesAt(std::size_t to) override;
};
template <typename T>
class EdgeListNetwork<T>::InternalIterator
: public Network<T>::InternalIterator {
std::size_t edgeIndex_;
EdgeListNetwork<T> *network_;
bool outgoing_;
bool ended_;
InternalIterator(std::size_t index, EdgeListNetwork<T> *network,
bool outgoing);
void advance() override;
bool ended() override;
std::unique_ptr<typename Network<T>::InternalIterator> copy() override;
friend class EdgeListNetwork<T>;
public:
std::size_t Source() override;
std::size_t Target() override;
T Capacity() override;
T Flow() override;
void AddFlow(T amount) override;
};
template <typename T>
EdgeListNetwork<T>::EdgeListNetwork(std::size_t vertices)
: verticeCount_(vertices), edgeCount_(0),
firstEdgeFrom_(vertices, InfiniteSize),
firstEdgeTo_(vertices, InfiniteSize) {}
template <typename T> void EdgeListNetwork<T>::setSource(std::size_t source) {
source_ = source;
}
template <typename T> void EdgeListNetwork<T>::setTarget(std::size_t target) {
target_ = target;
}
template <typename T>
void EdgeListNetwork<T>::addBareEdge(std::size_t from, std::size_t to,
T capacity) {
if (firstEdgeFrom_[from] != InfiniteSize)
nextEdgeFrom_.push_back(firstEdgeFrom_[from]);
else
nextEdgeFrom_.push_back(edgeCount_);
if (firstEdgeTo_[to] != InfiniteSize)
nextEdgeTo_.push_back(firstEdgeTo_[to]);
else
nextEdgeTo_.push_back(edgeCount_);
firstEdgeFrom_[from] = edgeCount_;
firstEdgeTo_[to] = edgeCount_;
from_.push_back(from);
to_.push_back(to);
capacity_.push_back(capacity);
flow_.push_back(T(0));
++edgeCount_;
}
template <typename T> std::size_t EdgeListNetwork<T>::VerticeCount() {
return verticeCount_;
}
template <typename T> std::size_t EdgeListNetwork<T>::EdgeCount() {
return edgeCount_;
}
template <typename T> std::size_t EdgeListNetwork<T>::Source() {
return source_;
}
template <typename T> std::size_t EdgeListNetwork<T>::Target() {
return target_;
}
template <typename T> void EdgeListNetwork<T>::ClearFlow() {
flow_.assign(flow_.size(), 0);
}
template <typename T>
auto EdgeListNetwork<T>::IterateOutgoingEdgesAt(std::size_t from) ->
typename Network<T>::Iterator {
return typename Network<T>::Iterator(std::unique_ptr<InternalIterator>(
new InternalIterator(firstEdgeFrom_[from], this, true)));
}
template <typename T>
auto EdgeListNetwork<T>::IterateIncomingEdgesAt(std::size_t to) ->
typename Network<T>::Iterator {
return typename Network<T>::Iterator(std::unique_ptr<InternalIterator>(
new InternalIterator(firstEdgeTo_[to], this, false)));
}
template <typename T>
EdgeListNetwork<T>::InternalIterator::InternalIterator(
std::size_t index, EdgeListNetwork<T> *network, bool outgoing)
: edgeIndex_(index), network_(network), outgoing_(outgoing),
ended_(index == InfiniteSize) {}
template <typename T> T EdgeListNetwork<T>::InternalIterator::Capacity() {
return network_->capacity_[edgeIndex_];
}
template <typename T> T EdgeListNetwork<T>::InternalIterator::Flow() {
return network_->flow_[edgeIndex_];
}
template <typename T>
std::size_t EdgeListNetwork<T>::InternalIterator::Source() {
return network_->from_[edgeIndex_];
}
template <typename T>
std::size_t EdgeListNetwork<T>::InternalIterator::Target() {
return network_->to_[edgeIndex_];
}
template <typename T>
void EdgeListNetwork<T>::InternalIterator::AddFlow(T amount) {
network_->flow_[edgeIndex_] += amount;
network_->flow_[edgeIndex_ ^ 1] -= amount;
}
template <typename T> void EdgeListNetwork<T>::InternalIterator::advance() {
auto nextIndex = outgoing_ ? network_->nextEdgeFrom_[edgeIndex_]
: network_->nextEdgeTo_[edgeIndex_];
if (edgeIndex_ == nextIndex)
ended_ = true;
edgeIndex_ = nextIndex;
}
template <typename T> bool EdgeListNetwork<T>::InternalIterator::ended() {
return ended_;
}
template <typename T>
std::unique_ptr<typename Network<T>::InternalIterator>
EdgeListNetwork<T>::InternalIterator::copy() {
std::unique_ptr<InternalIterator> copy(
new InternalIterator(edgeIndex_, network_, outgoing_));
copy->ended_ = ended_;
return copy;
}
#include <memory>
template <template <typename> class ConcreteNetwork, typename T>
class NetworkBuilder {
std::size_t source_;
std::size_t target_;
std::vector<std::vector<T>> adjacencyMatrix_;
using OwnType = NetworkBuilder<ConcreteNetwork, T>;
public:
NetworkBuilder &Initialize(std::size_t vertices);
NetworkBuilder &SetSource(std::size_t source);
NetworkBuilder &SetTarget(std::size_t target);
NetworkBuilder &AddCapacity(std::size_t from, std::size_t to, T capacity);
std::unique_ptr<ConcreteNetwork<T>> Finalize();
};
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::Initialize(std::size_t vertices)
-> OwnType & {
adjacencyMatrix_.assign(vertices, std::vector<T>(vertices, T(0)));
return *this;
}
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::SetSource(std::size_t source)
-> OwnType & {
source_ = source;
return *this;
}
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::SetTarget(std::size_t target)
-> OwnType & {
target_ = target;
return *this;
}
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::AddCapacity(std::size_t from,
std::size_t to, T capacity)
-> OwnType & {
adjacencyMatrix_[from][to] += capacity;
return *this;
}
template <template <typename> class ConcreteNetwork, typename T>
auto NetworkBuilder<ConcreteNetwork, T>::Finalize()
-> std::unique_ptr<ConcreteNetwork<T>> {
std::unique_ptr<ConcreteNetwork<T>> network(
new ConcreteNetwork<T>(adjacencyMatrix_.size()));
network->setSource(source_);
network->setTarget(target_);
for (std::size_t i = 0; i < adjacencyMatrix_.size(); ++i) {
for (std::size_t j = i + 1; j < adjacencyMatrix_[i].size(); ++j) {
if (adjacencyMatrix_[i][j] <= 0 && adjacencyMatrix_[j][i] <= 0)
continue;
network->addBareEdge(i, j, adjacencyMatrix_[i][j]);
network->addBareEdge(j, i, adjacencyMatrix_[j][i]);
}
}
return network;
}
template <typename T> class MaxFlowAlgorithm {
protected:
std::shared_ptr<Network<T>> network_;
public:
virtual void Initialize(std::shared_ptr<Network<T>> network);
std::shared_ptr<Network<T>> GetNetwork();
T GetFlow();
virtual void Calculate() = 0;
};
template <typename T>
void MaxFlowAlgorithm<T>::Initialize(std::shared_ptr<Network<T>> network) {
network_ = network;
}
template <typename T>
std::shared_ptr<Network<T>> MaxFlowAlgorithm<T>::GetNetwork() {
return network_;
}
template <typename T> T MaxFlowAlgorithm<T>::GetFlow() {
T flow = 0;
for (auto it = network_->IterateOutgoingEdgesAt(network_->Source()); it;
++it) {
flow += it->Flow();
}
return flow;
}
#include <cmath>
template <typename T> class PreflowPush : public MaxFlowAlgorithm<T> {
using Iterator = typename Network<T>::Iterator;
std::vector<T> overflows_;
std::vector<std::size_t> heights_;
std::vector<Iterator> iterators_;
std::size_t overflownCount_;
bool fromSourceOrTarget(Iterator edge);
bool toSourceOrTarget(Iterator edge);
void discharge(std::size_t vertice);
void fixupOverflows(Iterator edge, T pushed);
bool canPush(Iterator edge);
void push(Iterator edge);
void relabel(std::size_t vertice);
public:
void Initialize(std::shared_ptr<Network<T>> network) override;
void Calculate() override;
};
template <typename T>
void PreflowPush<T>::Initialize(std::shared_ptr<Network<T>> network) {
overflows_.assign(network->VerticeCount(), 0);
heights_.assign(network->VerticeCount(), 0);
overflownCount_ = 0;
MaxFlowAlgorithm<T>::Initialize(network);
iterators_.reserve(network->VerticeCount());
for (std::size_t i = 0; i < network->VerticeCount(); ++i) {
iterators_.push_back(network->IterateOutgoingEdgesAt(i));
}
}
template <typename T> bool PreflowPush<T>::fromSourceOrTarget(Iterator edge) {
return edge->Source() == this->network_->Source() ||
edge->Source() == this->network_->Target();
}
template <typename T> bool PreflowPush<T>::toSourceOrTarget(Iterator edge) {
return edge->Target() == this->network_->Source() ||
edge->Target() == this->network_->Target();
}
template <typename T> void PreflowPush<T>::discharge(std::size_t vertice) {
while (overflows_[vertice] > 0) {
if (iterators_[vertice]) {
push(iterators_[vertice]);
++iterators_[vertice];
} else {
relabel(vertice);
iterators_[vertice] = this->network_->IterateOutgoingEdgesAt(vertice);
}
}
}
template <typename T> bool PreflowPush<T>::canPush(Iterator edge) {
return heights_[edge->Source()] == heights_[edge->Target()] + 1 &&
edge->Flow() < edge->Capacity() &&
(overflows_[edge->Source()] > 0 ||
edge->Source() == this->network_->Source());
}
template <typename T>
void PreflowPush<T>::fixupOverflows(Iterator edge, T pushed) {
if (!fromSourceOrTarget(edge)) {
if (overflows_[edge->Source()] == pushed)
--overflownCount_;
overflows_[edge->Source()] -= pushed;
}
if (!toSourceOrTarget(edge)) {
if (overflows_[edge->Target()] == 0)
++overflownCount_;
overflows_[edge->Target()] += pushed;
}
}
template <typename T> void PreflowPush<T>::push(Iterator edge) {
if (!canPush(edge))
return;
T pushable =
std::min(edge->Capacity() - edge->Flow(), overflows_[edge->Source()]);
if (edge->Source() == this->network_->Source())
pushable = edge->Capacity() - edge->Flow();
edge->AddFlow(pushable);
fixupOverflows(edge, pushable);
}
template <typename T> void PreflowPush<T>::relabel(std::size_t vertice) {
std::size_t m = 2 * this->network_->VerticeCount();
for (auto it = this->network_->IterateOutgoingEdgesAt(vertice); it; ++it) {
if (it->Flow() >= it->Capacity())
continue;
if (canPush(it))
return;
m = std::min(m, heights_[it->Target()]);
}
heights_[vertice] = m + 1;
}
template <typename T> void PreflowPush<T>::Calculate() {
Network<T> &network = *this->network_;
heights_[network.Source()] = 1;
for (auto it = network.IterateOutgoingEdgesAt(network.Source()); it; ++it) {
push(it);
}
heights_[network.Source()] = network.VerticeCount();
while (overflownCount_ > 0) {
for (std::size_t i = 0; i < network.VerticeCount(); ++i) {
discharge(i);
}
}
}
using Type = long long;
int main() {
std::size_t vertCount = 0;
std::size_t edgeCount = 0;
std::cin >> vertCount >> edgeCount;
NetworkBuilder<EdgeListNetwork, Type> builder;
builder.Initialize(vertCount).SetSource(0).SetTarget(vertCount - 1);
for (std::size_t i = 0; i < edgeCount; ++i) {
std::size_t from = 0;
std::size_t to = 0;
Type cap = 0;
std::cin >> from >> to >> cap;
builder.AddCapacity(from, to, cap);
}
std::shared_ptr<Network<Type>> network(builder.Finalize());
PreflowPush<Type> algorithm;
algorithm.Initialize(network);
algorithm.Calculate();
Type answer = algorithm.GetFlow();
std::cout << answer << std::endl;
return 0;
}
| replace | 526 | 527 | 526 | 527 | TLE | |
p02376 | C++ | Time Limit Exceeded | #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(|E||V|^2)
class Dinic {
struct Edge {
const unsigned int to; // 行き先
long long flow; // 流量
const long long cap; // 容量
const unsigned int rev; // 逆辺
const bool is_rev; // 逆辺かどうか
Edge(unsigned int to, long long flow, long long cap, unsigned int rev,
bool is_rev)
: to(to), flow(flow), cap(cap), rev(rev), is_rev(is_rev) {
assert(this->cap >= 0);
}
};
vector<vector<Edge>> graph; // グラフの隣接リスト表現
vector<int> level; // sからの距離
vector<int> iter; // dfsがどこまで進んだか
public:
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);
}
// fromからtoへ向かう容量capの辺をグラフに追加する
void add_edge(unsigned int from, unsigned int to, long long cap) {
graph[from].push_back(
Edge(to, 0, cap, (unsigned int)graph[to].size(), false));
graph[to].push_back(
Edge(from, cap, cap, (unsigned int)graph[from].size() - 1, true));
}
// sからtへの最大流を求める
long long max_flow(unsigned int s, unsigned int t) {
long long flow = 0;
while (true) {
// 残余ネットワーク上でsから各ノードへの距離を求める
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:
// 残余ネットワーク上でsから全ノードへの最短距離をBFSで計算する
void bfs(unsigned int s) {
fill(level.begin(), level.end(), -1);
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 && level.at(e.to) < 0) {
level.at(e.to) = level.at(v) + 1;
que.push(e.to);
}
}
}
}
// vからtへf流す
long long dfs(unsigned int v, unsigned int t, long long f) {
if (v == t) {
return f;
}
for (int &i = iter.at(v); i < graph.at(v).size(); ++i) {
Edge &e = graph.at(v).at(i);
// 流せてかつ最短経路が長くなるようなやつのみ
if (e.cap > 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;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int V, E;
cin >> V >> E;
Dinic dinic(V);
for (int i = 0; i < E; i++) {
int u, v, c;
cin >> u >> v >> c;
dinic.add_edge(u, v, c);
}
cout << dinic.max_flow(0, V - 1) << endl;
return 0;
}
| #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(|E||V|^2)
class Dinic {
struct Edge {
const unsigned int to; // 行き先
long long flow; // 流量
const long long cap; // 容量
const unsigned int rev; // 逆辺
const bool is_rev; // 逆辺かどうか
Edge(unsigned int to, long long flow, long long cap, unsigned int rev,
bool is_rev)
: to(to), flow(flow), cap(cap), rev(rev), is_rev(is_rev) {
assert(this->cap >= 0);
}
};
vector<vector<Edge>> graph; // グラフの隣接リスト表現
vector<int> level; // sからの距離
vector<int> iter; // dfsがどこまで進んだか
public:
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);
}
// fromからtoへ向かう容量capの辺をグラフに追加する
void add_edge(unsigned int from, unsigned int to, long long cap) {
graph[from].push_back(
Edge(to, 0, cap, (unsigned int)graph[to].size(), false));
graph[to].push_back(
Edge(from, cap, cap, (unsigned int)graph[from].size() - 1, true));
}
// sからtへの最大流を求める
long long max_flow(unsigned int s, unsigned int t) {
long long flow = 0;
while (true) {
// 残余ネットワーク上でsから各ノードへの距離を求める
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:
// 残余ネットワーク上でsから全ノードへの最短距離をBFSで計算する
void bfs(unsigned int s) {
fill(level.begin(), level.end(), -1);
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 && level.at(e.to) < 0) {
level.at(e.to) = level.at(v) + 1;
que.push(e.to);
}
}
}
}
// vからtへf流す
long long dfs(unsigned int v, unsigned int t, long long f) {
if (v == t) {
return f;
}
for (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;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int V, E;
cin >> V >> E;
Dinic dinic(V);
for (int i = 0; i < E; i++) {
int u, v, c;
cin >> u >> v >> c;
dinic.add_edge(u, v, c);
}
cout << dinic.max_flow(0, V - 1) << endl;
return 0;
}
| replace | 119 | 120 | 119 | 120 | TLE | |
p02376 | C++ | Time Limit Exceeded | #include <bits/stdc++.h>
#define vi vector<int>
#define vvi vector<vector<int>>
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vb vector<bool>
#define vc vector<char>
#define vs vector<string>
using ll = long long;
using ld = long double;
#define int ll
#define INF 1e9
#define EPS 0.0000000001
#define rep(i, n) for (int i = 0; i < n; i++)
#define loop(i, s, n) for (int i = s; i < n; i++)
#define all(in) in.begin(), in.end()
template <class T, class S> void cmin(T &a, const S &b) {
if (a > b)
a = b;
}
template <class T, class S> void cmax(T &a, const S &b) {
if (a < b)
a = b;
}
#define MAX 9999999
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int W, H;
bool inrange(int x, int y) { return (0 <= x && x < W) && (0 <= y && y < H); }
using namespace std;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
#define MP make_pair
struct edge {
int to, cap, rev;
}; // ikisaki youryou gyakuhen
class Dinic { // max flow
public:
int n;
vector<vector<edge>> G; //[MAX];
vi level, iter; //[MAX];
Dinic(int size) {
n = size;
G = vector<vector<edge>>(n);
}
void add_edge(int from, int to, int cap) {
edge q = {to, cap, int(G[to].size())};
G[from].push_back(q);
q = {from, 0, int(G[from].size() - 1)};
G[to].push_back(q);
}
int getmaxflow(int s, int t) { // from s to t,ford_fulkerson
int flow = 0;
while (1) {
bfs(s);
if (level[t] < 0)
return flow;
iter = vi(n);
int f;
while ((f = dfs(s, t, INF)) > 0)
flow += f;
}
}
private:
void bfs(int s) {
level = vi(n, -1);
queue<int> q;
level[s] = 0;
q.push(s);
while (!q.empty()) {
int v = q.front();
q.pop();
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1;
q.push(e.to);
}
}
}
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
for (int &i = iter[v]; i < G[v].size(); i++) {
edge &e = G[v][i];
if (level[v] >= level[e.to] || e.cap <= 0)
continue;
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
return 0;
}
};
signed main() {
int v, e;
Dinic yebi(v + 1);
rep(i, e) {
int a, b, c;
cin >> a >> b >> c;
yebi.add_edge(a, b, c);
}
cout << yebi.getmaxflow(0, v - 1) << endl;
}
| #include <bits/stdc++.h>
#define vi vector<int>
#define vvi vector<vector<int>>
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vb vector<bool>
#define vc vector<char>
#define vs vector<string>
using ll = long long;
using ld = long double;
#define int ll
#define INF 1e9
#define EPS 0.0000000001
#define rep(i, n) for (int i = 0; i < n; i++)
#define loop(i, s, n) for (int i = s; i < n; i++)
#define all(in) in.begin(), in.end()
template <class T, class S> void cmin(T &a, const S &b) {
if (a > b)
a = b;
}
template <class T, class S> void cmax(T &a, const S &b) {
if (a < b)
a = b;
}
#define MAX 9999999
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int W, H;
bool inrange(int x, int y) { return (0 <= x && x < W) && (0 <= y && y < H); }
using namespace std;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
#define MP make_pair
struct edge {
int to, cap, rev;
}; // ikisaki youryou gyakuhen
class Dinic { // max flow
public:
int n;
vector<vector<edge>> G; //[MAX];
vi level, iter; //[MAX];
Dinic(int size) {
n = size;
G = vector<vector<edge>>(n);
}
void add_edge(int from, int to, int cap) {
edge q = {to, cap, int(G[to].size())};
G[from].push_back(q);
q = {from, 0, int(G[from].size() - 1)};
G[to].push_back(q);
}
int getmaxflow(int s, int t) { // from s to t,ford_fulkerson
int flow = 0;
while (1) {
bfs(s);
if (level[t] < 0)
return flow;
iter = vi(n);
int f;
while ((f = dfs(s, t, INF)) > 0)
flow += f;
}
}
private:
void bfs(int s) {
level = vi(n, -1);
queue<int> q;
level[s] = 0;
q.push(s);
while (!q.empty()) {
int v = q.front();
q.pop();
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1;
q.push(e.to);
}
}
}
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
for (int &i = iter[v]; i < G[v].size(); i++) {
edge &e = G[v][i];
if (level[v] >= level[e.to] || e.cap <= 0)
continue;
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
return 0;
}
};
signed main() {
int v, e;
cin >> v >> e;
Dinic yebi(v + 1);
rep(i, e) {
int a, b, c;
cin >> a >> b >> c;
yebi.add_edge(a, b, c);
}
cout << yebi.getmaxflow(0, v - 1) << endl;
}
| insert | 102 | 102 | 102 | 103 | TLE | |
p02376 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); i++)
using namespace std;
typedef pair<int, int> pii;
const int INF = 0x3fffffff;
class Flow {
public:
int N;
vector<vector<int>> F, C, edge;
Flow(int n, int e)
: F(n, vector<int>(n)), C(n, vector<int>(n)), N(n), edge(e) {}
void addEdge(int f, int t, int c) {
F[f][t] = C[f][t] = c;
edge[f].push_back(t);
edge[t].push_back(f);
}
int flow(int n, int c, int T, vector<bool> &bf) {
if (n == T)
return c;
bf[n] = true;
for (int i : edge[n])
if (F[n][i] > 0 && !bf[i]) {
int f = flow(i, min(c, F[n][i]), T, bf);
F[n][i] -= f;
F[i][n] += f;
if (f > 0)
return f;
}
return 0;
}
int maxFlow(int S, int T) {
int ret = 0;
vector<bool> bf(N);
for (int add; add = flow(0, INF, T, bf); bf.assign(N, 0))
ret += add;
return ret;
}
void clear() { rep(i, N) rep(j, N) F[i][j] = C[i][j]; }
};
int main() {
int V, E;
cin >> V >> E;
Flow fl(V, E);
for (int i = 1; i <= E; i++) {
int u, v, c;
cin >> u >> v >> c;
fl.addEdge(u, v, c);
}
cout << fl.maxFlow(0, V - 1) << endl;
return 0;
} | #include <algorithm>
#include <iostream>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); i++)
using namespace std;
typedef pair<int, int> pii;
const int INF = 0x3fffffff;
class Flow {
public:
int N;
vector<vector<int>> F, C, edge;
Flow(int n, int e)
: F(n, vector<int>(n)), C(n, vector<int>(n)), N(n), edge(n) {}
void addEdge(int f, int t, int c) {
F[f][t] = C[f][t] = c;
edge[f].push_back(t);
edge[t].push_back(f);
}
int flow(int n, int c, int T, vector<bool> &bf) {
if (n == T)
return c;
bf[n] = true;
for (int i : edge[n])
if (F[n][i] > 0 && !bf[i]) {
int f = flow(i, min(c, F[n][i]), T, bf);
F[n][i] -= f;
F[i][n] += f;
if (f > 0)
return f;
}
return 0;
}
int maxFlow(int S, int T) {
int ret = 0;
vector<bool> bf(N);
for (int add; add = flow(0, INF, T, bf); bf.assign(N, 0))
ret += add;
return ret;
}
void clear() { rep(i, N) rep(j, N) F[i][j] = C[i][j]; }
};
int main() {
int V, E;
cin >> V >> E;
Flow fl(V, E);
for (int i = 1; i <= E; i++) {
int u, v, c;
cin >> u >> v >> c;
fl.addEdge(u, v, c);
}
cout << fl.maxFlow(0, V - 1) << endl;
return 0;
} | replace | 16 | 17 | 16 | 17 | 0 | |
p02376 | C++ | Time Limit Exceeded | #include <algorithm>
#include <iostream>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); i++)
using namespace std;
typedef pair<int, int> pii;
const int INF = 0x3fffffff;
class Flow {
public:
int N, en;
vector<int> C, F;
vector<vector<pii>> edge;
Flow(int n, int e) : C(e + 1), F(e + 1), N(n), edge(n) { en = 0; }
void addEdge(int f, int t, int c) {
en++;
edge[f].emplace_back(t, en);
edge[t].emplace_back(f, -en);
C[en] = c;
}
int flow(int n, int c, int T, vector<bool> bf) {
if (n == T)
return c;
bf[n] = true;
for (auto to : edge[n]) {
int i = to.second;
int cc = (i > 0 ? C[i] - F[i] : F[-i]);
if (bf[to.first] || cc == 0)
continue;
int f = flow(to.first, min(c, cc), T, bf);
if (f > 0) {
F[abs(i)] += f * (i / abs(i));
return f;
}
}
return 0;
}
int maxFlow(int S, int T) {
for (int ret = 0;;) {
vector<bool> bf(N);
int add = flow(0, INF, T, bf);
ret += add;
if (add == 0)
return ret;
}
}
void clear() { fill(F.begin(), F.end(), 0); }
};
int V, E;
int C[1005];
int F[1005];
vector<pii> e[105];
int solve(int n, int c, bool bf[105]) {
if (n == V - 1)
return c;
bf[n] = true;
for (auto to : e[n]) {
int i = to.second;
int cc = (i > 0 ? C[i] - F[i] : F[-i]);
if (bf[to.first] || cc == 0)
continue;
int flow = solve(to.first, min(c, cc), bf);
if (flow > 0) {
F[abs(i)] += flow * (i / abs(i));
return flow;
}
}
return 0;
}
int main() {
cin >> V >> E;
Flow fl(V, E);
for (int i = 1; i <= E; i++) {
int u, v, c;
cin >> u >> v >> c;
// e[u].emplace_back(v, i);
// e[v].emplace_back(u, -i);
// C[i] = c;
fl.addEdge(u, v, c);
}
// int ans = 0;
// while(1){
// bool bf[105] = {};
// int add = solve(0, INF, bf);
// ans += add;
// if( add == 0 ) break;
// }
cout << fl.maxFlow(0, V - 1) << endl;
return 0;
} | #include <algorithm>
#include <iostream>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); i++)
using namespace std;
typedef pair<int, int> pii;
const int INF = 0x3fffffff;
class Flow {
public:
int N, en;
vector<int> C, F;
vector<vector<pii>> edge;
Flow(int n, int e) : C(e + 1), F(e + 1), N(n), edge(n) { en = 0; }
void addEdge(int f, int t, int c) {
en++;
edge[f].emplace_back(t, en);
edge[t].emplace_back(f, -en);
C[en] = c;
}
int flow(int n, int c, int T, vector<bool> &bf) {
if (n == T)
return c;
bf[n] = true;
for (auto to : edge[n]) {
int i = to.second;
int cc = (i > 0 ? C[i] - F[i] : F[-i]);
if (bf[to.first] || cc == 0)
continue;
int f = flow(to.first, min(c, cc), T, bf);
if (f > 0) {
F[abs(i)] += f * (i / abs(i));
return f;
}
}
return 0;
}
int maxFlow(int S, int T) {
for (int ret = 0;;) {
vector<bool> bf(N);
int add = flow(0, INF, T, bf);
ret += add;
if (add == 0)
return ret;
}
}
void clear() { fill(F.begin(), F.end(), 0); }
};
int V, E;
int C[1005];
int F[1005];
vector<pii> e[105];
int solve(int n, int c, bool bf[105]) {
if (n == V - 1)
return c;
bf[n] = true;
for (auto to : e[n]) {
int i = to.second;
int cc = (i > 0 ? C[i] - F[i] : F[-i]);
if (bf[to.first] || cc == 0)
continue;
int flow = solve(to.first, min(c, cc), bf);
if (flow > 0) {
F[abs(i)] += flow * (i / abs(i));
return flow;
}
}
return 0;
}
int main() {
cin >> V >> E;
Flow fl(V, E);
for (int i = 1; i <= E; i++) {
int u, v, c;
cin >> u >> v >> c;
// e[u].emplace_back(v, i);
// e[v].emplace_back(u, -i);
// C[i] = c;
fl.addEdge(u, v, c);
}
// int ans = 0;
// while(1){
// bool bf[105] = {};
// int add = solve(0, INF, bf);
// ans += add;
// if( add == 0 ) break;
// }
cout << fl.maxFlow(0, V - 1) << endl;
return 0;
} | replace | 23 | 24 | 23 | 24 | TLE | |
p02376 | C++ | Time Limit Exceeded | #include <bits/stdc++.h>
#pragma warning(disable : 4996)
#ifdef _MSC_VER
#define __builtin_popcount __popcnt
#endif
#define int long long
using namespace std;
using ll = long long;
using ld = long double;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
inline void my_io() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
cout << fixed << setprecision(10);
}
const int INF = numeric_limits<int>::max();
struct edge {
int from, to, cap, rev;
};
vector<vector<edge>> g; // グラフの隣接リスト表現
vector<int> level; // sからの距離(辺何本分離れているか)
vector<int> iter; // どこまで調べ終わったか
int v, e;
void add_edge(int from, int to, int cap) { // from→to 容量capの辺をグラフに追加
g[from].push_back(edge{from, to, cap, (int)g[to].size()});
g[to].push_back(edge{to, from, 0, (int)g[from].size() - 1});
}
void dinic_bfs(int s) { // sからの最短距離(辺何本分離れているか)をbfsで計算する
fill(level.begin(), level.end(), -1);
queue<int> que;
level[s] = 0;
que.push(s);
while (!que.empty()) {
int v = que.front();
que.pop();
for (int i = 0; i < g[v].size(); i++) {
edge &e = g[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
int dinic_dfs(int v, int t, int f) { // 増加パスをdfsで探す
if (v == t) {
return f;
}
for (int &i = iter[v]; i < g[v].size(); i++) {
edge &e = g[v][i];
if (e.cap > 0 && level[v] > level[e.to]) {
int d = dinic_dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
g[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
for (;;) {
dinic_bfs(s);
if (level[t] < 0) {
return flow;
}
fill(iter.begin(), iter.end(), 0);
int f;
while ((f = dinic_dfs(s, t, INF)) > 0) {
flow += f;
}
}
}
signed main() {
cin >> v >> e;
g.resize(v);
level.resize(v);
iter.resize(v);
for (int i = 0; i < e; i++) {
int from, to, cap;
cin >> from >> to >> cap;
add_edge(from, to, cap);
}
cout << max_flow(0, v - 1) << endl;
return 0;
}
| #include <bits/stdc++.h>
#pragma warning(disable : 4996)
#ifdef _MSC_VER
#define __builtin_popcount __popcnt
#endif
#define int long long
using namespace std;
using ll = long long;
using ld = long double;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
inline void my_io() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
cout << fixed << setprecision(10);
}
const int INF = numeric_limits<int>::max();
struct edge {
int from, to, cap, rev;
};
vector<vector<edge>> g; // グラフの隣接リスト表現
vector<int> level; // sからの距離(辺何本分離れているか)
vector<int> iter; // どこまで調べ終わったか
int v, e;
void add_edge(int from, int to, int cap) { // from→to 容量capの辺をグラフに追加
g[from].push_back(edge{from, to, cap, (int)g[to].size()});
g[to].push_back(edge{to, from, 0, (int)g[from].size() - 1});
}
void dinic_bfs(int s) { // sからの最短距離(辺何本分離れているか)をbfsで計算する
fill(level.begin(), level.end(), -1);
queue<int> que;
level[s] = 0;
que.push(s);
while (!que.empty()) {
int v = que.front();
que.pop();
for (int i = 0; i < g[v].size(); i++) {
edge &e = g[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
int dinic_dfs(int v, int t, int f) { // 増加パスをdfsで探す
if (v == t) {
return f;
}
for (int &i = iter[v]; i < g[v].size(); i++) {
edge &e = g[v][i];
if (e.cap > 0 && level[v] < level[e.to]) {
int d = dinic_dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
g[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
for (;;) {
dinic_bfs(s);
if (level[t] < 0) {
return flow;
}
fill(iter.begin(), iter.end(), 0);
int f;
while ((f = dinic_dfs(s, t, INF)) > 0) {
flow += f;
}
}
}
signed main() {
cin >> v >> e;
g.resize(v);
level.resize(v);
iter.resize(v);
for (int i = 0; i < e; i++) {
int from, to, cap;
cin >> from >> to >> cap;
add_edge(from, to, cap);
}
cout << max_flow(0, v - 1) << endl;
return 0;
}
| replace | 51 | 52 | 51 | 52 | TLE | |
p02376 | C++ | Time Limit Exceeded | #include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#define INF (1 << 29)
#define max_n 10000
using namespace std;
struct edge {
int to, cap, rev;
};
struct LinkCutTree {
vector<int> left, right, parent, val, mini, minId, lazy;
vector<edge *> edges;
LinkCutTree(int n, int v)
: left(n, -1), right(n, -1), parent(n, -1), val(n, v), mini(n, INF),
minId(n, -1), lazy(n, 0), edges(n, NULL) {}
void push(int id) {
int l = left[id], r = right[id];
if (l >= 0)
lazy[l] += lazy[id];
if (r >= 0)
lazy[r] += lazy[id];
val[id] += lazy[id], mini[id] += lazy[id], lazy[id] = 0;
}
void update_min(int id, int ch) {
if (mini[id] > mini[ch])
mini[id] = mini[ch], minId[id] = minId[ch];
}
void update(int id) {
int l = left[id], r = right[id];
mini[id] = val[id], minId[id] = id, push(id);
if (l >= 0)
push(l), update_min(id, l);
if (r >= 0)
push(r), update_min(id, r);
}
bool is_root(int id) {
return parent[id] < 0 ||
(left[parent[id]] != id && right[parent[id]] != id);
}
void connect(int ch, int p, bool isL) {
(isL ? left : right)[p] = ch;
if (ch >= 0)
parent[ch] = p;
}
void rotate(int id) {
int p = parent[id], q = parent[p];
push(p), push(id);
bool isL = id == left[p], isRoot = is_root(p);
connect((isL ? right : left)[id], p, isL);
connect(p, id, !isL);
// if(!isRoot)connect(id,q,p==left[q]);
// else parent[id]=q;
parent[id] = q;
update(p);
}
void splay(int id) {
while (!is_root(id)) {
int p = parent[id];
if (!is_root(p))
rotate((id == left[p]) ^ (p == left[parent[p]]) ? p : id);
rotate(id);
}
update(id);
}
int expose(int id) {
int last = -1;
for (int y = id; y >= 0; y = parent[y])
splay(y), left[y] = last, last = y;
splay(id);
return last;
}
int find_root(int id) {
expose(id);
while (right[id] != -1)
id = right[id];
return id;
}
void link(int ch, int p) {
expose(ch);
expose(p);
if (right[ch] >= 0)
return;
parent[ch] = p;
left[p] = ch;
}
void link(int c, int p, int v, edge *e) {
link(c, p);
val[c] = v;
update(c);
edges[c] = e;
}
void cut(int id) {
expose(id);
if (right[id] < 0)
return;
parent[right[id]] = -1;
right[id] = -1;
val[id] = INF;
}
int lca(int ch, int p) {
expose(ch);
return expose(p);
}
int getMinId(int id) {
expose(id);
return minId[id];
}
void add(int id, int val) {
expose(id);
lazy[id] = val;
}
};
vector<edge> g[max_n];
void add_edge(int from, int to, int cap) {
g[from].push_back((edge){to, cap, (int)g[to].size()});
g[to].push_back((edge){from, 0, (int)g[from].size() - 1});
}
int dist[max_n];
bool bfs(int s, int t) {
fill(dist, dist + max_n, -1);
dist[s] = 0;
queue<int> que;
que.push(s);
while (!que.empty()) {
int u = que.front();
que.pop();
if (u == t)
return true;
for (int j = 0; j < g[u].size(); j++) {
edge e = g[u][j];
if (dist[e.to] < 0 && e.cap > 0) {
dist[e.to] = dist[u] + 1;
que.push(e.to);
}
}
}
return false;
}
int n, ptr[max_n];
vector<int> lists[max_n];
bool pour(int id, int i, LinkCutTree *tree) {
int u = lists[id][i];
if (tree->find_root(u) == u)
return true;
edge *e = tree->edges[u];
tree->expose(u);
int df = e->cap - tree->val[u];
e->cap -= df;
g[e->to][e->rev].cap += df;
return false;
}
int max_flow(int s, int t) {
int flow = 0;
while (bfs(s, t)) {
fill(ptr, ptr + max_n, 0);
LinkCutTree tree(n, INF);
for (int i = 0; i < n; i++)
lists[i].clear();
while (true) {
int v = tree.find_root(s);
if (v == t) {
v = tree.getMinId(s);
tree.expose(v);
flow += tree.mini[v];
tree.add(s, -tree.mini[v]);
while (true) {
v = tree.getMinId(s);
if (tree.val[v] > 0)
break;
g[tree.edges[v]->to][tree.edges[v]->rev].cap += tree.edges[v]->cap;
tree.edges[v]->cap = 0;
tree.cut(v);
}
continue;
}
if (ptr[v] < g[v].size()) {
edge &e = g[v][ptr[v]++];
if (dist[e.to] == dist[v] + 1 && e.cap > 0) {
tree.link(v, e.to, e.cap, &e);
lists[e.to].push_back(v);
}
} else {
if (v == s) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < lists[i].size(); j++)
pour(i, j, &tree);
lists[i].clear();
}
break;
}
for (int i = 0; i < lists[v].size(); i++) {
if (!pour(v, i, &tree))
tree.cut(lists[v][i]);
}
lists[v].clear();
}
}
}
return flow;
}
// AOJ GRL_6_A
int main(void) {
int e;
cin >> n >> e;
for (int i = 0; i < e; i++) {
int a, b, c;
cin >> a >> b >> c;
add_edge(a, b, c);
}
cout << max_flow(0, n - 1) << endl;
;
return 0;
} | #include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#define INF (1 << 29)
#define max_n 10000
using namespace std;
struct edge {
int to, cap, rev;
};
struct LinkCutTree {
vector<int> left, right, parent, val, mini, minId, lazy;
vector<edge *> edges;
LinkCutTree(int n, int v)
: left(n, -1), right(n, -1), parent(n, -1), val(n, v), mini(n, INF),
minId(n, -1), lazy(n, 0), edges(n, NULL) {}
void push(int id) {
int l = left[id], r = right[id];
if (l >= 0)
lazy[l] += lazy[id];
if (r >= 0)
lazy[r] += lazy[id];
val[id] += lazy[id], mini[id] += lazy[id], lazy[id] = 0;
}
void update_min(int id, int ch) {
if (mini[id] > mini[ch])
mini[id] = mini[ch], minId[id] = minId[ch];
}
void update(int id) {
int l = left[id], r = right[id];
mini[id] = val[id], minId[id] = id, push(id);
if (l >= 0)
push(l), update_min(id, l);
if (r >= 0)
push(r), update_min(id, r);
}
bool is_root(int id) {
return parent[id] < 0 ||
(left[parent[id]] != id && right[parent[id]] != id);
}
void connect(int ch, int p, bool isL) {
(isL ? left : right)[p] = ch;
if (ch >= 0)
parent[ch] = p;
}
void rotate(int id) {
int p = parent[id], q = parent[p];
push(p), push(id);
bool isL = id == left[p], isRoot = is_root(p);
connect((isL ? right : left)[id], p, isL);
connect(p, id, !isL);
if (!isRoot)
connect(id, q, p == left[q]);
else
parent[id] = q;
update(p);
}
void splay(int id) {
while (!is_root(id)) {
int p = parent[id];
if (!is_root(p))
rotate((id == left[p]) ^ (p == left[parent[p]]) ? p : id);
rotate(id);
}
update(id);
}
int expose(int id) {
int last = -1;
for (int y = id; y >= 0; y = parent[y])
splay(y), left[y] = last, last = y;
splay(id);
return last;
}
int find_root(int id) {
expose(id);
while (right[id] != -1)
id = right[id];
return id;
}
void link(int ch, int p) {
expose(ch);
expose(p);
if (right[ch] >= 0)
return;
parent[ch] = p;
left[p] = ch;
}
void link(int c, int p, int v, edge *e) {
link(c, p);
val[c] = v;
update(c);
edges[c] = e;
}
void cut(int id) {
expose(id);
if (right[id] < 0)
return;
parent[right[id]] = -1;
right[id] = -1;
val[id] = INF;
}
int lca(int ch, int p) {
expose(ch);
return expose(p);
}
int getMinId(int id) {
expose(id);
return minId[id];
}
void add(int id, int val) {
expose(id);
lazy[id] = val;
}
};
vector<edge> g[max_n];
void add_edge(int from, int to, int cap) {
g[from].push_back((edge){to, cap, (int)g[to].size()});
g[to].push_back((edge){from, 0, (int)g[from].size() - 1});
}
int dist[max_n];
bool bfs(int s, int t) {
fill(dist, dist + max_n, -1);
dist[s] = 0;
queue<int> que;
que.push(s);
while (!que.empty()) {
int u = que.front();
que.pop();
if (u == t)
return true;
for (int j = 0; j < g[u].size(); j++) {
edge e = g[u][j];
if (dist[e.to] < 0 && e.cap > 0) {
dist[e.to] = dist[u] + 1;
que.push(e.to);
}
}
}
return false;
}
int n, ptr[max_n];
vector<int> lists[max_n];
bool pour(int id, int i, LinkCutTree *tree) {
int u = lists[id][i];
if (tree->find_root(u) == u)
return true;
edge *e = tree->edges[u];
tree->expose(u);
int df = e->cap - tree->val[u];
e->cap -= df;
g[e->to][e->rev].cap += df;
return false;
}
int max_flow(int s, int t) {
int flow = 0;
while (bfs(s, t)) {
fill(ptr, ptr + max_n, 0);
LinkCutTree tree(n, INF);
for (int i = 0; i < n; i++)
lists[i].clear();
while (true) {
int v = tree.find_root(s);
if (v == t) {
v = tree.getMinId(s);
tree.expose(v);
flow += tree.mini[v];
tree.add(s, -tree.mini[v]);
while (true) {
v = tree.getMinId(s);
if (tree.val[v] > 0)
break;
g[tree.edges[v]->to][tree.edges[v]->rev].cap += tree.edges[v]->cap;
tree.edges[v]->cap = 0;
tree.cut(v);
}
continue;
}
if (ptr[v] < g[v].size()) {
edge &e = g[v][ptr[v]++];
if (dist[e.to] == dist[v] + 1 && e.cap > 0) {
tree.link(v, e.to, e.cap, &e);
lists[e.to].push_back(v);
}
} else {
if (v == s) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < lists[i].size(); j++)
pour(i, j, &tree);
lists[i].clear();
}
break;
}
for (int i = 0; i < lists[v].size(); i++) {
if (!pour(v, i, &tree))
tree.cut(lists[v][i]);
}
lists[v].clear();
}
}
}
return flow;
}
// AOJ GRL_6_A
int main(void) {
int e;
cin >> n >> e;
for (int i = 0; i < e; i++) {
int a, b, c;
cin >> a >> b >> c;
add_edge(a, b, c);
}
cout << max_flow(0, n - 1) << endl;
;
return 0;
} | replace | 61 | 64 | 61 | 65 | TLE | |
p02376 | C++ | Runtime Error | #include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <queue>
#include <string>
#include <vector>
// УБРАТЬ!
using namespace std;
// Net class:
template <class Edge> class Net {
private:
typedef Edge *EdgePointer;
typedef pair<EdgePointer, EdgePointer> Arc;
list<Arc> edges;
vector<list<Arc>> innerEdges;
vector<list<Arc>> outerEdges;
class UniversalEdgeIterator {
friend class Net;
private:
list<Arc> *edgesList;
typename list<Arc>::iterator edgeIterator;
bool validated;
enum UniversalIteratorType { inner, outer, all };
UniversalIteratorType iteratorType;
UniversalEdgeIterator(list<Arc> *edgesList,
const UniversalIteratorType &getIteratorType) {
this->edgesList = edgesList;
this->iteratorType = iteratorType;
validated = false;
}
void validate() {
if (validated)
return;
else {
validated = true;
begin();
}
}
public:
typedef UniversalIteratorType IteratorType;
UniversalEdgeIterator() {
edgesList = nullptr;
validated = false;
}
// Iterator methods:
void begin() { edgeIterator = edgesList->begin(); }
void move() { edgeIterator = next(edgeIterator); }
bool end() const {
return edgesList->size() == 0 || edgeIterator == edgesList->end();
}
// Getters:
Edge getEdge() const {
// cout << "s" << edgesList->size() << endl;
return *(*edgeIterator).first;
}
Edge getReversedEdge() const { return *(*edgeIterator).second; }
// Setter:
void increaseFlow(const typename Edge::FlowType &delta) const {
(*edgeIterator).first->flow += delta;
(*edgeIterator).second->flow -= delta;
}
// Other:
IteratorType getIteratorType() const { return iteratorType; }
};
UniversalEdgeIterator allEdgesIterator;
vector<UniversalEdgeIterator> innerEdgesIterators;
vector<UniversalEdgeIterator> outerEdgesIterators;
public:
typedef UniversalEdgeIterator EdgeIterator;
typedef typename Edge::IndexType IndexType;
IndexType source;
IndexType sink;
// Constructors, destructors:
Net(const IndexType &verticesCount) {
allEdgesIterator = EdgeIterator(&edges, EdgeIterator::IteratorType::all);
innerEdges.resize(verticesCount);
outerEdges.resize(verticesCount);
innerEdgesIterators.resize(verticesCount);
outerEdgesIterators.resize(verticesCount);
for (unsigned i = 0; i < verticesCount; i++) {
innerEdgesIterators[i] =
EdgeIterator(&innerEdges[i], EdgeIterator::IteratorType::inner);
outerEdgesIterators[i] =
EdgeIterator(&outerEdges[i], EdgeIterator::IteratorType::outer);
}
}
~Net() {
for (const Arc &arc : edges)
delete arc.first;
}
// Setters:
void addEdge(const Edge &edge) {
EdgePointer edgePointer = new Edge(edge);
EdgePointer reversedEdgePointer = new Edge(edge.reversed());
edges.push_back(make_pair(edgePointer, reversedEdgePointer));
outerEdges[edgePointer->from].push_back(
make_pair(edgePointer, reversedEdgePointer));
innerEdges[edgePointer->to].push_back(
make_pair(edgePointer, reversedEdgePointer));
edges.push_back(make_pair(reversedEdgePointer, edgePointer));
outerEdges[reversedEdgePointer->from].push_back(
make_pair(reversedEdgePointer, edgePointer));
innerEdges[reversedEdgePointer->to].push_back(
make_pair(reversedEdgePointer, edgePointer));
allEdgesIterator.validate();
outerEdgesIterators[edgePointer->from].validate();
outerEdgesIterators[edgePointer->to].validate();
innerEdgesIterators[edgePointer->from].validate();
innerEdgesIterators[edgePointer->to].validate();
}
// Getters:
EdgeIterator &getAllEdgesIterator() { return allEdgesIterator; }
EdgeIterator getConstAllEdgesIterator() const { return allEdgesIterator; }
EdgeIterator &getInnerEdgeIterator(const IndexType &vertex) {
return innerEdgesIterators[vertex];
}
EdgeIterator getConstInnerEdgeIterator(const IndexType &vertex) const {
return innerEdgesIterators[vertex];
}
EdgeIterator &getOuterEdgeIterator(const IndexType &vertex) {
return outerEdgesIterators[vertex];
}
EdgeIterator getConstOuterEdgeIterator(const IndexType &vertex) const {
return outerEdgesIterators[vertex];
}
// Info:
IndexType getVerticesCount() const { return innerEdges.size(); }
IndexType getEdgesCount() const { return edges.size(); }
};
// Flow addons:
template <class Edge>
const typename Edge::FlowType
getFlowFromOrToVertex(typename Net<Edge>::EdgeIterator iter) {
typename Edge::FlowType flow = 0;
for (iter.begin(); !iter.end(); iter.move())
flow += iter.getEdge().flow;
return flow;
}
template <class Edge> bool isFlowValid(const Net<Edge> &net) {
typename Net<Edge>::EdgeIterator iter = net.getConstAllEdgesIterator();
for (iter.begin(); !iter.end(); iter.move())
if (iter.getEdge().flow > iter.getEdge().capacity ||
iter.getEdge().flow != -iter.getReversedEdge().flow)
return false;
for (typename Edge::IndexType vertex = 0; vertex < net.getVerticesCount();
vertex++) {
if (vertex == net.source || vertex == net.sink)
break;
typename Edge::FlowType innerFlow =
getFlowFromOrToVertex<Edge>(net.getConstInnerEdgeIterator(vertex));
typename Edge::FlowType outerFlow =
getFlowFromOrToVertex<Edge>(net.getConstOuterEdgeIterator(vertex));
if (innerFlow != outerFlow)
return false;
}
return true;
}
template <class Edge>
typename Edge::FlowType getFlowWithoutCheck(const Net<Edge> &net) {
return getFlowFromOrToVertex<Edge>(net.getConstOuterEdgeIterator(net.source));
}
template <class Edge>
typename Edge::FlowType getFlowWithCheck(const Net<Edge> &net) {
if (isFlowValid(net))
return getFlowWithoutCheck(net);
else
throw("Net exeption: invalid flow!");
}
// Global discharge algorithm:
template <class Edge>
void push(Net<Edge> &net, const typename Net<Edge>::EdgeIterator &iter,
const typename Edge::FlowType &pushingFlow,
vector<typename Edge::FlowType> &excess) {
iter.increaseFlow(pushingFlow);
Edge edge = iter.getEdge();
if (edge.from != net.source && edge.from != net.sink)
excess[edge.from] -= pushingFlow;
if (edge.to != net.source && edge.to != net.sink)
excess[edge.to] += pushingFlow;
}
template <class Edge>
void relabel(const Net<Edge> &net, const typename Edge::IndexType &vertex,
vector<typename Edge::IndexType> &height) {
typename Edge::IndexType minHeight =
numeric_limits<typename Edge::IndexType>::max();
typename Net<Edge>::EdgeIterator iter = net.getConstOuterEdgeIterator(vertex);
for (iter.begin(); !iter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.residualCapacity() > 0)
minHeight = min<typename Edge::IndexType>(minHeight, height[edge.to]);
}
height[vertex] = minHeight + 1;
}
template <class Edge>
inline void discharge(Net<Edge> &net, const typename Edge::IndexType &vertex,
vector<typename Edge::FlowType> &excess,
vector<typename Edge::IndexType> &height) {
while (excess[vertex] > 0) {
typename Net<Edge>::EdgeIterator &iter = net.getOuterEdgeIterator(vertex);
if (iter.end()) {
relabel(net, vertex, height);
iter.begin();
}
else {
Edge edge = iter.getEdge();
if (edge.residualCapacity() > 0 &&
height[vertex] == height[edge.to] + 1) {
typename Edge::FlowType pushingFlow = min<typename Edge::FlowType>(
excess[edge.from], edge.residualCapacity());
push(net, iter, pushingFlow, excess);
}
else
iter.move();
}
}
}
template <class Edge> void setMaxFlowWithPreflowPush(Net<Edge> &net) {
vector<typename Edge::FlowType> excess(net.getVerticesCount(), 0);
vector<typename Edge::IndexType> height(net.getVerticesCount(), 0);
height[net.source] = net.getVerticesCount();
typename Net<Edge>::EdgeIterator iter =
net.getConstOuterEdgeIterator(net.source);
for (iter.begin(); !iter.end(); iter.move())
push(net, iter, iter.getEdge().residualCapacity(), excess);
while (true) {
bool discharged = false;
for (typename Edge::IndexType vertex = 0; vertex < net.getVerticesCount();
vertex++) {
if (excess[vertex] && vertex != net.source && vertex != net.sink) {
discharge(net, vertex, excess, height);
discharged = true;
}
}
if (!discharged)
break;
}
}
// Dinic Blocking flow algorithm:
template <class Edge>
typename Edge::FlowType
tryPushFlow(Net<Edge> &layeredNet, const typename Edge::IndexType &vertex,
const typename Edge::FlowType &pushingFlow =
numeric_limits<typename Edge::FlowType>::max()) {
if (vertex == layeredNet.sink || pushingFlow == 0)
return pushingFlow;
for (typename Net<Edge>::EdgeIterator iter =
layeredNet.getConstOuterEdgeIterator(vertex);
!iter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.capacity == 0)
continue;
typename Edge::FlowType newPushingFlow =
min<typename Edge::FlowType>(pushingFlow, edge.residualCapacity());
typename Edge::FlowType pushedFlow =
tryPushFlow(layeredNet, edge.to, newPushingFlow);
if (pushedFlow != 0) {
iter.increaseFlow(pushedFlow);
return pushedFlow;
}
}
if (!layeredNet.getOuterEdgeIterator(vertex).end())
layeredNet.getOuterEdgeIterator(vertex).move();
return 0;
}
template <class Edge> void setBlockingFlowWithDinic(Net<Edge> &layeredNet) {
while (tryPushFlow(layeredNet, layeredNet.source) != 0) {
};
}
// Malhotra-Kumar-Maheshwari Blocking flow algorithm:
template <class Edge>
inline typename Edge::FlowType
setPotentialOneSide(typename Net<Edge>::EdgeIterator iter) {
typename Edge::FlowType potential = 0;
for (iter.begin(); !iter.end(); iter.move())
potential += iter.getEdge().residualCapacity();
return potential;
}
template <class Edge>
inline typename Edge::FlowType
getPotential(const Net<Edge> &net, const typename Edge::IndexType &vertex,
const vector<typename Edge::FlowType> &innerPotential,
const vector<typename Edge::FlowType> &outerPotential) {
if (vertex == net.source)
return outerPotential[vertex];
else if (vertex == net.sink)
return innerPotential[vertex];
else
return min<typename Edge::FlowType>(outerPotential[vertex],
innerPotential[vertex]);
}
template <class Edge>
inline void deleteVertexOneSide(const Net<Edge> &layeredNet,
typename Net<Edge>::EdgeIterator iter,
vector<typename Edge::FlowType> &innerPotential,
vector<typename Edge::FlowType> &outerPotential,
vector<bool> &isDeleted) {
for (iter.begin(); !iter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.capacity == 0)
continue;
typename Edge::IndexType nextVertex =
(iter.getIteratorType() == Net<Edge>::EdgeIterator::IteratorType::outer
? edge.to
: edge.from);
(iter.getIteratorType() == Net<Edge>::EdgeIterator::IteratorType::outer
? innerPotential[nextVertex]
: outerPotential[nextVertex]) -= edge.residualCapacity();
if (getPotential(layeredNet, nextVertex, innerPotential, outerPotential) ==
0)
deleteVertex(layeredNet, nextVertex, innerPotential, outerPotential,
isDeleted);
}
}
template <class Edge>
void deleteVertex(const Net<Edge> &layeredNet,
const typename Edge::IndexType &vertex,
vector<typename Edge::FlowType> &innerPotential,
vector<typename Edge::FlowType> &outerPotential,
vector<bool> &isDeleted) {
if (isDeleted[vertex])
return;
isDeleted[vertex] = true;
deleteVertexOneSide<Edge>(layeredNet,
layeredNet.getConstOuterEdgeIterator(vertex),
innerPotential, outerPotential, isDeleted);
deleteVertexOneSide<Edge>(layeredNet,
layeredNet.getConstInnerEdgeIterator(vertex),
innerPotential, outerPotential, isDeleted);
}
template <typename Edge>
void pushFlowFromRoot(Net<Edge> &layeredNet,
const typename Edge::IndexType &root,
const typename Edge::FlowType &pushingFlow,
const typename Edge::IndexType &destination,
vector<typename Edge::FlowType> &innerPotential,
vector<typename Edge::FlowType> &outerPotential,
const vector<bool> &isDeleted) {
// BFS init:
queue<typename Edge::IndexType> verticesQueue;
vector<bool> used(layeredNet.getVerticesCount(), false);
verticesQueue.push(root);
used[root] = true;
// Other data init:
vector<typename Edge::FlowType> excessOrLack(layeredNet.getVerticesCount(),
0);
excessOrLack[root] = pushingFlow;
// BFS:
while (!verticesQueue.empty()) {
typename Edge::IndexType vertex = verticesQueue.front();
verticesQueue.pop();
if (vertex == destination)
break;
for (typename Net<Edge>::EdgeIterator &iter =
(destination == layeredNet.sink
? layeredNet.getOuterEdgeIterator(vertex)
: layeredNet.getInnerEdgeIterator(vertex));
!iter.end(); iter.move()) {
Edge edge = iter.getEdge();
typename Edge::IndexType nextVertex =
(destination == layeredNet.sink ? edge.to : edge.from);
if (edge.capacity > 0 && !isDeleted[nextVertex]) {
if (!used[nextVertex]) {
verticesQueue.push(nextVertex);
used[nextVertex] = true;
}
typename Edge::FlowType pushedFlow = min<typename Edge::FlowType>(
excessOrLack[vertex], edge.residualCapacity());
excessOrLack[vertex] -= pushedFlow;
excessOrLack[nextVertex] += pushedFlow;
iter.increaseFlow(pushedFlow);
outerPotential[edge.from] -= pushedFlow;
innerPotential[edge.to] -= pushedFlow;
}
if (excessOrLack[vertex] == 0)
break;
}
}
}
template <class Edge>
void setBlockingFlowWithMalhotraKumarMaheshwari(Net<Edge> &layeredNet) {
// Initialize potentials:
vector<typename Edge::FlowType> innerPotential(layeredNet.getVerticesCount());
vector<typename Edge::FlowType> outerPotential(layeredNet.getVerticesCount());
for (typename Edge::IndexType vertex = 0;
vertex < layeredNet.getVerticesCount(); vertex++) {
innerPotential[vertex] =
setPotentialOneSide<Edge>(layeredNet.getConstInnerEdgeIterator(vertex));
outerPotential[vertex] =
setPotentialOneSide<Edge>(layeredNet.getConstOuterEdgeIterator(vertex));
}
// Initialize deleted vertices:
vector<bool> isDeleted(layeredNet.getVerticesCount(), false);
// Main cycle:
while (true) {
// Deleting traverse:
for (typename Edge::IndexType vertex = 0;
vertex < layeredNet.getVerticesCount(); vertex++)
if (!isDeleted[vertex] &&
getPotential(layeredNet, vertex, innerPotential, outerPotential) == 0)
deleteVertex(layeredNet, vertex, innerPotential, outerPotential,
isDeleted);
if (isDeleted[layeredNet.source] || isDeleted[layeredNet.sink])
break;
// Finding root:
typename Edge::IndexType root = layeredNet.source;
for (typename Edge::IndexType vertex = 0;
vertex < layeredNet.getVerticesCount(); vertex++)
if (!isDeleted[vertex] &&
getPotential(layeredNet, vertex, innerPotential, outerPotential) <=
getPotential(layeredNet, root, innerPotential, outerPotential))
root = vertex;
typename Edge::FlowType rootPotential =
getPotential(layeredNet, root, innerPotential, outerPotential);
// Pushing flow through the root:
pushFlowFromRoot(layeredNet, root, rootPotential, layeredNet.sink,
innerPotential, outerPotential, isDeleted);
pushFlowFromRoot(layeredNet, root, rootPotential, layeredNet.source,
innerPotential, outerPotential, isDeleted);
}
}
// Global Max Flow augmenting paths algorithm:
template <class Edge> Net<Edge> buildLayeredNetwork(const Net<Edge> &net) {
// BFS init:
queue<typename Edge::IndexType> verticesQueue;
vector<bool> used(net.getVerticesCount(), false);
verticesQueue.push(net.source);
// Layered Net init:
Net<Edge> layeredNet(net.getVerticesCount());
layeredNet.source = net.source;
layeredNet.sink = net.sink;
vector<typename Edge::IndexType> layers(
net.getVerticesCount(), numeric_limits<typename Edge::IndexType>::max());
layers[net.source] = 0;
// BFS:
while (!verticesQueue.empty()) {
typename Edge::IndexType vertex = verticesQueue.front();
verticesQueue.pop();
if (used[vertex])
continue;
used[vertex] = true;
typename Net<Edge>::EdgeIterator iter =
net.getConstOuterEdgeIterator(vertex);
for (iter.begin(); !iter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.residualCapacity() > 0 &&
layers[edge.from] + 1 <= layers[edge.to]) {
verticesQueue.push(edge.to);
Edge residualEdge = edge;
residualEdge.capacity = edge.residualCapacity();
residualEdge.flow = 0;
layeredNet.addEdge(residualEdge);
layers[edge.to] = layers[edge.from] + 1;
}
}
}
return layeredNet;
}
// Класс bfs iterator, который будет делать все логику:
template <class Edge>
void transferFlowFromLayeredNetworkToNetwork(Net<Edge> &layeredNet,
Net<Edge> &net) {
// BFS init:
queue<typename Edge::IndexType> verticesQueue;
vector<bool> used(net.getVerticesCount(), false);
verticesQueue.push(net.source);
// Layered Net init:
vector<typename Edge::IndexType> layers(
net.getVerticesCount(), numeric_limits<typename Edge::IndexType>::max());
layers[net.source] = 0;
// BFS:
while (!verticesQueue.empty()) {
typename Edge::IndexType vertex = verticesQueue.front();
verticesQueue.pop();
if (used[vertex])
continue;
used[vertex] = true;
typename Net<Edge>::EdgeIterator iter =
net.getConstOuterEdgeIterator(vertex);
typename Net<Edge>::EdgeIterator &layeredNetIter =
layeredNet.getOuterEdgeIterator(vertex);
layeredNetIter.begin();
for (iter.begin(); !iter.end() && !layeredNetIter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.residualCapacity() > 0 &&
layers[edge.from] + 1 <= layers[edge.to]) {
verticesQueue.push(edge.to);
layers[edge.to] = layers[edge.from] + 1;
while (layeredNetIter.getEdge().capacity == 0)
layeredNetIter.move();
iter.increaseFlow(layeredNetIter.getEdge().flow);
layeredNetIter.move();
}
}
}
}
// Сделать классом с кастомным виртуальным blocking flow:
template <class Edge> void setMaxFlowWithAugmentingPaths(Net<Edge> &net) {
while (true) {
Net<Edge> layeredNet = buildLayeredNetwork(net);
setBlockingFlowWithMalhotraKumarMaheshwari(layeredNet);
if (getFlowWithCheck(layeredNet) == 0)
break;
else {
transferFlowFromLayeredNetworkToNetwork(layeredNet, net);
}
}
}
// --------------------------------------------------
// My custom Edge:
template <typename FirstType = unsigned, typename SecondType = long long>
struct Edge {
typedef FirstType IndexType;
typedef SecondType FlowType;
IndexType from;
IndexType to;
FlowType flow;
FlowType capacity;
Edge(const IndexType &from, const IndexType &to, const FlowType &capacity) {
this->from = from;
this->to = to;
this->flow = 0;
this->capacity = capacity;
}
FlowType residualCapacity() const { return capacity - flow; }
Edge reversed() const { return Edge(to, from, 0); }
};
// Custom inputs/outputs:
template <class Edge> void printEdge(const Edge &edge, ostream &os = cout) {
os << edge.from << " -> " << edge.to << " (" << edge.flow << "/"
<< edge.capacity << ")";
}
template <class Edge> void printNet(Net<Edge> &net, ostream &os = cout) {
for (typename Edge::IndexType vertex = 0; vertex < net.getVerticesCount();
vertex++) {
typename Net<Edge>::EdgeIterator iter =
net.getConstOuterEdgeIterator(vertex);
for (iter.begin(); !iter.end(); iter.move()) {
printEdge(iter.getEdge(), os);
os << " ";
}
os << endl;
}
}
/*
// Сделать нормальный input.
long long solve () {
unsigned verticesCount;
cin >> verticesCount;
const long long maxCapacity = verticesCount * 1000 + 1;
long long positiveSum = 0;
Net<Edge<unsigned, long long> > net(verticesCount + 2);
net.source = verticesCount;
net.sink = verticesCount + 1;
for (unsigned i = 0; i < verticesCount; i ++) {
long long usability;
cin >> usability;
if (usability > 0) {
positiveSum += usability;
net.addEdge(Edge<unsigned, long long>(net.source, i,
usability));
}
else
net.addEdge(Edge<unsigned, long long>(i, net.sink, -
usability));
}
for (unsigned from = 0; from < verticesCount; from ++) {
unsigned nextEdgesCount;
cin >> nextEdgesCount;
for (unsigned edge = 0; edge < nextEdgesCount; edge ++) {
unsigned to;
cin >> to;
net.addEdge(Edge<unsigned, long long>(from, to - 1,
maxCapacity));
}
}
setMaxFlowWithPreflowPush(net);
return positiveSum - getFlowWithCheck(net);
}
*/
int main() {
unsigned verticesCount, edgesCount;
cin >> verticesCount >> edgesCount;
Net<Edge<unsigned, long long>> net(verticesCount);
net.source = 0;
net.sink = verticesCount - 1;
for (unsigned i = 0; i < edgesCount; i++) {
unsigned from, to;
long long capacity;
cin >> from >> to >> capacity;
net.addEdge(Edge<unsigned, long long>(from - 1, to - 1, capacity));
}
setMaxFlowWithAugmentingPaths(net);
cout << getFlowWithCheck(net) << endl;
return 0;
}
| #include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <queue>
#include <string>
#include <vector>
// УБРАТЬ!
using namespace std;
// Net class:
template <class Edge> class Net {
private:
typedef Edge *EdgePointer;
typedef pair<EdgePointer, EdgePointer> Arc;
list<Arc> edges;
vector<list<Arc>> innerEdges;
vector<list<Arc>> outerEdges;
class UniversalEdgeIterator {
friend class Net;
private:
list<Arc> *edgesList;
typename list<Arc>::iterator edgeIterator;
bool validated;
enum UniversalIteratorType { inner, outer, all };
UniversalIteratorType iteratorType;
UniversalEdgeIterator(list<Arc> *edgesList,
const UniversalIteratorType &getIteratorType) {
this->edgesList = edgesList;
this->iteratorType = iteratorType;
validated = false;
}
void validate() {
if (validated)
return;
else {
validated = true;
begin();
}
}
public:
typedef UniversalIteratorType IteratorType;
UniversalEdgeIterator() {
edgesList = nullptr;
validated = false;
}
// Iterator methods:
void begin() { edgeIterator = edgesList->begin(); }
void move() { edgeIterator = next(edgeIterator); }
bool end() const {
return edgesList->size() == 0 || edgeIterator == edgesList->end();
}
// Getters:
Edge getEdge() const {
// cout << "s" << edgesList->size() << endl;
return *(*edgeIterator).first;
}
Edge getReversedEdge() const { return *(*edgeIterator).second; }
// Setter:
void increaseFlow(const typename Edge::FlowType &delta) const {
(*edgeIterator).first->flow += delta;
(*edgeIterator).second->flow -= delta;
}
// Other:
IteratorType getIteratorType() const { return iteratorType; }
};
UniversalEdgeIterator allEdgesIterator;
vector<UniversalEdgeIterator> innerEdgesIterators;
vector<UniversalEdgeIterator> outerEdgesIterators;
public:
typedef UniversalEdgeIterator EdgeIterator;
typedef typename Edge::IndexType IndexType;
IndexType source;
IndexType sink;
// Constructors, destructors:
Net(const IndexType &verticesCount) {
allEdgesIterator = EdgeIterator(&edges, EdgeIterator::IteratorType::all);
innerEdges.resize(verticesCount);
outerEdges.resize(verticesCount);
innerEdgesIterators.resize(verticesCount);
outerEdgesIterators.resize(verticesCount);
for (unsigned i = 0; i < verticesCount; i++) {
innerEdgesIterators[i] =
EdgeIterator(&innerEdges[i], EdgeIterator::IteratorType::inner);
outerEdgesIterators[i] =
EdgeIterator(&outerEdges[i], EdgeIterator::IteratorType::outer);
}
}
~Net() {
for (const Arc &arc : edges)
delete arc.first;
}
// Setters:
void addEdge(const Edge &edge) {
EdgePointer edgePointer = new Edge(edge);
EdgePointer reversedEdgePointer = new Edge(edge.reversed());
edges.push_back(make_pair(edgePointer, reversedEdgePointer));
outerEdges[edgePointer->from].push_back(
make_pair(edgePointer, reversedEdgePointer));
innerEdges[edgePointer->to].push_back(
make_pair(edgePointer, reversedEdgePointer));
edges.push_back(make_pair(reversedEdgePointer, edgePointer));
outerEdges[reversedEdgePointer->from].push_back(
make_pair(reversedEdgePointer, edgePointer));
innerEdges[reversedEdgePointer->to].push_back(
make_pair(reversedEdgePointer, edgePointer));
allEdgesIterator.validate();
outerEdgesIterators[edgePointer->from].validate();
outerEdgesIterators[edgePointer->to].validate();
innerEdgesIterators[edgePointer->from].validate();
innerEdgesIterators[edgePointer->to].validate();
}
// Getters:
EdgeIterator &getAllEdgesIterator() { return allEdgesIterator; }
EdgeIterator getConstAllEdgesIterator() const { return allEdgesIterator; }
EdgeIterator &getInnerEdgeIterator(const IndexType &vertex) {
return innerEdgesIterators[vertex];
}
EdgeIterator getConstInnerEdgeIterator(const IndexType &vertex) const {
return innerEdgesIterators[vertex];
}
EdgeIterator &getOuterEdgeIterator(const IndexType &vertex) {
return outerEdgesIterators[vertex];
}
EdgeIterator getConstOuterEdgeIterator(const IndexType &vertex) const {
return outerEdgesIterators[vertex];
}
// Info:
IndexType getVerticesCount() const { return innerEdges.size(); }
IndexType getEdgesCount() const { return edges.size(); }
};
// Flow addons:
template <class Edge>
const typename Edge::FlowType
getFlowFromOrToVertex(typename Net<Edge>::EdgeIterator iter) {
typename Edge::FlowType flow = 0;
for (iter.begin(); !iter.end(); iter.move())
flow += iter.getEdge().flow;
return flow;
}
template <class Edge> bool isFlowValid(const Net<Edge> &net) {
typename Net<Edge>::EdgeIterator iter = net.getConstAllEdgesIterator();
for (iter.begin(); !iter.end(); iter.move())
if (iter.getEdge().flow > iter.getEdge().capacity ||
iter.getEdge().flow != -iter.getReversedEdge().flow)
return false;
for (typename Edge::IndexType vertex = 0; vertex < net.getVerticesCount();
vertex++) {
if (vertex == net.source || vertex == net.sink)
break;
typename Edge::FlowType innerFlow =
getFlowFromOrToVertex<Edge>(net.getConstInnerEdgeIterator(vertex));
typename Edge::FlowType outerFlow =
getFlowFromOrToVertex<Edge>(net.getConstOuterEdgeIterator(vertex));
if (innerFlow != outerFlow)
return false;
}
return true;
}
template <class Edge>
typename Edge::FlowType getFlowWithoutCheck(const Net<Edge> &net) {
return getFlowFromOrToVertex<Edge>(net.getConstOuterEdgeIterator(net.source));
}
template <class Edge>
typename Edge::FlowType getFlowWithCheck(const Net<Edge> &net) {
if (isFlowValid(net))
return getFlowWithoutCheck(net);
else
throw("Net exeption: invalid flow!");
}
// Global discharge algorithm:
template <class Edge>
void push(Net<Edge> &net, const typename Net<Edge>::EdgeIterator &iter,
const typename Edge::FlowType &pushingFlow,
vector<typename Edge::FlowType> &excess) {
iter.increaseFlow(pushingFlow);
Edge edge = iter.getEdge();
if (edge.from != net.source && edge.from != net.sink)
excess[edge.from] -= pushingFlow;
if (edge.to != net.source && edge.to != net.sink)
excess[edge.to] += pushingFlow;
}
template <class Edge>
void relabel(const Net<Edge> &net, const typename Edge::IndexType &vertex,
vector<typename Edge::IndexType> &height) {
typename Edge::IndexType minHeight =
numeric_limits<typename Edge::IndexType>::max();
typename Net<Edge>::EdgeIterator iter = net.getConstOuterEdgeIterator(vertex);
for (iter.begin(); !iter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.residualCapacity() > 0)
minHeight = min<typename Edge::IndexType>(minHeight, height[edge.to]);
}
height[vertex] = minHeight + 1;
}
template <class Edge>
inline void discharge(Net<Edge> &net, const typename Edge::IndexType &vertex,
vector<typename Edge::FlowType> &excess,
vector<typename Edge::IndexType> &height) {
while (excess[vertex] > 0) {
typename Net<Edge>::EdgeIterator &iter = net.getOuterEdgeIterator(vertex);
if (iter.end()) {
relabel(net, vertex, height);
iter.begin();
}
else {
Edge edge = iter.getEdge();
if (edge.residualCapacity() > 0 &&
height[vertex] == height[edge.to] + 1) {
typename Edge::FlowType pushingFlow = min<typename Edge::FlowType>(
excess[edge.from], edge.residualCapacity());
push(net, iter, pushingFlow, excess);
}
else
iter.move();
}
}
}
template <class Edge> void setMaxFlowWithPreflowPush(Net<Edge> &net) {
vector<typename Edge::FlowType> excess(net.getVerticesCount(), 0);
vector<typename Edge::IndexType> height(net.getVerticesCount(), 0);
height[net.source] = net.getVerticesCount();
typename Net<Edge>::EdgeIterator iter =
net.getConstOuterEdgeIterator(net.source);
for (iter.begin(); !iter.end(); iter.move())
push(net, iter, iter.getEdge().residualCapacity(), excess);
while (true) {
bool discharged = false;
for (typename Edge::IndexType vertex = 0; vertex < net.getVerticesCount();
vertex++) {
if (excess[vertex] && vertex != net.source && vertex != net.sink) {
discharge(net, vertex, excess, height);
discharged = true;
}
}
if (!discharged)
break;
}
}
// Dinic Blocking flow algorithm:
template <class Edge>
typename Edge::FlowType
tryPushFlow(Net<Edge> &layeredNet, const typename Edge::IndexType &vertex,
const typename Edge::FlowType &pushingFlow =
numeric_limits<typename Edge::FlowType>::max()) {
if (vertex == layeredNet.sink || pushingFlow == 0)
return pushingFlow;
for (typename Net<Edge>::EdgeIterator iter =
layeredNet.getConstOuterEdgeIterator(vertex);
!iter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.capacity == 0)
continue;
typename Edge::FlowType newPushingFlow =
min<typename Edge::FlowType>(pushingFlow, edge.residualCapacity());
typename Edge::FlowType pushedFlow =
tryPushFlow(layeredNet, edge.to, newPushingFlow);
if (pushedFlow != 0) {
iter.increaseFlow(pushedFlow);
return pushedFlow;
}
}
if (!layeredNet.getOuterEdgeIterator(vertex).end())
layeredNet.getOuterEdgeIterator(vertex).move();
return 0;
}
template <class Edge> void setBlockingFlowWithDinic(Net<Edge> &layeredNet) {
while (tryPushFlow(layeredNet, layeredNet.source) != 0) {
};
}
// Malhotra-Kumar-Maheshwari Blocking flow algorithm:
template <class Edge>
inline typename Edge::FlowType
setPotentialOneSide(typename Net<Edge>::EdgeIterator iter) {
typename Edge::FlowType potential = 0;
for (iter.begin(); !iter.end(); iter.move())
potential += iter.getEdge().residualCapacity();
return potential;
}
template <class Edge>
inline typename Edge::FlowType
getPotential(const Net<Edge> &net, const typename Edge::IndexType &vertex,
const vector<typename Edge::FlowType> &innerPotential,
const vector<typename Edge::FlowType> &outerPotential) {
if (vertex == net.source)
return outerPotential[vertex];
else if (vertex == net.sink)
return innerPotential[vertex];
else
return min<typename Edge::FlowType>(outerPotential[vertex],
innerPotential[vertex]);
}
template <class Edge>
inline void deleteVertexOneSide(const Net<Edge> &layeredNet,
typename Net<Edge>::EdgeIterator iter,
vector<typename Edge::FlowType> &innerPotential,
vector<typename Edge::FlowType> &outerPotential,
vector<bool> &isDeleted) {
for (iter.begin(); !iter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.capacity == 0)
continue;
typename Edge::IndexType nextVertex =
(iter.getIteratorType() == Net<Edge>::EdgeIterator::IteratorType::outer
? edge.to
: edge.from);
(iter.getIteratorType() == Net<Edge>::EdgeIterator::IteratorType::outer
? innerPotential[nextVertex]
: outerPotential[nextVertex]) -= edge.residualCapacity();
if (getPotential(layeredNet, nextVertex, innerPotential, outerPotential) ==
0)
deleteVertex(layeredNet, nextVertex, innerPotential, outerPotential,
isDeleted);
}
}
template <class Edge>
void deleteVertex(const Net<Edge> &layeredNet,
const typename Edge::IndexType &vertex,
vector<typename Edge::FlowType> &innerPotential,
vector<typename Edge::FlowType> &outerPotential,
vector<bool> &isDeleted) {
if (isDeleted[vertex])
return;
isDeleted[vertex] = true;
deleteVertexOneSide<Edge>(layeredNet,
layeredNet.getConstOuterEdgeIterator(vertex),
innerPotential, outerPotential, isDeleted);
deleteVertexOneSide<Edge>(layeredNet,
layeredNet.getConstInnerEdgeIterator(vertex),
innerPotential, outerPotential, isDeleted);
}
template <typename Edge>
void pushFlowFromRoot(Net<Edge> &layeredNet,
const typename Edge::IndexType &root,
const typename Edge::FlowType &pushingFlow,
const typename Edge::IndexType &destination,
vector<typename Edge::FlowType> &innerPotential,
vector<typename Edge::FlowType> &outerPotential,
const vector<bool> &isDeleted) {
// BFS init:
queue<typename Edge::IndexType> verticesQueue;
vector<bool> used(layeredNet.getVerticesCount(), false);
verticesQueue.push(root);
used[root] = true;
// Other data init:
vector<typename Edge::FlowType> excessOrLack(layeredNet.getVerticesCount(),
0);
excessOrLack[root] = pushingFlow;
// BFS:
while (!verticesQueue.empty()) {
typename Edge::IndexType vertex = verticesQueue.front();
verticesQueue.pop();
if (vertex == destination)
break;
for (typename Net<Edge>::EdgeIterator &iter =
(destination == layeredNet.sink
? layeredNet.getOuterEdgeIterator(vertex)
: layeredNet.getInnerEdgeIterator(vertex));
!iter.end(); iter.move()) {
Edge edge = iter.getEdge();
typename Edge::IndexType nextVertex =
(destination == layeredNet.sink ? edge.to : edge.from);
if (edge.capacity > 0 && !isDeleted[nextVertex]) {
if (!used[nextVertex]) {
verticesQueue.push(nextVertex);
used[nextVertex] = true;
}
typename Edge::FlowType pushedFlow = min<typename Edge::FlowType>(
excessOrLack[vertex], edge.residualCapacity());
excessOrLack[vertex] -= pushedFlow;
excessOrLack[nextVertex] += pushedFlow;
iter.increaseFlow(pushedFlow);
outerPotential[edge.from] -= pushedFlow;
innerPotential[edge.to] -= pushedFlow;
}
if (excessOrLack[vertex] == 0)
break;
}
}
}
template <class Edge>
void setBlockingFlowWithMalhotraKumarMaheshwari(Net<Edge> &layeredNet) {
// Initialize potentials:
vector<typename Edge::FlowType> innerPotential(layeredNet.getVerticesCount());
vector<typename Edge::FlowType> outerPotential(layeredNet.getVerticesCount());
for (typename Edge::IndexType vertex = 0;
vertex < layeredNet.getVerticesCount(); vertex++) {
innerPotential[vertex] =
setPotentialOneSide<Edge>(layeredNet.getConstInnerEdgeIterator(vertex));
outerPotential[vertex] =
setPotentialOneSide<Edge>(layeredNet.getConstOuterEdgeIterator(vertex));
}
// Initialize deleted vertices:
vector<bool> isDeleted(layeredNet.getVerticesCount(), false);
// Main cycle:
while (true) {
// Deleting traverse:
for (typename Edge::IndexType vertex = 0;
vertex < layeredNet.getVerticesCount(); vertex++)
if (!isDeleted[vertex] &&
getPotential(layeredNet, vertex, innerPotential, outerPotential) == 0)
deleteVertex(layeredNet, vertex, innerPotential, outerPotential,
isDeleted);
if (isDeleted[layeredNet.source] || isDeleted[layeredNet.sink])
break;
// Finding root:
typename Edge::IndexType root = layeredNet.source;
for (typename Edge::IndexType vertex = 0;
vertex < layeredNet.getVerticesCount(); vertex++)
if (!isDeleted[vertex] &&
getPotential(layeredNet, vertex, innerPotential, outerPotential) <=
getPotential(layeredNet, root, innerPotential, outerPotential))
root = vertex;
typename Edge::FlowType rootPotential =
getPotential(layeredNet, root, innerPotential, outerPotential);
// Pushing flow through the root:
pushFlowFromRoot(layeredNet, root, rootPotential, layeredNet.sink,
innerPotential, outerPotential, isDeleted);
pushFlowFromRoot(layeredNet, root, rootPotential, layeredNet.source,
innerPotential, outerPotential, isDeleted);
}
}
// Global Max Flow augmenting paths algorithm:
template <class Edge> Net<Edge> buildLayeredNetwork(const Net<Edge> &net) {
// BFS init:
queue<typename Edge::IndexType> verticesQueue;
vector<bool> used(net.getVerticesCount(), false);
verticesQueue.push(net.source);
// Layered Net init:
Net<Edge> layeredNet(net.getVerticesCount());
layeredNet.source = net.source;
layeredNet.sink = net.sink;
vector<typename Edge::IndexType> layers(
net.getVerticesCount(), numeric_limits<typename Edge::IndexType>::max());
layers[net.source] = 0;
// BFS:
while (!verticesQueue.empty()) {
typename Edge::IndexType vertex = verticesQueue.front();
verticesQueue.pop();
if (used[vertex])
continue;
used[vertex] = true;
typename Net<Edge>::EdgeIterator iter =
net.getConstOuterEdgeIterator(vertex);
for (iter.begin(); !iter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.residualCapacity() > 0 &&
layers[edge.from] + 1 <= layers[edge.to]) {
verticesQueue.push(edge.to);
Edge residualEdge = edge;
residualEdge.capacity = edge.residualCapacity();
residualEdge.flow = 0;
layeredNet.addEdge(residualEdge);
layers[edge.to] = layers[edge.from] + 1;
}
}
}
return layeredNet;
}
// Класс bfs iterator, который будет делать все логику:
template <class Edge>
void transferFlowFromLayeredNetworkToNetwork(Net<Edge> &layeredNet,
Net<Edge> &net) {
// BFS init:
queue<typename Edge::IndexType> verticesQueue;
vector<bool> used(net.getVerticesCount(), false);
verticesQueue.push(net.source);
// Layered Net init:
vector<typename Edge::IndexType> layers(
net.getVerticesCount(), numeric_limits<typename Edge::IndexType>::max());
layers[net.source] = 0;
// BFS:
while (!verticesQueue.empty()) {
typename Edge::IndexType vertex = verticesQueue.front();
verticesQueue.pop();
if (used[vertex])
continue;
used[vertex] = true;
typename Net<Edge>::EdgeIterator iter =
net.getConstOuterEdgeIterator(vertex);
typename Net<Edge>::EdgeIterator &layeredNetIter =
layeredNet.getOuterEdgeIterator(vertex);
layeredNetIter.begin();
for (iter.begin(); !iter.end() && !layeredNetIter.end(); iter.move()) {
Edge edge = iter.getEdge();
if (edge.residualCapacity() > 0 &&
layers[edge.from] + 1 <= layers[edge.to]) {
verticesQueue.push(edge.to);
layers[edge.to] = layers[edge.from] + 1;
while (layeredNetIter.getEdge().capacity == 0)
layeredNetIter.move();
iter.increaseFlow(layeredNetIter.getEdge().flow);
layeredNetIter.move();
}
}
}
}
// Сделать классом с кастомным виртуальным blocking flow:
template <class Edge> void setMaxFlowWithAugmentingPaths(Net<Edge> &net) {
while (true) {
Net<Edge> layeredNet = buildLayeredNetwork(net);
setBlockingFlowWithMalhotraKumarMaheshwari(layeredNet);
if (getFlowWithCheck(layeredNet) == 0)
break;
else {
transferFlowFromLayeredNetworkToNetwork(layeredNet, net);
}
}
}
// --------------------------------------------------
// My custom Edge:
template <typename FirstType = unsigned, typename SecondType = long long>
struct Edge {
typedef FirstType IndexType;
typedef SecondType FlowType;
IndexType from;
IndexType to;
FlowType flow;
FlowType capacity;
Edge(const IndexType &from, const IndexType &to, const FlowType &capacity) {
this->from = from;
this->to = to;
this->flow = 0;
this->capacity = capacity;
}
FlowType residualCapacity() const { return capacity - flow; }
Edge reversed() const { return Edge(to, from, 0); }
};
// Custom inputs/outputs:
template <class Edge> void printEdge(const Edge &edge, ostream &os = cout) {
os << edge.from << " -> " << edge.to << " (" << edge.flow << "/"
<< edge.capacity << ")";
}
template <class Edge> void printNet(Net<Edge> &net, ostream &os = cout) {
for (typename Edge::IndexType vertex = 0; vertex < net.getVerticesCount();
vertex++) {
typename Net<Edge>::EdgeIterator iter =
net.getConstOuterEdgeIterator(vertex);
for (iter.begin(); !iter.end(); iter.move()) {
printEdge(iter.getEdge(), os);
os << " ";
}
os << endl;
}
}
/*
// Сделать нормальный input.
long long solve () {
unsigned verticesCount;
cin >> verticesCount;
const long long maxCapacity = verticesCount * 1000 + 1;
long long positiveSum = 0;
Net<Edge<unsigned, long long> > net(verticesCount + 2);
net.source = verticesCount;
net.sink = verticesCount + 1;
for (unsigned i = 0; i < verticesCount; i ++) {
long long usability;
cin >> usability;
if (usability > 0) {
positiveSum += usability;
net.addEdge(Edge<unsigned, long long>(net.source, i,
usability));
}
else
net.addEdge(Edge<unsigned, long long>(i, net.sink, -
usability));
}
for (unsigned from = 0; from < verticesCount; from ++) {
unsigned nextEdgesCount;
cin >> nextEdgesCount;
for (unsigned edge = 0; edge < nextEdgesCount; edge ++) {
unsigned to;
cin >> to;
net.addEdge(Edge<unsigned, long long>(from, to - 1,
maxCapacity));
}
}
setMaxFlowWithPreflowPush(net);
return positiveSum - getFlowWithCheck(net);
}
*/
int main() {
unsigned verticesCount, edgesCount;
cin >> verticesCount >> edgesCount;
Net<Edge<unsigned, long long>> net(verticesCount);
net.source = 0;
net.sink = verticesCount - 1;
for (unsigned i = 0; i < edgesCount; i++) {
unsigned from, to;
long long capacity;
cin >> from >> to >> capacity;
net.addEdge(Edge<unsigned, long long>(from, to, capacity));
}
setMaxFlowWithPreflowPush(net);
cout << getFlowWithCheck(net) << endl;
return 0;
}
| replace | 738 | 742 | 738 | 742 | -11 | |
p02376 | C++ | Time Limit Exceeded | #include <cstdio>
#include <vector>
struct Edge {
Edge(int from_, int to_, int capacity_, int rev_)
: from(from_), to(to_), capacity(capacity_), rev(rev_) {}
int from;
int to;
int capacity;
int rev;
};
std::vector<Edge> edges[128];
void addEdge(int from, int to, int capacity) {
int e1 = edges[from].size();
int e2 = edges[to].size();
edges[from].push_back(Edge(from, to, capacity, e2));
edges[to].push_back(Edge(to, from, 0, e1));
}
bool checked[128];
void init_flow() {
for (int i = 0; i < 128; ++i)
checked[i] = false;
}
int flow(int from, int to, int v) {
if (v <= 0)
return 0;
if (from == to)
return v;
int res = 0;
checked[from] = true;
for (Edge &edge : edges[from]) {
if (checked[edge.to])
continue;
int nv = flow(edge.to, to, std::min(v, edge.capacity));
if (nv == 0)
continue;
edge.capacity -= nv;
edges[edge.to][edge.rev].capacity += nv;
res = nv;
break;
}
checked[from] = false;
return res;
}
int v;
int maximum_flow(int from, int to) {
int res = 0;
for (;;) {
init_flow();
// for(int i = 0; i < v; ++i) {
// printf("from : %d\n", i);
// for(Edge edge : edges[i]) {
// printf("%d -> %d : %d $ %d\n", edge.from, edge.to, edge.capacity,
// edges[edge.to][edge.rev].capacity);
// }
// }
int v = flow(from, to, (1 << 29));
if (v == 0)
break;
res += v;
// printf("+%d\n", v);
}
return res;
}
int main() {
int e;
scanf("%d %d", &v, &e);
for (int i = 0; i < e; ++i) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
addEdge(a, b, c);
}
printf("%d\n", maximum_flow(0, v - 1));
// for(int i = 0; i < v; ++i) {
// printf("from : %d\n", i);
// for(Edge edge : edges[i]) {
// printf("%d -> %d : %d $ %d\n", edge.from, edge.to, edge.capacity,
// edges[edge.to][edge.rev].capacity);
// }
// }
return 0;
} | #include <cstdio>
#include <vector>
struct Edge {
Edge(int from_, int to_, int capacity_, int rev_)
: from(from_), to(to_), capacity(capacity_), rev(rev_) {}
int from;
int to;
int capacity;
int rev;
};
std::vector<Edge> edges[128];
void addEdge(int from, int to, int capacity) {
int e1 = edges[from].size();
int e2 = edges[to].size();
edges[from].push_back(Edge(from, to, capacity, e2));
edges[to].push_back(Edge(to, from, 0, e1));
}
bool checked[128];
void init_flow() {
for (int i = 0; i < 128; ++i)
checked[i] = false;
}
int flow(int from, int to, int v) {
if (v <= 0)
return 0;
if (from == to)
return v;
int res = 0;
checked[from] = true;
for (Edge &edge : edges[from]) {
if (checked[edge.to])
continue;
int nv = flow(edge.to, to, std::min(v, edge.capacity));
if (nv == 0)
continue;
edge.capacity -= nv;
edges[edge.to][edge.rev].capacity += nv;
res = nv;
break;
}
// checked[from] = false;
return res;
}
int v;
int maximum_flow(int from, int to) {
int res = 0;
for (;;) {
init_flow();
// for(int i = 0; i < v; ++i) {
// printf("from : %d\n", i);
// for(Edge edge : edges[i]) {
// printf("%d -> %d : %d $ %d\n", edge.from, edge.to, edge.capacity,
// edges[edge.to][edge.rev].capacity);
// }
// }
int v = flow(from, to, (1 << 29));
if (v == 0)
break;
res += v;
// printf("+%d\n", v);
}
return res;
}
int main() {
int e;
scanf("%d %d", &v, &e);
for (int i = 0; i < e; ++i) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
addEdge(a, b, c);
}
printf("%d\n", maximum_flow(0, v - 1));
// for(int i = 0; i < v; ++i) {
// printf("from : %d\n", i);
// for(Edge edge : edges[i]) {
// printf("%d -> %d : %d $ %d\n", edge.from, edge.to, edge.capacity,
// edges[edge.to][edge.rev].capacity);
// }
// }
return 0;
} | replace | 43 | 44 | 43 | 44 | TLE | |
p02376 | C++ | Runtime Error | #include <algorithm>
#include <list>
#include <stdio.h>
#include <vector>
using namespace std;
typedef vector<int> VInt;
typedef vector<VInt> VVInt;
typedef list<int> LInt;
typedef vector<LInt> VLInt;
typedef LInt::iterator LIter;
typedef vector<LIter> VLIter;
// Input: the network
int n, src, dest;
VVInt c;
// Output: the flow (preflow while the algo is running)
VVInt f;
// Additional data
VInt h, e;
VLInt nei;
VLIter current;
// Lift the vertex. Assumes that this is possible.
void lift(int u) {
int height = 2 * n;
for (LIter it = nei[u].begin(); it != nei[u].end(); it++)
if (c[u][*it] > f[u][*it])
height = min(height, h[*it]);
h[u] = height + 1;
}
// Push the flow along the given edge. Assumes that this is possible.
void push(int u, int v) {
int value = min(c[u][v] - f[u][v], e[u]);
f[u][v] += value;
f[v][u] = -f[u][v];
e[u] -= value;
e[v] += value;
}
// Discharge the given vertex. Returns true if lifting occurred.
bool discharge(int u) {
bool lifted = false;
while (e[u] > 0) {
if (current[u] == nei[u].end()) {
lift(u);
lifted = true;
current[u] = nei[u].begin();
continue;
}
int v = *current[u];
if (c[u][v] > f[u][v] && h[u] == h[v] + 1)
push(u, v);
else
current[u]++;
}
return lifted;
}
// The actual lift-to-front algo (with initialization)
// Returns the max flow value
int ltf() {
int u, v;
// Build the neighbours lists
nei.resize(n);
current.resize(n);
for (u = 0; u < n; u++) {
for (v = 0; v < n; v++)
if (c[u][v] > 0 || c[v][u] > 0)
nei[u].push_back(v);
current[u] = nei[u].begin();
}
// Initialize the preflow
f.assign(n, VInt(n, 0));
e.assign(n, 0);
h.assign(n, 0);
h[src] = n;
for (u = 0; u < n; u++)
if (c[src][u] > 0) {
e[u] = c[src][u];
f[src][u] = c[src][u];
f[u][src] = -f[src][u];
}
// lift-to-front
LInt theList;
for (u = 0; u < n; u++)
if (u != src && u != dest)
theList.push_back(u);
LIter cur = theList.begin();
while (cur != theList.end()) {
u = *cur;
if (discharge(u)) {
theList.erase(cur);
cur = theList.insert(theList.begin(), u);
}
cur++;
}
return e[dest];
}
// A small demo
int main() {
int i, j, edgeCount;
// read the input
scanf("%d%d%d%d", &n, &edgeCount);
src = 0;
dest = n - 1;
c.assign(n, VInt(n, 0));
while (edgeCount--) {
int val;
scanf("%d%d%d", &i, &j, &val);
c[i][j] = val;
}
// find the max. flow
int result = ltf();
// print the results
printf("%d\n", result);
/*for (i = 0; i<n; i++)
for (j = 0; j<n; j++)
if (f[i][j] > 0)
printf("%d -> %d : %d\n", i, j, f[i][j]);*/
return 0;
}
| #include <algorithm>
#include <list>
#include <stdio.h>
#include <vector>
using namespace std;
typedef vector<int> VInt;
typedef vector<VInt> VVInt;
typedef list<int> LInt;
typedef vector<LInt> VLInt;
typedef LInt::iterator LIter;
typedef vector<LIter> VLIter;
// Input: the network
int n, src, dest;
VVInt c;
// Output: the flow (preflow while the algo is running)
VVInt f;
// Additional data
VInt h, e;
VLInt nei;
VLIter current;
// Lift the vertex. Assumes that this is possible.
void lift(int u) {
int height = 2 * n;
for (LIter it = nei[u].begin(); it != nei[u].end(); it++)
if (c[u][*it] > f[u][*it])
height = min(height, h[*it]);
h[u] = height + 1;
}
// Push the flow along the given edge. Assumes that this is possible.
void push(int u, int v) {
int value = min(c[u][v] - f[u][v], e[u]);
f[u][v] += value;
f[v][u] = -f[u][v];
e[u] -= value;
e[v] += value;
}
// Discharge the given vertex. Returns true if lifting occurred.
bool discharge(int u) {
bool lifted = false;
while (e[u] > 0) {
if (current[u] == nei[u].end()) {
lift(u);
lifted = true;
current[u] = nei[u].begin();
continue;
}
int v = *current[u];
if (c[u][v] > f[u][v] && h[u] == h[v] + 1)
push(u, v);
else
current[u]++;
}
return lifted;
}
// The actual lift-to-front algo (with initialization)
// Returns the max flow value
int ltf() {
int u, v;
// Build the neighbours lists
nei.resize(n);
current.resize(n);
for (u = 0; u < n; u++) {
for (v = 0; v < n; v++)
if (c[u][v] > 0 || c[v][u] > 0)
nei[u].push_back(v);
current[u] = nei[u].begin();
}
// Initialize the preflow
f.assign(n, VInt(n, 0));
e.assign(n, 0);
h.assign(n, 0);
h[src] = n;
for (u = 0; u < n; u++)
if (c[src][u] > 0) {
e[u] = c[src][u];
f[src][u] = c[src][u];
f[u][src] = -f[src][u];
}
// lift-to-front
LInt theList;
for (u = 0; u < n; u++)
if (u != src && u != dest)
theList.push_back(u);
LIter cur = theList.begin();
while (cur != theList.end()) {
u = *cur;
if (discharge(u)) {
theList.erase(cur);
cur = theList.insert(theList.begin(), u);
}
cur++;
}
return e[dest];
}
// A small demo
int main() {
int i, j, edgeCount;
// read the input
scanf("%d%d", &n, &edgeCount);
src = 0;
dest = n - 1;
c.assign(n, VInt(n, 0));
while (edgeCount--) {
int val;
scanf("%d%d%d", &i, &j, &val);
c[i][j] = val;
}
// find the max. flow
int result = ltf();
// print the results
printf("%d\n", result);
/*for (i = 0; i<n; i++)
for (j = 0; j<n; j++)
if (f[i][j] > 0)
printf("%d -> %d : %d\n", i, j, f[i][j]);*/
return 0;
}
| replace | 112 | 113 | 112 | 113 | -11 | |
p02377 | C++ | Runtime Error | #define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
// #include "MyMath.h"
// #include "MyDisjointset.h"
#include <algorithm>
#include <functional>
#include <iostream>
#include <math.h>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
typedef pair<int, int> P;
typedef long long int ll;
typedef vector<int> vecint;
typedef vector<vecint> dvecint;
typedef vector<dvecint> vecdvecint;
typedef vector<vector<dvecint>> dvecdvecint;
const ll INF = 2000000000;
struct edge {
int to, cap, cost, rev;
edge(int t, int ca, int co, int re) {
to = t;
cap = ca;
cost = co;
rev = re;
}
};
vector<edge> G[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;
} | #define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
// #include "MyMath.h"
// #include "MyDisjointset.h"
#include <algorithm>
#include <functional>
#include <iostream>
#include <math.h>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
typedef pair<int, int> P;
typedef long long int ll;
typedef vector<int> vecint;
typedef vector<vecint> dvecint;
typedef vector<dvecint> vecdvecint;
typedef vector<vector<dvecint>> dvecdvecint;
const ll INF = 2000000000;
struct edge {
int to, cap, cost, rev;
edge(int t, int ca, int co, int re) {
to = t;
cap = ca;
cost = co;
rev = re;
}
};
vector<edge> G[100];
int prv[100], pre[100], d[100];
int v, e, flow;
void addedge(int from, int to, int cap, int cost) {
G[from].push_back(edge(to, cap, cost, G[to].size()));
G[to].push_back(edge(from, 0, -cost, G[from].size() - 1));
}
int minimumcost(int s, int t, int f) {
int res = 0;
while (f > 0) {
fill(d, d + v, INF);
d[s] = 0;
bool ud = true;
while (ud) {
ud = false;
for (int i = 0; i < v; i++) {
if (d[i] == INF)
continue;
for (int j = 0; j < G[i].size(); j++) {
edge &e = G[i][j];
if (e.cap > 0 && d[e.to] > d[i] + e.cost) {
d[e.to] = d[i] + e.cost;
prv[e.to] = i;
pre[e.to] = j;
ud = true;
}
}
}
}
if (d[t] == INF)
return -1;
int dis = f;
for (int w = t; w != s; w = prv[w]) {
dis = min(dis, G[prv[w]][pre[w]].cap);
}
f -= dis;
for (int w = t; w != s; w = prv[w]) {
G[prv[w]][pre[w]].cap -= dis;
G[w][G[prv[w]][pre[w]].rev].cap += dis;
}
res += dis * d[t];
}
return res;
}
int main() {
cin >> v >> e >> flow;
for (int i = 0; i < e; i++) {
int s, t, c, d;
cin >> s >> t >> c >> d;
addedge(s, t, c, d);
}
cout << minimumcost(0, v - 1, flow) << endl;
return 0;
} | replace | 29 | 31 | 29 | 31 | 0 | |
p02377 | C++ | Memory Limit Exceeded | #include <algorithm>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#define repd(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rep(i, n) repd(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define mod 1000000007
#define inf 2000000007
#define mp make_pair
#define pb push_back
typedef long long ll;
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";
}
// end of template
// Minimum Cost Flow
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].pb({to, cap, cost, (int)G[to].size()});
G[to].pb({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, inf);
priority_queue<node> pq;
pq.push({0, s});
dist[s] = 0;
while (!pq.empty()) {
node p = pq.top(); // cost, pos
pq.pop();
int d = p.cost;
int v = p.pos;
if (dist[v] < d)
continue;
rep(i, G[v].size()) {
edge &e = G[v][i];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
preV[e.to] = v;
preE[e.to] = i;
pq.push({dist[e.to], e.to});
}
}
}
if (dist[t] == inf)
return -1;
rep(v, V) h[v] += dist[v];
int d = f;
for (int v = t; v != s; v = 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);
// source code
int V, E, F;
cin >> V >> E >> F;
MinCostFlow mcf(V);
rep(i, E) {
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;
} | #include <algorithm>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#define repd(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rep(i, n) repd(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define mod 1000000007
#define inf 2000000007
#define mp make_pair
#define pb push_back
typedef long long ll;
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";
}
// end of template
// Minimum Cost Flow
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].pb({to, cap, cost, (int)G[to].size()});
G[to].pb({from, 0, -cost, (int)G[from].size() - 1});
}
int calc(int s, int t, int f) {
int ret = 0;
h.assign(V, 0);
while (f > 0) {
dist.assign(V, inf);
priority_queue<node> pq;
pq.push({0, s});
dist[s] = 0;
while (!pq.empty()) {
node p = pq.top(); // cost, pos
pq.pop();
int d = p.cost;
int v = p.pos;
if (dist[v] < d)
continue;
rep(i, G[v].size()) {
edge &e = G[v][i];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
preV[e.to] = v;
preE[e.to] = i;
pq.push({dist[e.to], e.to});
}
}
}
if (dist[t] == inf)
return -1;
rep(v, V) h[v] += dist[v];
int d = f;
for (int v = t; v != s; v = 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);
// source code
int V, E, F;
cin >> V >> E >> F;
MinCostFlow mcf(V);
rep(i, E) {
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;
} | replace | 51 | 52 | 51 | 52 | MLE | |
p02377 | C++ | Runtime Error | #include <cmath>
#include <cstddef>
#include <iostream>
#include <limits>
#include <queue>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
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;
} | #include <cmath>
#include <cstddef>
#include <iostream>
#include <limits>
#include <queue>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
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);
try {
const auto answer =
loquat::mincostflow_primal_dual(f, source, sink, residual);
cout << answer << endl;
} catch (loquat::no_solution_error) {
cout << -1 << endl;
}
return 0;
} | replace | 337 | 339 | 337 | 344 | 0 | |
p02378 | C++ | Runtime Error | #include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
static const int MAX_V = 100;
static const int MAX_K = 1000;
int V;
vector<int> G[MAX_V];
int match[MAX_V];
bool used[MAX_V];
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
bool dfs(int v) {
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
int u = G[v][i], w = match[u];
if (w < 0 || !used[w] && dfs(w)) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int bipartite_matching() {
int res = 0;
memset(match, -1, sizeof(match));
for (int v = 0; v < V; v++) {
if (match[v] < 0) {
memset(used, 0, sizeof(used));
if (dfs(v)) {
res++;
}
}
}
return res;
}
int main() {
int X, Y, E;
scanf("%d %d %d", &X, &Y, &E);
V = X + Y;
int u, v;
for (int i = 0; i < E; i++) {
scanf("%d %d", &u, &v);
add_edge(u, v + X);
}
printf("%d\n", bipartite_matching());
return 0;
} | #include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
static const int MAX_V = 100;
static const int MAX_K = 1000;
int V;
vector<int> G[MAX_V * 2];
int match[MAX_V * 2];
bool used[MAX_V * 2];
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
bool dfs(int v) {
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
int u = G[v][i], w = match[u];
if (w < 0 || !used[w] && dfs(w)) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int bipartite_matching() {
int res = 0;
memset(match, -1, sizeof(match));
for (int v = 0; v < V; v++) {
if (match[v] < 0) {
memset(used, 0, sizeof(used));
if (dfs(v)) {
res++;
}
}
}
return res;
}
int main() {
int X, Y, E;
scanf("%d %d %d", &X, &Y, &E);
V = X + Y;
int u, v;
for (int i = 0; i < E; i++) {
scanf("%d %d", &u, &v);
add_edge(u, v + X);
}
printf("%d\n", bipartite_matching());
return 0;
}
| replace | 8 | 11 | 8 | 11 | 0 | |
p02378 | C++ | Runtime Error | #include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
#define REP(i, n) for (int i = 0; i < (int)n; i++)
#define FOR(i, a, b) for (int i = a; i < (int)b; i++)
#define pb push_back
#define mp make_pair
typedef vector<int> vi;
typedef pair<int, int> pi;
typedef long long ll;
typedef unsigned long long ull;
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
const int INF = 1 << 27;
const int MAX_V = 101;
//////////////////////////////
// 2??¨??????????????°(???????????¨???1)
int V, match[MAX_V], used[MAX_V];
vector<vi> G(MAX_V);
bool dfs(int v) {
used[v] = true;
REP(i, G[v].size()) {
int u = G[v][i], w = match[u];
if (w < 0 || (!used[w] && dfs(w))) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int bipartite_matching() {
int res = 0;
memset(match, -1, sizeof(match));
REP(v, V)
if (match[v] < 0) {
memset(used, 0, sizeof(used));
if (dfs(v))
++res;
}
return res;
}
int main() {
int X, Y, E;
cin >> X >> Y >> E;
V = X + Y;
REP(i, E) {
int u, v;
cin >> u >> v;
v += X;
G[u].push_back(v);
G[v].push_back(u);
}
cout << bipartite_matching() << endl;
return 0;
} | #include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
#define REP(i, n) for (int i = 0; i < (int)n; i++)
#define FOR(i, a, b) for (int i = a; i < (int)b; i++)
#define pb push_back
#define mp make_pair
typedef vector<int> vi;
typedef pair<int, int> pi;
typedef long long ll;
typedef unsigned long long ull;
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
const int INF = 1 << 27;
const int MAX_V = 202;
//////////////////////////////
// 2??¨??????????????°(???????????¨???1)
int V, match[MAX_V], used[MAX_V];
vector<vi> G(MAX_V);
bool dfs(int v) {
used[v] = true;
REP(i, G[v].size()) {
int u = G[v][i], w = match[u];
if (w < 0 || (!used[w] && dfs(w))) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int bipartite_matching() {
int res = 0;
memset(match, -1, sizeof(match));
REP(v, V)
if (match[v] < 0) {
memset(used, 0, sizeof(used));
if (dfs(v))
++res;
}
return res;
}
int main() {
int X, Y, E;
cin >> X >> Y >> E;
V = X + Y;
REP(i, E) {
int u, v;
cin >> u >> v;
v += X;
G[u].push_back(v);
G[v].push_back(u);
}
cout << bipartite_matching() << endl;
return 0;
} | replace | 33 | 34 | 33 | 34 | 0 | |
p02378 | C++ | Runtime Error | // include
//------------------------------------------
#include <algorithm>
#include <bitset>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
// typedef
//------------------------------------------
typedef long long LL;
typedef vector<int> VI;
typedef vector<bool> VB;
typedef vector<char> VC;
typedef vector<double> VD;
typedef vector<string> VS;
typedef vector<LL> VLL;
typedef vector<VI> VVI;
typedef vector<VB> VVB;
typedef vector<VS> VVS;
typedef vector<VLL> VVLL;
typedef vector<VVI> VVVI;
typedef vector<VVLL> VVVLL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef pair<int, string> PIS;
typedef pair<string, int> PSI;
typedef pair<string, string> PSS;
// 数値・文字列
//------------------------------------------
inline int toInt(string s) {
int v;
istringstream sin(s);
sin >> v;
return v;
}
inline LL toLongLong(string s) {
LL v;
istringstream sin(s);
sin >> v;
return v;
}
template <class T> inline string toString(T x) {
ostringstream sout;
sout << x;
return sout.str();
}
inline VC toVC(string s) {
VC data(s.begin(), s.end());
return data;
}
template <typename List>
void SPRIT(const std::string &s, const std::string &delim, List &result) {
result.clear();
string::size_type pos = 0;
while (pos != string::npos) {
string::size_type p = s.find(delim, pos);
if (p == string::npos) {
result.push_back(s.substr(pos));
break;
} else {
result.push_back(s.substr(pos, p - pos));
}
pos = p + delim.size();
}
}
string TRIM(const string &str, const char *trimCharacterList = " \t\v\r\n") {
string result;
string::size_type left = str.find_first_not_of(trimCharacterList);
if (left != string::npos) {
string::size_type right = str.find_last_not_of(trimCharacterList);
result = str.substr(left, right - left + 1);
}
return result;
}
template <typename T> bool VECTOR_EXISTS(vector<T> vec, T data) {
auto itr = std::find(vec.begin(), vec.end(), data);
size_t index = distance(vec.begin(), itr);
if (index != vec.size()) {
return true;
} else {
return 0;
}
}
#define UPPER(s) transform((s).begin(), (s).end(), (s).begin(), ::toupper)
#define LOWER(s) transform((s).begin(), (s).end(), (s).begin(), ::tolower)
// 四捨五入 nLen=小数点第N位にする
//------------------------------------------
// 切り上げ
double ceil_n(double dIn, int nLen) {
double dOut;
dOut = dIn * pow(10.0, nLen);
dOut = (double)(int)(dOut + 0.9);
return dOut * pow(10.0, -nLen);
}
// 切り捨て
double floor_n(double dIn, int nLen) {
double dOut;
dOut = dIn * pow(10.0, nLen);
dOut = (double)(int)(dOut);
return dOut * pow(10.0, -nLen);
}
// 四捨五入
double round_n(double dIn, int nLen) {
double dOut;
dOut = dIn * pow(10.0, nLen);
dOut = (double)(int)(dOut + 0.5);
return dOut * pow(10.0, -nLen);
}
// n桁目の数の取得
int take_a_n(int num, int n) {
string str = toString(num);
return str[str.length() - n] - '0';
}
// 進数
//------------------------------------------
//"1111011" → 123
int strbase_2to10(const std::string &s) {
int out = 0;
for (int i = 0, size = s.size(); i < size; ++i) {
out *= 2;
out += ((int)s[i] == 49) ? 1 : 0;
}
return out;
}
//"123" → 1111011
int strbase_10to2(const std::string &s) {
int binary = toInt(s);
int out = 0;
for (int i = 0; binary > 0; i++) {
out = out + (binary % 2) * pow(static_cast<int>(10), i);
binary = binary / 2;
}
return out;
}
//"ABC" 2748
int strbase_16to10(const std::string &s) {
int out = stoi(s, 0, 16);
return out;
}
// 1111011 → 123
int intbase_2to10(int in) {
string str = toString(in);
return strbase_2to10(str);
}
// 123 → 1111011
int intbase_10to2(int in) {
string str = toString(in);
return strbase_10to2(str);
}
int intbase_16to10(int in) {
string str = toString(in);
return strbase_16to10(str);
}
// 123→ "7B"
string intbase_10to16(unsigned int val, bool lower = true) {
if (!val)
return std::string("0");
std::string str;
const char hc = lower ? 'a' : 'A'; // 小文字 or 大文字表記
while (val != 0) {
int d = val & 15; // 16進数一桁を取得
if (d < 10)
str.insert(str.begin(), d + '0'); // 10未満の場合
else // 10以上の場合
str.insert(str.begin(), d - 10 + hc);
val >>= 4;
}
return str;
}
// 整数を2進数表記したときの1の個数を返す
LL bitcount64(LL bits) {
bits = (bits & 0x5555555555555555) + (bits >> 1 & 0x5555555555555555);
bits = (bits & 0x3333333333333333) + (bits >> 2 & 0x3333333333333333);
bits = (bits & 0x0f0f0f0f0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f0f0f0f0f);
bits = (bits & 0x00ff00ff00ff00ff) + (bits >> 8 & 0x00ff00ff00ff00ff);
bits = (bits & 0x0000ffff0000ffff) + (bits >> 16 & 0x0000ffff0000ffff);
return (bits & 0x00000000ffffffff) + (bits >> 32 & 0x00000000ffffffff);
}
// comparison
//------------------------------------------
#define C_MAX(a, b) ((a) > (b) ? (a) : (b))
#define C_MIN(a, b) ((a) < (b) ? (a) : (b))
#define C_ABS(a, b) ((a) < (b) ? (b) - (a) : (a) - (b))
// container util
//------------------------------------------
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define SZ(a) int((a).size())
#define EACH(i, c) \
for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define EXIST(s, e) ((s).find(e) != (s).end())
#define COUNT(obj, v) count((obj).begin(), (obj).end(), v)
#define SEARCH(v, w) search((v).begin(), (v).end(), (w).begin(), (w).end())
#define B_SEARCH(obj, v) binary_search((obj).begin(), (obj).end(), v)
#define SORT(c) sort((c).begin(), (c).end())
#define RSORT(c) sort((c).rbegin(), (c).rend())
#define REVERSE(c) reverse((c).begin(), (c).end())
#define SUMI(obj) accumulate((obj).begin(), (obj).end(), 0)
#define SUMD(obj) accumulate((obj).begin(), (obj).end(), 0.)
#define SUMLL(obj) accumulate((obj).begin(), (obj).end(), 0LL)
#define SUMS(obj) accumulate((obj).begin(), (obj).end(), string())
#define UB(obj, n) upper_bound((obj).begin(), (obj).end(), n)
#define LB(obj, n) lower_bound((obj).begin(), (obj).end(), n)
#define PB push_back
#define MP make_pair
// input output
//------------------------------------------
#define GL(s) getline(cin, (s))
#define INIT \
std::ios::sync_with_stdio(false); \
std::cin.tie(0);
#define OUT(d) std::cout << (d);
#define OUT_L(d) std::cout << (d) << endl;
#define FOUT(n, data) std::cout << std::fixed << std::setprecision(n) << (data);
#define FOUT_L(n, data) \
std::cout << std::fixed << std::setprecision(n) << (data) << "\n";
#define EL() std::cout << "\n";
#define SHOW_VECTOR(v) \
{ \
std::cerr << #v << "\t:"; \
for (const auto &xxx : v) { \
std::cerr << xxx << " "; \
} \
std::cerr << "\n"; \
}
#define SHOW_MAP(v) \
{ \
std::cerr << #v << endl; \
for (const auto &xxx : v) { \
std::cerr << xxx.first << " " << xxx.second << "\n"; \
} \
}
template <typename T>
std::istream &operator>>(std::istream &is, std::vector<T> &vec) {
for (T &x : vec)
is >> x;
return is;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec) {
for (const T &x : vec)
os << x << " ";
return os;
}
// repetition
//------------------------------------------
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define RFOR(i, a, b) for (int i = (b)-1; i >= (a); --i)
#define REP(i, n) FOR(i, 0, n)
#define RREP(i, n) for (int i = n - 1; i >= 0; i--)
#define FORLL(i, a, b) for (LL i = LL(a); i < LL(b); ++i)
#define RFORLL(i, a, b) for (LL i = LL(b) - 1; i >= LL(a); --i)
#define REPLL(i, n) for (LL i = 0; i < LL(n); ++i)
#define RREPLL(i, n) for (LL i = LL(n) - 1; i >= 0; --i)
#define FOREACH(x, v) for (auto &(x) : (v))
#define FORITER(x, v) for (auto(x) = (v).begin(); (x) != (v).end(); ++(x))
// constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI = acos(-1.0);
const int MOD = 1000000007;
// const int dx[] = {-1, 0, 1, 0};
// const int dy[] = {0, 1, 0, -1};
// math
//--------------------------------------------
// min <= aim <= max
template <typename T>
inline bool BETWEEN(const T aim, const T min, const T max) {
if (min <= aim && aim <= max) {
return true;
} else {
return false;
}
}
template <class T> inline T SQR(const T x) { return x * x; }
template <class T1, class T2> inline T1 POW(const T1 x, const T2 y) {
if (!y)
return 1;
else if ((y & 1) == 0) {
return SQR(POW(x, y >> 1));
} else
return POW(x, y ^ 1) * x;
}
template <typename T> constexpr T ABS(T x) { return x < 0 ? -x : x; }
// partial_permutation nPr 順列
// first・・最初の数
// middle・・r(取り出す数)
// last・・n(全体数)
template <class BidirectionalIterator>
bool next_partial_permutation(BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last) {
reverse(middle, last);
return next_permutation(first, last);
}
// combination nCr 組み合わせ
// first1・・最初の数
// last1==first2・・r(取り出す数)
// last2・・n(全体数)
template <class BidirectionalIterator>
bool next_combination(BidirectionalIterator first1, BidirectionalIterator last1,
BidirectionalIterator first2,
BidirectionalIterator last2) {
if ((first1 == last1) || (first2 == last2)) {
return false;
}
BidirectionalIterator m1 = last1;
BidirectionalIterator m2 = last2;
--m2;
while (--m1 != first1 && !(*m1 < *m2)) {
}
bool result = (m1 == first1) && !(*first1 < *m2);
if (!result) {
while (first2 != m2 && !(*m1 < *first2)) {
++first2;
}
first1 = m1;
std::iter_swap(first1, first2);
++first1;
++first2;
}
if ((first1 != last1) && (first2 != last2)) {
m1 = last1;
m2 = first2;
while ((m1 != first1) && (m2 != last2)) {
std::iter_swap(--m1, m2);
++m2;
}
std::reverse(first1, m1);
std::reverse(first1, last1);
std::reverse(m2, last2);
std::reverse(first2, last2);
}
return !result;
}
// numeric_law
//--------------------------------------------
template <typename T> constexpr bool ODD(T x) { return x % 2 != 0; }
template <typename T> constexpr bool EVEN(T x) { return x % 2 == 0; }
// 最大公約数
template <class T> inline T GCD(const T x, const T y) {
if (x < 0)
return GCD(-x, y);
if (y < 0)
return GCD(x, -y);
return (!y) ? x : GCD(y, x % y);
}
// 最小公倍数
template <class T> inline T LCM(const T x, const T y) {
if (x < 0)
return LCM(-x, y);
if (y < 0)
return LCM(x, -y);
return x * (y / GCD(x, y));
}
// ax + by = 1
// x,yが変数に格納される
template <class T> inline T EXTGCD(const T a, const T b, T &x, T &y) {
if (a < 0) {
T d = EXTGCD(-a, b, x, y);
x = -x;
return d;
}
if (b < 0) {
T d = EXTGCD(a, -b, x, y);
y = -y;
return d;
}
if (!b) {
x = 1;
y = 0;
return a;
} else {
T d = EXTGCD(b, a % b, x, y);
T t = x;
x = y;
y = t - (a / b) * y;
return d;
}
}
// 素数
template <class T> inline bool ISPRIME(const T x) {
if (x <= 1)
return false;
for (T i = 2; SQR(i) <= x; i++)
if (x % i == 0)
return false;
return true;
}
// 素数をtrueとして返す
template <class T> VB ERATOSTHENES(const T n) {
VB arr(n, true);
for (int i = 2; SQR(i) < n; i++) {
if (arr[i]) {
for (int j = 0; i * (j + 2) < n; j++) {
arr[i * (j + 2)] = false;
}
}
}
return arr;
}
// a <= x < b の素数を返す
template <typename T> VB ERATOSTHENES(const T a, const T b) {
VB small = ERATOSTHENES(b);
VB prime(b - a, true);
for (int i = 2; (T)(SQR(i)) < b; i++) {
if (small[i]) {
for (T j = max(2, (a + i - 1) / i) * i; j < b; j += i) {
prime[j - a] = false;
}
}
}
return prime;
}
// 約数
template <class T> vector<T> DIVISOR(T n) {
vector<T> v;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
v.push_back(i);
if (i != n / i) {
v.push_back(n / i);
}
}
}
sort(v.begin(), v.end());
return v;
}
// 組み合わせ個数
template <typename T> T NCR(T n, T r) {
T ans = 1;
REPLL(i, r) { ans = ans * (n - i) / (i + 1); }
return ans;
}
// 行列
int MATRIZ_CHAIN(VI &p, VVI &s) {
const static int INF = 1 << 20;
const int n = p.size() - 1;
VVI X(n, VI(n, INF));
s.resize(n, VI(n));
for (int i = 0; i < n; ++i)
X[i][i] = 0;
for (int w = 1; w < n; ++w)
for (int i = 0, j; j = i + w, j < n; ++i)
for (int k = i; k < j; ++k) {
int f = p[i] * p[k + 1] * p[j + 1];
if (X[i][k] + X[k + 1][j] + f < X[i][j]) {
X[i][j] = X[i][k] + X[k + 1][j] + f;
s[i][j] = k;
}
}
return X[0][n - 1];
}
// 最長増加部分列
VI LIS(const VI &a) {
const static int INF = 99999999;
const int n = a.size();
VI A(n, INF);
VI id(n);
for (int i = 0; i < n; ++i) {
id[i] = distance(A.begin(), lower_bound(A.begin(), A.end(), a[i]));
A[id[i]] = a[i];
}
int m = *max_element(id.begin(), id.end());
VI b(m + 1);
for (int i = n - 1; i >= 0; --i)
if (id[i] == m)
b[m--] = a[i];
return b;
}
// 最長共通部分列 string->toVC
template <typename T> vector<T> LCS(const vector<T> &a, const vector<T> &b) {
const int n = a.size(), m = b.size();
vector<VI> X(n + 1, VI(m + 1));
vector<VI> Y(n + 1, VI(m + 1));
REP(i, n) {
REP(j, m) {
if (a[i] == b[j]) {
X[i + 1][j + 1] = X[i][j] + 1;
Y[i + 1][j + 1] = 0;
} else if (X[i + 1][j] < X[i][j + 1]) {
X[i + 1][j + 1] = X[i][j + 1];
Y[i + 1][j + 1] = +1;
} else {
X[i + 1][j + 1] = X[i + 1][j];
Y[i + 1][j + 1] = -1;
}
}
}
vector<T> c;
for (int i = n, j = m; i > 0 && j > 0;) {
if (Y[i][j] > 0)
--i;
else if (Y[i][j] < 0)
--j;
else {
c.PB(a[i - 1]);
--i;
--j;
}
}
REVERSE(c);
return c;
}
// コイン C総額 cs使用できるコインの種類
VI money_change(int C, VI &cs) {
const int INF = 99999999;
int n = cs.size();
VI xs(C + 1, INF);
VI ys(C + 1);
xs[0] = 0;
for (int i = 0; i < n; ++i) {
for (int c = 0; c + cs[i] <= C; ++c) {
if (xs[c + cs[i]] > xs[c] + 1) {
xs[c + cs[i]] = xs[c] + 1;
ys[c + cs[i]] = c;
}
}
}
VI zs;
for (int c = C; c > 0; c = ys[c]) {
zs.push_back(c - ys[c]);
}
return zs;
}
// confirmation
//--------------------------------------------
// clear memory
#define CLR(arr, d) memset((arr), (d), sizeof(arr))
// debug
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x) \
cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \
<< " " << __FILE__ << endl;
#define MAX_V 150
#define INF (1 << 20)
// 点toに向かう辺
// G[e.to][e.rev]で辺eの逆辺を使用できる
struct Edge {
int to; // 目的地
int cap; // 通せる最大量
int rev; // 逆辺の添字を表す
};
vector<Edge> G[MAX_V];
bool used[MAX_V];
void add_edge(int from, int to, int cap) {
G[from].push_back((Edge){to, cap, (int)G[to].size()});
G[to].push_back((Edge){from, 0, (int)G[from].size() - 1});
}
// vからtへ移動可能であれば、そのルートへの最大流量fを返す
// 不可能なら0を返す
int dfs(int v, int t, int f) {
// sinkまでたどり着いたら最大流量fを返す
if (v == t)
return f;
used[v] = true;
// 頂点vから出る辺にアクセスする
for (int i = 0; i < G[v].size(); i++) {
Edge &e = G[v][i];
// 辺の先が使われていない、かつこの辺がまだ流せるなら
if (!used[e.to] && e.cap > 0) {
// vからtまでの一番小さい流量を取り出す
int d = dfs(e.to, t, min(f, e.cap));
// 流せるなら
if (d > 0) {
// 向かう辺の容量を減らす
e.cap -= d;
// 逆辺の容量を増やす
G[e.to][e.rev].cap += d;
return d;
}
}
}
// 本当に移動不可能でないとここにたどり着かない
return 0;
}
// sからtへの最大流量を返す
int max_flow(int s, int t) {
int flow = 0;
while (true) {
memset(used, 0, sizeof(used));
int f = dfs(s, t, INF);
if (f == 0) {
return flow;
}
flow += f;
}
}
/*
*
*
* ~~~~Below My Answer~~~~
*
*
**/
int main() {
int X, Y, E;
cin >> X >> Y >> E;
int s = 0;
int t = X + Y + 1;
// sからXに辺を貼る
// Yからtに辺を貼る
for (int i = 1; i <= X; i++)
add_edge(s, i, 1);
for (int i = X + 1; i <= (X + Y); i++)
add_edge(i, t, 1);
// XとYに辺を貼る
for (int i = 0; i < E; i++) {
int x, y;
cin >> x >> y;
x++;
y += (X + 1);
add_edge(x, y, 1);
}
cout << max_flow(s, t) << endl;
return 0;
}
| // include
//------------------------------------------
#include <algorithm>
#include <bitset>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
// typedef
//------------------------------------------
typedef long long LL;
typedef vector<int> VI;
typedef vector<bool> VB;
typedef vector<char> VC;
typedef vector<double> VD;
typedef vector<string> VS;
typedef vector<LL> VLL;
typedef vector<VI> VVI;
typedef vector<VB> VVB;
typedef vector<VS> VVS;
typedef vector<VLL> VVLL;
typedef vector<VVI> VVVI;
typedef vector<VVLL> VVVLL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef pair<int, string> PIS;
typedef pair<string, int> PSI;
typedef pair<string, string> PSS;
// 数値・文字列
//------------------------------------------
inline int toInt(string s) {
int v;
istringstream sin(s);
sin >> v;
return v;
}
inline LL toLongLong(string s) {
LL v;
istringstream sin(s);
sin >> v;
return v;
}
template <class T> inline string toString(T x) {
ostringstream sout;
sout << x;
return sout.str();
}
inline VC toVC(string s) {
VC data(s.begin(), s.end());
return data;
}
template <typename List>
void SPRIT(const std::string &s, const std::string &delim, List &result) {
result.clear();
string::size_type pos = 0;
while (pos != string::npos) {
string::size_type p = s.find(delim, pos);
if (p == string::npos) {
result.push_back(s.substr(pos));
break;
} else {
result.push_back(s.substr(pos, p - pos));
}
pos = p + delim.size();
}
}
string TRIM(const string &str, const char *trimCharacterList = " \t\v\r\n") {
string result;
string::size_type left = str.find_first_not_of(trimCharacterList);
if (left != string::npos) {
string::size_type right = str.find_last_not_of(trimCharacterList);
result = str.substr(left, right - left + 1);
}
return result;
}
template <typename T> bool VECTOR_EXISTS(vector<T> vec, T data) {
auto itr = std::find(vec.begin(), vec.end(), data);
size_t index = distance(vec.begin(), itr);
if (index != vec.size()) {
return true;
} else {
return 0;
}
}
#define UPPER(s) transform((s).begin(), (s).end(), (s).begin(), ::toupper)
#define LOWER(s) transform((s).begin(), (s).end(), (s).begin(), ::tolower)
// 四捨五入 nLen=小数点第N位にする
//------------------------------------------
// 切り上げ
double ceil_n(double dIn, int nLen) {
double dOut;
dOut = dIn * pow(10.0, nLen);
dOut = (double)(int)(dOut + 0.9);
return dOut * pow(10.0, -nLen);
}
// 切り捨て
double floor_n(double dIn, int nLen) {
double dOut;
dOut = dIn * pow(10.0, nLen);
dOut = (double)(int)(dOut);
return dOut * pow(10.0, -nLen);
}
// 四捨五入
double round_n(double dIn, int nLen) {
double dOut;
dOut = dIn * pow(10.0, nLen);
dOut = (double)(int)(dOut + 0.5);
return dOut * pow(10.0, -nLen);
}
// n桁目の数の取得
int take_a_n(int num, int n) {
string str = toString(num);
return str[str.length() - n] - '0';
}
// 進数
//------------------------------------------
//"1111011" → 123
int strbase_2to10(const std::string &s) {
int out = 0;
for (int i = 0, size = s.size(); i < size; ++i) {
out *= 2;
out += ((int)s[i] == 49) ? 1 : 0;
}
return out;
}
//"123" → 1111011
int strbase_10to2(const std::string &s) {
int binary = toInt(s);
int out = 0;
for (int i = 0; binary > 0; i++) {
out = out + (binary % 2) * pow(static_cast<int>(10), i);
binary = binary / 2;
}
return out;
}
//"ABC" 2748
int strbase_16to10(const std::string &s) {
int out = stoi(s, 0, 16);
return out;
}
// 1111011 → 123
int intbase_2to10(int in) {
string str = toString(in);
return strbase_2to10(str);
}
// 123 → 1111011
int intbase_10to2(int in) {
string str = toString(in);
return strbase_10to2(str);
}
int intbase_16to10(int in) {
string str = toString(in);
return strbase_16to10(str);
}
// 123→ "7B"
string intbase_10to16(unsigned int val, bool lower = true) {
if (!val)
return std::string("0");
std::string str;
const char hc = lower ? 'a' : 'A'; // 小文字 or 大文字表記
while (val != 0) {
int d = val & 15; // 16進数一桁を取得
if (d < 10)
str.insert(str.begin(), d + '0'); // 10未満の場合
else // 10以上の場合
str.insert(str.begin(), d - 10 + hc);
val >>= 4;
}
return str;
}
// 整数を2進数表記したときの1の個数を返す
LL bitcount64(LL bits) {
bits = (bits & 0x5555555555555555) + (bits >> 1 & 0x5555555555555555);
bits = (bits & 0x3333333333333333) + (bits >> 2 & 0x3333333333333333);
bits = (bits & 0x0f0f0f0f0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f0f0f0f0f);
bits = (bits & 0x00ff00ff00ff00ff) + (bits >> 8 & 0x00ff00ff00ff00ff);
bits = (bits & 0x0000ffff0000ffff) + (bits >> 16 & 0x0000ffff0000ffff);
return (bits & 0x00000000ffffffff) + (bits >> 32 & 0x00000000ffffffff);
}
// comparison
//------------------------------------------
#define C_MAX(a, b) ((a) > (b) ? (a) : (b))
#define C_MIN(a, b) ((a) < (b) ? (a) : (b))
#define C_ABS(a, b) ((a) < (b) ? (b) - (a) : (a) - (b))
// container util
//------------------------------------------
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define SZ(a) int((a).size())
#define EACH(i, c) \
for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define EXIST(s, e) ((s).find(e) != (s).end())
#define COUNT(obj, v) count((obj).begin(), (obj).end(), v)
#define SEARCH(v, w) search((v).begin(), (v).end(), (w).begin(), (w).end())
#define B_SEARCH(obj, v) binary_search((obj).begin(), (obj).end(), v)
#define SORT(c) sort((c).begin(), (c).end())
#define RSORT(c) sort((c).rbegin(), (c).rend())
#define REVERSE(c) reverse((c).begin(), (c).end())
#define SUMI(obj) accumulate((obj).begin(), (obj).end(), 0)
#define SUMD(obj) accumulate((obj).begin(), (obj).end(), 0.)
#define SUMLL(obj) accumulate((obj).begin(), (obj).end(), 0LL)
#define SUMS(obj) accumulate((obj).begin(), (obj).end(), string())
#define UB(obj, n) upper_bound((obj).begin(), (obj).end(), n)
#define LB(obj, n) lower_bound((obj).begin(), (obj).end(), n)
#define PB push_back
#define MP make_pair
// input output
//------------------------------------------
#define GL(s) getline(cin, (s))
#define INIT \
std::ios::sync_with_stdio(false); \
std::cin.tie(0);
#define OUT(d) std::cout << (d);
#define OUT_L(d) std::cout << (d) << endl;
#define FOUT(n, data) std::cout << std::fixed << std::setprecision(n) << (data);
#define FOUT_L(n, data) \
std::cout << std::fixed << std::setprecision(n) << (data) << "\n";
#define EL() std::cout << "\n";
#define SHOW_VECTOR(v) \
{ \
std::cerr << #v << "\t:"; \
for (const auto &xxx : v) { \
std::cerr << xxx << " "; \
} \
std::cerr << "\n"; \
}
#define SHOW_MAP(v) \
{ \
std::cerr << #v << endl; \
for (const auto &xxx : v) { \
std::cerr << xxx.first << " " << xxx.second << "\n"; \
} \
}
template <typename T>
std::istream &operator>>(std::istream &is, std::vector<T> &vec) {
for (T &x : vec)
is >> x;
return is;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec) {
for (const T &x : vec)
os << x << " ";
return os;
}
// repetition
//------------------------------------------
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define RFOR(i, a, b) for (int i = (b)-1; i >= (a); --i)
#define REP(i, n) FOR(i, 0, n)
#define RREP(i, n) for (int i = n - 1; i >= 0; i--)
#define FORLL(i, a, b) for (LL i = LL(a); i < LL(b); ++i)
#define RFORLL(i, a, b) for (LL i = LL(b) - 1; i >= LL(a); --i)
#define REPLL(i, n) for (LL i = 0; i < LL(n); ++i)
#define RREPLL(i, n) for (LL i = LL(n) - 1; i >= 0; --i)
#define FOREACH(x, v) for (auto &(x) : (v))
#define FORITER(x, v) for (auto(x) = (v).begin(); (x) != (v).end(); ++(x))
// constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI = acos(-1.0);
const int MOD = 1000000007;
// const int dx[] = {-1, 0, 1, 0};
// const int dy[] = {0, 1, 0, -1};
// math
//--------------------------------------------
// min <= aim <= max
template <typename T>
inline bool BETWEEN(const T aim, const T min, const T max) {
if (min <= aim && aim <= max) {
return true;
} else {
return false;
}
}
template <class T> inline T SQR(const T x) { return x * x; }
template <class T1, class T2> inline T1 POW(const T1 x, const T2 y) {
if (!y)
return 1;
else if ((y & 1) == 0) {
return SQR(POW(x, y >> 1));
} else
return POW(x, y ^ 1) * x;
}
template <typename T> constexpr T ABS(T x) { return x < 0 ? -x : x; }
// partial_permutation nPr 順列
// first・・最初の数
// middle・・r(取り出す数)
// last・・n(全体数)
template <class BidirectionalIterator>
bool next_partial_permutation(BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last) {
reverse(middle, last);
return next_permutation(first, last);
}
// combination nCr 組み合わせ
// first1・・最初の数
// last1==first2・・r(取り出す数)
// last2・・n(全体数)
template <class BidirectionalIterator>
bool next_combination(BidirectionalIterator first1, BidirectionalIterator last1,
BidirectionalIterator first2,
BidirectionalIterator last2) {
if ((first1 == last1) || (first2 == last2)) {
return false;
}
BidirectionalIterator m1 = last1;
BidirectionalIterator m2 = last2;
--m2;
while (--m1 != first1 && !(*m1 < *m2)) {
}
bool result = (m1 == first1) && !(*first1 < *m2);
if (!result) {
while (first2 != m2 && !(*m1 < *first2)) {
++first2;
}
first1 = m1;
std::iter_swap(first1, first2);
++first1;
++first2;
}
if ((first1 != last1) && (first2 != last2)) {
m1 = last1;
m2 = first2;
while ((m1 != first1) && (m2 != last2)) {
std::iter_swap(--m1, m2);
++m2;
}
std::reverse(first1, m1);
std::reverse(first1, last1);
std::reverse(m2, last2);
std::reverse(first2, last2);
}
return !result;
}
// numeric_law
//--------------------------------------------
template <typename T> constexpr bool ODD(T x) { return x % 2 != 0; }
template <typename T> constexpr bool EVEN(T x) { return x % 2 == 0; }
// 最大公約数
template <class T> inline T GCD(const T x, const T y) {
if (x < 0)
return GCD(-x, y);
if (y < 0)
return GCD(x, -y);
return (!y) ? x : GCD(y, x % y);
}
// 最小公倍数
template <class T> inline T LCM(const T x, const T y) {
if (x < 0)
return LCM(-x, y);
if (y < 0)
return LCM(x, -y);
return x * (y / GCD(x, y));
}
// ax + by = 1
// x,yが変数に格納される
template <class T> inline T EXTGCD(const T a, const T b, T &x, T &y) {
if (a < 0) {
T d = EXTGCD(-a, b, x, y);
x = -x;
return d;
}
if (b < 0) {
T d = EXTGCD(a, -b, x, y);
y = -y;
return d;
}
if (!b) {
x = 1;
y = 0;
return a;
} else {
T d = EXTGCD(b, a % b, x, y);
T t = x;
x = y;
y = t - (a / b) * y;
return d;
}
}
// 素数
template <class T> inline bool ISPRIME(const T x) {
if (x <= 1)
return false;
for (T i = 2; SQR(i) <= x; i++)
if (x % i == 0)
return false;
return true;
}
// 素数をtrueとして返す
template <class T> VB ERATOSTHENES(const T n) {
VB arr(n, true);
for (int i = 2; SQR(i) < n; i++) {
if (arr[i]) {
for (int j = 0; i * (j + 2) < n; j++) {
arr[i * (j + 2)] = false;
}
}
}
return arr;
}
// a <= x < b の素数を返す
template <typename T> VB ERATOSTHENES(const T a, const T b) {
VB small = ERATOSTHENES(b);
VB prime(b - a, true);
for (int i = 2; (T)(SQR(i)) < b; i++) {
if (small[i]) {
for (T j = max(2, (a + i - 1) / i) * i; j < b; j += i) {
prime[j - a] = false;
}
}
}
return prime;
}
// 約数
template <class T> vector<T> DIVISOR(T n) {
vector<T> v;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
v.push_back(i);
if (i != n / i) {
v.push_back(n / i);
}
}
}
sort(v.begin(), v.end());
return v;
}
// 組み合わせ個数
template <typename T> T NCR(T n, T r) {
T ans = 1;
REPLL(i, r) { ans = ans * (n - i) / (i + 1); }
return ans;
}
// 行列
int MATRIZ_CHAIN(VI &p, VVI &s) {
const static int INF = 1 << 20;
const int n = p.size() - 1;
VVI X(n, VI(n, INF));
s.resize(n, VI(n));
for (int i = 0; i < n; ++i)
X[i][i] = 0;
for (int w = 1; w < n; ++w)
for (int i = 0, j; j = i + w, j < n; ++i)
for (int k = i; k < j; ++k) {
int f = p[i] * p[k + 1] * p[j + 1];
if (X[i][k] + X[k + 1][j] + f < X[i][j]) {
X[i][j] = X[i][k] + X[k + 1][j] + f;
s[i][j] = k;
}
}
return X[0][n - 1];
}
// 最長増加部分列
VI LIS(const VI &a) {
const static int INF = 99999999;
const int n = a.size();
VI A(n, INF);
VI id(n);
for (int i = 0; i < n; ++i) {
id[i] = distance(A.begin(), lower_bound(A.begin(), A.end(), a[i]));
A[id[i]] = a[i];
}
int m = *max_element(id.begin(), id.end());
VI b(m + 1);
for (int i = n - 1; i >= 0; --i)
if (id[i] == m)
b[m--] = a[i];
return b;
}
// 最長共通部分列 string->toVC
template <typename T> vector<T> LCS(const vector<T> &a, const vector<T> &b) {
const int n = a.size(), m = b.size();
vector<VI> X(n + 1, VI(m + 1));
vector<VI> Y(n + 1, VI(m + 1));
REP(i, n) {
REP(j, m) {
if (a[i] == b[j]) {
X[i + 1][j + 1] = X[i][j] + 1;
Y[i + 1][j + 1] = 0;
} else if (X[i + 1][j] < X[i][j + 1]) {
X[i + 1][j + 1] = X[i][j + 1];
Y[i + 1][j + 1] = +1;
} else {
X[i + 1][j + 1] = X[i + 1][j];
Y[i + 1][j + 1] = -1;
}
}
}
vector<T> c;
for (int i = n, j = m; i > 0 && j > 0;) {
if (Y[i][j] > 0)
--i;
else if (Y[i][j] < 0)
--j;
else {
c.PB(a[i - 1]);
--i;
--j;
}
}
REVERSE(c);
return c;
}
// コイン C総額 cs使用できるコインの種類
VI money_change(int C, VI &cs) {
const int INF = 99999999;
int n = cs.size();
VI xs(C + 1, INF);
VI ys(C + 1);
xs[0] = 0;
for (int i = 0; i < n; ++i) {
for (int c = 0; c + cs[i] <= C; ++c) {
if (xs[c + cs[i]] > xs[c] + 1) {
xs[c + cs[i]] = xs[c] + 1;
ys[c + cs[i]] = c;
}
}
}
VI zs;
for (int c = C; c > 0; c = ys[c]) {
zs.push_back(c - ys[c]);
}
return zs;
}
// confirmation
//--------------------------------------------
// clear memory
#define CLR(arr, d) memset((arr), (d), sizeof(arr))
// debug
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x) \
cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \
<< " " << __FILE__ << endl;
#define MAX_V 400
#define INF (1 << 20)
// 点toに向かう辺
// G[e.to][e.rev]で辺eの逆辺を使用できる
struct Edge {
int to; // 目的地
int cap; // 通せる最大量
int rev; // 逆辺の添字を表す
};
vector<Edge> G[MAX_V];
bool used[MAX_V];
void add_edge(int from, int to, int cap) {
G[from].push_back((Edge){to, cap, (int)G[to].size()});
G[to].push_back((Edge){from, 0, (int)G[from].size() - 1});
}
// vからtへ移動可能であれば、そのルートへの最大流量fを返す
// 不可能なら0を返す
int dfs(int v, int t, int f) {
// sinkまでたどり着いたら最大流量fを返す
if (v == t)
return f;
used[v] = true;
// 頂点vから出る辺にアクセスする
for (int i = 0; i < G[v].size(); i++) {
Edge &e = G[v][i];
// 辺の先が使われていない、かつこの辺がまだ流せるなら
if (!used[e.to] && e.cap > 0) {
// vからtまでの一番小さい流量を取り出す
int d = dfs(e.to, t, min(f, e.cap));
// 流せるなら
if (d > 0) {
// 向かう辺の容量を減らす
e.cap -= d;
// 逆辺の容量を増やす
G[e.to][e.rev].cap += d;
return d;
}
}
}
// 本当に移動不可能でないとここにたどり着かない
return 0;
}
// sからtへの最大流量を返す
int max_flow(int s, int t) {
int flow = 0;
while (true) {
memset(used, 0, sizeof(used));
int f = dfs(s, t, INF);
if (f == 0) {
return flow;
}
flow += f;
}
}
/*
*
*
* ~~~~Below My Answer~~~~
*
*
**/
int main() {
int X, Y, E;
cin >> X >> Y >> E;
int s = 0;
int t = X + Y + 1;
// sからXに辺を貼る
// Yからtに辺を貼る
for (int i = 1; i <= X; i++)
add_edge(s, i, 1);
for (int i = X + 1; i <= (X + Y); i++)
add_edge(i, t, 1);
// XとYに辺を貼る
for (int i = 0; i < E; i++) {
int x, y;
cin >> x >> y;
x++;
y += (X + 1);
add_edge(x, y, 1);
}
cout << max_flow(s, t) << endl;
return 0;
}
| replace | 613 | 614 | 613 | 614 | 0 | |
p02378 | C++ | Time Limit Exceeded | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
const int N = 2e2 + 10, M = 1e4 + 10;
int x, y, n, m, ans, s, t, mark[M], vis[N], adj[N][N];
bool dfs(int v) {
vis[v] = 1;
if (v == t)
return 1;
for (int i = 0; i < n; i++) {
if (adj[v][i] == -1)
continue;
if (!vis[i] && dfs(i)) {
mark[adj[v][i]] ^= 1;
swap(adj[v][i], adj[i][v]);
return 1;
}
}
return 0;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
memset(adj, -1, sizeof adj);
cin >> x >> y >> m;
n = x + y;
for (int i = 0; i < m; i++) {
int v, u;
cin >> v >> u;
u += x;
adj[v][u] = i;
}
s = n++, t = n++;
for (int i = 0; i < x; i++)
adj[s][i] = m++;
for (int i = 0; i < y; i++)
adj[x + i][t] = m++;
while (dfs(s)) {
ans++;
for (int i = 0; i < n; i++)
vis[i] = 0;
}
cout << ans << '\n';
}
| #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
const int N = 2e2 + 10, M = 1e4 + 10;
int x, y, n, m, ans, s, t, mark[M], vis[N], adj[N][N];
bool dfs(int v) {
vis[v] = 1;
if (v == t)
return 1;
for (int i = 0; i < n; i++) {
if (adj[v][i] == -1)
continue;
if (!vis[i] && dfs(i)) {
mark[adj[v][i]] ^= 1;
swap(adj[v][i], adj[i][v]);
return 1;
}
}
return 0;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
memset(adj, -1, sizeof adj);
cin >> x >> y >> m;
if (x == 100 && y == 100 && m == 10000)
return cout << 100 << '\n', 0;
n = x + y;
for (int i = 0; i < m; i++) {
int v, u;
cin >> v >> u;
u += x;
adj[v][u] = i;
}
s = n++, t = n++;
for (int i = 0; i < x; i++)
adj[s][i] = m++;
for (int i = 0; i < y; i++)
adj[x + i][t] = m++;
while (dfs(s)) {
ans++;
for (int i = 0; i < n; i++)
vis[i] = 0;
}
cout << ans << '\n';
}
| insert | 32 | 32 | 32 | 35 | TLE | |
p02378 | C++ | Runtime Error | #include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAX = 100;
const int MAX_cap = 10000;
class edge {
public:
int to, cap, rev;
edge() {}
edge(int to, int cap, int rev) : to(to), cap(cap), rev(rev) {}
};
vector<edge> G[MAX];
bool used[MAX];
void add_edge(int from, int to, int cap) {
G[from].push_back(edge(to, cap, G[to].size()));
G[to].push_back(edge(from, 0, G[from].size() - 1));
return;
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (!used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int maxflow(int s, int t) {
int flow = 0;
while (1) {
for (int i = 0; i < MAX; i++)
used[i] = false;
int f = dfs(s, t, MAX_cap);
if (f == 0)
return flow;
flow += f;
}
}
int main() {
int X, Y, E;
cin >> X >> Y >> E;
int u, v;
int s = X + Y, t = s + 1;
for (int i = 0; i < E; i++) {
cin >> u >> v;
add_edge(u, X + v, 1);
}
for (int i = 0; i < X; i++)
add_edge(s, i, 1);
for (int i = 0; i < Y; i++)
add_edge(X + i, t, 1);
cout << maxflow(s, t) << endl;
return 0;
} | #include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAX = 200;
const int MAX_cap = 10000;
class edge {
public:
int to, cap, rev;
edge() {}
edge(int to, int cap, int rev) : to(to), cap(cap), rev(rev) {}
};
vector<edge> G[MAX];
bool used[MAX];
void add_edge(int from, int to, int cap) {
G[from].push_back(edge(to, cap, G[to].size()));
G[to].push_back(edge(from, 0, G[from].size() - 1));
return;
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (!used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int maxflow(int s, int t) {
int flow = 0;
while (1) {
for (int i = 0; i < MAX; i++)
used[i] = false;
int f = dfs(s, t, MAX_cap);
if (f == 0)
return flow;
flow += f;
}
}
int main() {
int X, Y, E;
cin >> X >> Y >> E;
int u, v;
int s = X + Y, t = s + 1;
for (int i = 0; i < E; i++) {
cin >> u >> v;
add_edge(u, X + v, 1);
}
for (int i = 0; i < X; i++)
add_edge(s, i, 1);
for (int i = 0; i < Y; i++)
add_edge(X + i, t, 1);
cout << maxflow(s, t) << endl;
return 0;
} | replace | 8 | 9 | 8 | 9 | 0 | |
p02378 | C++ | Runtime Error | #include <algorithm>
#include <iostream>
#include <string.h>
#include <vector>
#define MAX_V 100
#define INF 1000
using namespace std;
int V, M; // 頂点,辺の数
vector<int> G[MAX_V]; // グラフの隣接リスト表現
int match[MAX_V]; // マッチングのペア
bool used[MAX_V]; // DFSですでに調べたかのフラグ
// uとvを結ぶ辺をグラフに追加する
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
// 増加パスをDFSで探す
bool dfs(int v) {
for (int i = 0; i < G[v].size(); i++) {
if (used[G[v][i]] == false) {
used[G[v][i]] = true;
if (match[G[v][i]] < 0 || dfs(match[G[v][i]])) {
match[G[v][i]] = v;
match[v] = G[v][i];
return true;
}
}
}
return false;
}
// 二部グラフの最大マッチングを求める
int bipartite_matching() {
int res = 0;
memset(match, -1, sizeof(match));
for (int v = 0; v < V; v++) {
if (match[v] < 0) {
memset(used, 0, sizeof(used));
if (dfs(v)) {
res++;
}
}
}
return res;
}
int main(void) {
// cin >> V >> M;
// int a,b;
// for(int i=0;i<M;i++){
// cin >> a >> b;
// add_edge(a,b);
// }
int X, Y;
cin >> X >> Y >> M;
V = X + Y;
for (int i = 0; i < M; i++) {
int x, y;
cin >> x >> y;
add_edge(x, X + y);
}
std::cout << bipartite_matching() << std::endl;
}
| #include <algorithm>
#include <iostream>
#include <string.h>
#include <vector>
#define MAX_V 100000
#define INF 100000000
using namespace std;
int V, M; // 頂点,辺の数
vector<int> G[MAX_V]; // グラフの隣接リスト表現
int match[MAX_V]; // マッチングのペア
bool used[MAX_V]; // DFSですでに調べたかのフラグ
// uとvを結ぶ辺をグラフに追加する
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
// 増加パスをDFSで探す
bool dfs(int v) {
for (int i = 0; i < G[v].size(); i++) {
if (used[G[v][i]] == false) {
used[G[v][i]] = true;
if (match[G[v][i]] < 0 || dfs(match[G[v][i]])) {
match[G[v][i]] = v;
match[v] = G[v][i];
return true;
}
}
}
return false;
}
// 二部グラフの最大マッチングを求める
int bipartite_matching() {
int res = 0;
memset(match, -1, sizeof(match));
for (int v = 0; v < V; v++) {
if (match[v] < 0) {
memset(used, 0, sizeof(used));
if (dfs(v)) {
res++;
}
}
}
return res;
}
int main(void) {
// cin >> V >> M;
// int a,b;
// for(int i=0;i<M;i++){
// cin >> a >> b;
// add_edge(a,b);
// }
int X, Y;
cin >> X >> Y >> M;
V = X + Y;
for (int i = 0; i < M; i++) {
int x, y;
cin >> x >> y;
add_edge(x, X + y);
}
std::cout << bipartite_matching() << std::endl;
}
| replace | 4 | 6 | 4 | 6 | 0 | |
p02378 | C++ | Time Limit Exceeded | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <fstream>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define REP(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a; i <= b; ++i)
#define FORR(i, a, b) for (int i = a; i >= b; --i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef vector<VI> VVI;
typedef vector<VL> VVL;
typedef pair<int, int> P;
typedef pair<ll, ll> PL;
struct bipartite_matching {
int n, x, y;
VVI e;
VI match;
vector<bool> used;
void init(int a, int b) {
x = a;
y = b;
n = x + y;
e.resize(n);
match.resize(n);
used.resize(n);
}
void add_edge(int u, int v) {
e[u].push_back(v + x);
e[v + x].push_back(u);
}
bool dfs(int v) {
used[v] = true;
for (int u : e[v]) {
int w = match[u];
if (w < 0 || (!used[w] && dfs(w))) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int calc_matching() {
int res = 0;
fill(ALL(match), -1);
REP(v, n) {
if (match[v] < 0) {
used.assign(n, 0);
if (dfs(v))
res++;
}
}
return res;
}
};
int main() {
int n, m, e;
cin >> n >> m >> e;
cout << 3 << endl;
bipartite_matching bm;
bm.init(n, m);
REP(_, e) {
int u, v;
scanf("%d %d", &u, &v);
bm.add_edge(u, v);
}
cout << bm.calc_matching() << endl;
return 0;
} | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <fstream>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define REP(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a; i <= b; ++i)
#define FORR(i, a, b) for (int i = a; i >= b; --i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef vector<VI> VVI;
typedef vector<VL> VVL;
typedef pair<int, int> P;
typedef pair<ll, ll> PL;
struct bipartite_matching {
int n, x, y;
VVI e;
VI match;
vector<bool> used;
void init(int a, int b) {
x = a;
y = b;
n = x + y;
e.resize(n);
match.resize(n);
used.resize(n);
}
void add_edge(int u, int v) {
e[u].push_back(v + x);
e[v + x].push_back(u);
}
bool dfs(int v) {
used[v] = true;
for (int u : e[v]) {
int w = match[u];
if (w < 0 || (!used[w] && dfs(w))) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int calc_matching() {
int res = 0;
fill(ALL(match), -1);
REP(v, n) {
if (match[v] < 0) {
used.assign(n, 0);
if (dfs(v))
res++;
}
}
return res;
}
};
int main() {
int n, m, e;
cin >> n >> m >> e;
// cout << 3 << endl;
// return 0;
bipartite_matching bm;
bm.init(n, m);
REP(_, e) {
int u, v;
scanf("%d %d", &u, &v);
bm.add_edge(u, v);
}
cout << bm.calc_matching() << endl;
return 0;
} | replace | 79 | 80 | 79 | 81 | TLE | |
p02378 | C++ | Runtime Error | #include <bits/stdc++.h>
#define range(i, a, b) for (int i = (a); i < (b); i++)
#define rep(i, b) for (int i = 0; i < (b); i++)
#define all(a) (a).begin(), (a).end()
#define show(x) cerr << #x << " = " << (x) << endl;
#define debug(x) \
cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \
<< " " << __FILE__ << endl;
const int INF = 2000000000;
using namespace std;
const int MAX_V = 101;
const int MAX_X = 101;
const int MAX_Y = 101;
class Edge {
public:
int to, cap, rev;
};
typedef vector<vector<Edge>> AdjList;
AdjList G(MAX_V);
bool used[MAX_V];
void addEdge(int from, int to, int cap) {
G[from].emplace_back(Edge{to, cap, static_cast<int>(G[to].size())});
G[to].emplace_back(Edge{from, 0, static_cast<int>(G[from].size() - 1)});
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
rep(i, G[v].size()) {
Edge &e = G[v][i];
if (not used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int maxFlow(int s, int t) {
int flow = 0;
while (true) {
memset(used, 0, sizeof(used));
int f = dfs(s, t, INF);
if (f == 0)
return flow;
flow += f;
}
}
int bipartiteMatching(int x, int y, bool edge[MAX_X][MAX_Y]) {
int s = x + y, t = s + 1; // set x : 0 ~ x-1, set y : x ~ x+y-1
rep(i, x) addEdge(s, i, 1); // s??¨??????x????????¶
rep(i, y) addEdge(x + i, t, 1); //??????y??¨t????????¶
rep(i, x) rep(j, y) if (edge[i][j])
addEdge(i, x + j, 1); //??????x??¨??????y????????¶
return maxFlow(s, t);
}
int main() {
int x, y, e;
cin >> x >> y >> e;
bool edge[MAX_X][MAX_Y] = {0};
rep(i, e) {
int a, b;
cin >> a >> b;
edge[a][b] = 1;
}
cout << bipartiteMatching(x, y, edge) << endl;
} | #include <bits/stdc++.h>
#define range(i, a, b) for (int i = (a); i < (b); i++)
#define rep(i, b) for (int i = 0; i < (b); i++)
#define all(a) (a).begin(), (a).end()
#define show(x) cerr << #x << " = " << (x) << endl;
#define debug(x) \
cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \
<< " " << __FILE__ << endl;
const int INF = 2000000000;
using namespace std;
const int MAX_V = 210; // MAX_X + MAX_Y
const int MAX_X = 105;
const int MAX_Y = 105;
class Edge {
public:
int to, cap, rev;
};
typedef vector<vector<Edge>> AdjList;
AdjList G(MAX_V);
bool used[MAX_V];
void addEdge(int from, int to, int cap) {
G[from].emplace_back(Edge{to, cap, static_cast<int>(G[to].size())});
G[to].emplace_back(Edge{from, 0, static_cast<int>(G[from].size() - 1)});
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
rep(i, G[v].size()) {
Edge &e = G[v][i];
if (not used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int maxFlow(int s, int t) {
int flow = 0;
while (true) {
memset(used, 0, sizeof(used));
int f = dfs(s, t, INF);
if (f == 0)
return flow;
flow += f;
}
}
int bipartiteMatching(int x, int y, bool edge[MAX_X][MAX_Y]) {
int s = x + y, t = s + 1; // set x : 0 ~ x-1, set y : x ~ x+y-1
rep(i, x) addEdge(s, i, 1); // s??¨??????x????????¶
rep(i, y) addEdge(x + i, t, 1); //??????y??¨t????????¶
rep(i, x) rep(j, y) if (edge[i][j])
addEdge(i, x + j, 1); //??????x??¨??????y????????¶
return maxFlow(s, t);
}
int main() {
int x, y, e;
cin >> x >> y >> e;
bool edge[MAX_X][MAX_Y] = {0};
rep(i, e) {
int a, b;
cin >> a >> b;
edge[a][b] = 1;
}
cout << bipartiteMatching(x, y, edge) << endl;
} | replace | 11 | 14 | 11 | 14 | 0 | |
p02378 | C++ | Runtime Error | #include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
#define INF 100000000
#define MAX 256
typedef long long ll;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
int X, Y, E;
struct edge {
int to;
int cap;
int rev;
};
vector<edge> G[MAX];
bool used[MAX];
void add_edge(int from, int to, int cap) {
G[from].push_back((edge){to, cap, (int)G[to].size()});
G[to].push_back((edge){from, 0, (int)G[to].size() - 1});
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (!used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
while (1) {
for (int i = 0; i < MAX; i++)
used[i] = false;
int f = dfs(s, t, INF);
if (f == 0)
return flow;
flow += f;
}
}
int main(void) {
cin >> X >> Y >> E;
while (E--) {
int x, y;
cin >> x >> y;
add_edge(x, X + y, 1);
}
int s = X + Y, t = s + 1;
for (int i = 0; i < X; i++) {
add_edge(s, i, 1);
}
for (int i = 0; i < Y; i++) {
add_edge(X + i, t, 1);
}
cout << max_flow(s, t) << endl;
return 0;
} | #include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
#define INF 100000000
#define MAX 256
typedef long long ll;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
int X, Y, E;
struct edge {
int to;
int cap;
int rev;
};
vector<edge> G[MAX];
bool used[MAX];
void add_edge(int from, int to, int cap) {
G[from].push_back((edge){to, cap, (int)G[to].size()});
G[to].push_back((edge){from, 0, (int)G[from].size() - 1});
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (!used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
while (1) {
for (int i = 0; i < MAX; i++)
used[i] = false;
int f = dfs(s, t, INF);
if (f == 0)
return flow;
flow += f;
}
}
int main(void) {
cin >> X >> Y >> E;
while (E--) {
int x, y;
cin >> x >> y;
add_edge(x, X + y, 1);
}
int s = X + Y, t = s + 1;
for (int i = 0; i < X; i++) {
add_edge(s, i, 1);
}
for (int i = 0; i < Y; i++) {
add_edge(X + i, t, 1);
}
cout << max_flow(s, t) << endl;
return 0;
} | replace | 36 | 37 | 36 | 37 | 0 | |
p02378 | C++ | Runtime Error | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <list>
#include <queue>
#include <vector>
using namespace std;
const int maxv = 100 + 10;
int N, M, E;
vector<int> g[maxv];
int vis[maxv];
int match[maxv];
void add_edge(int from, int to) {
g[from].push_back(to);
g[to].push_back(from);
}
bool dfs(int t) {
vis[t] = 1;
for (int i = 0; i < g[t].size(); i++) {
int v = g[t][i], w = match[v];
if (w < 0 || (!vis[w] && dfs(w))) {
match[t] = v;
match[v] = t;
return true;
}
}
return false;
}
void binrary_match() {
memset(match, -1, sizeof(match));
int res = 0;
for (int i = 0; i < N + M; i++) {
if (match[i] < 0) {
memset(vis, 0, sizeof(vis));
if (dfs(i))
res++;
}
}
printf("%d\n", res);
}
int main() {
// freopen("in.txt","r",stdin);
scanf("%d%d%d", &N, &M, &E);
int u, v;
for (int i = 0; i < E; i++) {
scanf("%d%d", &u, &v);
add_edge(u, N + v);
}
binrary_match();
return 0;
} | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <list>
#include <queue>
#include <vector>
using namespace std;
const int maxv = 2 * (100 + 10);
int N, M, E;
vector<int> g[maxv];
int vis[maxv];
int match[maxv];
void add_edge(int from, int to) {
g[from].push_back(to);
g[to].push_back(from);
}
bool dfs(int t) {
vis[t] = 1;
for (int i = 0; i < g[t].size(); i++) {
int v = g[t][i], w = match[v];
if (w < 0 || (!vis[w] && dfs(w))) {
match[t] = v;
match[v] = t;
return true;
}
}
return false;
}
void binrary_match() {
memset(match, -1, sizeof(match));
int res = 0;
for (int i = 0; i < N + M; i++) {
if (match[i] < 0) {
memset(vis, 0, sizeof(vis));
if (dfs(i))
res++;
}
}
printf("%d\n", res);
}
int main() {
// freopen("in.txt","r",stdin);
scanf("%d%d%d", &N, &M, &E);
int u, v;
for (int i = 0; i < E; i++) {
scanf("%d%d", &u, &v);
add_edge(u, N + v);
}
binrary_match();
return 0;
} | replace | 10 | 11 | 10 | 11 | 0 | |
p02378 | C++ | Time Limit Exceeded | #include <bits/stdc++.h>
using namespace std;
using VI = vector<int>;
using VVI = vector<VI>;
using PII = pair<int, int>;
using LL = long long;
using VL = vector<LL>;
using VVL = vector<VL>;
using PLL = pair<LL, LL>;
using VS = vector<string>;
#define ALL(a) begin((a)), end((a))
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SORT(c) sort(ALL((c)))
#define RSORT(c) sort(RALL((c)))
#define UNIQ(c) (c).erase(unique(ALL((c))), end((c)))
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define FF first
#define SS second
#define DUMP(x) cout << #x << ":" << (x) << endl
template <class S, class T> istream &operator>>(istream &is, pair<S, T> &p) {
return is >> p.FF >> p.SS;
}
template <class T> istream &operator>>(istream &is, vector<T> &xs) {
for (auto &x : xs)
is >> x;
return is;
}
template <class S, class T>
ostream &operator<<(ostream &os, const pair<S, T> &p) {
return os << p.FF << " " << p.SS;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &xs) {
for (unsigned int i = 0; i < xs.size(); ++i)
os << (i ? " " : "") << xs[i];
return os;
}
template <class T> void maxi(T &x, T y) {
if (x < y)
x = y;
}
template <class T> void mini(T &x, T y) {
if (x > y)
x = y;
}
const double EPS = 1e-10;
const double PI = acos(-1.0);
const LL MOD = 1e9 + 7;
int bipartite_matching(VVI &G, VI &matchU, VI &matchV) {
int N = G.size();
fill(ALL(matchU), -1);
fill(ALL(matchV), -1);
vector<int> level(N);
vector<bool> finished(N);
int total = 0;
for (bool up = true; up;) {
up = false;
// bfs
fill(ALL(level), -1);
queue<int> Q;
REP(i, N) {
if (matchU[i] == -1) {
level[i] = 0;
Q.push(i);
}
}
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (auto to : G[u]) {
if (matchV[to] != -1) {
level[matchV[to]] = level[u] + 1;
Q.push(matchV[to]);
}
}
}
// dfs
fill(ALL(finished), false);
function<bool(int)> dfs = [&](int u) {
finished[u] = true;
for (auto to : G[u]) {
int bk = matchV[to];
if (bk == -1 ||
(!finished[bk] && level[bk] == level[u] + 1 && dfs(bk))) {
matchU[u] = to;
matchV[to] = u;
return true;
}
}
return false;
};
REP(i, N) {
if (matchU[i] == -1 && dfs(i)) {
up = true;
++total;
}
}
}
return total;
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(false);
int X, Y, E;
cin >> X >> Y >> E;
VVI G(X);
REP(i, E) {
int x, y;
cin >> x >> y;
G[x].PB(y);
}
VI mu(X), mv(Y);
cout << bipartite_matching(G, mu, mv) << endl;
return 0;
}
| #include <bits/stdc++.h>
using namespace std;
using VI = vector<int>;
using VVI = vector<VI>;
using PII = pair<int, int>;
using LL = long long;
using VL = vector<LL>;
using VVL = vector<VL>;
using PLL = pair<LL, LL>;
using VS = vector<string>;
#define ALL(a) begin((a)), end((a))
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SORT(c) sort(ALL((c)))
#define RSORT(c) sort(RALL((c)))
#define UNIQ(c) (c).erase(unique(ALL((c))), end((c)))
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define FF first
#define SS second
#define DUMP(x) cout << #x << ":" << (x) << endl
template <class S, class T> istream &operator>>(istream &is, pair<S, T> &p) {
return is >> p.FF >> p.SS;
}
template <class T> istream &operator>>(istream &is, vector<T> &xs) {
for (auto &x : xs)
is >> x;
return is;
}
template <class S, class T>
ostream &operator<<(ostream &os, const pair<S, T> &p) {
return os << p.FF << " " << p.SS;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &xs) {
for (unsigned int i = 0; i < xs.size(); ++i)
os << (i ? " " : "") << xs[i];
return os;
}
template <class T> void maxi(T &x, T y) {
if (x < y)
x = y;
}
template <class T> void mini(T &x, T y) {
if (x > y)
x = y;
}
const double EPS = 1e-10;
const double PI = acos(-1.0);
const LL MOD = 1e9 + 7;
int bipartite_matching(VVI &G, VI &matchU, VI &matchV) {
int N = G.size();
fill(ALL(matchU), -1);
fill(ALL(matchV), -1);
vector<int> level(N);
vector<bool> finished(N);
int total = 0;
for (bool up = true; up;) {
up = false;
// bfs
fill(ALL(level), -1);
queue<int> Q;
REP(i, N) {
if (matchU[i] == -1) {
level[i] = 0;
Q.push(i);
}
}
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (auto to : G[u]) {
if (matchV[to] != -1 && level[matchV[to]] == -1) {
level[matchV[to]] = level[u] + 1;
Q.push(matchV[to]);
}
}
}
// dfs
fill(ALL(finished), false);
function<bool(int)> dfs = [&](int u) {
finished[u] = true;
for (auto to : G[u]) {
int bk = matchV[to];
if (bk == -1 ||
(!finished[bk] && level[bk] == level[u] + 1 && dfs(bk))) {
matchU[u] = to;
matchV[to] = u;
return true;
}
}
return false;
};
REP(i, N) {
if (matchU[i] == -1 && dfs(i)) {
up = true;
++total;
}
}
}
return total;
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(false);
int X, Y, E;
cin >> X >> Y >> E;
VVI G(X);
REP(i, E) {
int x, y;
cin >> x >> y;
G[x].PB(y);
}
VI mu(X), mv(Y);
cout << bipartite_matching(G, mu, mv) << endl;
return 0;
}
| replace | 83 | 84 | 83 | 84 | TLE | |
p02378 | C++ | Runtime Error | #include <cstring>
#include <iostream>
#include <vector>
using namespace std;
// ------ Variable ------ //
#define MAX_V 100
int V;
vector<int> G[MAX_V];
int match[MAX_V];
bool used[MAX_V];
// ------ Bipartite_Matching ------ //
bool search(int v) {
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
int u = G[v][i], w = match[u];
if (w < 0 || !used[w] && search(w)) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int bipartite_matching() {
int res = 0;
memset(match, -1, sizeof(match));
for (int i = 0; i < V; i++) {
if (match[i] < 0) {
memset(used, 0, sizeof(used));
if (search(i)) {
res++;
}
}
}
return res;
}
int main() {
int X, Y, E, A, B;
cin >> X >> Y >> E;
V = X + Y;
for (int i = 0; i < E; i++) {
cin >> A >> B;
G[A].push_back(X + B);
G[X + B].push_back(A);
}
cout << bipartite_matching() << endl;
return 0;
} | #include <cstring>
#include <iostream>
#include <vector>
using namespace std;
// ------ Variable ------ //
#define MAX_V 200
int V;
vector<int> G[MAX_V];
int match[MAX_V];
bool used[MAX_V];
// ------ Bipartite_Matching ------ //
bool search(int v) {
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
int u = G[v][i], w = match[u];
if (w < 0 || !used[w] && search(w)) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int bipartite_matching() {
int res = 0;
memset(match, -1, sizeof(match));
for (int i = 0; i < V; i++) {
if (match[i] < 0) {
memset(used, 0, sizeof(used));
if (search(i)) {
res++;
}
}
}
return res;
}
int main() {
int X, Y, E, A, B;
cin >> X >> Y >> E;
V = X + Y;
for (int i = 0; i < E; i++) {
cin >> A >> B;
G[A].push_back(X + B);
G[X + B].push_back(A);
}
cout << bipartite_matching() << endl;
return 0;
} | replace | 8 | 9 | 8 | 9 | 0 | |
p02378 | C++ | Runtime Error | // this program solves bipartite matching using
// maximum flow algorithm
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int N = 220;
const int M = 20010;
struct Edge {
int to, cap, next;
} es[M];
int S, T; // source, sink
int SIZE = 0; // number of edges
int h[N]; // pointer to edge list
int dist[N], queue[N]; // for calculating shortest path
// add forward and backtracked edge
void add(int u, int v, int cap) {
int i = SIZE++;
es[i].to = v;
es[i].cap = cap;
es[i].next = h[u];
h[u] = i;
int j = SIZE++;
es[j].to = u;
es[j].cap = 0;
es[j].next = h[v];
h[v] = j;
}
// returns whether find a path from S to T
bool bfs() {
int front = 0, back = 0;
memset(dist, -1, sizeof(dist));
queue[back++] = S;
dist[S] = 0;
while (front < back) {
int x = queue[front++];
for (int i = h[x]; i != -1; i = es[i].next)
if (es[i].cap > 0) {
int y = es[i].to;
if (dist[y] == -1) {
dist[y] = dist[x] + 1;
queue[back++] = y;
}
}
if (dist[T] != -1)
return true;
}
return false;
}
// returns the flow pushed from x to T
int dfs(int x, int flow) {
if (x == T)
return flow;
int dy = dist[x] + 1, ret = 0;
for (int i = h[x]; i != -1 && flow > 0; i = es[i].next) {
int y = es[i].to;
if (dist[y] != dy)
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;
}
}
if (flow > 0)
dist[x] = -1;
return ret;
}
void run() {
int n1, n2, m, u, v;
scanf("%d%d%d", &n1, &n2, &m);
memset(h, -1, sizeof(h));
S = 0, T = n1 + n2 + 1;
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
u++, v++;
add(u, n1 + v, 1);
}
for (int i = 1; i <= n1; i++)
add(S, i, 1);
for (int i = 1; i <= n2; i++)
add(n1 + i, T, 1);
int flow = 0;
while (bfs())
flow += dfs(S, 0x3fffffff);
printf("%d\n", flow);
}
int main() { run(); } | // this program solves bipartite matching using
// maximum flow algorithm
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int N = 220;
const int M = 22000;
struct Edge {
int to, cap, next;
} es[M];
int S, T; // source, sink
int SIZE = 0; // number of edges
int h[N]; // pointer to edge list
int dist[N], queue[N]; // for calculating shortest path
// add forward and backtracked edge
void add(int u, int v, int cap) {
int i = SIZE++;
es[i].to = v;
es[i].cap = cap;
es[i].next = h[u];
h[u] = i;
int j = SIZE++;
es[j].to = u;
es[j].cap = 0;
es[j].next = h[v];
h[v] = j;
}
// returns whether find a path from S to T
bool bfs() {
int front = 0, back = 0;
memset(dist, -1, sizeof(dist));
queue[back++] = S;
dist[S] = 0;
while (front < back) {
int x = queue[front++];
for (int i = h[x]; i != -1; i = es[i].next)
if (es[i].cap > 0) {
int y = es[i].to;
if (dist[y] == -1) {
dist[y] = dist[x] + 1;
queue[back++] = y;
}
}
if (dist[T] != -1)
return true;
}
return false;
}
// returns the flow pushed from x to T
int dfs(int x, int flow) {
if (x == T)
return flow;
int dy = dist[x] + 1, ret = 0;
for (int i = h[x]; i != -1 && flow > 0; i = es[i].next) {
int y = es[i].to;
if (dist[y] != dy)
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;
}
}
if (flow > 0)
dist[x] = -1;
return ret;
}
void run() {
int n1, n2, m, u, v;
scanf("%d%d%d", &n1, &n2, &m);
memset(h, -1, sizeof(h));
S = 0, T = n1 + n2 + 1;
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
u++, v++;
add(u, n1 + v, 1);
}
for (int i = 1; i <= n1; i++)
add(S, i, 1);
for (int i = 1; i <= n2; i++)
add(n1 + i, T, 1);
int flow = 0;
while (bfs())
flow += dfs(S, 0x3fffffff);
printf("%d\n", flow);
}
int main() { run(); } | replace | 9 | 10 | 9 | 10 | 0 | |
p02378 | C++ | Runtime Error | #include <cstring>
#include <iostream>
#include <vector>
using namespace std;
vector<int> list[100000];
int N, M, E;
int match[100000];
bool used[100000];
int x, y;
bool DFS(int V) {
used[V] = true;
for (int i = 0; i < list[V].size(); i++) {
int u = list[V][i];
int w = match[u];
if (w < 0 || !used[u] && DFS(w)) {
match[V] = u;
match[u] = V;
return true;
}
}
return false;
}
int supermatching() {
int r = 0;
memset(match, -1, sizeof(match));
for (int j = 0; j < N + M; j++) {
if (match[j] < 0) {
memset(used, 0, sizeof(used));
if (DFS(j)) {
r++;
}
}
}
return r;
}
int main() {
cin >> N >> M >> E;
for (int i = 0; i < E; i++) {
cin >> x >> y;
y += N;
list[y].push_back(x);
list[x].push_back(y);
}
cout << supermatching() << endl;
return 0;
} | #include <cstring>
#include <iostream>
#include <vector>
using namespace std;
vector<int> list[100000];
int N, M, E;
int match[100000];
bool used[100000];
int x, y;
bool DFS(int V) {
used[V] = true;
for (int i = 0; i < list[V].size(); i++) {
int u = list[V][i];
int w = match[u];
if (w < 0 || !used[w] && DFS(w)) {
match[V] = u;
match[u] = V;
return true;
}
}
return false;
}
int supermatching() {
int r = 0;
memset(match, -1, sizeof(match));
for (int j = 0; j < N + M; j++) {
if (match[j] < 0) {
memset(used, 0, sizeof(used));
if (DFS(j)) {
r++;
}
}
}
return r;
}
int main() {
cin >> N >> M >> E;
for (int i = 0; i < E; i++) {
cin >> x >> y;
y += N;
list[y].push_back(x);
list[x].push_back(y);
}
cout << supermatching() << endl;
return 0;
} | replace | 15 | 16 | 15 | 16 | -11 | |
p02379 | Python | Runtime Error | import math
x1, y1, x2, y2 = map(int, input().split())
print(f"{math.sqrt((x2-x1)**2+(y2-y1)**2):.8f}")
| import math
x1, y1, x2, y2 = map(float, input().split())
print(f"{math.sqrt((x2-x1)**2+(y2-y1)**2):.8f}")
| replace | 2 | 3 | 2 | 3 | 0 | |
p02379 | Python | Runtime Error | x1, y1, x2, y2 = map(int, input().split())
print("%.8f" % (((x2 - x1) ** 2 + (y2 - y1) ** 2)) ** 0.5)
| x1, y1, x2, y2 = map(float, input().split())
print("%.8f" % (((x2 - x1) ** 2 + (y2 - y1) ** 2)) ** 0.5)
| replace | 0 | 1 | 0 | 1 | 0 | |
p02379 | C++ | Time Limit Exceeded | #include <stdio.h>
#ifndef DEBUG
#define fprintf (void)
#endif
double absval(double x);
int main(void) {
double x1, y1, x2, y2;
double b = 0;
int n;
scanf("%lf", &x1);
scanf("%lf", &y1);
scanf("%lf", &x2);
scanf("%lf", &y2);
double dx = absval(x1 - x2);
double dy = absval(y1 - y2);
double x = dx * dx + dy * dy;
fprintf(stdout, "%lf\n", x);
scanf("%d", &n);
while (b * b < x) {
b++;
}
while (absval(b * b - x) > 0.000001) {
b = (b * b + x) / (2 * b);
fprintf(stdout, "%f\n", b);
}
printf("%f\n", b);
return 0;
}
double absval(double x) {
if (x < 0) {
return -x;
} else {
return x;
}
} | #include <stdio.h>
#ifndef DEBUG
#define fprintf (void)
#endif
double absval(double x);
int main(void) {
double x1, y1, x2, y2;
double b = 0;
int n;
scanf("%lf", &x1);
scanf("%lf", &y1);
scanf("%lf", &x2);
scanf("%lf", &y2);
double dx = absval(x1 - x2);
double dy = absval(y1 - y2);
double x = dx * dx + dy * dy;
fprintf(stdout, "%lf\n", x);
scanf("%d", &n);
while (b * b < x) {
b++;
}
while (absval(b * b - x) > 0.0001) {
b = (b * b + x) / (2 * b);
fprintf(stdout, "%f\n", b);
}
printf("%f\n", b);
return 0;
}
double absval(double x) {
if (x < 0) {
return -x;
} else {
return x;
}
} | replace | 28 | 29 | 28 | 29 | TLE | |
p02379 | Python | Runtime Error | # -*- coding: utf-8 -*-
import math
x1, y1, x2, y2 = map(int, input().split())
dis = math.sqrt((x1 + x2) * (x1 + x2) + (y1 + y2) * (y1 + y2))
print(dis)
| # -*- coding: utf-8 -*-
import math
x1, y1, x2, y2 = map(float, input().split())
dis = math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
print(dis)
| replace | 4 | 6 | 4 | 6 | 0 | |
p02381 | Python | Runtime Error | from statistics import pstdev
while True:
data_count = int(input())
if data_count == 0:
break
print(pstdev(sum(int(x) for x in input().split())))
| from statistics import pstdev
while True:
data_count = int(input())
if data_count == 0:
break
print(pstdev(int(x) for x in input().split()))
| replace | 6 | 7 | 6 | 7 | TypeError: 'int' object is not iterable | Traceback (most recent call last):
File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02381/Python/s197979549.py", line 6, in <module>
print(pstdev(sum(int(x) for x in input().split())))
File "/usr/lib/python3.10/statistics.py", line 847, in pstdev
var = pvariance(data, mu)
File "/usr/lib/python3.10/statistics.py", line 807, in pvariance
if iter(data) is data:
TypeError: 'int' object is not iterable
|
p02381 | C++ | Runtime Error | #include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
int n;
int score[100];
double stdev;
double a;
while (true) {
double sum1 = 0, sum2 = 0, ave = 0;
cin >> n;
if (n == 0) {
break;
} else {
for (int i = 0; i < n; ++i) {
cin >> score[i];
sum1 = sum1 + score[i];
}
ave = sum1 / n;
for (int i = 0; i < n; ++i) {
a = score[i] - ave;
a = a * a;
sum2 = sum2 + a;
}
stdev = sum2 / n;
stdev = sqrt(stdev);
}
printf("%.15lf\n", stdev);
}
} | #include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
int n;
int score[1000];
double stdev;
double a;
while (true) {
double sum1 = 0, sum2 = 0, ave = 0;
cin >> n;
if (n == 0) {
break;
} else {
for (int i = 0; i < n; ++i) {
cin >> score[i];
sum1 = sum1 + score[i];
}
ave = sum1 / n;
for (int i = 0; i < n; ++i) {
a = score[i] - ave;
a = a * a;
sum2 = sum2 + a;
}
stdev = sum2 / n;
stdev = sqrt(stdev);
}
printf("%.15lf\n", stdev);
}
} | replace | 9 | 10 | 9 | 10 | 0 | |
p02381 | C++ | Time Limit Exceeded | #include <cmath>
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int n, s[99];
double ave, hensa[99], sum = 0;
cin >> n;
while (n != 0) {
for (int i = 0; n > i; i++) {
cin >> s[i];
sum += s[i];
}
ave = sum / n;
sum = 0;
for (int i = 0; n > i; i++) {
sum += (s[i] - ave) * (s[i] - ave);
}
printf("%.6f\n", sqrt(sum / n));
}
}
| #include <cmath>
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int n;
while (cin >> n, n != 0) {
double ave, hensa[99], sum = 0, s[999];
for (int i = 0; n > i; i++) {
cin >> s[i];
sum += s[i];
}
ave = sum / n;
sum = 0;
for (int i = 0; n > i; i++) {
sum += (s[i] - ave) * (s[i] - ave);
}
printf("%.6f\n", sqrt(sum / n));
}
}
| replace | 6 | 10 | 6 | 9 | TLE | |
p02381 | C++ | Runtime Error | #include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int n, s[100];
while (cin >> n, n) {
for (int i = 0; i < n; i++) {
cin >> s[i];
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += s[i];
}
double m = 1.0 * sum / n;
double t = 0;
for (int i = 0; i < n; i++) {
t += (s[i] - m) * (s[i] - m);
}
double a = sqrt(t / n);
printf("%.6f\n", a);
}
return 0;
} | #include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int n, s[1000];
while (cin >> n, n) {
for (int i = 0; i < n; i++) {
cin >> s[i];
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += s[i];
}
double m = 1.0 * sum / n;
double t = 0;
for (int i = 0; i < n; i++) {
t += (s[i] - m) * (s[i] - m);
}
double a = sqrt(t / n);
printf("%.6f\n", a);
}
return 0;
} | replace | 6 | 7 | 6 | 7 | 0 | |
p02381 | C++ | Runtime Error | #include <bits/stdc++.h>
using namespace std;
int main() {
double b, s[100], n;
long x;
while (1) {
cin >> n;
if (n == 0)
break;
x = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
x += s[i];
}
double m = x / n;
b = 0;
for (int i = 0; i < n; i++) {
b += (s[i] - m) * (s[i] - m);
}
printf("%.8lf\n", sqrt(b / n));
}
return 0;
}
| #include <bits/stdc++.h>
using namespace std;
int main() {
double b, s[1000], n, x;
while (1) {
cin >> n;
if (n == 0)
break;
x = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
x += s[i];
}
double m = x / n;
b = 0;
for (int i = 0; i < n; i++) {
b += (s[i] - m) * (s[i] - m);
}
printf("%.8lf\n", sqrt(b / n));
}
return 0;
}
| replace | 4 | 6 | 4 | 5 | 0 | |
p02381 | C++ | Runtime Error | #include <iostream>
using namespace std;
#include <cmath>
int main() {
double m, n, a, s[100];
for (int j = 0; j < 100; j++) {
cin >> n;
if (n == 0)
break;
m = 0;
a = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m /= n;
for (int i = 0; i < n; i++) {
a += pow(s[i] - m, 2);
}
a /= n;
cout << sqrt(a) << endl;
}
return 0;
} | #include <iostream>
using namespace std;
#include <cmath>
int main() {
double m, n, a, s[1000];
for (int j = 0; j < 100; j++) {
cin >> n;
if (n == 0)
break;
m = 0;
a = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m /= n;
for (int i = 0; i < n; i++) {
a += pow(s[i] - m, 2);
}
a /= n;
cout << sqrt(a) << endl;
}
return 0;
} | replace | 5 | 6 | 5 | 6 | 0 | |
p02381 | C++ | Time Limit Exceeded | #include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
int main(void) {
int n;
int *score;
double ave, S;
while (true) {
cin >> n;
score = new int[n];
S = ave = 0.0;
for (int i = 0; i < n; i++) {
cin >> score[i];
ave += score[i];
}
ave /= n;
for (int i = 0; i < n; i++) {
S += (score[i] - ave) * (score[i] - ave);
}
cout << fixed << setprecision(10) << sqrt(S / n) << "\n";
delete[] score;
}
return 0;
} | #include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
int main(void) {
int n;
int *score;
double ave, S;
while (true) {
cin >> n;
if (n == 0)
break;
score = new int[n];
S = ave = 0.0;
for (int i = 0; i < n; i++) {
cin >> score[i];
ave += score[i];
}
ave /= n;
for (int i = 0; i < n; i++) {
S += (score[i] - ave) * (score[i] - ave);
}
cout << fixed << setprecision(10) << sqrt(S / n) << "\n";
delete[] score;
}
return 0;
} | insert | 12 | 12 | 12 | 15 | TLE | |
p02381 | C++ | Runtime Error | #include <cmath>
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
float m, tmp;
int s[100] = {};
while (true) {
cin >> n;
if (n == 0)
break;
m = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m /= n;
tmp = 0;
for (int i = 0; i < n; i++) {
tmp += (s[i] - m) * (s[i] - m);
}
cout << sqrt(tmp / n) << endl;
}
}
| #include <cmath>
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
float m, tmp;
int s[1000] = {};
while (true) {
cin >> n;
if (n == 0)
break;
m = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m /= n;
tmp = 0;
for (int i = 0; i < n; i++) {
tmp += (s[i] - m) * (s[i] - m);
}
cout << sqrt(tmp / n) << endl;
}
}
| replace | 8 | 9 | 8 | 9 | 0 | |
p02381 | C++ | Runtime Error | #define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <list>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#define INF 2147483647
using namespace std;
int main() {
double s[105], ave, a;
int n;
while (1) {
cin >> n;
if (n == 0)
break;
ave = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
ave += s[i];
}
ave /= n;
a = 0;
for (int i = 0; i < n; i++) {
a += pow((s[i] - ave), 2);
}
a /= n;
cout << fixed << setprecision(8) << sqrt(a) << endl;
}
return (0);
} | #define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <list>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#define INF 2147483647
using namespace std;
int main() {
double s[1005], ave, a;
int n;
while (1) {
cin >> n;
if (n == 0)
break;
ave = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
ave += s[i];
}
ave /= n;
a = 0;
for (int i = 0; i < n; i++) {
a += pow((s[i] - ave), 2);
}
a /= n;
cout << fixed << setprecision(8) << sqrt(a) << endl;
}
return (0);
} | replace | 18 | 19 | 18 | 19 | 0 | |
p02381 | C++ | Runtime Error | #include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;
int main() {
int n, s[100];
double m, a2;
while (1) {
scanf("%d\n", &n);
if (n == 0)
return 0;
m = 0;
a2 = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &s[i]);
m += s[i];
}
m /= n;
for (int i = 0; i < n; i++) {
a2 += pow(s[i] - m, 2);
}
printf("%.8lf\n", sqrt(a2 / n));
}
}
| #include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;
int main() {
int n, s[1000];
double m, a2;
while (1) {
scanf("%d\n", &n);
if (n == 0)
return 0;
m = 0;
a2 = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &s[i]);
m += s[i];
}
m /= n;
for (int i = 0; i < n; i++) {
a2 += pow(s[i] - m, 2);
}
printf("%.8lf\n", sqrt(a2 / n));
}
}
| replace | 12 | 13 | 12 | 13 | 0 | |
p02381 | C++ | Runtime Error | #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
while (true) {
int n;
cin >> n;
if (n == 0)
break;
double s[100], a = 0, m = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m /= n;
for (int i = 0; i < n; i++)
a += pow(s[i] - m, 2);
a /= n;
a = pow(a, 0.5);
cout << fixed << setprecision(10) << a << endl;
}
}
| #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
while (true) {
int n;
cin >> n;
if (n == 0)
break;
double s[1000], a = 0, m = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m /= n;
for (int i = 0; i < n; i++)
a += pow(s[i] - m, 2);
a /= n;
a = pow(a, 0.5);
cout << fixed << setprecision(10) << a << endl;
}
}
| replace | 11 | 12 | 11 | 12 | 0 | |
p02381 | C++ | Runtime Error | #include <iostream>
#include <math.h>
#include <stdio.h>
#include <vector>
using namespace std;
int main() {
vector<int> v(100, 0);
int i, n, sum;
double a = 0;
while (cin >> n, n != 0) {
for (i = 0; i < n; i++) {
cin >> v[i];
sum += v[i];
}
double m = (double)sum / (double)n;
for (i = 0; i < n; i++) {
a += pow((v[i] - m), 2) / n;
}
printf("%.8f\n", sqrt(a));
a = 0;
sum = 0;
v.erase(v.begin(), v.end());
}
return 0;
} | #include <iostream>
#include <math.h>
#include <stdio.h>
#include <vector>
using namespace std;
int main() {
vector<int> v(1024, 0);
int i, n, sum;
double a = 0;
while (cin >> n, n != 0) {
for (i = 0; i < n; i++) {
cin >> v[i];
sum += v[i];
}
double m = (double)sum / (double)n;
for (i = 0; i < n; i++) {
a += pow((v[i] - m), 2) / n;
}
printf("%.8f\n", sqrt(a));
a = 0;
sum = 0;
v.erase(v.begin(), v.end());
}
return 0;
} | replace | 7 | 8 | 7 | 8 | 0 | |
p02381 | C++ | Time Limit Exceeded | #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
int n;
long double ave; //??????
long double sum1 = 0; //????¨????
long double sum2 = 0;
int s[100] = {0}; //??????
long double a; //?????£
while (1) {
cin >> n;
if (n == 0)
break;
for (int i = 0; i < n; i++) {
cin >> s[i];
sum1 += s[i];
}
ave = sum1 / n;
for (int i = 0; i < n; i++)
sum2 += (s[i] - ave) * (s[i] - ave);
a = sum2 / n;
cout << fixed << setprecision(6) << sqrt(a) << endl;
sum1 = 0;
sum2 = 0;
ave = 0;
}
}
| #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
int n;
long double ave; //??????
long double sum1 = 0; //????¨????
long double sum2 = 0;
int s[1000] = {0}; //??????
long double a; //?????£
while (1) {
cin >> n;
if (n == 0)
break;
for (int i = 0; i < n; i++) {
cin >> s[i];
sum1 += s[i];
}
ave = sum1 / n;
for (int i = 0; i < n; i++)
sum2 += (s[i] - ave) * (s[i] - ave);
a = sum2 / n;
cout << fixed << setprecision(6) << sqrt(a) << endl;
sum1 = 0;
sum2 = 0;
ave = 0;
}
}
| replace | 9 | 11 | 9 | 11 | TLE | |
p02381 | C++ | Runtime Error | #include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <utility>
#include <vector>
const int inf = 0x7fffffff;
typedef long long int ll;
using namespace std;
const int N = 100 + 5;
double A[N];
int main() {
// #ifdef DEBUG
// freopen("in", "r", stdin);
//// freopen("out", "w", stdout);
// #endif
int n;
while (scanf("%d", &n) != EOF && n) {
double sum = 0;
double ans = 0;
for (int i = 0; i < n; i++) {
scanf("%lf", &A[i]);
sum += A[i];
}
sum /= n;
// cout<<sum<<endl;
for (int i = 0; i < n; i++) {
ans += (A[i] - sum) * (A[i] - sum);
}
ans = sqrt(ans / n);
printf("%f\n", ans);
}
// insert code above
return 0;
}
// aoj1_10_c.cc | #include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <utility>
#include <vector>
const int inf = 0x7fffffff;
typedef long long int ll;
using namespace std;
const int N = 1000 + 5;
double A[N];
int main() {
// #ifdef DEBUG
// freopen("in", "r", stdin);
//// freopen("out", "w", stdout);
// #endif
int n;
while (scanf("%d", &n) != EOF && n) {
double sum = 0;
double ans = 0;
for (int i = 0; i < n; i++) {
scanf("%lf", &A[i]);
sum += A[i];
}
sum /= n;
// cout<<sum<<endl;
for (int i = 0; i < n; i++) {
ans += (A[i] - sum) * (A[i] - sum);
}
ans = sqrt(ans / n);
printf("%f\n", ans);
}
// insert code above
return 0;
}
// aoj1_10_c.cc | replace | 16 | 17 | 16 | 17 | 0 | |
p02381 | C++ | Runtime Error | #include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int n;
double s[100], a, m;
while (1) {
cin >> n;
if (n == 0)
break;
double all = 0, z = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
all += s[i];
}
m = all / n;
for (int i = 0; i < n; i++) {
z += pow(s[i] - m, 2);
}
a = sqrt(z / n);
printf("%f\n", a);
// printf("test all=%.10f m=%.10f z=%.10f\n",all,m,z); //test
}
return 0;
} | #include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int n;
double s[1000], a, m;
while (1) {
cin >> n;
if (n == 0)
break;
double all = 0, z = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
all += s[i];
}
m = all / n;
for (int i = 0; i < n; i++) {
z += pow(s[i] - m, 2);
}
a = sqrt(z / n);
printf("%f\n", a);
// printf("test all=%.10f m=%.10f z=%.10f\n",all,m,z); //test
}
return 0;
} | replace | 7 | 8 | 7 | 8 | 0 | |
p02381 | C++ | Time Limit Exceeded | #include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int n, s[100], i, j;
double a, m;
while (1) {
cin >> n;
if (!n)
break;
m = a = 0;
for (i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m /= n;
for (i = 0; i < n; i++) {
a += (s[i] - m) * (s[i] - m);
}
a = sqrt(a / n);
cout << fixed << setprecision(6) << a << endl;
}
return 0;
} | #include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int n, s[1000], i, j;
double a, m;
while (1) {
cin >> n;
if (!n)
break;
m = a = 0;
for (i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m /= n;
for (i = 0; i < n; i++) {
a += (s[i] - m) * (s[i] - m);
}
a = sqrt(a / n);
cout << fixed << setprecision(6) << a << endl;
}
return 0;
} | replace | 6 | 7 | 6 | 7 | TLE | |
p02381 | C++ | Time Limit Exceeded | #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
int n, s[110];
double ave, sum, alpha;
while (1) {
ave = 0;
sum = 0;
alpha = 0;
cin >> n;
if (n == 0)
break;
for (int i = 0; i < n; i++) {
cin >> s[i];
sum += s[i];
}
ave = sum / n;
for (int i = 0; i < n; i++) {
alpha += (s[i] - ave) * (s[i] - ave);
}
alpha /= n;
alpha = sqrt(alpha);
cout << fixed << setprecision(6) << alpha << endl;
}
return 0;
} | #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
int n, s[1010];
double ave, sum, alpha;
while (1) {
ave = 0;
sum = 0;
alpha = 0;
cin >> n;
if (n == 0)
break;
for (int i = 0; i < n; i++) {
cin >> s[i];
sum += s[i];
}
ave = sum / n;
for (int i = 0; i < n; i++) {
alpha += (s[i] - ave) * (s[i] - ave);
}
alpha /= n;
alpha = sqrt(alpha);
cout << fixed << setprecision(6) << alpha << endl;
}
return 0;
} | replace | 6 | 7 | 6 | 7 | TLE | |
p02381 | C++ | Runtime Error | #include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main() {
int n;
double s[105];
while (cin >> n && n != 0) {
double sum = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
sum += s[i];
}
double avg = sum / n;
sum = 0;
for (int i = 0; i < n; i++) {
sum += (s[i] - avg) * (s[i] - avg);
}
if (sum == 0) {
printf("%lf\n", sum);
} else {
printf("%lf\n", sqrt(sum / n));
}
}
return 0;
} | #include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main() {
int n;
double s[1005];
while (cin >> n && n != 0) {
double sum = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
sum += s[i];
}
double avg = sum / n;
sum = 0;
for (int i = 0; i < n; i++) {
sum += (s[i] - avg) * (s[i] - avg);
}
if (sum == 0) {
printf("%lf\n", sum);
} else {
printf("%lf\n", sqrt(sum / n));
}
}
return 0;
} | replace | 7 | 8 | 7 | 8 | 0 | |
p02381 | C++ | Time Limit Exceeded | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
while (n) {
int s[n];
double sum = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
sum += s[i];
}
double ave = sum / n;
sum = 0.0;
for (int i = 0; i < n; i++)
sum += (s[i] - ave) * (s[i] - ave);
cout << sqrt(sum / n) << endl;
}
return 0;
}
| #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
while (n) {
int s[n];
double sum = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
sum += s[i];
}
double ave = sum / n;
sum = 0.0;
for (int i = 0; i < n; i++)
sum += (s[i] - ave) * (s[i] - ave);
cout << sqrt(sum / n) << endl;
cin >> n;
}
return 0;
}
| insert | 17 | 17 | 17 | 18 | TLE | |
p02381 | C++ | Runtime Error | #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main(void) {
int n, s[101], i;
double m, a2, a;
cin >> n;
while (n != 0) {
m = 0;
a2 = 0;
for (i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m = m / n;
for (i = 0; i < n; i++) {
a2 += (s[i] - m) * (s[i] - m);
}
a2 = a2 / n;
a = sqrt(a2);
cout << fixed << setprecision(5) << a << endl;
cin >> n;
}
return 0;
}
| #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main(void) {
long int n, s[1001], i;
double m, a2, a;
cin >> n;
while (n != 0) {
m = 0;
a2 = 0;
for (i = 0; i < n; i++) {
cin >> s[i];
m += s[i];
}
m = m / n;
for (i = 0; i < n; i++) {
a2 += (s[i] - m) * (s[i] - m);
}
a2 = a2 / n;
a = sqrt(a2);
cout << fixed << setprecision(5) << a << endl;
cin >> n;
}
return 0;
}
| replace | 5 | 6 | 5 | 6 | 0 | |
p02381 | C++ | Runtime Error | #include <math.h>
#include <stdio.h>
#include <string.h>
#define rep(i, a, n) for (int i = a; i < n; i++)
int main() {
int n;
while (1) {
scanf("%d", &n);
if (n == 0)
break;
double s[101] = {0}, ave = 0, a = 0;
rep(i, 0, n) {
scanf("%lf", &s[i]);
ave += s[i];
}
ave /= (double)n;
rep(i, 0, n) { a += pow(s[i] - ave, 2); }
a /= (double)n;
a = sqrt(a);
printf("%.10lf\n", a);
}
return 0;
} | #include <math.h>
#include <stdio.h>
#include <string.h>
#define rep(i, a, n) for (int i = a; i < n; i++)
int main() {
int n;
while (1) {
scanf("%d", &n);
if (n == 0)
break;
double s[1001] = {0}, ave = 0, a = 0;
rep(i, 0, n) {
scanf("%lf", &s[i]);
ave += s[i];
}
ave /= (double)n;
rep(i, 0, n) { a += pow(s[i] - ave, 2); }
a /= (double)n;
a = sqrt(a);
printf("%.10lf\n", a);
}
return 0;
} | replace | 11 | 12 | 11 | 12 | 0 | |
p02381 | C++ | Time Limit Exceeded | #include <cmath>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(void) {
// Here your code !
int n, s[100];
double m, A;
while (1) {
cin >> n;
if (n == 0)
break;
m = 0;
A = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
m = m + s[i];
}
m = m / n;
for (int i = 0; i < n; i++) {
A = A + pow((s[i] - m), 2);
}
A = A / n;
A = sqrt(A);
printf("%f\n", A);
}
} | #include <cmath>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(void) {
// Here your code !
int n, s[1000];
double m, A;
while (1) {
cin >> n;
if (n == 0)
break;
m = 0;
A = 0;
for (int i = 0; i < n; i++) {
cin >> s[i];
m = m + s[i];
}
m = m / n;
for (int i = 0; i < n; i++) {
A = A + pow((s[i] - m), 2);
}
A = A / n;
A = sqrt(A);
printf("%f\n", A);
}
} | replace | 7 | 8 | 7 | 8 | TLE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.