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
p02648
C++
Runtime Error
// warm heart, wagging tail,and a smile just for you! // ███████████ // ███╬╬╬╬╬╬╬╬╬╬███ // ███╬╬╬╬╬████╬╬╬╬╬╬███ // ███████████ // ██╬╬╬╬╬████╬╬████╬╬╬╬╬██ // █████████╬╬╬╬╬████████████╬╬╬╬╬██╬╬╬╬╬╬███╬╬╬╬╬██ // ████████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████████╬╬╬╬╬╬██╬╬╬╬╬╬╬██ // ████╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████████╬╬╬╬╬╬╬╬╬╬╬██ // ███╬╬╬█╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬███╬╬╬╬╬╬╬█████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬████████╬╬╬╬╬██ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬╬╬╬╬╬███ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬██ // ████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████╬╬╬╬╬████ // █████████████╬╬╬╬╬╬╬╬██╬╬╬╬╬████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬██████ // ████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬██████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██████╬╬╬╬╬╬╬███████████╬╬╬╬╬╬╬╬██╬╬╬██╬╬╬██ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████╬╬╬╬╬╬╬╬╬╬╬█╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬██ // ██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬▓▓▓▓▓▓╬╬╬████╬╬████╬╬╬╬╬╬╬▓▓▓▓▓▓▓▓██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬███ // ██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██████▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓▓▓▓▓▓██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬█████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██ // ██████████████ // ████╬╬╬╬╬╬███████████████████████████╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████ // ███████ █████ // ███████████████████ // #include "bits/stdc++.h" using namespace std; #define INF (1 << 30) #define LINF (1LL << 60) #define fs first #define sc second // #define int long long #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define RFOR(i, a, b) for (int i = (b - 1); i >= (a); --i) #define REP(i, n) FOR(i, 0, (n)) #define RREP(i, n) RFOR(i, 0, (n)) #define ITR(itr, mp) for (auto itr = (mp).begin(); itr != (mp).end(); ++itr) #define RITR(itr, mp) for (auto itr = (mp).rbegin(); itr != (mp).rend(); ++itr) #define range(i, a, b) ((a) <= (i) && (i) < (b)) #define debug(x) cout << #x << " = " << (x) << endl #define SP << " " << template <typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; } template <typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; } #define MSB(x) (63 - __builtin_clzll(x)) #define pcnt(x) (__builtin_popcountll(x)) #define parity(i, j) (i & (1LL << j)) typedef pair<int, int> P; typedef tuple<int, int, int> T; typedef vector<int> vec; typedef vector<vector<int>> mat; const int N = 1 << 18, M = 1e5 + 10; vec v(N, 0), w(N, 0); signed main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; REP(i, n) cin >> v[i] >> w[i]; vec dp[512]; REP(i, 512) { int x = i; vec a(M, 0), id; while (1) { id.push_back(x); if (!x) break; x = (x - 1) / 2; } REP(i, 1 << id.size()) { int val = 0, we = 0; REP(j, id.size()) { if (parity(i, j)) val += v[id[j]], we += w[id[j]]; } if (we < M) chmax(a[we], val); } REP(i, M - 1) chmax(dp[i + 1], dp[i]); dp[i] = a; } int q; cin >> q; REP(_, q) { int x, l; cin >> x >> l; x--; vec id; while (x >= 512) { id.push_back(x); x = (x - 1) / 2; } int ans = 0; REP(i, 1 << id.size()) { int val = 0, we = 0; REP(j, id.size()) { if (parity(i, j)) val += v[id[j]], we += w[id[j]]; } if (we <= l) chmax(ans, val + dp[x][l - we]); } cout << ans << "\n"; } return 0; }
// warm heart, wagging tail,and a smile just for you! // ███████████ // ███╬╬╬╬╬╬╬╬╬╬███ // ███╬╬╬╬╬████╬╬╬╬╬╬███ // ███████████ // ██╬╬╬╬╬████╬╬████╬╬╬╬╬██ // █████████╬╬╬╬╬████████████╬╬╬╬╬██╬╬╬╬╬╬███╬╬╬╬╬██ // ████████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████████╬╬╬╬╬╬██╬╬╬╬╬╬╬██ // ████╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████████╬╬╬╬╬╬╬╬╬╬╬██ // ███╬╬╬█╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬███╬╬╬╬╬╬╬█████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬████████╬╬╬╬╬██ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬╬╬╬╬╬███ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬██ // ████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████╬╬╬╬╬████ // █████████████╬╬╬╬╬╬╬╬██╬╬╬╬╬████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬██████ // ████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬██████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██████╬╬╬╬╬╬╬███████████╬╬╬╬╬╬╬╬██╬╬╬██╬╬╬██ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████╬╬╬╬╬╬╬╬╬╬╬█╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬██ // ██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬▓▓▓▓▓▓╬╬╬████╬╬████╬╬╬╬╬╬╬▓▓▓▓▓▓▓▓██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬███ // ██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██████▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓▓▓▓▓▓██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██╬╬╬╬█████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████ // ███╬╬╬╬╬╬╬╬╬╬╬╬╬█████╬╬╬╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬███╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬██ // ██████████████ // ████╬╬╬╬╬╬███████████████████████████╬╬╬╬╬██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████ // ███████ █████ // ███████████████████ // #include "bits/stdc++.h" using namespace std; #define INF (1 << 30) #define LINF (1LL << 60) #define fs first #define sc second // #define int long long #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define RFOR(i, a, b) for (int i = (b - 1); i >= (a); --i) #define REP(i, n) FOR(i, 0, (n)) #define RREP(i, n) RFOR(i, 0, (n)) #define ITR(itr, mp) for (auto itr = (mp).begin(); itr != (mp).end(); ++itr) #define RITR(itr, mp) for (auto itr = (mp).rbegin(); itr != (mp).rend(); ++itr) #define range(i, a, b) ((a) <= (i) && (i) < (b)) #define debug(x) cout << #x << " = " << (x) << endl #define SP << " " << template <typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; } template <typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; } #define MSB(x) (63 - __builtin_clzll(x)) #define pcnt(x) (__builtin_popcountll(x)) #define parity(i, j) (i & (1LL << j)) typedef pair<int, int> P; typedef tuple<int, int, int> T; typedef vector<int> vec; typedef vector<vector<int>> mat; const int N = 1 << 18, M = 1e5 + 10; vec v(N, 0), w(N, 0); signed main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; REP(i, n) cin >> v[i] >> w[i]; vec dp[512]; REP(i, 512) { int x = i; vec a(M, 0), id; while (1) { id.push_back(x); if (!x) break; x = (x - 1) / 2; } REP(i, 1 << id.size()) { int val = 0, we = 0; REP(j, id.size()) { if (parity(i, j)) val += v[id[j]], we += w[id[j]]; } if (we < M) chmax(a[we], val); } REP(j, M - 1) chmax(a[j + 1], a[j]); dp[i] = a; } int q; cin >> q; REP(_, q) { int x, l; cin >> x >> l; x--; vec id; while (x >= 512) { id.push_back(x); x = (x - 1) / 2; } int ans = 0; REP(i, 1 << id.size()) { int val = 0, we = 0; REP(j, id.size()) { if (parity(i, j)) val += v[id[j]], we += w[id[j]]; } if (we <= l) chmax(ans, val + dp[x][l - we]); } cout << ans << "\n"; } return 0; }
replace
89
90
89
90
-6
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
p02648
C++
Runtime Error
#include <bits/stdc++.h> #define long long long int using namespace std; // @author: pashka int BUBEN = (1 << 9) - 1; int MAX = 100001; int main() { ios::sync_with_stdio(false); int n; cin >> n; vector<int> v(n), w(n); for (int i = 0; i < n; i++) { cin >> v[i] >> w[i]; } int nn = min(n, BUBEN); vector<vector<int>> d(nn, vector<int>(MAX)); for (int j = w[0]; j < MAX; j++) { d[0][j] = v[0]; } for (int i = 1; i < nn; i++) { int p = (i - 1) / 2; for (int j = 0; j < MAX; j++) { d[i][j] = d[p][j]; if (j >= w[i]) { d[i][j] = max(d[i][j], d[p][j - w[i]] + v[i]); } } } int q; cin >> q; while (q--) { int t, l; cin >> t >> l; t--; vector<int> c; while (t > BUBEN) { c.push_back(t); t = (t - 1) / 2; } int m = c.size(); int res = 0; for (int x = 0; x < (1 << m); x++) { int sv = 0; int sw = 0; for (int i = 0; i < m; i++) { if (x & (1 << i)) { sv += v[c[i]]; sw += w[c[i]]; } } if (sw <= l) { res = max(res, sv + d[t][l - sw]); } } cout << res << "\n"; } return 0; }
#include <bits/stdc++.h> #define long long long int using namespace std; // @author: pashka int BUBEN = (1 << 9) - 1; int MAX = 100001; int main() { ios::sync_with_stdio(false); int n; cin >> n; vector<int> v(n), w(n); for (int i = 0; i < n; i++) { cin >> v[i] >> w[i]; } int nn = min(n, BUBEN); vector<vector<int>> d(nn, vector<int>(MAX)); for (int j = w[0]; j < MAX; j++) { d[0][j] = v[0]; } for (int i = 1; i < nn; i++) { int p = (i - 1) / 2; for (int j = 0; j < MAX; j++) { d[i][j] = d[p][j]; if (j >= w[i]) { d[i][j] = max(d[i][j], d[p][j - w[i]] + v[i]); } } } int q; cin >> q; while (q--) { int t, l; cin >> t >> l; t--; vector<int> c; while (t >= BUBEN) { c.push_back(t); t = (t - 1) / 2; } int m = c.size(); int res = 0; for (int x = 0; x < (1 << m); x++) { int sv = 0; int sw = 0; for (int i = 0; i < m; i++) { if (x & (1 << i)) { sv += v[c[i]]; sw += w[c[i]]; } } if (sw <= l) { res = max(res, sv + d[t][l - sw]); } } cout << res << "\n"; } return 0; }
replace
39
40
39
40
0
p02648
C++
Time Limit Exceeded
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; // #define int long long // #define double long double #define rep(i, n) for (int i = 0; i < (int)(n); ++i) #define rep1(i, n) for (int i = 1; i < (int)(n); ++i) #define repeq(i, n) for (int i = 0; i <= (int)(n); ++i) #define rep1eq(i, n) for (int i = 1; i <= (int)(n); ++i) #define rrep(i, n) for (int i = (int)(n)-1; i >= 0; --i) #define rrep1(i, n) for (int i = (int)(n)-1; i > 0; --i) #define rrepeq(i, n) for (int i = (int)(n); i >= 0; --i) #define rrep1eq(i, n) for (int i = (int)(n); i > 0; --i) #define REP(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i) #define RREP(i, a, b) for (int i = (int)(a); i >= (int)(b); --i) #define ALL(a) (a).begin(), (a).end() #define RALL(a) (a).rbegin(), (a).rend() using ll = long long; using vi = vector<int>; using vl = vector<ll>; using vb = vector<bool>; template <typename T> using Graph = vector<vector<T>>; template <typename T> using Spacial = vector<vector<vector<T>>>; using pii = pair<int, int>; using pll = pair<ll, ll>; template <typename T> using greater_priority_queue = priority_queue<T, vector<T>, greater<T>>; const int MOD = 1e9 + 7; const int MOD2 = 998244353; // const double EPS = 1e-9; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; string interval[2] = {" ", "\n"}; // {" ", "\n"} template <typename T> struct is_plural : false_type {}; template <typename T1, typename T2> struct is_plural<pair<T1, T2>> : true_type {}; template <typename T> struct is_plural<vector<T>> : true_type {}; template <typename T> struct is_plural<complex<T>> : true_type {}; template <typename T1, typename T2> istream &operator>>(istream &is, pair<T1, T2> &p) { return is >> p.first >> p.second; } template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { return os << p.first << " " << p.second; } template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto itr = vec.begin(); itr != vec.end(); ++itr) is >> *itr; return is; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { if (vec.empty()) return os; bool pl = is_plural<T>(); os << vec.front(); for (auto itr = ++vec.begin(); itr != vec.end(); ++itr) os << interval[pl] << *itr; return os; } bool CoutYN(bool a, string y = "Yes", string n = "No") { cout << (a ? y : n) << "\n"; return a; } template <typename T1, typename T2> inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); } template <typename T1, typename T2> inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); } long long modpow(int a, long long n, int mod = MOD) { long long ret = 1; do { if (n & 1) ret = ret * a % mod; a = 1LL * a * a % mod; } while (n >>= 1); return ret; } template <typename T> T GCD(T a, T b) { return b ? GCD(b, a % b) : a; } template <typename T> T LCM(T a, T b) { return a / GCD(a, b) * b; } template <typename T1, typename T2> bool CompareBySecond(pair<T1, T2> a, pair<T1, T2> b) { return a.second != b.second ? a.second < b.second : a.first < b.first; } template <typename T1, typename T2> bool CompareByInverse(pair<T1, T2> a, pair<T1, T2> b) { return a.first != b.first ? a.first < b.first : a.second > b.second; } /* -------- <templates end> -------- */ pii operator+(pii a, pii b) { return {a.first + b.first, a.second + b.second}; } void solve() { int n; cin >> n; vector<pii> g(n); cin >> g; const int num = 12; const int sz = 1 << num; vector<map<int, int>> calc(sz); calc[0][0] = 0; rep(i, num) { int x = 1 << i; for (int j = x; j < 2 * x; ++j) { for (auto &p : calc[j / 2]) { chmax(calc[j][p.first], p.second); chmax(calc[j][p.first + g[j - 1].second], p.second + g[j - 1].first); } vi erase; int MAX = -1; for (auto &p : calc[j]) { if (p.second <= MAX) erase.emplace_back(p.first); else MAX = p.second; } for (auto &v : erase) { calc[j].erase(v); } } } int q; cin >> q; while (q--) { int v, L; cin >> v >> L; vector<pii> vec(1); while (v >= sz) { int s = vec.size(); rep(i, s) vec.emplace_back(vec[i] + g[v - 1]); v >>= 1; } int ans = 0; for (auto &p : vec) { if (L < p.second) continue; auto itr = --calc[v].upper_bound(L - p.second); chmax(ans, itr->second + p.first); } cout << ans << '\n'; } } /* -------- <programs end> -------- */ signed main() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(10); solve(); return 0; }
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; // #define int long long // #define double long double #define rep(i, n) for (int i = 0; i < (int)(n); ++i) #define rep1(i, n) for (int i = 1; i < (int)(n); ++i) #define repeq(i, n) for (int i = 0; i <= (int)(n); ++i) #define rep1eq(i, n) for (int i = 1; i <= (int)(n); ++i) #define rrep(i, n) for (int i = (int)(n)-1; i >= 0; --i) #define rrep1(i, n) for (int i = (int)(n)-1; i > 0; --i) #define rrepeq(i, n) for (int i = (int)(n); i >= 0; --i) #define rrep1eq(i, n) for (int i = (int)(n); i > 0; --i) #define REP(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i) #define RREP(i, a, b) for (int i = (int)(a); i >= (int)(b); --i) #define ALL(a) (a).begin(), (a).end() #define RALL(a) (a).rbegin(), (a).rend() using ll = long long; using vi = vector<int>; using vl = vector<ll>; using vb = vector<bool>; template <typename T> using Graph = vector<vector<T>>; template <typename T> using Spacial = vector<vector<vector<T>>>; using pii = pair<int, int>; using pll = pair<ll, ll>; template <typename T> using greater_priority_queue = priority_queue<T, vector<T>, greater<T>>; const int MOD = 1e9 + 7; const int MOD2 = 998244353; // const double EPS = 1e-9; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; string interval[2] = {" ", "\n"}; // {" ", "\n"} template <typename T> struct is_plural : false_type {}; template <typename T1, typename T2> struct is_plural<pair<T1, T2>> : true_type {}; template <typename T> struct is_plural<vector<T>> : true_type {}; template <typename T> struct is_plural<complex<T>> : true_type {}; template <typename T1, typename T2> istream &operator>>(istream &is, pair<T1, T2> &p) { return is >> p.first >> p.second; } template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { return os << p.first << " " << p.second; } template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto itr = vec.begin(); itr != vec.end(); ++itr) is >> *itr; return is; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { if (vec.empty()) return os; bool pl = is_plural<T>(); os << vec.front(); for (auto itr = ++vec.begin(); itr != vec.end(); ++itr) os << interval[pl] << *itr; return os; } bool CoutYN(bool a, string y = "Yes", string n = "No") { cout << (a ? y : n) << "\n"; return a; } template <typename T1, typename T2> inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); } template <typename T1, typename T2> inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); } long long modpow(int a, long long n, int mod = MOD) { long long ret = 1; do { if (n & 1) ret = ret * a % mod; a = 1LL * a * a % mod; } while (n >>= 1); return ret; } template <typename T> T GCD(T a, T b) { return b ? GCD(b, a % b) : a; } template <typename T> T LCM(T a, T b) { return a / GCD(a, b) * b; } template <typename T1, typename T2> bool CompareBySecond(pair<T1, T2> a, pair<T1, T2> b) { return a.second != b.second ? a.second < b.second : a.first < b.first; } template <typename T1, typename T2> bool CompareByInverse(pair<T1, T2> a, pair<T1, T2> b) { return a.first != b.first ? a.first < b.first : a.second > b.second; } /* -------- <templates end> -------- */ pii operator+(pii a, pii b) { return {a.first + b.first, a.second + b.second}; } void solve() { int n; cin >> n; vector<pii> g(n); cin >> g; const int num = 11; const int sz = 1 << num; vector<map<int, int>> calc(sz); calc[0][0] = 0; rep(i, num) { int x = 1 << i; for (int j = x; j < 2 * x; ++j) { for (auto &p : calc[j / 2]) { chmax(calc[j][p.first], p.second); chmax(calc[j][p.first + g[j - 1].second], p.second + g[j - 1].first); } vi erase; int MAX = -1; for (auto &p : calc[j]) { if (p.second <= MAX) erase.emplace_back(p.first); else MAX = p.second; } for (auto &v : erase) { calc[j].erase(v); } } } int q; cin >> q; while (q--) { int v, L; cin >> v >> L; vector<pii> vec(1); while (v >= sz) { int s = vec.size(); rep(i, s) vec.emplace_back(vec[i] + g[v - 1]); v >>= 1; } int ans = 0; for (auto &p : vec) { if (L < p.second) continue; auto itr = --calc[v].upper_bound(L - p.second); chmax(ans, itr->second + p.first); } cout << ans << '\n'; } } /* -------- <programs end> -------- */ signed main() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(10); solve(); return 0; }
replace
107
108
107
108
TLE
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; const int maxD = 1 << 9, maxQ = 100009, maxN = (1 << 18) + 9; int maxL, N, Q, v[maxN], w[maxN], id[20], ans[maxQ]; vector<int> dp; vector<pair<int, int>> qr[maxQ]; void df0(int nod) { if (nod >= maxD) { if (!qr[nod].empty()) { int nr = 1; id[0] = nod; while (id[nr - 1] / 2 >= maxD) id[nr] = id[nr - 1] / 2, nr++; for (auto q : qr[nod]) { int L = q.first, pos = q.second; for (int msk = 0; msk < (1 << nr); msk++) { int tV = 0, tW = 0; for (int i = 0; i < nr; i++) if (msk & (1 << i)) tV += v[id[i]], tW += w[id[i]]; if (tW <= L && dp[L - tW] + tV > ans[pos]) ans[pos] = dp[L - tW] + tV; } } } if (nod * 2 <= N) df0(nod << 1); if (nod * 2 < N) df0(nod << 1 | 1); return; } vector<int> old = dp; for (int i = w[nod]; i <= maxL; i++) if (old[i - w[nod]] + v[nod] > dp[i]) dp[i] = old[i - w[nod]] + v[nod]; /* printf ("%d: ", nod); for (int i=0; i<=maxL; i++) printf ("(%d, %d) ", i, dp[i]); printf ("\n");*/ for (auto q : qr[nod]) { // printf ("%d -> (%d, %d)\n", q.second, q.first, dp[q.first]); ans[q.second] = dp[q.first]; } if (nod * 2 <= N) df0(nod << 1); if (nod * 2 < N) df0(nod << 1 | 1); dp = old; } int main() { // freopen ("input", "r", stdin); // freopen ("output", "w", stdout); scanf("%d", &N); for (int i = 1; i <= N; i++) scanf("%d %d", &v[i], &w[i]); scanf("%d", &Q); for (int i = 1; i <= Q; i++) { int x, y; scanf("%d %d", &x, &y); if (y > maxL) maxL = y; qr[x].push_back({y, i}); } dp = vector<int>(maxL + 2, 0); df0(1); for (int i = 1; i <= Q; i++) printf("%d\n", ans[i]); return 0; }
#include <bits/stdc++.h> using namespace std; const int maxD = 1 << 9, maxQ = 100009, maxN = (1 << 18) + 9; int maxL, N, Q, v[maxN], w[maxN], id[20], ans[maxQ]; vector<int> dp; vector<pair<int, int>> qr[maxN]; void df0(int nod) { if (nod >= maxD) { if (!qr[nod].empty()) { int nr = 1; id[0] = nod; while (id[nr - 1] / 2 >= maxD) id[nr] = id[nr - 1] / 2, nr++; for (auto q : qr[nod]) { int L = q.first, pos = q.second; for (int msk = 0; msk < (1 << nr); msk++) { int tV = 0, tW = 0; for (int i = 0; i < nr; i++) if (msk & (1 << i)) tV += v[id[i]], tW += w[id[i]]; if (tW <= L && dp[L - tW] + tV > ans[pos]) ans[pos] = dp[L - tW] + tV; } } } if (nod * 2 <= N) df0(nod << 1); if (nod * 2 < N) df0(nod << 1 | 1); return; } vector<int> old = dp; for (int i = w[nod]; i <= maxL; i++) if (old[i - w[nod]] + v[nod] > dp[i]) dp[i] = old[i - w[nod]] + v[nod]; /* printf ("%d: ", nod); for (int i=0; i<=maxL; i++) printf ("(%d, %d) ", i, dp[i]); printf ("\n");*/ for (auto q : qr[nod]) { // printf ("%d -> (%d, %d)\n", q.second, q.first, dp[q.first]); ans[q.second] = dp[q.first]; } if (nod * 2 <= N) df0(nod << 1); if (nod * 2 < N) df0(nod << 1 | 1); dp = old; } int main() { // freopen ("input", "r", stdin); // freopen ("output", "w", stdout); scanf("%d", &N); for (int i = 1; i <= N; i++) scanf("%d %d", &v[i], &w[i]); scanf("%d", &Q); for (int i = 1; i <= Q; i++) { int x, y; scanf("%d %d", &x, &y); if (y > maxL) maxL = y; qr[x].push_back({y, i}); } dp = vector<int>(maxL + 2, 0); df0(1); for (int i = 1; i <= Q; i++) printf("%d\n", ans[i]); return 0; }
replace
7
8
7
8
0
p02648
C++
Runtime Error
#include <bits/stdc++.h> #define lsb(x) (x & (-x)) #define ll long long #define ull unsigned long long #define Test(tt) cout << "Case #" << tt << ": " using namespace std; const int MAXN = (int)1e5; int value[MAXN + 1], weight[MAXN + 1]; vector<pair<int, int>> qry[MAXN + 1]; vector<pair<ll, ll>> sums[20][2]; ll sol[MAXN + 1]; ll pref_mx[1 << 10]; void dfs(int nod, int lvl, int n) { if (nod > n) return; if (sums[lvl - 1][0].size() > sums[lvl - 1][1].size()) { swap(sums[lvl - 1][0], sums[lvl - 1][1]); } int sza = (int)sums[lvl - 1][0].size(), szb = (int)sums[lvl - 1][0].size(); int a = 0, b = 0; while (a < sza || b < szb) { if (b == szb || (a < sza && sums[lvl - 1][0][a].second + weight[nod] <= sums[lvl - 1][0][b].second)) { sums[lvl][0].push_back({sums[lvl - 1][0][a].first + value[nod], sums[lvl - 1][0][a].second + weight[nod]}); a++; } else { sums[lvl][0].push_back(sums[lvl - 1][0][b]); b++; } } sums[lvl][1] = sums[lvl - 1][1]; pref_mx[0] = sums[lvl][1][0].first; for (int i = 1; i < (int)sums[lvl][1].size(); i++) { pref_mx[i] = max(pref_mx[i - 1], sums[lvl][1][i].first); } for (auto it : qry[nod]) { int j = (int)sums[lvl][1].size() - 1; for (int i = 0; i < (int)sums[lvl][0].size(); i++) { while (j >= 0 && sums[lvl][0][i].second + sums[lvl][1][j].second > it.first) { j--; } if (j >= 0) { sol[it.second] = max(sol[it.second], sums[lvl][0][i].first + pref_mx[j]); } } } /*for(int i = 0; i < 2; i++) { for(auto it : sums[lvl][i]) { cerr << it.first << " " << it.second << " "; } cerr << "\n"; } cerr << "\n\n";*/ dfs(2 * nod, lvl + 1, n); dfs(2 * nod + 1, lvl + 1, n); sums[lvl][0].clear(); sums[lvl][1].clear(); } int main() { #ifdef HOME ifstream cin("B.in"); ofstream cout("B.out"); #endif int i, n, q; ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin >> n; for (i = 1; i <= n; i++) { cin >> value[i] >> weight[i]; } cin >> q; for (i = 1; i <= q; i++) { int nod, l; cin >> nod >> l; qry[nod].push_back({l, i}); } sums[0][0].push_back({0, 0}); sums[0][1].push_back({0, 0}); dfs(1, 1, n); for (i = 1; i <= q; i++) { cout << sol[i] << "\n"; } return 0; }
#include <bits/stdc++.h> #define lsb(x) (x & (-x)) #define ll long long #define ull unsigned long long #define Test(tt) cout << "Case #" << tt << ": " using namespace std; const int MAXN = (1 << 18); int value[MAXN + 1], weight[MAXN + 1]; vector<pair<int, int>> qry[MAXN + 1]; vector<pair<ll, ll>> sums[20][2]; ll sol[MAXN + 1]; ll pref_mx[1 << 10]; void dfs(int nod, int lvl, int n) { if (nod > n) return; if (sums[lvl - 1][0].size() > sums[lvl - 1][1].size()) { swap(sums[lvl - 1][0], sums[lvl - 1][1]); } int sza = (int)sums[lvl - 1][0].size(), szb = (int)sums[lvl - 1][0].size(); int a = 0, b = 0; while (a < sza || b < szb) { if (b == szb || (a < sza && sums[lvl - 1][0][a].second + weight[nod] <= sums[lvl - 1][0][b].second)) { sums[lvl][0].push_back({sums[lvl - 1][0][a].first + value[nod], sums[lvl - 1][0][a].second + weight[nod]}); a++; } else { sums[lvl][0].push_back(sums[lvl - 1][0][b]); b++; } } sums[lvl][1] = sums[lvl - 1][1]; pref_mx[0] = sums[lvl][1][0].first; for (int i = 1; i < (int)sums[lvl][1].size(); i++) { pref_mx[i] = max(pref_mx[i - 1], sums[lvl][1][i].first); } for (auto it : qry[nod]) { int j = (int)sums[lvl][1].size() - 1; for (int i = 0; i < (int)sums[lvl][0].size(); i++) { while (j >= 0 && sums[lvl][0][i].second + sums[lvl][1][j].second > it.first) { j--; } if (j >= 0) { sol[it.second] = max(sol[it.second], sums[lvl][0][i].first + pref_mx[j]); } } } /*for(int i = 0; i < 2; i++) { for(auto it : sums[lvl][i]) { cerr << it.first << " " << it.second << " "; } cerr << "\n"; } cerr << "\n\n";*/ dfs(2 * nod, lvl + 1, n); dfs(2 * nod + 1, lvl + 1, n); sums[lvl][0].clear(); sums[lvl][1].clear(); } int main() { #ifdef HOME ifstream cin("B.in"); ofstream cout("B.out"); #endif int i, n, q; ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin >> n; for (i = 1; i <= n; i++) { cin >> value[i] >> weight[i]; } cin >> q; for (i = 1; i <= q; i++) { int nod, l; cin >> nod >> l; qry[nod].push_back({l, i}); } sums[0][0].push_back({0, 0}); sums[0][1].push_back({0, 0}); dfs(1, 1, n); for (i = 1; i <= q; i++) { cout << sol[i] << "\n"; } return 0; }
replace
8
9
8
9
0
p02648
C++
Time Limit Exceeded
#include <algorithm> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define int long long #define MOD 1000000007 #define rep(i, n) for (int i = 0; i < (n); i++) #define itrep(i, a) for (auto i = (a).begin(); i != (a).end(); i++) #define REP(i, a, n) for (int i = (a); i <= (n); i++) #define all(a) (a).begin(), (a).end() #define mp(a, b) make_pair((a), (b)) using namespace std; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, -1, 0, 1}; template <class T> void inputVector(vector<T> &v, int n) { v.resize(n); for (int i = 0; i < v.size(); i++) cin >> v[i]; } const int INF = LLONG_MAX / 10; const int BORDER = 9; int N; vector<int> V, W; vector<vector<pair<int, int>>> m; int getMaxValue(const vector<pair<int, int>> &m, int L) { auto it = upper_bound(all(m), mp(L, INF)); it--; return it->second; } int getDepth(int now) { now++; int ret = -1; while (now) { now >>= 1; ret++; } return ret; } void f(int now, vector<pair<int, int>> &parentMap) { if (now >= N) return; m[now] = parentMap; for (auto &pr : parentMap) { if (pr.first == INF) break; m[now].push_back(mp(pr.first + W[now], pr.second + V[now])); } sort(all(m[now])); vector<int> eraseIds; int prevVal = -1; rep(i, m[now].size()) { auto &pr = m[now][i]; if (pr.first == INF) break; if (pr.first == m[now][i + 1].first) eraseIds.push_back(i); else if (pr.second <= prevVal) eraseIds.push_back(i); else prevVal = pr.second; } rep(i, eraseIds.size()) { m[now].erase(m[now].begin() + (eraseIds[i] - i)); } if (getDepth(now) == BORDER) { vector<pair<int, int>> tmp; tmp.push_back(mp(0, 0)); tmp.push_back(mp(INF, INF)); f(now * 2 + 1, tmp); f(now * 2 + 2, tmp); } else { f(now * 2 + 1, m[now]); f(now * 2 + 2, m[now]); } // cerr << "node " << now << endl; // for (auto &pr : m[now]) { // cerr << " " << pr.first << " -> " << pr.second << endl; // } // cerr << " complete " << now << " : size=" << m[now].size() << endl; } int solve(int v, int L) { int depth = getDepth(v); if (depth <= BORDER) { return getMaxValue(m[v], L); } // cerr << "PASS" << endl; int parent = v; while (depth > BORDER) { parent = (parent - 1) / 2; depth--; } // cerr << " child:" << endl; // for (auto &pr : m[v]) cerr << " (" << pr.first << ", " << pr.second << ")" // << endl; cerr << " parent(" << parent << "):" << endl; for (auto &pr : // m[parent]) cerr << " (" << pr.first << ", " << pr.second << ")" << endl; int ret = 0; for (auto &pr : m[v]) { if (pr.first > L) break; ret = max(ret, pr.second + getMaxValue(m[parent], L - pr.first)); } return ret; } signed main() { cin >> N; V.resize(N); W.resize(N); m.resize(N); rep(i, N) cin >> V[i] >> W[i]; vector<pair<int, int>> tmp; tmp.push_back(mp(0, 0)); tmp.push_back(mp(INF, INF)); f(0, tmp); int Q; cin >> Q; rep(_, Q) { int v, L; cin >> v >> L; v--; cout << solve(v, L) << endl; } return 0; }
#include <algorithm> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define int long long #define MOD 1000000007 #define rep(i, n) for (int i = 0; i < (n); i++) #define itrep(i, a) for (auto i = (a).begin(); i != (a).end(); i++) #define REP(i, a, n) for (int i = (a); i <= (n); i++) #define all(a) (a).begin(), (a).end() #define mp(a, b) make_pair((a), (b)) using namespace std; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, -1, 0, 1}; template <class T> void inputVector(vector<T> &v, int n) { v.resize(n); for (int i = 0; i < v.size(); i++) cin >> v[i]; } const int INF = LLONG_MAX / 10; const int BORDER = 11; int N; vector<int> V, W; vector<vector<pair<int, int>>> m; int getMaxValue(const vector<pair<int, int>> &m, int L) { auto it = upper_bound(all(m), mp(L, INF)); it--; return it->second; } int getDepth(int now) { now++; int ret = -1; while (now) { now >>= 1; ret++; } return ret; } void f(int now, vector<pair<int, int>> &parentMap) { if (now >= N) return; m[now] = parentMap; for (auto &pr : parentMap) { if (pr.first == INF) break; m[now].push_back(mp(pr.first + W[now], pr.second + V[now])); } sort(all(m[now])); vector<int> eraseIds; int prevVal = -1; rep(i, m[now].size()) { auto &pr = m[now][i]; if (pr.first == INF) break; if (pr.first == m[now][i + 1].first) eraseIds.push_back(i); else if (pr.second <= prevVal) eraseIds.push_back(i); else prevVal = pr.second; } rep(i, eraseIds.size()) { m[now].erase(m[now].begin() + (eraseIds[i] - i)); } if (getDepth(now) == BORDER) { vector<pair<int, int>> tmp; tmp.push_back(mp(0, 0)); tmp.push_back(mp(INF, INF)); f(now * 2 + 1, tmp); f(now * 2 + 2, tmp); } else { f(now * 2 + 1, m[now]); f(now * 2 + 2, m[now]); } // cerr << "node " << now << endl; // for (auto &pr : m[now]) { // cerr << " " << pr.first << " -> " << pr.second << endl; // } // cerr << " complete " << now << " : size=" << m[now].size() << endl; } int solve(int v, int L) { int depth = getDepth(v); if (depth <= BORDER) { return getMaxValue(m[v], L); } // cerr << "PASS" << endl; int parent = v; while (depth > BORDER) { parent = (parent - 1) / 2; depth--; } // cerr << " child:" << endl; // for (auto &pr : m[v]) cerr << " (" << pr.first << ", " << pr.second << ")" // << endl; cerr << " parent(" << parent << "):" << endl; for (auto &pr : // m[parent]) cerr << " (" << pr.first << ", " << pr.second << ")" << endl; int ret = 0; for (auto &pr : m[v]) { if (pr.first > L) break; ret = max(ret, pr.second + getMaxValue(m[parent], L - pr.first)); } return ret; } signed main() { cin >> N; V.resize(N); W.resize(N); m.resize(N); rep(i, N) cin >> V[i] >> W[i]; vector<pair<int, int>> tmp; tmp.push_back(mp(0, 0)); tmp.push_back(mp(INF, INF)); f(0, tmp); int Q; cin >> Q; rep(_, Q) { int v, L; cin >> v >> L; v--; cout << solve(v, L) << endl; } return 0; }
replace
39
40
39
40
TLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; #define ALL(x) x.begin(), x.end() #define rep(i, n) for (int i = 0; i < (n); i++) #define debug(v) \ cout << #v << ":"; \ for (auto x : v) { \ cout << x << ' '; \ } \ cout << endl; #define INF 1000000000 #define mod 1000000007 using ll = long long; const ll LINF = 1001002003004005006ll; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; // ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } ll dp[600][100100]; int k = 8; signed main() { cin.tie(0); ios::sync_with_stdio(0); int n; cin >> n; int v[n + 1], w[n + 1]; for (int i = 1; i <= n; i++) cin >> v[i] >> w[i]; rep(i, 600) rep(j, 100100) dp[i][j] = 0; for (int cur = 1; cur <= min((1 << k), n); cur++) { int par = cur / 2; for (int i = 100000; i >= 0; i--) { chmax(dp[cur][i], dp[par][i]); if (i + w[cur] < 100100) chmax(dp[cur][i + w[cur]], dp[par][i] + v[cur]); } } int q; cin >> q; while (q--) { int node, l; cin >> node >> l; if (node < (1 << k)) { cout << dp[node][l] << endl; continue; } vector<int> vv, ww; for (; node >= (1 << k); node >>= 1) vv.push_back(v[node]), ww.push_back(w[node]); int t = (int)vv.size(); ll ans = 0; for (int bit = 0; bit < (1 << t); bit++) { ll wsum = 0, vsum = 0; rep(i, t) if ((bit >> i) & 1) wsum += ww[i], vsum += vv[i]; if (wsum <= l) chmax(ans, vsum + dp[node][l - wsum]); } cout << ans << "\n"; } return 0; }
#include <bits/stdc++.h> using namespace std; #define ALL(x) x.begin(), x.end() #define rep(i, n) for (int i = 0; i < (n); i++) #define debug(v) \ cout << #v << ":"; \ for (auto x : v) { \ cout << x << ' '; \ } \ cout << endl; #define INF 1000000000 #define mod 1000000007 using ll = long long; const ll LINF = 1001002003004005006ll; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; // ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } int dp[1025][100100]; int k = 10; signed main() { cin.tie(0); ios::sync_with_stdio(0); int n; cin >> n; int v[n + 1], w[n + 1]; for (int i = 1; i <= n; i++) cin >> v[i] >> w[i]; rep(i, 600) rep(j, 100100) dp[i][j] = 0; for (int cur = 1; cur <= min((1 << k), n); cur++) { int par = cur / 2; for (int i = 100000; i >= 0; i--) { chmax(dp[cur][i], dp[par][i]); if (i + w[cur] < 100100) chmax(dp[cur][i + w[cur]], dp[par][i] + v[cur]); } } int q; cin >> q; while (q--) { int node, l; cin >> node >> l; if (node < (1 << k)) { cout << dp[node][l] << endl; continue; } vector<int> vv, ww; for (; node >= (1 << k); node >>= 1) vv.push_back(v[node]), ww.push_back(w[node]); int t = (int)vv.size(); ll ans = 0; for (int bit = 0; bit < (1 << t); bit++) { ll wsum = 0, vsum = 0; rep(i, t) if ((bit >> i) & 1) wsum += ww[i], vsum += vv[i]; if (wsum <= l) chmax(ans, vsum + dp[node][l - wsum]); } cout << ans << "\n"; } return 0; }
replace
32
34
32
34
TLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll N, Q; vector<pair<ll, ll>> tree; vector<pair<ll, ll>> que; vector<vector<ll>> best_per_weight; int max_idx = 1; ll max_l; ll brute_force(int v, ll w, ll acc_val, ll max_wq) { if (v < max_idx) { return best_per_weight[v][max_wq - w] + acc_val; } else { ll c_value = tree[v].first; ll c_weight = tree[v].second; int parent = (v - 1) / 2; ll not_pick = brute_force(parent, w, acc_val, max_wq); ll pick; if (c_weight + w > max_wq) return not_pick; else { pick = brute_force(parent, c_weight + w, acc_val + c_value, max_wq); } return pick > not_pick ? pick : not_pick; } } int main() { cin >> N; for (int i = 0; i < N; i++) { ll v, w; cin >> v >> w; tree.push_back(make_pair(v, w)); } cin >> Q; max_l = 0; for (int i = 0; i < Q; i++) { ll v, l; cin >> v >> l; que.push_back(make_pair(v - 1, l)); if (max_l < l) max_l = l; } int max_idx = 1024 > N ? N : 1024; for (int i = 0; i < max_idx; i++) { // vector<ll> b_val(max_l+1, 0); vector<ll> b_val; if (i == 0) { ll c_value = tree[i].first; ll c_weight = tree[i].second; if (c_weight <= max_l) { for (int k = 0; k < c_weight; k++) { b_val.push_back(0); } for (int k = c_weight; k < max_l + 1; k++) { b_val.push_back(c_value); } } } else { ll c_value = tree[i].first; ll c_weight = tree[i].second; for (int j = 0; j < max_l + 1; j++) { int parent = (i - 1) / 2; int prev_idx = j - c_weight; if (prev_idx < 0) b_val.push_back(best_per_weight[parent][j]); else { ll tmp = best_per_weight[parent][prev_idx] + c_value; tmp = tmp > best_per_weight[parent][j] ? tmp : best_per_weight[parent][j]; b_val.push_back(tmp); } } } best_per_weight.push_back(b_val); } // // cout << "FInish" << endl; for (auto q : que) { int v = q.first; int L = q.second; ll best_val = brute_force(v, 0, 0, L); cout << best_val << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll N, Q; vector<pair<ll, ll>> tree; vector<pair<ll, ll>> que; vector<vector<ll>> best_per_weight; int max_idx = 1; ll max_l; ll brute_force(int v, ll w, ll acc_val, ll max_wq) { if (v < max_idx) { return best_per_weight[v][max_wq - w] + acc_val; } else { ll c_value = tree[v].first; ll c_weight = tree[v].second; int parent = (v - 1) / 2; ll not_pick = brute_force(parent, w, acc_val, max_wq); ll pick; if (c_weight + w > max_wq) return not_pick; else { pick = brute_force(parent, c_weight + w, acc_val + c_value, max_wq); } return pick > not_pick ? pick : not_pick; } } int main() { cin >> N; for (int i = 0; i < N; i++) { ll v, w; cin >> v >> w; tree.push_back(make_pair(v, w)); } cin >> Q; max_l = 0; for (int i = 0; i < Q; i++) { ll v, l; cin >> v >> l; que.push_back(make_pair(v - 1, l)); if (max_l < l) max_l = l; } max_idx = 1024 > N ? N : 1024; for (int i = 0; i < max_idx; i++) { // vector<ll> b_val(max_l+1, 0); vector<ll> b_val; if (i == 0) { ll c_value = tree[i].first; ll c_weight = tree[i].second; if (c_weight <= max_l) { for (int k = 0; k < c_weight; k++) { b_val.push_back(0); } for (int k = c_weight; k < max_l + 1; k++) { b_val.push_back(c_value); } } } else { ll c_value = tree[i].first; ll c_weight = tree[i].second; for (int j = 0; j < max_l + 1; j++) { int parent = (i - 1) / 2; int prev_idx = j - c_weight; if (prev_idx < 0) b_val.push_back(best_per_weight[parent][j]); else { ll tmp = best_per_weight[parent][prev_idx] + c_value; tmp = tmp > best_per_weight[parent][j] ? tmp : best_per_weight[parent][j]; b_val.push_back(tmp); } } } best_per_weight.push_back(b_val); } // // cout << "FInish" << endl; for (auto q : que) { int v = q.first; int L = q.second; ll best_val = brute_force(v, 0, 0, L); cout << best_val << endl; } return 0; }
replace
52
53
52
53
TLE
p02648
C++
Runtime Error
#include <bits/stdc++.h> #define rep(a, n) for (ll a = 0; a < (n); ++a) using namespace std; typedef long long ll; typedef pair<ll, ll> P; typedef vector<vector<ll>> Graph; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } const ll INF = 1e18; ll n, q; vector<ll> V, W, v, L; ll dp[1100][100010]; int main() { cin >> n; V.resize(n); W.resize(n); rep(i, n) cin >> V[i] >> W[i]; cin >> q; v.resize(q); L.resize(q); rep(i, q) { cin >> v[i] >> L[i]; v[i]--; } rep(i, min(n, 1024LL)) { if (i == 0) { rep(j, 100010) { if (j - W[0] < 0) continue; dp[0][j] = V[0]; } } else { ll p = (i - 1) / 2; rep(j, 100010) { dp[i][j] = dp[p][j]; if (j - W[i] < 0) continue; chmax(dp[i][j], dp[p][j - W[i]] + V[i]); } } } rep(i, q) { if (v[i] < 1024) { ll ans = dp[v[i]][L[i]]; cout << ans << endl; } else { ll now = v[i]; ll ans = 0; int d = 0; ll tmp = now; while (tmp > 0) { tmp--; tmp /= 2; d++; } d -= 9; for (int bit = 0; bit < (1 << d); bit++) { ll weight = 0, value = 0; ll cd = now; rep(j, d) { if ((bit >> j) & 1) { weight += W[cd]; value += V[cd]; cd = (cd - 1) / 2; } else { cd = (cd - 1) / 2; } } if (L[now] - weight < 0) continue; chmax(ans, dp[cd][L[i] - weight] + value); } cout << ans << endl; } } return 0; }
#include <bits/stdc++.h> #define rep(a, n) for (ll a = 0; a < (n); ++a) using namespace std; typedef long long ll; typedef pair<ll, ll> P; typedef vector<vector<ll>> Graph; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } const ll INF = 1e18; ll n, q; vector<ll> V, W, v, L; ll dp[1100][100010]; int main() { cin >> n; V.resize(n); W.resize(n); rep(i, n) cin >> V[i] >> W[i]; cin >> q; v.resize(q); L.resize(q); rep(i, q) { cin >> v[i] >> L[i]; v[i]--; } rep(i, min(n, 1024LL)) { if (i == 0) { rep(j, 100010) { if (j - W[0] < 0) continue; dp[0][j] = V[0]; } } else { ll p = (i - 1) / 2; rep(j, 100010) { dp[i][j] = dp[p][j]; if (j - W[i] < 0) continue; chmax(dp[i][j], dp[p][j - W[i]] + V[i]); } } } rep(i, q) { if (v[i] < 1024) { ll ans = dp[v[i]][L[i]]; cout << ans << endl; } else { ll now = v[i]; ll ans = 0; int d = 0; ll tmp = now; while (tmp > 0) { tmp--; tmp /= 2; d++; } d -= 9; for (int bit = 0; bit < (1 << d); bit++) { ll weight = 0, value = 0; ll cd = now; rep(j, d) { if ((bit >> j) & 1) { weight += W[cd]; value += V[cd]; cd = (cd - 1) / 2; } else { cd = (cd - 1) / 2; } } if (L[i] - weight < 0) continue; chmax(ans, dp[cd][L[i] - weight] + value); } cout << ans << endl; } } return 0; }
replace
82
83
82
83
-11
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") typedef vector<int> vi; typedef long long lint; typedef unsigned int uint; typedef pair<int, int> pii; typedef pair<lint, lint> pll; typedef unsigned long long ulint; #define endl '\n' #define fst first #define sed second #define pb push_back #define mp make_pair #define rint register int #define SZ(x) (int((x).size())) #define all(x) (x).begin(), (x).end() #define reveal(x) cerr << #x << " = " << (x) << endl #define rep(it, f, e) for (rint it = (f); it <= (e); ++it) #define per(it, f, e) for (rint it = (f); it >= (e); --it) #define repe(it, x) for (auto it = (x).begin(); it != (x).end(); ++it) const int INF = 1e5; const int MAXN = (1 << 18) + 20; int V[MAXN], W[MAXN]; map<int, lint> state[(1 << 9) + 20]; lint dp[(1 << 9) + 20][INF + 5]; inline void update(int i, int w, lint v) { if (w > INF) return; state[i][w] = max(state[i][w], v); } inline void dfs(int u, int lim) { for (auto &st : state[u]) { dp[u][st.fst] = max(dp[u][st.fst], st.sed); } rep(v, u * 2, u * 2 + 1) { if (v > lim) continue; for (auto &st : state[u]) { update(v, st.fst, st.sed); update(v, st.fst + W[v], st.sed + V[v]); } dfs(v, lim); } } int main() { ios::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL); int n; cin >> n; rep(i, 1, n) { cin >> V[i] >> W[i]; } state[1][0] = 0; state[1][W[1]] = V[1]; int lim = min(n, (1 << 9) - 1); dfs(1, lim); rep(i, 1, lim) rep(j, 1, INF) { dp[i][j] = max(dp[i][j], dp[i][j - 1]); } int q; cin >> q; while (q--) { int p, l; cin >> p >> l; lint res = 0; function<void(int, int, int)> solve; solve = [&](int u, int w, int v) { if (w > l) return; if (u <= lim) { res = max(res, v + dp[u][l - w]); return; } solve(u << 1, w, v); solve(u << 1, w + W[u], v + V[u]); }; solve(p, 0, 0); cout << res << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") typedef vector<int> vi; typedef long long lint; typedef unsigned int uint; typedef pair<int, int> pii; typedef pair<lint, lint> pll; typedef unsigned long long ulint; #define endl '\n' #define fst first #define sed second #define pb push_back #define mp make_pair #define rint register int #define SZ(x) (int((x).size())) #define all(x) (x).begin(), (x).end() #define reveal(x) cerr << #x << " = " << (x) << endl #define rep(it, f, e) for (rint it = (f); it <= (e); ++it) #define per(it, f, e) for (rint it = (f); it >= (e); --it) #define repe(it, x) for (auto it = (x).begin(); it != (x).end(); ++it) const int INF = 1e5; const int MAXN = (1 << 18) + 20; int V[MAXN], W[MAXN]; map<int, lint> state[(1 << 9) + 20]; lint dp[(1 << 9) + 20][INF + 5]; inline void update(int i, int w, lint v) { if (w > INF) return; state[i][w] = max(state[i][w], v); } inline void dfs(int u, int lim) { for (auto &st : state[u]) { dp[u][st.fst] = max(dp[u][st.fst], st.sed); } rep(v, u * 2, u * 2 + 1) { if (v > lim) continue; for (auto &st : state[u]) { update(v, st.fst, st.sed); update(v, st.fst + W[v], st.sed + V[v]); } dfs(v, lim); } } int main() { ios::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL); int n; cin >> n; rep(i, 1, n) { cin >> V[i] >> W[i]; } state[1][0] = 0; state[1][W[1]] = V[1]; int lim = min(n, (1 << 9) - 1); dfs(1, lim); rep(i, 1, lim) rep(j, 1, INF) { dp[i][j] = max(dp[i][j], dp[i][j - 1]); } int q; cin >> q; while (q--) { int p, l; cin >> p >> l; lint res = 0; function<void(int, int, int)> solve; solve = [&](int u, int w, int v) { if (w > l) return; if (u <= lim) { res = max(res, v + dp[u][l - w]); return; } solve(u >> 1, w, v); solve(u >> 1, w + W[u], v + V[u]); }; solve(p, 0, 0); cout << res << endl; } return 0; }
replace
70
72
70
72
-11
p02648
C++
Runtime Error
#include <bits/stdc++.h> #define FASTIO using namespace std; using ll = long long; using Vi = vector<int>; using Vl = vector<ll>; using Pii = pair<int, int>; using Pll = pair<ll, ll>; constexpr int I_INF = numeric_limits<int>::max(); constexpr ll L_INF = numeric_limits<ll>::max(); template <typename T1, typename T2> bool chmin(T1 &a, const T2 &b) { if (a > b) { a = b; return true; } return false; } template <typename T1, typename T2> bool chmax(T1 &a, const T2 &b) { if (a < b) { a = b; return true; } return false; } class Prints { private: class __Prints { public: __Prints(const char *sep, const char *term) : sep(sep), term(term) {} template <class... Args> void operator()(const Args &...args) const { print(args...); } private: const char *sep, *term; void print() const { std::cout << term; } void print_rest() const { std::cout << term; } template <class T, class... Tail> void print(const T &head, const Tail &...tail) const { std::cout << head, print_rest(tail...); } template <class T, class... Tail> void print_rest(const T &head, const Tail &...tail) const { std::cout << sep << head, print_rest(tail...); } }; public: Prints() {} __Prints operator()(const char *sep = " ", const char *term = "\n") const { return __Prints(sep, term); } }; Prints prints; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% constexpr ll MX_W = 100000; ll dp1[600][100010]; void solve() { ll N; cin >> N; Vl V(N + 1), W(N + 1); for (ll i = 1; i <= N; i++) { cin >> V[i] >> W[i]; } ll th = N / 2; for (ll i = 1; i <= th; i++) { for (ll j = 0; j <= MX_W; j++) { chmax(dp1[i][j], dp1[i >> 1][j]); if (j - W[i] >= 0) chmax(dp1[i][j], dp1[i >> 1][j - W[i]] + V[i]); } } ll Q; cin >> Q; vector<Pll> d; while (Q--) { ll v, L; cin >> v >> L; d.clear(); int idx = v; while (idx > th) { d.emplace_back(V[idx], W[idx]); idx >>= 1; } ll res = 0; ll sz = (ll)d.size(); for (ll mask = 0; mask < (1ll << sz); mask++) { ll tv = 0, tw = 0; for (ll i = 0; i < sz; i++) { if (mask >> i & 1) { tv += d[i].first; tw += d[i].second; } } if (tw > L) continue; chmax(res, tv + dp1[idx][L - tw]); } prints()(res); } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int main() { #ifdef FASTIO cin.tie(nullptr), cout.tie(nullptr); ios::sync_with_stdio(false); #endif #ifdef FILEINPUT ifstream ifs("./in_out/input.txt"); cin.rdbuf(ifs.rdbuf()); #endif #ifdef FILEOUTPUT ofstream ofs("./in_out/output.txt"); cout.rdbuf(ofs.rdbuf()); #endif cout << setprecision(18) << fixed; solve(); cout << flush; return 0; }
#include <bits/stdc++.h> #define FASTIO using namespace std; using ll = long long; using Vi = vector<int>; using Vl = vector<ll>; using Pii = pair<int, int>; using Pll = pair<ll, ll>; constexpr int I_INF = numeric_limits<int>::max(); constexpr ll L_INF = numeric_limits<ll>::max(); template <typename T1, typename T2> bool chmin(T1 &a, const T2 &b) { if (a > b) { a = b; return true; } return false; } template <typename T1, typename T2> bool chmax(T1 &a, const T2 &b) { if (a < b) { a = b; return true; } return false; } class Prints { private: class __Prints { public: __Prints(const char *sep, const char *term) : sep(sep), term(term) {} template <class... Args> void operator()(const Args &...args) const { print(args...); } private: const char *sep, *term; void print() const { std::cout << term; } void print_rest() const { std::cout << term; } template <class T, class... Tail> void print(const T &head, const Tail &...tail) const { std::cout << head, print_rest(tail...); } template <class T, class... Tail> void print_rest(const T &head, const Tail &...tail) const { std::cout << sep << head, print_rest(tail...); } }; public: Prints() {} __Prints operator()(const char *sep = " ", const char *term = "\n") const { return __Prints(sep, term); } }; Prints prints; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% constexpr ll MX_W = 100000; ll dp1[600][100010]; void solve() { ll N; cin >> N; Vl V(N + 1), W(N + 1); for (ll i = 1; i <= N; i++) { cin >> V[i] >> W[i]; } ll th; { ll left = -1, right = N; while (right - left > 1) { ll mid = (right + left) >> 1; if (mid * mid <= N) { left = mid; } else { right = mid; } } th = left; } for (ll i = 1; i <= th; i++) { for (ll j = 0; j <= MX_W; j++) { chmax(dp1[i][j], dp1[i >> 1][j]); if (j - W[i] >= 0) chmax(dp1[i][j], dp1[i >> 1][j - W[i]] + V[i]); } } ll Q; cin >> Q; vector<Pll> d; while (Q--) { ll v, L; cin >> v >> L; d.clear(); int idx = v; while (idx > th) { d.emplace_back(V[idx], W[idx]); idx >>= 1; } ll res = 0; ll sz = (ll)d.size(); for (ll mask = 0; mask < (1ll << sz); mask++) { ll tv = 0, tw = 0; for (ll i = 0; i < sz; i++) { if (mask >> i & 1) { tv += d[i].first; tw += d[i].second; } } if (tw > L) continue; chmax(res, tv + dp1[idx][L - tw]); } prints()(res); } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int main() { #ifdef FASTIO cin.tie(nullptr), cout.tie(nullptr); ios::sync_with_stdio(false); #endif #ifdef FILEINPUT ifstream ifs("./in_out/input.txt"); cin.rdbuf(ifs.rdbuf()); #endif #ifdef FILEOUTPUT ofstream ofs("./in_out/output.txt"); cout.rdbuf(ofs.rdbuf()); #endif cout << setprecision(18) << fixed; solve(); cout << flush; return 0; }
replace
73
74
73
86
-11
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const ll maxn = 1e5 + 5; const ll mod = 1e9 + 7; const ld PI = acos((ld)-1); #define pb push_back #define endl '\n' #define dokme(x) return (cout << x, 0); #define migmig \ ios::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); #define ms(x, y) memset(x, y, sizeof x); #define file_init \ freopen("input.txt", "r+", stdin); \ freopen("output.txt", "w+", stdout); ll pw(ll a, ll b, ll md = mod) { ll res = 1; while (b) { if (b & 1) { res = (a * res) % md; } a = (a * a) % md; b >>= 1; } return (res); } int n; int mxval[510][maxn]; int w[(1 << 18) + 5], v[(1 << 18) + 5]; int q; int w2[20]; int v2[20]; void solve(int x) { int pos = x; int cnt = 0; while (x != 0) { w2[cnt] = w[x]; v2[cnt++] = v[x]; x /= 2; } for (int i = 0; i < (1 << cnt); i++) { int sum = 0; int val = 0; for (int j = 0; j < cnt; j++) { if (i & (1 << j)) sum += w2[j], val += v2[j]; } if (sum <= 100000) mxval[pos][sum] = max(mxval[pos][sum], val); } for (int i = 1; i < maxn; i++) mxval[pos][i] = max(mxval[pos][i], mxval[pos][i - 1]); } void prep() { for (int i = 1; i <= min(n, 510); i++) { solve(i); } } void solve(int x, int l) { int mx = 0; int cnt = 0; while (x > 510) { w2[cnt] = w[x]; v2[cnt++] = v[x]; x /= 2; } for (int i = 0; i < (1 << cnt); i++) { int sum = 0; int val = 0; for (int j = 0; j < cnt; j++) { if (i & (1 << j)) sum += w2[j], val += v2[j]; } if (sum <= l) mx = max(mx, val); if (l >= sum) mx = max(mx, val + mxval[x][l - sum]); } cout << mx << endl; } int main() { migmig cin >> n; for (int i = 1; i <= n; i++) cin >> v[i] >> w[i]; prep(); cin >> q; while (q--) { int x, l; cin >> x >> l; if (x <= 510) { cout << mxval[x][l] << endl; continue; } solve(x, l); } return (0); }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const ll maxn = 1e5 + 5; const ll mod = 1e9 + 7; const ld PI = acos((ld)-1); #define pb push_back #define endl '\n' #define dokme(x) return (cout << x, 0); #define migmig \ ios::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); #define ms(x, y) memset(x, y, sizeof x); #define file_init \ freopen("input.txt", "r+", stdin); \ freopen("output.txt", "w+", stdout); ll pw(ll a, ll b, ll md = mod) { ll res = 1; while (b) { if (b & 1) { res = (a * res) % md; } a = (a * a) % md; b >>= 1; } return (res); } int n; int mxval[520][maxn]; int w[(1 << 18) + 5], v[(1 << 18) + 5]; int q; int w2[20]; int v2[20]; void solve(int x) { int pos = x; int cnt = 0; while (x != 0) { w2[cnt] = w[x]; v2[cnt++] = v[x]; x /= 2; } for (int i = 0; i < (1 << cnt); i++) { int sum = 0; int val = 0; for (int j = 0; j < cnt; j++) { if (i & (1 << j)) sum += w2[j], val += v2[j]; } if (sum <= 100000) mxval[pos][sum] = max(mxval[pos][sum], val); } for (int i = 1; i < maxn; i++) mxval[pos][i] = max(mxval[pos][i], mxval[pos][i - 1]); } void prep() { for (int i = 1; i <= min(n, 510); i++) { solve(i); } } void solve(int x, int l) { int mx = 0; int cnt = 0; while (x > 510) { w2[cnt] = w[x]; v2[cnt++] = v[x]; x /= 2; } for (int i = 0; i < (1 << cnt); i++) { int sum = 0; int val = 0; for (int j = 0; j < cnt; j++) { if (i & (1 << j)) sum += w2[j], val += v2[j]; } if (sum <= l) mx = max(mx, val); if (l >= sum) mx = max(mx, val + mxval[x][l - sum]); } cout << mx << endl; } int main() { migmig cin >> n; for (int i = 1; i <= n; i++) cin >> v[i] >> w[i]; prep(); cin >> q; while (q--) { int x, l; cin >> x >> l; if (x <= 510) { cout << mxval[x][l] << endl; continue; } solve(x, l); } return (0); }
replace
38
39
38
39
-11
p02648
C++
Time Limit Exceeded
// https://atcoder.jp/contests/tokiomarine2020/tasks/tokiomarine2020_d #define CIN_ONLY #define DECIMAL_DIGITS 10 #define STATIC_MOD 1e9 + 7 #ifdef BTK /*<head>*/ #include "Template.hpp" /*</head>*/ #else /*<body>*/ /* #region auto includes */ /* #region stl */ /*<stl>*/ #include <bits/stdc++.h> #include <sys/types.h> #include <unistd.h> using namespace std; /*</stl>*/ /* #endregion */ /* #region template/Grid.hpp*/ /** * @brief グリッドをラップするための関数 * @tparam T std::string や std;:vector を想定 * @tparam U 周りに配置する要素の型 * @param grid 入力、R > 0 でないとバグる * @param material 周りに配置する要素 * @return std::vector<T> material で 周りを埋めた grid */ template <typename T, typename U> inline std::vector<T> wrapGrid(std::vector<T> grid, U material) { std::vector<T> wrappedGrid(grid.size() + 2, T(grid[0].size() + 2, material)); for (std::size_t i = 0; i < grid.size(); i++) { for (std::size_t j = 0; j < grid[i].size(); j++) { wrappedGrid[i + 1][j + 1] = grid[i][j]; } } return wrappedGrid; } /** * @brief * */ constexpr int dr4[] = {0, 1, 0, -1}; constexpr int dc4[] = {-1, 0, 1, 0}; /* #endregion */ /* #region template/IncludeSTL.hpp*/ /** * @file IncludeSTL.hpp * @author btk * @brief 標準ライブラリをincludeするだけ * @version 0.1 * @date 2019-07-21 * @todo 何故か2回includeされる(展開scriptに * @copyright Copyright (c) 2019 * */ /* #endregion */ /* #region template/Macro.hpp*/ /** * @file Macro.hpp * @author btk * @brief マクロとか,LLとか * @version 0.1 * @date 2019-07-13 * * @copyright Copyright (c) 2019 * */ //! LL using LL = long long; /** * @def DEBUG * @brief デバッグ用のif文 提出時はif(0)で実行されない */ /*</head>*/ #ifdef BTK #define DEBUG if (1) #else #ifdef CIN_ONLY #define FAST_IO #endif #define DEBUG if (0) #endif /** * @def ALL(v) * @brief * ALLマクロ */ #define ALL(v) (v).begin(), (v).end() /** * @def REC(ret, ...) * @brief * 再帰ラムダをするためのマクロ */ #define REC(ret, ...) std::function<ret(__VA_ARGS__)> /** * @def VAR_NAME(var) * @brief 変数名を取得する */ #define VAR_NAME(var) #var /** * @brief * rangeで生まれる使わない変数を消す用(警告消し) */ template <typename T> inline T &unused_var(T &v) { return v; } template <typename T> std::vector<T> nestingVector(std::size_t size) { return std::vector<T>(size); } template <typename T, typename... Ts> inline auto nestingVector(std::size_t size, Ts... ts) { return std::vector<decltype(nestingVector<T>(ts...))>( size, nestingVector<T>(ts...)); } /* #endregion */ /* #region template/IO.hpp*/ /** * @file IO.hpp * @author btk * @brief cin高速化とか,出力の小数桁固定とか * @version 0.1 * @date 2019-07-13 * * @copyright Copyright (c) 2019 */ /** * @brief 入出力の設定を行うための構造体 */ struct cww { /** * @brief Construct a new cww::cww object * @details * CIN_ONLYを定義すると,submit時にcinとscanfの同期を切る設定が走る * DECIMAL_DIGITSを定義すると,doubleの出力時指定した桁数分小数部を吐くようになる */ cww() { #ifdef FAST_IO std::ios::sync_with_stdio(false); std::cin.tie(0); #endif #ifdef DECIMAL_DIGITS std::cout << std::fixed; std::cout << std::setprecision(DECIMAL_DIGITS); #endif } }; //! 入出力設定構造体を実体化 cww star; /** * @brief * vectorに直接cin流すためのやつ * @tparam T * @param is * @param v * @return istream& */ template <typename T> std::istream &operator>>(std::istream &is, std::vector<T> &v) { for (auto &it : v) is >> it; return is; } /* #endregion */ /* #region template/Loop.hpp*/ /** * @file Loop.hpp * @author btk * @brief rangeとかループ系のクラス * @version 0.1 * @date 2019-07-13 * * @copyright Copyright (c) 2019 * */ /** * @brief * rangeを逆向きに操作したいとき用 * @details * ループの範囲は[bg,ed)なので注意 * @see range */ class reverse_range { private: struct I { int x; int operator*() { return x - 1; } bool operator!=(I &lhs) { return x > lhs.x; } void operator++() { --x; } }; I i, n; public: /** * @brief Construct a new reverse range object * * @param n */ reverse_range(int n) : i({0}), n({n}) {} /** * @brief Construct a new reverse range object * * @param i * @param n */ reverse_range(int i, int n) : i({i}), n({n}) {} /** * @brief * begin iterator * @return I& */ I &begin() { return n; } /** * @brief * end iterator * @return I& */ I &end() { return i; } }; /** * @brief * python みたいな range-based for を実現 * @details * ループの範囲は[bg,ed)なので注意 * !つけると逆向きにループが回る (reverse_range) * 空間計算量はO(1) * 使わない変数ができて警告が出がちなので,unused_varとかを使って警告消しするとよい */ class range { private: struct I { int x; int operator*() { return x; } bool operator!=(I &lhs) { return x < lhs.x; } void operator++() { ++x; } }; I i, n; public: /** * @brief Construct a new range object * * @param n */ range(int n) : i({0}), n({n}) {} /** * @brief Construct a new range object * * @param i * @param n */ range(int i, int n) : i({i}), n({n}) {} /** * @brief * begin iterator * @return I& */ I &begin() { return i; } /** * @brief * end iterator * @return I& */ I &end() { return n; } /** * @brief * 逆向きに参照するrange(reverse_rangeを取得できるs) * @return reverse_range */ reverse_range operator!() { return reverse_range(*i, *n); } }; /* #endregion */ /* #region template/Math.hpp*/ /** * @brief gcd, ceil等自作算数用関数を集める。stdと被るので名前空間を区切る */ namespace math { /** * @brief aとbの最大公約数 * @param a int64 * @param b int64 * @return int64 最大公約数 */ int64_t gcd(int64_t a, int64_t b) { return (b == 0) ? a : gcd(b, a % b); } /** * @brief aとbの最小公倍数 * @param a int64 * @param b int64 * @return int64 最小公倍数 */ int64_t lcm(int64_t a, int64_t b) { return (a / gcd(a, b)) * b; } /** * @brief 拡張ユークリッド互除法 * @details ax + by = gとなるx,yを求める * @param a 入力 * @param b 入力 * @param x 値引き継ぎ用の変数 * @param y 値引き継ぎ用の変数 * @return int64_t g:aとbの最大公約数 */ int64_t extgcd(int64_t a, int64_t b, int64_t &x, int64_t &y) { int64_t g = a; x = 1; y = 0; if (b != 0) g = extgcd(b, a % b, y, x), y -= (a / b) * x; return g; } /** * @brief u/dを切り上げした整数を求める * @todo 負の数への対応 * @tparam T 整数型 * @param u 入力 * @param d 入力 * @return T 切り上げ後の値 */ template <typename T> inline T ceil(T u, T d) { return (u + d - (T)1) / d; } } // namespace math /* #endregion */ /* #region template/MinMaxOperation.hpp*/ /** * @file MinMaxOperation.hpp * @author btk * @brief 最大値とか最小値を求める * @version 0.1 * @date 2019-07-04 * * @copyright Copyright (c) 2019 * */ /** * @brief 2項の最小値求める * * @tparam T */ template <typename T> struct min_op { /** * @brief 本体 * * @param l * @param r * @return T */ static T exec(const T l, const T r) { return l < r ? l : r; } }; /** * @brief 2項の最大値求める * * @tparam T */ template <typename T> struct max_op { /** * @brief 本体 * * @param l * @param r * @return T */ static T exec(const T l, const T r) { return l > r ? l : r; } }; /** * @brief テンプレート再帰の末尾 * * @tparam F 二項演算 * @tparam T * @param v * @return T */ template <typename F, typename T> inline T multi_op(T &&v) { return v; } /** * @brief 複数項における演算の結果を返す * * @tparam F * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename F, typename T, typename... Ts> inline T multi_op(const T head, Ts &&...tail) { return F::exec(head, multi_op<F>(tail...)); } /** * @brief 複数項の最小値 * @see multi_op * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename T, typename... Ts> inline T multi_min(T head, Ts... tail) { return multi_op<min_op<T>>(head, tail...); } /** * @brief 複数項の最大値 * @see multi_op * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename T, typename... Ts> inline T multi_max(T head, Ts... tail) { return multi_op<max_op<T>>(head, tail...); } /** * @brief * 先頭の値をFで参照する関数に基づいて変更できたらする * @tparam F * @tparam T * @tparam Ts * @param target * @param candidates * @return true * @return false */ template <typename F, typename T, typename... Ts> inline bool ch_op(T &target, Ts &&...candidates) { const T old = target; target = multi_op<F>(target, candidates...); return old != target; } /** * @brief change min * @tparam T 型 * @param target 変更する値 * @param candidates * @return 更新があればtrue */ template <typename T, typename... Ts> inline bool chmin(T &target, Ts &&...candidates) { return ch_op<min_op<T>>(target, candidates...); } /** * @brief chminのmax版 * @see chmin * @tparam T 型 * @param target 変更する値 * @param candidates * @return 更新があればtrue */ template <typename T, typename... Ts> inline bool chmax(T &target, Ts &&...candidates) { return ch_op<max_op<T>>(target, candidates...); } /* #endregion */ /* #region template/Random.hpp*/ /** * @file Random.hpp * @author btk * @brief 乱数生成系 * @version 0.1 * @date 2019-07-13 * @copyright Copyright (c) 2019 */ //! 乱数のシード値をプロセスIDとして取得 const pid_t pid = getpid(); /** * @brief XorShift32の実装 */ class XorShift32 { private: //! XorShiftの現在の値 unsigned value; /** * @brief XorShift32のアルゴリズムに基づいて value を更新 */ inline void update() { value = value ^ (value << 13); value = value ^ (value >> 17); value = value ^ (value << 5); } /** * @brief 値を更新し,更新前の値を返却 * @return unsigned 呼び出し時の value を用いる */ inline unsigned get() { unsigned v = value; update(); return v; } public: /** * @brief [0, 2^bit) の範囲の乱数値を取り出す * @tparam デフォルトは31 * @return int */ template <int bit = 31> inline int next_int() { return (int)(get() >> (32 - bit)); } /** * @brief [-2^bit,2^bit)の範囲の乱数値を取り出す * @tparam デフォルトは31 * @return int */ template <int bit = 31> inline int next_signed() { unsigned v = get(); return (int)((v >> (31 - bit)) - (1 << (bit))); } /** * @brief next_int呼び出し時の最大値を取得 * @tparam 31 * @return int */ template <int bit = 31> inline int range_max() { return (int)((1u << bit) - 1); }; /** * @brief Construct a new XorShift32 object * @param seed * @details 初期シードをvalueとするXorShift32のインスタンスを生成 */ XorShift32(const unsigned seed) { value = seed; update(); } /** * @brief Construct a new XorShift 32 object * @details 初期シードをプロセスIDとするXorShift32のインスタンスを生成 */ XorShift32() : XorShift32(pid) {} }; /* #endregion */ /* #region template/Strings.hpp*/ /** * @file Strings.hpp * @author btk * @brief 文字列を扱いやすくするライブラリ * @version 0.1 * @date 2020-02-02 * * @copyright Copyright (c) 2020 * */ /** * @brief コレクションを文字列に変換する関数 * @tparam T コレクションの型、range-based for に対応している必要あり * @tparam U 区切り文字の型 * @param v コレクション * @param delimiter 区切り文字 * @return std::string delimiterで結合された文字列 */ template <typename T, typename U> std::string join(const T &v, const U delimiter) { std::stringstream ss; bool isFirst = true; for (auto &it : v) { if (!isFirst) { ss << delimiter; } isFirst = false; ss << it; } return ss.str(); } /** * @brief コレクションを文字列に変換する関数(イテレータ版) * @tparam ITR イテレータ型 * @tparam T 区切り文字の型 * @param bg 開始 * @param ed 終了 * @param delimiter 区切り文字 * @return std::string delimiterで結合された文字列 */ template <typename ITR, typename T> std::string join(const ITR bg, const ITR ed, const T delimiter) { std::stringstream ss; bool isFirst = true; for (auto it = bg; it != ed; ++it) { if (!isFirst) { ss << delimiter; } isFirst = false; ss << *it; } return ss.str(); } /* #endregion */ /* #region Template.hpp*/ /** * @file Template.hpp * @brief 競技プログラミング用テンプレート * @author btk15049 * @date 2019/05/02 */ /* #endregion */ /* #endregion */ /*</body>*/ #endif constexpr int HALF = 1; int N, Q; LL V[312345]; LL W[312345]; int key[112345]; LL L[112345]; vector<int> lQ; map<int, vector<int>> hQ; LL ret[212345]; LL pre[112345]; int main() { /* write here */ cin >> N; for (int i : range(N)) { cin >> V[i + 1] >> W[i + 1]; } cin >> Q; for (int i : range(Q)) { cin >> key[i] >> L[i]; if (key[i] < (1 << HALF)) { lQ.emplace_back(i); } else { int p = key[i]; while (p >= (1 << HALF)) p /= 2; hQ[p].emplace_back(i); } } for (int i : lQ) { vector<int> vs; vs.reserve(HALF); vs.push_back(key[i]); while (vs.back() > 1) { int k = vs.back() / 2; vs.push_back(k); } int h = vs.size(); for (int _b : range(1 << h)) { bitset<HALF> b(_b); LL cost = 0; LL value = 0; for (int j : range(h)) { if (b[j]) { cost += W[vs[j]]; value += V[vs[j]]; } } if (cost <= L[i]) { chmax(ret[i], value); } } } for (auto kv : hQ) { int p = kv.first; auto q = kv.second; fill(pre, pre + 112345, 0ll); { vector<int> vs; vs.reserve(HALF); vs.push_back(p); while (vs.back() > 1) { int k = vs.back() / 2; vs.push_back(k); } // cerr << "before: " << p << " " << join(vs, ",") << endl; int h = vs.size(); for (int _b : range(1 << h)) { bitset<18 - HALF> b(_b); LL cost = 0; LL value = 0; for (int j : range(h)) { if (b[j]) { cost += W[vs[j]]; value += V[vs[j]]; } } if (cost <= 112345) { chmax(pre[cost], value); } } } for (int i : range(112344)) { chmax(pre[i + 1], pre[i]); } for (int i : q) { vector<int> vs; vs.reserve(HALF); vs.push_back(key[i]); while (vs.back() > p) { int k = vs.back() / 2; if (p == k) break; vs.push_back(k); } // cerr << "after: " << key[i] << " " << join(vs, ",") << endl; int h = vs.size(); for (int _b : range(1 << h)) { bitset<18 - HALF> b(_b); LL cost = 0; LL value = 0; for (int j : range(h)) { if (b[j]) { cost += W[vs[j]]; value += V[vs[j]]; } } // cerr << cost << " - " << value << endl; if (cost <= L[i]) { chmax(ret[i], value + pre[L[i] - cost]); } } } } for (int i : range(Q)) { cout << ret[i] << "\n"; } return 0; }
// https://atcoder.jp/contests/tokiomarine2020/tasks/tokiomarine2020_d #define CIN_ONLY #define DECIMAL_DIGITS 10 #define STATIC_MOD 1e9 + 7 #ifdef BTK /*<head>*/ #include "Template.hpp" /*</head>*/ #else /*<body>*/ /* #region auto includes */ /* #region stl */ /*<stl>*/ #include <bits/stdc++.h> #include <sys/types.h> #include <unistd.h> using namespace std; /*</stl>*/ /* #endregion */ /* #region template/Grid.hpp*/ /** * @brief グリッドをラップするための関数 * @tparam T std::string や std;:vector を想定 * @tparam U 周りに配置する要素の型 * @param grid 入力、R > 0 でないとバグる * @param material 周りに配置する要素 * @return std::vector<T> material で 周りを埋めた grid */ template <typename T, typename U> inline std::vector<T> wrapGrid(std::vector<T> grid, U material) { std::vector<T> wrappedGrid(grid.size() + 2, T(grid[0].size() + 2, material)); for (std::size_t i = 0; i < grid.size(); i++) { for (std::size_t j = 0; j < grid[i].size(); j++) { wrappedGrid[i + 1][j + 1] = grid[i][j]; } } return wrappedGrid; } /** * @brief * */ constexpr int dr4[] = {0, 1, 0, -1}; constexpr int dc4[] = {-1, 0, 1, 0}; /* #endregion */ /* #region template/IncludeSTL.hpp*/ /** * @file IncludeSTL.hpp * @author btk * @brief 標準ライブラリをincludeするだけ * @version 0.1 * @date 2019-07-21 * @todo 何故か2回includeされる(展開scriptに * @copyright Copyright (c) 2019 * */ /* #endregion */ /* #region template/Macro.hpp*/ /** * @file Macro.hpp * @author btk * @brief マクロとか,LLとか * @version 0.1 * @date 2019-07-13 * * @copyright Copyright (c) 2019 * */ //! LL using LL = long long; /** * @def DEBUG * @brief デバッグ用のif文 提出時はif(0)で実行されない */ /*</head>*/ #ifdef BTK #define DEBUG if (1) #else #ifdef CIN_ONLY #define FAST_IO #endif #define DEBUG if (0) #endif /** * @def ALL(v) * @brief * ALLマクロ */ #define ALL(v) (v).begin(), (v).end() /** * @def REC(ret, ...) * @brief * 再帰ラムダをするためのマクロ */ #define REC(ret, ...) std::function<ret(__VA_ARGS__)> /** * @def VAR_NAME(var) * @brief 変数名を取得する */ #define VAR_NAME(var) #var /** * @brief * rangeで生まれる使わない変数を消す用(警告消し) */ template <typename T> inline T &unused_var(T &v) { return v; } template <typename T> std::vector<T> nestingVector(std::size_t size) { return std::vector<T>(size); } template <typename T, typename... Ts> inline auto nestingVector(std::size_t size, Ts... ts) { return std::vector<decltype(nestingVector<T>(ts...))>( size, nestingVector<T>(ts...)); } /* #endregion */ /* #region template/IO.hpp*/ /** * @file IO.hpp * @author btk * @brief cin高速化とか,出力の小数桁固定とか * @version 0.1 * @date 2019-07-13 * * @copyright Copyright (c) 2019 */ /** * @brief 入出力の設定を行うための構造体 */ struct cww { /** * @brief Construct a new cww::cww object * @details * CIN_ONLYを定義すると,submit時にcinとscanfの同期を切る設定が走る * DECIMAL_DIGITSを定義すると,doubleの出力時指定した桁数分小数部を吐くようになる */ cww() { #ifdef FAST_IO std::ios::sync_with_stdio(false); std::cin.tie(0); #endif #ifdef DECIMAL_DIGITS std::cout << std::fixed; std::cout << std::setprecision(DECIMAL_DIGITS); #endif } }; //! 入出力設定構造体を実体化 cww star; /** * @brief * vectorに直接cin流すためのやつ * @tparam T * @param is * @param v * @return istream& */ template <typename T> std::istream &operator>>(std::istream &is, std::vector<T> &v) { for (auto &it : v) is >> it; return is; } /* #endregion */ /* #region template/Loop.hpp*/ /** * @file Loop.hpp * @author btk * @brief rangeとかループ系のクラス * @version 0.1 * @date 2019-07-13 * * @copyright Copyright (c) 2019 * */ /** * @brief * rangeを逆向きに操作したいとき用 * @details * ループの範囲は[bg,ed)なので注意 * @see range */ class reverse_range { private: struct I { int x; int operator*() { return x - 1; } bool operator!=(I &lhs) { return x > lhs.x; } void operator++() { --x; } }; I i, n; public: /** * @brief Construct a new reverse range object * * @param n */ reverse_range(int n) : i({0}), n({n}) {} /** * @brief Construct a new reverse range object * * @param i * @param n */ reverse_range(int i, int n) : i({i}), n({n}) {} /** * @brief * begin iterator * @return I& */ I &begin() { return n; } /** * @brief * end iterator * @return I& */ I &end() { return i; } }; /** * @brief * python みたいな range-based for を実現 * @details * ループの範囲は[bg,ed)なので注意 * !つけると逆向きにループが回る (reverse_range) * 空間計算量はO(1) * 使わない変数ができて警告が出がちなので,unused_varとかを使って警告消しするとよい */ class range { private: struct I { int x; int operator*() { return x; } bool operator!=(I &lhs) { return x < lhs.x; } void operator++() { ++x; } }; I i, n; public: /** * @brief Construct a new range object * * @param n */ range(int n) : i({0}), n({n}) {} /** * @brief Construct a new range object * * @param i * @param n */ range(int i, int n) : i({i}), n({n}) {} /** * @brief * begin iterator * @return I& */ I &begin() { return i; } /** * @brief * end iterator * @return I& */ I &end() { return n; } /** * @brief * 逆向きに参照するrange(reverse_rangeを取得できるs) * @return reverse_range */ reverse_range operator!() { return reverse_range(*i, *n); } }; /* #endregion */ /* #region template/Math.hpp*/ /** * @brief gcd, ceil等自作算数用関数を集める。stdと被るので名前空間を区切る */ namespace math { /** * @brief aとbの最大公約数 * @param a int64 * @param b int64 * @return int64 最大公約数 */ int64_t gcd(int64_t a, int64_t b) { return (b == 0) ? a : gcd(b, a % b); } /** * @brief aとbの最小公倍数 * @param a int64 * @param b int64 * @return int64 最小公倍数 */ int64_t lcm(int64_t a, int64_t b) { return (a / gcd(a, b)) * b; } /** * @brief 拡張ユークリッド互除法 * @details ax + by = gとなるx,yを求める * @param a 入力 * @param b 入力 * @param x 値引き継ぎ用の変数 * @param y 値引き継ぎ用の変数 * @return int64_t g:aとbの最大公約数 */ int64_t extgcd(int64_t a, int64_t b, int64_t &x, int64_t &y) { int64_t g = a; x = 1; y = 0; if (b != 0) g = extgcd(b, a % b, y, x), y -= (a / b) * x; return g; } /** * @brief u/dを切り上げした整数を求める * @todo 負の数への対応 * @tparam T 整数型 * @param u 入力 * @param d 入力 * @return T 切り上げ後の値 */ template <typename T> inline T ceil(T u, T d) { return (u + d - (T)1) / d; } } // namespace math /* #endregion */ /* #region template/MinMaxOperation.hpp*/ /** * @file MinMaxOperation.hpp * @author btk * @brief 最大値とか最小値を求める * @version 0.1 * @date 2019-07-04 * * @copyright Copyright (c) 2019 * */ /** * @brief 2項の最小値求める * * @tparam T */ template <typename T> struct min_op { /** * @brief 本体 * * @param l * @param r * @return T */ static T exec(const T l, const T r) { return l < r ? l : r; } }; /** * @brief 2項の最大値求める * * @tparam T */ template <typename T> struct max_op { /** * @brief 本体 * * @param l * @param r * @return T */ static T exec(const T l, const T r) { return l > r ? l : r; } }; /** * @brief テンプレート再帰の末尾 * * @tparam F 二項演算 * @tparam T * @param v * @return T */ template <typename F, typename T> inline T multi_op(T &&v) { return v; } /** * @brief 複数項における演算の結果を返す * * @tparam F * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename F, typename T, typename... Ts> inline T multi_op(const T head, Ts &&...tail) { return F::exec(head, multi_op<F>(tail...)); } /** * @brief 複数項の最小値 * @see multi_op * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename T, typename... Ts> inline T multi_min(T head, Ts... tail) { return multi_op<min_op<T>>(head, tail...); } /** * @brief 複数項の最大値 * @see multi_op * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename T, typename... Ts> inline T multi_max(T head, Ts... tail) { return multi_op<max_op<T>>(head, tail...); } /** * @brief * 先頭の値をFで参照する関数に基づいて変更できたらする * @tparam F * @tparam T * @tparam Ts * @param target * @param candidates * @return true * @return false */ template <typename F, typename T, typename... Ts> inline bool ch_op(T &target, Ts &&...candidates) { const T old = target; target = multi_op<F>(target, candidates...); return old != target; } /** * @brief change min * @tparam T 型 * @param target 変更する値 * @param candidates * @return 更新があればtrue */ template <typename T, typename... Ts> inline bool chmin(T &target, Ts &&...candidates) { return ch_op<min_op<T>>(target, candidates...); } /** * @brief chminのmax版 * @see chmin * @tparam T 型 * @param target 変更する値 * @param candidates * @return 更新があればtrue */ template <typename T, typename... Ts> inline bool chmax(T &target, Ts &&...candidates) { return ch_op<max_op<T>>(target, candidates...); } /* #endregion */ /* #region template/Random.hpp*/ /** * @file Random.hpp * @author btk * @brief 乱数生成系 * @version 0.1 * @date 2019-07-13 * @copyright Copyright (c) 2019 */ //! 乱数のシード値をプロセスIDとして取得 const pid_t pid = getpid(); /** * @brief XorShift32の実装 */ class XorShift32 { private: //! XorShiftの現在の値 unsigned value; /** * @brief XorShift32のアルゴリズムに基づいて value を更新 */ inline void update() { value = value ^ (value << 13); value = value ^ (value >> 17); value = value ^ (value << 5); } /** * @brief 値を更新し,更新前の値を返却 * @return unsigned 呼び出し時の value を用いる */ inline unsigned get() { unsigned v = value; update(); return v; } public: /** * @brief [0, 2^bit) の範囲の乱数値を取り出す * @tparam デフォルトは31 * @return int */ template <int bit = 31> inline int next_int() { return (int)(get() >> (32 - bit)); } /** * @brief [-2^bit,2^bit)の範囲の乱数値を取り出す * @tparam デフォルトは31 * @return int */ template <int bit = 31> inline int next_signed() { unsigned v = get(); return (int)((v >> (31 - bit)) - (1 << (bit))); } /** * @brief next_int呼び出し時の最大値を取得 * @tparam 31 * @return int */ template <int bit = 31> inline int range_max() { return (int)((1u << bit) - 1); }; /** * @brief Construct a new XorShift32 object * @param seed * @details 初期シードをvalueとするXorShift32のインスタンスを生成 */ XorShift32(const unsigned seed) { value = seed; update(); } /** * @brief Construct a new XorShift 32 object * @details 初期シードをプロセスIDとするXorShift32のインスタンスを生成 */ XorShift32() : XorShift32(pid) {} }; /* #endregion */ /* #region template/Strings.hpp*/ /** * @file Strings.hpp * @author btk * @brief 文字列を扱いやすくするライブラリ * @version 0.1 * @date 2020-02-02 * * @copyright Copyright (c) 2020 * */ /** * @brief コレクションを文字列に変換する関数 * @tparam T コレクションの型、range-based for に対応している必要あり * @tparam U 区切り文字の型 * @param v コレクション * @param delimiter 区切り文字 * @return std::string delimiterで結合された文字列 */ template <typename T, typename U> std::string join(const T &v, const U delimiter) { std::stringstream ss; bool isFirst = true; for (auto &it : v) { if (!isFirst) { ss << delimiter; } isFirst = false; ss << it; } return ss.str(); } /** * @brief コレクションを文字列に変換する関数(イテレータ版) * @tparam ITR イテレータ型 * @tparam T 区切り文字の型 * @param bg 開始 * @param ed 終了 * @param delimiter 区切り文字 * @return std::string delimiterで結合された文字列 */ template <typename ITR, typename T> std::string join(const ITR bg, const ITR ed, const T delimiter) { std::stringstream ss; bool isFirst = true; for (auto it = bg; it != ed; ++it) { if (!isFirst) { ss << delimiter; } isFirst = false; ss << *it; } return ss.str(); } /* #endregion */ /* #region Template.hpp*/ /** * @file Template.hpp * @brief 競技プログラミング用テンプレート * @author btk15049 * @date 2019/05/02 */ /* #endregion */ /* #endregion */ /*</body>*/ #endif constexpr int HALF = 9; int N, Q; LL V[312345]; LL W[312345]; int key[112345]; LL L[112345]; vector<int> lQ; map<int, vector<int>> hQ; LL ret[212345]; LL pre[112345]; int main() { /* write here */ cin >> N; for (int i : range(N)) { cin >> V[i + 1] >> W[i + 1]; } cin >> Q; for (int i : range(Q)) { cin >> key[i] >> L[i]; if (key[i] < (1 << HALF)) { lQ.emplace_back(i); } else { int p = key[i]; while (p >= (1 << HALF)) p /= 2; hQ[p].emplace_back(i); } } for (int i : lQ) { vector<int> vs; vs.reserve(HALF); vs.push_back(key[i]); while (vs.back() > 1) { int k = vs.back() / 2; vs.push_back(k); } int h = vs.size(); for (int _b : range(1 << h)) { bitset<HALF> b(_b); LL cost = 0; LL value = 0; for (int j : range(h)) { if (b[j]) { cost += W[vs[j]]; value += V[vs[j]]; } } if (cost <= L[i]) { chmax(ret[i], value); } } } for (auto kv : hQ) { int p = kv.first; auto q = kv.second; fill(pre, pre + 112345, 0ll); { vector<int> vs; vs.reserve(HALF); vs.push_back(p); while (vs.back() > 1) { int k = vs.back() / 2; vs.push_back(k); } // cerr << "before: " << p << " " << join(vs, ",") << endl; int h = vs.size(); for (int _b : range(1 << h)) { bitset<18 - HALF> b(_b); LL cost = 0; LL value = 0; for (int j : range(h)) { if (b[j]) { cost += W[vs[j]]; value += V[vs[j]]; } } if (cost <= 112345) { chmax(pre[cost], value); } } } for (int i : range(112344)) { chmax(pre[i + 1], pre[i]); } for (int i : q) { vector<int> vs; vs.reserve(HALF); vs.push_back(key[i]); while (vs.back() > p) { int k = vs.back() / 2; if (p == k) break; vs.push_back(k); } // cerr << "after: " << key[i] << " " << join(vs, ",") << endl; int h = vs.size(); for (int _b : range(1 << h)) { bitset<18 - HALF> b(_b); LL cost = 0; LL value = 0; for (int j : range(h)) { if (b[j]) { cost += W[vs[j]]; value += V[vs[j]]; } } // cerr << cost << " - " << value << endl; if (cost <= L[i]) { chmax(ret[i], value + pre[L[i] - cost]); } } } } for (int i : range(Q)) { cout << ret[i] << "\n"; } return 0; }
replace
632
633
632
633
TLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; #define rep(i, n) for (int i = 0; i < int(n); ++i) #define all(a) (a).begin(), (a).end() typedef long long ll; #define rep1(i, n) for (int i = 1; i <= int(n); ++i) #define lb(s, x) (lower_bound(all(s), x) - s.begin()) #define debug(x) cerr << (#x) << ": " << (x) << endl template <class T, class U> ostream &operator<<(ostream &o, const pair<T, U> &p) { o << "(" << p.first << ", " << p.second << ")"; return o; } #define print(v) \ { \ cerr << #v << ": [ "; \ for (auto _ : v) \ cerr << _ << ", "; \ cerr << "]" << endl; \ } using P = pair<ll, ll>; #define w first #define v second vector<P> all_enumerate(vector<P> vp, ll W, bool need_sort) { int N = vp.size(); vector<P> dp; for (int mask = 0; mask < (1 << N); mask++) { ll sumV = 0, sumW = 0; for (int i = 0; i < N; i++) { if (mask & (1 << i)) { sumV += vp[i].v; sumW += vp[i].w; } } if (sumW <= W) { dp.push_back({sumW, sumV}); } } if (!need_sort) return dp; // V降順 sort(dp.begin(), dp.end(), [](P a, P b) { return a.v != b.v ? a.v > b.v : a.w < b.w; }); vector<P> res; int w_border = W + 1; for (P s : dp) { if (w_border > s.w) { w_border = s.w; res.push_back(s); } } // V昇順 & W昇順 reverse(res.begin(), res.end()); return res; } int main(void) { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector<int> v(n + 1), w(n + 1); rep1(i, n) { cin >> v[i] >> w[i]; } int H2 = log2(n) / 2; vector<vector<P>> dp((1 << H2) + 1); for (int i = 1; i < (1 << H2); i++) { if (i > n) break; vector<P> vp; int x = i; while (x) { vp.push_back({w[x], v[x]}); x /= 2; } dp[i] = all_enumerate(vp, 100000LL, true); } int Q; cin >> Q; rep(q, Q) { int x, L; cin >> x >> L; vector<P> vp; while ((1 << H2) <= x) { vp.push_back({w[x], v[x]}); x /= 2; } vector<P> dp1 = dp[x]; vector<P> dp2 = all_enumerate(vp, L, false); ll max_v = 0; for (P p : dp2) { int pos = lb(dp1, P({L - p.w + 1, 0LL})) - 1; if (pos < 0) { if (p.w <= L) { max_v = max(max_v, p.v); } } else { if (p.w + dp1[pos].w <= L) { max_v = max(max_v, p.v + dp1[pos].v); } } } cout << max_v << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; #define rep(i, n) for (int i = 0; i < int(n); ++i) #define all(a) (a).begin(), (a).end() typedef long long ll; #define rep1(i, n) for (int i = 1; i <= int(n); ++i) #define lb(s, x) (lower_bound(all(s), x) - s.begin()) #define debug(x) cerr << (#x) << ": " << (x) << endl template <class T, class U> ostream &operator<<(ostream &o, const pair<T, U> &p) { o << "(" << p.first << ", " << p.second << ")"; return o; } #define print(v) \ { \ cerr << #v << ": [ "; \ for (auto _ : v) \ cerr << _ << ", "; \ cerr << "]" << endl; \ } using P = pair<ll, ll>; #define w first #define v second vector<P> all_enumerate(vector<P> vp, ll W, bool need_sort) { int N = vp.size(); vector<P> dp; for (int mask = 0; mask < (1 << N); mask++) { ll sumV = 0, sumW = 0; for (int i = 0; i < N; i++) { if (mask & (1 << i)) { sumV += vp[i].v; sumW += vp[i].w; } } if (sumW <= W) { dp.push_back({sumW, sumV}); } } if (!need_sort) return dp; // V降順 sort(dp.begin(), dp.end(), [](P a, P b) { return a.v != b.v ? a.v > b.v : a.w < b.w; }); vector<P> res; int w_border = W + 1; for (P s : dp) { if (w_border > s.w) { w_border = s.w; res.push_back(s); } } // V昇順 & W昇順 reverse(res.begin(), res.end()); return res; } int main(void) { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector<int> v(n + 1), w(n + 1); rep1(i, n) { cin >> v[i] >> w[i]; } int H2 = log2(n) / 2 + 2; vector<vector<P>> dp((1 << H2) + 1); for (int i = 1; i < (1 << H2); i++) { if (i > n) break; vector<P> vp; int x = i; while (x) { vp.push_back({w[x], v[x]}); x /= 2; } dp[i] = all_enumerate(vp, 100000LL, true); } int Q; cin >> Q; rep(q, Q) { int x, L; cin >> x >> L; vector<P> vp; while ((1 << H2) <= x) { vp.push_back({w[x], v[x]}); x /= 2; } vector<P> dp1 = dp[x]; vector<P> dp2 = all_enumerate(vp, L, false); ll max_v = 0; for (P p : dp2) { int pos = lb(dp1, P({L - p.w + 1, 0LL})) - 1; if (pos < 0) { if (p.w <= L) { max_v = max(max_v, p.v); } } else { if (p.w + dp1[pos].w <= L) { max_v = max(max_v, p.v + dp1[pos].v); } } } cout << max_v << endl; } return 0; }
replace
66
67
66
67
TLE
p02648
C++
Runtime Error
#include <algorithm> #include <assert.h> #include <bitset> #include <cmath> #include <cstdlib> #include <ctime> #include <functional> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; typedef long long ll; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<char> vc; typedef vector<string> vs; typedef vector<bool> vb; typedef vector<double> vd; typedef pair<ll, ll> P; typedef vector<P> vpl; typedef tuple<ll, ll, ll> tapu; #define rep(i, n) for (ll i = 0; i < (n); i++) #define REP(i, a, b) for (int i = (a); i < (b); i++) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() const int inf = 1 << 30; const ll linf = 1LL << 62; const int MAX = 510000; ll dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; ll dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; const double pi = acos(-1); const double eps = 1e-7; template <typename T1, typename T2> inline bool chmin(T1 &a, T2 b) { if (a > b) { a = b; return true; } else return false; } template <typename T1, typename T2> inline bool chmax(T1 &a, T2 b) { if (a < b) { a = b; return true; } else return false; } template <typename T> inline void print(T &a) { rep(i, a.size()) cout << a[i] << " "; cout << "\n"; } template <typename T1, typename T2> inline void print2(T1 a, T2 b) { cout << a << " " << b << "\n"; } template <typename T1, typename T2, typename T3> inline void print3(T1 a, T2 b, T3 c) { cout << a << " " << b << " " << c << "\n"; } const int mod = 1e9 + 7; // const int mod = 998244353; int main() { int n; cin >> n; vector<int> V(n + 1), W(n + 1); rep(i, n) cin >> V[i + 1] >> W[i + 1]; int M = 1024; vector<vector<pair<int, int>>> vp(M); vp[0].emplace_back(0, 0); REP(i, 1, M + 1) { if (i > n) break; vector<pair<int, int>> vv; for (auto b : vp[i / 2]) { vv.emplace_back(b); vv.emplace_back(b.first + W[i], b.second + V[i]); } sort(all(vv)); int now = -1; for (auto b : vv) { if (now < b.second) { vp[i].push_back(b); now = b.second; } } } int q; cin >> q; while (q--) { int v, L; scanf("%d%d", &v, &L); vector<pair<int, int>> acc; acc.emplace_back(0, 0); while (v > M) { vector<pair<int, int>> tmp; for (auto b : acc) { tmp.emplace_back(b); tmp.emplace_back(b.first + W[v], b.second + V[v]); } acc = tmp; v >>= 1; } int ans = 0; for (auto b : acc) { pair<int, int> pp = {L - b.first, inf}; auto itr = lower_bound(all(vp[v]), pp); if (itr != vp[v].begin()) { itr--; chmax(ans, (*itr).second + b.second); } } cout << ans << "\n"; } }
#include <algorithm> #include <assert.h> #include <bitset> #include <cmath> #include <cstdlib> #include <ctime> #include <functional> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; typedef long long ll; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<char> vc; typedef vector<string> vs; typedef vector<bool> vb; typedef vector<double> vd; typedef pair<ll, ll> P; typedef vector<P> vpl; typedef tuple<ll, ll, ll> tapu; #define rep(i, n) for (ll i = 0; i < (n); i++) #define REP(i, a, b) for (int i = (a); i < (b); i++) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() const int inf = 1 << 30; const ll linf = 1LL << 62; const int MAX = 510000; ll dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; ll dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; const double pi = acos(-1); const double eps = 1e-7; template <typename T1, typename T2> inline bool chmin(T1 &a, T2 b) { if (a > b) { a = b; return true; } else return false; } template <typename T1, typename T2> inline bool chmax(T1 &a, T2 b) { if (a < b) { a = b; return true; } else return false; } template <typename T> inline void print(T &a) { rep(i, a.size()) cout << a[i] << " "; cout << "\n"; } template <typename T1, typename T2> inline void print2(T1 a, T2 b) { cout << a << " " << b << "\n"; } template <typename T1, typename T2, typename T3> inline void print3(T1 a, T2 b, T3 c) { cout << a << " " << b << " " << c << "\n"; } const int mod = 1e9 + 7; // const int mod = 998244353; int main() { int n; cin >> n; vector<int> V(n + 1), W(n + 1); rep(i, n) cin >> V[i + 1] >> W[i + 1]; int M = 1024; vector<vector<pair<int, int>>> vp(M + 1); vp[0].emplace_back(0, 0); REP(i, 1, M + 1) { if (i > n) break; vector<pair<int, int>> vv; for (auto b : vp[i / 2]) { vv.emplace_back(b); vv.emplace_back(b.first + W[i], b.second + V[i]); } sort(all(vv)); int now = -1; for (auto b : vv) { if (now < b.second) { vp[i].push_back(b); now = b.second; } } } int q; cin >> q; while (q--) { int v, L; scanf("%d%d", &v, &L); vector<pair<int, int>> acc; acc.emplace_back(0, 0); while (v > M) { vector<pair<int, int>> tmp; for (auto b : acc) { tmp.emplace_back(b); tmp.emplace_back(b.first + W[v], b.second + V[v]); } acc = tmp; v >>= 1; } int ans = 0; for (auto b : acc) { pair<int, int> pp = {L - b.first, inf}; auto itr = lower_bound(all(vp[v]), pp); if (itr != vp[v].begin()) { itr--; chmax(ans, (*itr).second + b.second); } } cout << ans << "\n"; } }
replace
70
71
70
71
0
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> Pii; const int SAKAIME = 2048; const int MAX_W = 300000; const int MAX_N = 100000; vector<vector<int>> memo(SAKAIME + 1, vector<int>(MAX_W + 1, 0)); vector<Pii> VW(MAX_N + 1); int dfs(int v, int l) { if (v <= SAKAIME) return memo[v][l]; int t = 0; if (l - VW[v].second >= 0) t = VW[v].first + dfs(v / 2, l - VW[v].second); return max(dfs(v / 2, l), t); } int main() { int N; cin >> N; for (int i = 1; i <= N; i++) cin >> VW[i].first >> VW[i].second; for (int i = 1; i <= min(SAKAIME, N); i++) { for (int j = 1; j <= MAX_W; j++) { if (j - VW[i].second >= 0) memo[i][j] = VW[i].first + memo[i / 2][j - VW[i].second]; memo[i][j] = max(memo[i / 2][j], memo[i][j]); } } int Q; cin >> Q; while (Q--) { int v, l; cin >> v >> l; cout << dfs(v, l) << endl; } }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> Pii; const int SAKAIME = 2048; const int MAX_W = 100000; const int MAX_N = 300000; vector<vector<int>> memo(SAKAIME + 1, vector<int>(MAX_W + 1, 0)); vector<Pii> VW(MAX_N + 1); int dfs(int v, int l) { if (v <= SAKAIME) return memo[v][l]; int t = 0; if (l - VW[v].second >= 0) t = VW[v].first + dfs(v / 2, l - VW[v].second); return max(dfs(v / 2, l), t); } int main() { int N; cin >> N; for (int i = 1; i <= N; i++) cin >> VW[i].first >> VW[i].second; for (int i = 1; i <= min(SAKAIME, N); i++) { for (int j = 1; j <= MAX_W; j++) { if (j - VW[i].second >= 0) memo[i][j] = VW[i].first + memo[i / 2][j - VW[i].second]; memo[i][j] = max(memo[i / 2][j], memo[i][j]); } } int Q; cin >> Q; while (Q--) { int v, l; cin >> v >> l; cout << dfs(v, l) << endl; } }
replace
6
8
6
8
-6
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
p02648
C++
Time Limit Exceeded
#pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") #pragma GCC optimize("unroll-loops") // #pragma warning(disable : 4996) #ifdef _MSC_VER #include <intrin.h> #define __builtin_popcount __popcnt #define __builtin_popcountll __popcnt64 #endif #include <limits.h> #include <math.h> #include <time.h> #include <algorithm> #include <array> #include <bitset> #include <cassert> #include <complex> #include <cstdio> #include <cstring> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; #define REP(i, n) for (int i = 0; i < (n); ++i) #define REPR(i, n) for (int i = n - 1; i >= 0; --i) #define FOR(i, m, n) for (int i = m; i < n; ++i) #define FORR(i, m, n) for (int i = m - 1; i >= n; --i) #define SORT(v, n) sort(v, v + n); #define VSORT(v) sort(v.begin(), v.end()); #define REVERSE(v, n) reverse(v, v + n); #define VREVERSE(v) reverse(v.begin(), v.end()) #define ll long long #define print(x) cout << (x) << '\n' #define pe(x) cout << (x) << " " #define DEBUG(x) cout << #x << ": " << x << endl #define lb(v, n) lower_bound(v.begin(), v.end(), (n)) #define ub(v, n) upper_bound(v.begin(), v.end(), (n)) // #define int long long #define double long double #define all(x) (x).begin(), (x).end() #define print_space(v) \ REP(i, v.size()) cout << v[i] << ((i == v.size() - 1) ? "\n" : " ") template <typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; } template <typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; } typedef pair<int, int> pii; typedef pair<long long, long long> pll; typedef array<int, 3> arr3; std::random_device rd; std::mt19937 mt(rd()); constexpr ll MOD = 1e9 + 7; constexpr int MAX = 500050; const double pi = acos(-1); constexpr double EPS = 1e-8; constexpr ll LINF = 1e18 + 1; constexpr int INF = 1e9 + 1; int N; vector<int> G[500050]; int par[500050]; int V[500050], W[500050]; int dp[(1 << 9) + 2][100010]; // int calc(int n, int L) { // vector<int>v, w; // while (true) { // v.push_back(V[n]); // w.push_back(W[n]); // if (par[n] == n)break; // n = par[n]; // } // int siz = v.size(); // REP(i, siz + 1)REP(j, L + 1)dp[i][j] = 0; // REP(i, siz)REP(j, L + 1) { // chmax(dp[i + 1][j], dp[i][j]); // if (j + w[i] <= L) { // chmax(dp[i + 1][j + w[i]], dp[i][j] + v[i]); // } // } // ll ans = 0; // REP(j, L + 1)chmax(ans, dp[siz][j]); // return ans; // } int cv[100010], cw[100010]; void solve() { cin >> N; REP(i, N) { cin >> V[i] >> W[i]; if (i == 0) par[i] = i; else par[i] = (i - 1) / 2; } int small_n = min(1 << 8, N); REP(i, small_n) { if (i == 0) { dp[0][W[i]] = V[i]; REP(j, 100001) chmax(dp[0][j + 1], dp[0][j]); } else { int p = par[i]; REP(j, 100010) { chmax(dp[i][j], dp[p][j]); if (j + W[i] <= 100000) chmax(dp[i][j + W[i]], dp[p][j] + V[i]); } REP(j, 100001) chmax(dp[i][j + 1], dp[i][j]); } // REP(j, 100010) { // chmax(dp[i*2+2][j], dp[i][j]); // if (j + W[i] <= 100000)chmax(dp[i*2+2][j + W[i]], dp[i][j] + V[i]); // chmax(dp[i * 2+1][j], dp[i][j]); // if (j + W[i] <= 100000)chmax(dp[i*2+1][j + W[i]], dp[i][j] + V[i]); // } // REP(j, 100001) { // chmax(dp[i*2+2][j + 1], dp[i*2+2][j]); // chmax(dp[i * 2+1][j + 1], dp[i * 2+1][j]); // } } int Q; cin >> Q; REP(_, Q) { int v, L; cin >> v >> L; if (v <= small_n) print(dp[v - 1][L]); else { int idx = 0; v--; int num = v; while (num >= small_n) { cv[idx] = V[num]; cw[idx] = W[num]; idx++; num = par[num]; } int p = num; ll res = 0; REP(bit, 1 << idx) { int sumw = 0; ll sumv = 0; REP(i, idx) { if (bit & (1 << i)) { sumw += cw[i]; sumv += cv[i]; } if (sumw > L) break; } if (sumw > L) continue; int rem = L - sumw; chmax(res, sumv + dp[p][rem]); } print(res); } } } signed main() { cin.tie(0); ios::sync_with_stdio(false); mt.seed((int)(time(0))); // REP(_, 10000)test(); // int q; // cin >> q; // while (q--) solve(); }
#pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") #pragma GCC optimize("unroll-loops") // #pragma warning(disable : 4996) #ifdef _MSC_VER #include <intrin.h> #define __builtin_popcount __popcnt #define __builtin_popcountll __popcnt64 #endif #include <limits.h> #include <math.h> #include <time.h> #include <algorithm> #include <array> #include <bitset> #include <cassert> #include <complex> #include <cstdio> #include <cstring> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; #define REP(i, n) for (int i = 0; i < (n); ++i) #define REPR(i, n) for (int i = n - 1; i >= 0; --i) #define FOR(i, m, n) for (int i = m; i < n; ++i) #define FORR(i, m, n) for (int i = m - 1; i >= n; --i) #define SORT(v, n) sort(v, v + n); #define VSORT(v) sort(v.begin(), v.end()); #define REVERSE(v, n) reverse(v, v + n); #define VREVERSE(v) reverse(v.begin(), v.end()) #define ll long long #define print(x) cout << (x) << '\n' #define pe(x) cout << (x) << " " #define DEBUG(x) cout << #x << ": " << x << endl #define lb(v, n) lower_bound(v.begin(), v.end(), (n)) #define ub(v, n) upper_bound(v.begin(), v.end(), (n)) // #define int long long #define double long double #define all(x) (x).begin(), (x).end() #define print_space(v) \ REP(i, v.size()) cout << v[i] << ((i == v.size() - 1) ? "\n" : " ") template <typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; } template <typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; } typedef pair<int, int> pii; typedef pair<long long, long long> pll; typedef array<int, 3> arr3; std::random_device rd; std::mt19937 mt(rd()); constexpr ll MOD = 1e9 + 7; constexpr int MAX = 500050; const double pi = acos(-1); constexpr double EPS = 1e-8; constexpr ll LINF = 1e18 + 1; constexpr int INF = 1e9 + 1; int N; vector<int> G[500050]; int par[500050]; int V[500050], W[500050]; int dp[(1 << 9) + 2][100010]; // int calc(int n, int L) { // vector<int>v, w; // while (true) { // v.push_back(V[n]); // w.push_back(W[n]); // if (par[n] == n)break; // n = par[n]; // } // int siz = v.size(); // REP(i, siz + 1)REP(j, L + 1)dp[i][j] = 0; // REP(i, siz)REP(j, L + 1) { // chmax(dp[i + 1][j], dp[i][j]); // if (j + w[i] <= L) { // chmax(dp[i + 1][j + w[i]], dp[i][j] + v[i]); // } // } // ll ans = 0; // REP(j, L + 1)chmax(ans, dp[siz][j]); // return ans; // } int cv[100010], cw[100010]; void solve() { cin >> N; REP(i, N) { cin >> V[i] >> W[i]; if (i == 0) par[i] = i; else par[i] = (i - 1) / 2; } int small_n = min(1 << 9, N); REP(i, small_n) { if (i == 0) { dp[0][W[i]] = V[i]; REP(j, 100001) chmax(dp[0][j + 1], dp[0][j]); } else { int p = par[i]; REP(j, 100010) { chmax(dp[i][j], dp[p][j]); if (j + W[i] <= 100000) chmax(dp[i][j + W[i]], dp[p][j] + V[i]); } REP(j, 100001) chmax(dp[i][j + 1], dp[i][j]); } // REP(j, 100010) { // chmax(dp[i*2+2][j], dp[i][j]); // if (j + W[i] <= 100000)chmax(dp[i*2+2][j + W[i]], dp[i][j] + V[i]); // chmax(dp[i * 2+1][j], dp[i][j]); // if (j + W[i] <= 100000)chmax(dp[i*2+1][j + W[i]], dp[i][j] + V[i]); // } // REP(j, 100001) { // chmax(dp[i*2+2][j + 1], dp[i*2+2][j]); // chmax(dp[i * 2+1][j + 1], dp[i * 2+1][j]); // } } int Q; cin >> Q; REP(_, Q) { int v, L; cin >> v >> L; if (v <= small_n) print(dp[v - 1][L]); else { int idx = 0; v--; int num = v; while (num >= small_n) { cv[idx] = V[num]; cw[idx] = W[num]; idx++; num = par[num]; } int p = num; ll res = 0; REP(bit, 1 << idx) { int sumw = 0; ll sumv = 0; REP(i, idx) { if (bit & (1 << i)) { sumw += cw[i]; sumv += cv[i]; } if (sumw > L) break; } if (sumw > L) continue; int rem = L - sumw; chmax(res, sumv + dp[p][rem]); } print(res); } } } signed main() { cin.tie(0); ios::sync_with_stdio(false); mt.seed((int)(time(0))); // REP(_, 10000)test(); // int q; // cin >> q; // while (q--) solve(); }
replace
114
115
114
115
TLE
p02648
C++
Time Limit Exceeded
// Problem : D - Knapsack Queries on a tree // Contest : AtCoder - Tokio Marine & Nichido Fire Insurance Programming Contest // 2020 URL : // https://atcoder.jp/contests/tokiomarine2020/tasks/tokiomarine2020_d Memory // Limit : 1024 MB Time Limit : 3000 ms Powered by CP Editor // (https://github.com/cpeditor/cpeditor) #ifndef OUUAN #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math") #endif #include <bits/stdc++.h> #define int ll // #define FAST_IOSTREAM 1 #define For(i, l, r) for (int i = (l), i##end = (r); i <= i##end; ++i) #define FOR(i, r, l) for (int i = (r), i##end = (l); i >= i##end; --i) #define SON(i, u) for (int i = head[u]; i; i = nxt[i]) #define BE(x) (x).begin(), (x).end() #define BE1(x) ((x).begin() + 1), (x).end() #define fi first #define se second #define pb push_back #define eb emplace_back #define pq priority_queue #define min minOfDifferentTypes #define max maxOfDifferentTypes #define y1 why_is_there_a_function_called_y1 using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vvi v2i; typedef vector<vvi> v3i; typedef vector<v3i> v4i; typedef vector<bool> vb; typedef vector<vb> vvb; typedef vvb v2b; typedef vector<vvb> v3b; typedef vector<v3b> v4b; typedef vector<pii> vpii; typedef vector<vpii> vvpii; typedef vvpii v2pii; typedef vector<vvpii> v3pii; typedef vector<v3pii> v4pii; typedef vector<double> vd; typedef vector<vd> vvd; typedef vvd v2d; typedef vector<v2d> v3d; typedef vector<v3d> v4d; const double inf = 1e121; const double eps = 1e-10; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int randint(int l, int r) { int out = rng() % (r - l + 1) + l; return out >= l ? out : out + r - l + 1; } template <typename A, typename B> string to_string(pair<A, B> p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p); string to_string(const string &s) { return '"' + s + '"'; } string to_string(const char *s) { return to_string((string)s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ","; } first = false; res += to_string(v[i]); } res += "}"; return res; } template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ","; } first = false; res += to_string(x); } res += "}"; return res; } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + "," + to_string(p.second) + ")"; } template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + "," + to_string(get<1>(p)) + "," + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + "," + to_string(get<1>(p)) + "," + to_string(get<2>(p)) + "," + to_string(get<3>(p)) + ")"; } template <typename A, typename B, typename C, typename D, typename E> string to_string(tuple<A, B, C, D, E> p) { return "(" + to_string(get<0>(p)) + "," + to_string(get<1>(p)) + "," + to_string(get<2>(p)) + "," + to_string(get<3>(p)) + "," + to_string(get<4>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } template <typename T> struct is_pair { static const bool value = false; }; template <typename T, typename U> struct is_pair<std::pair<T, U>> { static const bool value = true; }; #ifdef OUUAN #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) #else #define debug(...) 42 #endif #ifdef int const int INF = 0x3f3f3f3f3f3f3f3fll; #else const int INF = 0x3f3f3f3f; #endif #ifdef FAST_IOSTREAM #define br cout << '\n' #define sp cout << ' ' #define fl cout.flush() ll read() { ll x; cin >> x; return x; } template <typename T> void read(T &x) { cin >> x; } template <typename T> void write(const T &x) { cout << x; } #else #define br putchar('\n') #define sp putchar(' ') #define fl fflush(stdout) template <typename T> typename enable_if<!is_integral<T>::value && !is_pair<T>::value, void>::type read(T &x) { cin >> x; } ll read() { char c; ll out = 0, f = 1; for (c = getchar(); !isdigit(c) && c != '-'; c = getchar()) { } if (c == '-') { f = -1; c = getchar(); } for (; isdigit(c); c = getchar()) out = (out << 3) + (out << 1) + c - '0'; return out * f; } template <typename T> typename enable_if<is_integral<T>::value, T>::type read(T &x) { char c; T f = 1; x = 0; for (c = getchar(); !isdigit(c) && c != '-'; c = getchar()) { } if (c == '-') { f = -1; c = getchar(); } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; return x *= f; } char read(char &x) { for (x = getchar(); isspace(x); x = getchar()) { } return x; } double read(double &x) { scanf("%lf", &x); return x; } template <typename T> typename enable_if<!is_integral<T>::value && !is_pair<T>::value, void>::type write(const T &x) { cout << x; } template <typename T> typename enable_if<is_integral<T>::value, void>::type write(const T &x) { if (x < 0) { putchar('-'); write(-x); return; } if (x > 9) write(x / 10); putchar(x % 10 + '0'); } void write(const char &x) { putchar(x); } void write(const double &x) { printf("%.10lf", x); } #endif template <typename T> typename enable_if<is_pair<T>::value, void>::type read(T &x) { read(x.fi); read(x.se); } template <typename T> typename enable_if<is_pair<T>::value, void>::type write(const T &x) { write(x.fi); sp; write(x.se); } template <typename T, typename... Args> void read(T &x, Args &...args) { read(x); read(args...); } template < typename OutputIt, typename = typename enable_if< is_same<output_iterator_tag, typename iterator_traits<OutputIt>::iterator_category>::value || (is_base_of<forward_iterator_tag, typename iterator_traits<OutputIt>:: iterator_category>::value && !is_const<OutputIt>::value)>::type> void read(OutputIt __first, OutputIt __last) { for (; __first != __last; ++__first) read(*__first); } template < typename InputIt, typename = typename enable_if<is_base_of< input_iterator_tag, typename iterator_traits<InputIt>::iterator_category>::value>::type> void wts(InputIt __first, InputIt __last) { bool isFirst = true; for (; __first != __last; ++__first) { if (isFirst) isFirst = false; else sp; write(*__first); } br; } template < typename InputIt, typename = typename enable_if<is_base_of< input_iterator_tag, typename iterator_traits<InputIt>::iterator_category>::value>::type> void wtb(InputIt __first, InputIt __last) { for (; __first != __last; ++__first) { write(*__first); br; } } template <typename T> void wts(const T &x) { write(x); sp; } template <typename T> void wtb(const T &x) { write(x); br; } template <typename T> void wte(const T &x) { write(x); exit(0); } template <typename T, typename... Args> void wts(const T &x, Args... args) { wts(x); wts(args...); } template <typename T, typename... Args> void wtb(const T &x, Args... args) { wts(x); wtb(args...); } template <typename T, typename... Args> void wte(const T &x, Args... args) { wts(x); wte(args...); } template <typename T1, typename T2> inline bool up(T1 &x, const T2 &y) { return x < y ? x = y, 1 : 0; } template <typename T1, typename T2> inline bool dn(T1 &x, const T2 &y) { return y < x ? x = y, 1 : 0; } template <typename T1, typename T2, typename T3> inline bool inRange(const T1 &x, const T2 &l, const T3 &r) { return !(x < l) && !(r < x); } template <typename T1, typename T2> inline auto minOfDifferentTypes(const T1 &x, const T2 &y) -> decltype(x < y ? x : y) { return x < y ? x : y; } template <typename T1, typename T2> inline auto maxOfDifferentTypes(const T1 &x, const T2 &y) -> decltype(x < y ? y : x) { return x < y ? y : x; } template <typename T1, typename T2, typename T3> inline T1 &madd(T1 &x, const T2 &y, const T3 &modulo) { return x = (ll)(x + y + modulo) % modulo; } template <typename T1, typename T2, typename T3> inline T1 &mmul(T1 &x, const T2 &y, const T3 &modulo) { return x = (ll)x * y % modulo; } template <typename T1, typename T2, typename T3> inline int modadd(int x, int y, int modulo) { return (x += y) >= modulo ? x - modulo : x; } inline int isinf(int x) { return x < INF ? x : -1; } inline void yesno(bool x) { wtb(x ? "Yes" : "No"); } /* ------------------------------------------------------------------------------------------------------------------- */ signed main() { #ifdef FAST_IOSTREAM ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #endif int n = read(); vi v(n + 1), w(n + 1); For(i, 1, n) read(v[i], w[i]); int q = read(); int B = min(n, pow(n * q, 0.666) + 1); vvpii p(B + 1); For(u, 1, B) { vi a; for (int x = u; x; x /= 2) a.pb(x); vpii tmp; for (int i = 0; i < (1 << a.size()); ++i) { int sumv = 0, sumw = 0; for (int j = 0; j < (int)a.size(); ++j) { if ((i >> j) & 1) { sumv += v[a[j]]; sumw += w[a[j]]; } } tmp.eb(sumw, sumv); } sort(BE(tmp)); for (auto x : tmp) { if (p[u].empty()) p[u].pb(x); else if (x.fi == p[u].back().fi) { p[u].pop_back(); p[u].pb(x); } else if (x.se > p[u].back().se) p[u].pb(x); } } while (q--) { int u, l; read(u, l); if (u <= B) wtb(prev(upper_bound(BE(p[u]), pii(l, INF)))->se); else { vi a; int r = 1; for (int x = u;; x /= 2) { if (x <= B) { r = x; break; } a.pb(x); } int ans = 0; for (int i = 0; i < (1 << a.size()); ++i) { int sumv = 0, sumw = 0; for (int j = 0; j < (int)a.size(); ++j) { if ((i >> j) & 1) { sumv += v[a[j]]; sumw += w[a[j]]; } } if (sumw > l) continue; up(ans, sumv + prev(upper_bound(BE(p[r]), pii(l - sumw, INF)))->se); } wtb(ans); } } return 0; }
// Problem : D - Knapsack Queries on a tree // Contest : AtCoder - Tokio Marine & Nichido Fire Insurance Programming Contest // 2020 URL : // https://atcoder.jp/contests/tokiomarine2020/tasks/tokiomarine2020_d Memory // Limit : 1024 MB Time Limit : 3000 ms Powered by CP Editor // (https://github.com/cpeditor/cpeditor) #ifndef OUUAN #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math") #endif #include <bits/stdc++.h> #define int ll // #define FAST_IOSTREAM 1 #define For(i, l, r) for (int i = (l), i##end = (r); i <= i##end; ++i) #define FOR(i, r, l) for (int i = (r), i##end = (l); i >= i##end; --i) #define SON(i, u) for (int i = head[u]; i; i = nxt[i]) #define BE(x) (x).begin(), (x).end() #define BE1(x) ((x).begin() + 1), (x).end() #define fi first #define se second #define pb push_back #define eb emplace_back #define pq priority_queue #define min minOfDifferentTypes #define max maxOfDifferentTypes #define y1 why_is_there_a_function_called_y1 using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vvi v2i; typedef vector<vvi> v3i; typedef vector<v3i> v4i; typedef vector<bool> vb; typedef vector<vb> vvb; typedef vvb v2b; typedef vector<vvb> v3b; typedef vector<v3b> v4b; typedef vector<pii> vpii; typedef vector<vpii> vvpii; typedef vvpii v2pii; typedef vector<vvpii> v3pii; typedef vector<v3pii> v4pii; typedef vector<double> vd; typedef vector<vd> vvd; typedef vvd v2d; typedef vector<v2d> v3d; typedef vector<v3d> v4d; const double inf = 1e121; const double eps = 1e-10; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int randint(int l, int r) { int out = rng() % (r - l + 1) + l; return out >= l ? out : out + r - l + 1; } template <typename A, typename B> string to_string(pair<A, B> p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p); string to_string(const string &s) { return '"' + s + '"'; } string to_string(const char *s) { return to_string((string)s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ","; } first = false; res += to_string(v[i]); } res += "}"; return res; } template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ","; } first = false; res += to_string(x); } res += "}"; return res; } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + "," + to_string(p.second) + ")"; } template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + "," + to_string(get<1>(p)) + "," + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + "," + to_string(get<1>(p)) + "," + to_string(get<2>(p)) + "," + to_string(get<3>(p)) + ")"; } template <typename A, typename B, typename C, typename D, typename E> string to_string(tuple<A, B, C, D, E> p) { return "(" + to_string(get<0>(p)) + "," + to_string(get<1>(p)) + "," + to_string(get<2>(p)) + "," + to_string(get<3>(p)) + "," + to_string(get<4>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } template <typename T> struct is_pair { static const bool value = false; }; template <typename T, typename U> struct is_pair<std::pair<T, U>> { static const bool value = true; }; #ifdef OUUAN #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) #else #define debug(...) 42 #endif #ifdef int const int INF = 0x3f3f3f3f3f3f3f3fll; #else const int INF = 0x3f3f3f3f; #endif #ifdef FAST_IOSTREAM #define br cout << '\n' #define sp cout << ' ' #define fl cout.flush() ll read() { ll x; cin >> x; return x; } template <typename T> void read(T &x) { cin >> x; } template <typename T> void write(const T &x) { cout << x; } #else #define br putchar('\n') #define sp putchar(' ') #define fl fflush(stdout) template <typename T> typename enable_if<!is_integral<T>::value && !is_pair<T>::value, void>::type read(T &x) { cin >> x; } ll read() { char c; ll out = 0, f = 1; for (c = getchar(); !isdigit(c) && c != '-'; c = getchar()) { } if (c == '-') { f = -1; c = getchar(); } for (; isdigit(c); c = getchar()) out = (out << 3) + (out << 1) + c - '0'; return out * f; } template <typename T> typename enable_if<is_integral<T>::value, T>::type read(T &x) { char c; T f = 1; x = 0; for (c = getchar(); !isdigit(c) && c != '-'; c = getchar()) { } if (c == '-') { f = -1; c = getchar(); } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; return x *= f; } char read(char &x) { for (x = getchar(); isspace(x); x = getchar()) { } return x; } double read(double &x) { scanf("%lf", &x); return x; } template <typename T> typename enable_if<!is_integral<T>::value && !is_pair<T>::value, void>::type write(const T &x) { cout << x; } template <typename T> typename enable_if<is_integral<T>::value, void>::type write(const T &x) { if (x < 0) { putchar('-'); write(-x); return; } if (x > 9) write(x / 10); putchar(x % 10 + '0'); } void write(const char &x) { putchar(x); } void write(const double &x) { printf("%.10lf", x); } #endif template <typename T> typename enable_if<is_pair<T>::value, void>::type read(T &x) { read(x.fi); read(x.se); } template <typename T> typename enable_if<is_pair<T>::value, void>::type write(const T &x) { write(x.fi); sp; write(x.se); } template <typename T, typename... Args> void read(T &x, Args &...args) { read(x); read(args...); } template < typename OutputIt, typename = typename enable_if< is_same<output_iterator_tag, typename iterator_traits<OutputIt>::iterator_category>::value || (is_base_of<forward_iterator_tag, typename iterator_traits<OutputIt>:: iterator_category>::value && !is_const<OutputIt>::value)>::type> void read(OutputIt __first, OutputIt __last) { for (; __first != __last; ++__first) read(*__first); } template < typename InputIt, typename = typename enable_if<is_base_of< input_iterator_tag, typename iterator_traits<InputIt>::iterator_category>::value>::type> void wts(InputIt __first, InputIt __last) { bool isFirst = true; for (; __first != __last; ++__first) { if (isFirst) isFirst = false; else sp; write(*__first); } br; } template < typename InputIt, typename = typename enable_if<is_base_of< input_iterator_tag, typename iterator_traits<InputIt>::iterator_category>::value>::type> void wtb(InputIt __first, InputIt __last) { for (; __first != __last; ++__first) { write(*__first); br; } } template <typename T> void wts(const T &x) { write(x); sp; } template <typename T> void wtb(const T &x) { write(x); br; } template <typename T> void wte(const T &x) { write(x); exit(0); } template <typename T, typename... Args> void wts(const T &x, Args... args) { wts(x); wts(args...); } template <typename T, typename... Args> void wtb(const T &x, Args... args) { wts(x); wtb(args...); } template <typename T, typename... Args> void wte(const T &x, Args... args) { wts(x); wte(args...); } template <typename T1, typename T2> inline bool up(T1 &x, const T2 &y) { return x < y ? x = y, 1 : 0; } template <typename T1, typename T2> inline bool dn(T1 &x, const T2 &y) { return y < x ? x = y, 1 : 0; } template <typename T1, typename T2, typename T3> inline bool inRange(const T1 &x, const T2 &l, const T3 &r) { return !(x < l) && !(r < x); } template <typename T1, typename T2> inline auto minOfDifferentTypes(const T1 &x, const T2 &y) -> decltype(x < y ? x : y) { return x < y ? x : y; } template <typename T1, typename T2> inline auto maxOfDifferentTypes(const T1 &x, const T2 &y) -> decltype(x < y ? y : x) { return x < y ? y : x; } template <typename T1, typename T2, typename T3> inline T1 &madd(T1 &x, const T2 &y, const T3 &modulo) { return x = (ll)(x + y + modulo) % modulo; } template <typename T1, typename T2, typename T3> inline T1 &mmul(T1 &x, const T2 &y, const T3 &modulo) { return x = (ll)x * y % modulo; } template <typename T1, typename T2, typename T3> inline int modadd(int x, int y, int modulo) { return (x += y) >= modulo ? x - modulo : x; } inline int isinf(int x) { return x < INF ? x : -1; } inline void yesno(bool x) { wtb(x ? "Yes" : "No"); } /* ------------------------------------------------------------------------------------------------------------------- */ signed main() { #ifdef FAST_IOSTREAM ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #endif int n = read(); vi v(n + 1), w(n + 1); For(i, 1, n) read(v[i], w[i]); int q = read(); int B = min(n, pow(n * q, 0.333) + 1); vvpii p(B + 1); For(u, 1, B) { vi a; for (int x = u; x; x /= 2) a.pb(x); vpii tmp; for (int i = 0; i < (1 << a.size()); ++i) { int sumv = 0, sumw = 0; for (int j = 0; j < (int)a.size(); ++j) { if ((i >> j) & 1) { sumv += v[a[j]]; sumw += w[a[j]]; } } tmp.eb(sumw, sumv); } sort(BE(tmp)); for (auto x : tmp) { if (p[u].empty()) p[u].pb(x); else if (x.fi == p[u].back().fi) { p[u].pop_back(); p[u].pb(x); } else if (x.se > p[u].back().se) p[u].pb(x); } } while (q--) { int u, l; read(u, l); if (u <= B) wtb(prev(upper_bound(BE(p[u]), pii(l, INF)))->se); else { vi a; int r = 1; for (int x = u;; x /= 2) { if (x <= B) { r = x; break; } a.pb(x); } int ans = 0; for (int i = 0; i < (1 << a.size()); ++i) { int sumv = 0, sumw = 0; for (int j = 0; j < (int)a.size(); ++j) { if ((i >> j) & 1) { sumv += v[a[j]]; sumw += w[a[j]]; } } if (sumw > l) continue; up(ans, sumv + prev(upper_bound(BE(p[r]), pii(l - sumw, INF)))->se); } wtb(ans); } } return 0; }
replace
347
348
347
348
TLE
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using ull = unsigned long long; using uint = unsigned; using pcc = pair<char, char>; using pii = pair<int, int>; using pll = pair<ll, ll>; using pdd = pair<double, double>; using tuplis = array<ll, 3>; template <class T> using pq = priority_queue<T, vector<T>, greater<T>>; const ll LINF = 0x1fffffffffffffff; const ll MINF = 0x7fffffffffff; const int INF = 0x3fffffff; const int MOD = 1000000007; const int MODD = 998244353; const ld DINF = numeric_limits<ld>::infinity(); const ld EPS = 1e-9; const ld PI = 3.1415926535897932; const ll dx[] = {0, 1, 0, -1, 1, -1, 1, -1}; const ll dy[] = {1, 0, -1, 0, 1, 1, -1, -1}; #define overload4(_1, _2, _3, _4, name, ...) name #define overload3(_1, _2, _3, name, ...) name #define rep1(n) for (ll i = 0; i < n; ++i) #define rep2(i, n) for (ll i = 0; i < n; ++i) #define rep3(i, a, b) for (ll i = a; i < b; ++i) #define rep4(i, a, b, c) for (ll i = a; i < b; i += c) #define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__) #define rrep1(n) for (ll i = (n); i--;) #define rrep2(i, n) for (ll i = (n); i--;) #define rrep3(i, a, b) for (ll i = (b); i-- > (a);) #define rrep4(i, a, b, c) for (ll i = a + (b - a - 1) / c * c; i >= a; i -= c) #define rrep(...) \ overload4(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__) #define each(i, a) for (auto &&i : a) #define eachs2(x, y, a) for (auto &&[x, y] : a) #define eachs3(x, y, z, a) for (auto &&[x, y, z] : a) #define eachs(...) overload4(__VA_ARGS__, eachs3, eachs2)(__VA_ARGS__) #define all1(i) begin(i), end(i) #define all2(i, a) begin(i), begin(i) + a #define all3(i, a, b) begin(i) + a, begin(i) + b #define all(...) overload3(__VA_ARGS__, all3, all2, all1)(__VA_ARGS__) #define rall1(i) (i).rbegin(), (i).rend() #define rall2(i, k) (i).rbegin(), (i).rbegin() + k #define rall3(i, a, b) (i).rbegin() + a, (i).rbegin() + b #define rall(...) overload3(__VA_ARGS__, rall3, rall2, rall1)(__VA_ARGS__) #define sum(...) accumulate(all(__VA_ARGS__), 0LL) #define dsum(...) accumulate(all(__VA_ARGS__), 0.0L) #define elif else if #define unless(a) if (!(a)) #define mp make_pair #define mt make_tuple #define INT(...) \ int __VA_ARGS__; \ in(__VA_ARGS__) #define LL(...) \ ll __VA_ARGS__; \ in(__VA_ARGS__) #define ULL(...) \ ull __VA_ARGS__; \ in(__VA_ARGS__) #define STR(...) \ string __VA_ARGS__; \ in(__VA_ARGS__) #define CHR(...) \ char __VA_ARGS__; \ in(__VA_ARGS__) #define DBL(...) \ double __VA_ARGS__; \ in(__VA_ARGS__) #define LD(...) \ ld __VA_ARGS__; \ in(__VA_ARGS__) #define Sort(a) sort(all(a)) #define Rev(a) reverse(all(a)) #define Uniq(a) \ sort(all(a)); \ a.erase(unique(all(a)), end(a)) #define vec(type, name, ...) vector<type> name(__VA_ARGS__) #define VEC(type, name, size) \ vector<type> name(size); \ in(name) #define vv(type, name, h, ...) \ vector<vector<type>> name(h, vector<type>(__VA_ARGS__)) #define VV(type, name, h, w) \ vector<vector<type>> name(h, vector<type>(w)); \ in(name) #define vvv(type, name, h, w, ...) \ vector<vector<vector<type>>> name( \ h, vector<vector<type>>(w, vector<type>(__VA_ARGS__))) template <class T> auto min(const T &a) { return *min_element(all(a)); } template <class T> auto max(const T &a) { return *max_element(all(a)); } inline ll popcnt(ull a) { return __builtin_popcountll(a); } ll gcd(ll a, ll b) { while (b) { ll c = b; b = a % b; a = c; } return a; } ll lcm(ll a, ll b) { if (!a || !b) return 0; return a * b / gcd(a, b); } ll intpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; a *= a; b /= 2; } return ans; } ll modpow(ll a, ll b, ll p) { ll ans = 1; while (b) { if (b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; } template <class T, class U> bool chmin(T &a, const U &b) { if (a > b) { a = b; return 1; } return 0; } template <class T, class U> bool chmax(T &a, const U &b) { if (a < b) { a = b; return 1; } return 0; } vector<ll> iota(ll n) { vector<ll> a(n); iota(a.begin(), a.end(), 0); return a; } vector<pll> factor(ull x) { vector<pll> ans; for (ll i = 2; i * i <= x; i++) if (x % i == 0) { ans.push_back({i, 1}); while ((x /= i) % i == 0) ans.back().second++; } if (x != 1) ans.push_back({x, 1}); return ans; } map<ll, ll> factor_map(ull x) { map<ll, ll> ans; for (ll i = 2; i * i <= x; i++) if (x % i == 0) { ans[i] = 1; while ((x /= i) % i == 0) ans[i]++; } if (x != 1) ans[x] = 1; return ans; } vector<uint> divisor(uint x) { vector<uint> ans; for (uint i = 1; i * i <= x; i++) if (x % i == 0) ans.push_back(i); rrep(ans.size() - (ans.back() * ans.back() == x)) ans.push_back(x / ans[i]); return ans; } template <class T> unordered_map<T, ll> press(vector<T> &a) { auto b = a; sort(all(b)); b.erase(unique(all(b)), b.end()); unordered_map<T, ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; } template <class T> map<T, ll> press_map(vector<T> &a) { auto b = a; sort(all(b)); b.erase(unique(all(b)), b.end()); map<T, ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; } int scan() { return getchar(); } void scan(int &a) { scanf("%d", &a); } void scan(unsigned &a) { scanf("%u", &a); } void scan(long &a) { scanf("%ld", &a); } void scan(long long &a) { scanf("%lld", &a); } void scan(unsigned long long &a) { scanf("%llu", &a); } void scan(char &a) { do { a = getchar(); } while (a == ' ' || a == '\n'); } void scan(float &a) { scanf("%f", &a); } void scan(double &a) { scanf("%lf", &a); } void scan(long double &a) { scanf("%Lf", &a); } void scan(vector<bool> &a) { for (unsigned i = 0; i < a.size(); i++) { int b; scan(b); a[i] = b; } } void scan(char a[]) { scanf("%s", a); } void scan(string &a) { cin >> a; } template <class T> void scan(vector<T> &); template <class T, size_t size> void scan(array<T, size> &); template <class T, class L> void scan(pair<T, L> &); template <class T, size_t size> void scan(T (&)[size]); template <class T> void scan(vector<T> &a) { for (auto &&i : a) scan(i); } template <class T> void scan(deque<T> &a) { for (auto &&i : a) scan(i); } template <class T, size_t size> void scan(array<T, size> &a) { for (auto &&i : a) scan(i); } template <class T, class L> void scan(pair<T, L> &p) { scan(p.first); scan(p.second); } template <class T, size_t size> void scan(T (&a)[size]) { for (auto &&i : a) scan(i); } template <class T> void scan(T &a) { cin >> a; } void in() {} template <class Head, class... Tail> void in(Head &head, Tail &...tail) { scan(head); in(tail...); } void print() { putchar(' '); } void print(bool a) { printf("%d", a); } void print(int a) { printf("%d", a); } void print(unsigned a) { printf("%u", a); } void print(long a) { printf("%ld", a); } void print(long long a) { printf("%lld", a); } void print(unsigned long long a) { printf("%llu", a); } void print(char a) { printf("%c", a); } void print(char a[]) { printf("%s", a); } void print(const char a[]) { printf("%s", a); } void print(float a) { printf("%.15f", a); } void print(double a) { printf("%.15f", a); } void print(long double a) { printf("%.15Lf", a); } void print(const string &a) { for (auto &&i : a) print(i); } template <class T> void print(const vector<T> &); template <class T, size_t size> void print(const array<T, size> &); template <class T, class L> void print(const pair<T, L> &p); template <class T, size_t size> void print(const T (&)[size]); template <class T> void print(const vector<T> &a) { if (a.empty()) return; print(a[0]); for (auto i = a.begin(); ++i != a.end();) { putchar(' '); print(*i); } } template <class T> void print(const deque<T> &a) { if (a.empty()) return; print(a[0]); for (auto i = a.begin(); ++i != a.end();) { putchar(' '); print(*i); } } template <class T, size_t size> void print(const array<T, size> &a) { print(a[0]); for (auto i = a.begin(); ++i != a.end();) { putchar(' '); print(*i); } } template <class T, class L> void print(const pair<T, L> &p) { print(p.first); putchar(' '); print(p.second); } template <class T, size_t size> void print(const T (&a)[size]) { print(a[0]); for (auto i = a; ++i != end(a);) { putchar(' '); print(*i); } } template <class T> void print(const T &a) { cout << a; } int out() { putchar('\n'); return 0; } template <class T> int out(const T &t) { print(t); putchar('\n'); return 0; } template <class Head, class... Tail> int out(const Head &head, const Tail &...tail) { print(head); putchar(' '); out(tail...); return 0; } #ifdef DEBUG inline ll __lg(ull __n) { return sizeof(ull) * __CHAR_BIT__ - 1 - __builtin_clzll(__n); } #define debug(...) \ { \ print(#__VA_ARGS__); \ print(":"); \ out(__VA_ARGS__); \ } #else #define debug(...) void(0) #endif int first(bool i = true) { return out(i ? "first" : "second"); } int yes(bool i = true) { return out(i ? "yes" : "no"); } int Yes(bool i = true) { return out(i ? "Yes" : "No"); } int No() { return out("No"); } int YES(bool i = true) { return out(i ? "YES" : "NO"); } int NO() { return out("NO"); } int Yay(bool i = true) { return out(i ? "Yay!" : ":("); } int possible(bool i = true) { return out(i ? "possible" : "impossible"); } int Possible(bool i = true) { return out(i ? "Possible" : "Impossible"); } int POSSIBLE(bool i = true) { return out(i ? "POSSIBLE" : "IMPOSSIBLE"); } void Case(ll i) { printf("Case #%lld: ", i); } vector<pll> add(const vector<pll> &a, pll val) { vector<pll> ans; pll min = {-LINF, -LINF}; ll at1 = 0, at2 = 0; auto add = [&](pll x) { if (ans.empty()) { ans.push_back(x); return; } if (ans.back().second == x.second) chmax(ans.back().first, x.first); elif (ans.back().first < x.first) ans.push_back(x); }; while (at2 < a.size()) { if (at1 == a.size()) { add({a[at2].first + val.first, a[at2].second + val.second}); at2++; continue; } if (a[at1].second < a[at2].second + val.second) add(a[at1++]); else { add({a[at2].first + val.first, a[at2].second + val.second}); at2++; } } return ans; } signed main() { LL(n); VEC(pll, a, n); a.insert(a.begin(), pll{}); vec(vector<pll>, b, 1 << 9); b[0].push_back(pll{}); rep(i, 1, 1 << 9) if (i <= n) b[i] = add(b[i >> 1], a[i]); LL(q); rep(q) { LL(v, l); ll bit = __lg(v); ll cen = v >> bit / 2; vector<pll> c(1); while (v > cen) { c = add(c, a[v]); v >>= 1; } ll ans = 0; ll at = b[cen].size() - 1; each(i, c) { if (i.second > l) break; while (i.second + b[cen][at].second > l) at--; chmax(ans, i.first + b[cen][at].first); } out(ans); } }
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using ull = unsigned long long; using uint = unsigned; using pcc = pair<char, char>; using pii = pair<int, int>; using pll = pair<ll, ll>; using pdd = pair<double, double>; using tuplis = array<ll, 3>; template <class T> using pq = priority_queue<T, vector<T>, greater<T>>; const ll LINF = 0x1fffffffffffffff; const ll MINF = 0x7fffffffffff; const int INF = 0x3fffffff; const int MOD = 1000000007; const int MODD = 998244353; const ld DINF = numeric_limits<ld>::infinity(); const ld EPS = 1e-9; const ld PI = 3.1415926535897932; const ll dx[] = {0, 1, 0, -1, 1, -1, 1, -1}; const ll dy[] = {1, 0, -1, 0, 1, 1, -1, -1}; #define overload4(_1, _2, _3, _4, name, ...) name #define overload3(_1, _2, _3, name, ...) name #define rep1(n) for (ll i = 0; i < n; ++i) #define rep2(i, n) for (ll i = 0; i < n; ++i) #define rep3(i, a, b) for (ll i = a; i < b; ++i) #define rep4(i, a, b, c) for (ll i = a; i < b; i += c) #define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__) #define rrep1(n) for (ll i = (n); i--;) #define rrep2(i, n) for (ll i = (n); i--;) #define rrep3(i, a, b) for (ll i = (b); i-- > (a);) #define rrep4(i, a, b, c) for (ll i = a + (b - a - 1) / c * c; i >= a; i -= c) #define rrep(...) \ overload4(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__) #define each(i, a) for (auto &&i : a) #define eachs2(x, y, a) for (auto &&[x, y] : a) #define eachs3(x, y, z, a) for (auto &&[x, y, z] : a) #define eachs(...) overload4(__VA_ARGS__, eachs3, eachs2)(__VA_ARGS__) #define all1(i) begin(i), end(i) #define all2(i, a) begin(i), begin(i) + a #define all3(i, a, b) begin(i) + a, begin(i) + b #define all(...) overload3(__VA_ARGS__, all3, all2, all1)(__VA_ARGS__) #define rall1(i) (i).rbegin(), (i).rend() #define rall2(i, k) (i).rbegin(), (i).rbegin() + k #define rall3(i, a, b) (i).rbegin() + a, (i).rbegin() + b #define rall(...) overload3(__VA_ARGS__, rall3, rall2, rall1)(__VA_ARGS__) #define sum(...) accumulate(all(__VA_ARGS__), 0LL) #define dsum(...) accumulate(all(__VA_ARGS__), 0.0L) #define elif else if #define unless(a) if (!(a)) #define mp make_pair #define mt make_tuple #define INT(...) \ int __VA_ARGS__; \ in(__VA_ARGS__) #define LL(...) \ ll __VA_ARGS__; \ in(__VA_ARGS__) #define ULL(...) \ ull __VA_ARGS__; \ in(__VA_ARGS__) #define STR(...) \ string __VA_ARGS__; \ in(__VA_ARGS__) #define CHR(...) \ char __VA_ARGS__; \ in(__VA_ARGS__) #define DBL(...) \ double __VA_ARGS__; \ in(__VA_ARGS__) #define LD(...) \ ld __VA_ARGS__; \ in(__VA_ARGS__) #define Sort(a) sort(all(a)) #define Rev(a) reverse(all(a)) #define Uniq(a) \ sort(all(a)); \ a.erase(unique(all(a)), end(a)) #define vec(type, name, ...) vector<type> name(__VA_ARGS__) #define VEC(type, name, size) \ vector<type> name(size); \ in(name) #define vv(type, name, h, ...) \ vector<vector<type>> name(h, vector<type>(__VA_ARGS__)) #define VV(type, name, h, w) \ vector<vector<type>> name(h, vector<type>(w)); \ in(name) #define vvv(type, name, h, w, ...) \ vector<vector<vector<type>>> name( \ h, vector<vector<type>>(w, vector<type>(__VA_ARGS__))) template <class T> auto min(const T &a) { return *min_element(all(a)); } template <class T> auto max(const T &a) { return *max_element(all(a)); } inline ll popcnt(ull a) { return __builtin_popcountll(a); } ll gcd(ll a, ll b) { while (b) { ll c = b; b = a % b; a = c; } return a; } ll lcm(ll a, ll b) { if (!a || !b) return 0; return a * b / gcd(a, b); } ll intpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; a *= a; b /= 2; } return ans; } ll modpow(ll a, ll b, ll p) { ll ans = 1; while (b) { if (b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; } template <class T, class U> bool chmin(T &a, const U &b) { if (a > b) { a = b; return 1; } return 0; } template <class T, class U> bool chmax(T &a, const U &b) { if (a < b) { a = b; return 1; } return 0; } vector<ll> iota(ll n) { vector<ll> a(n); iota(a.begin(), a.end(), 0); return a; } vector<pll> factor(ull x) { vector<pll> ans; for (ll i = 2; i * i <= x; i++) if (x % i == 0) { ans.push_back({i, 1}); while ((x /= i) % i == 0) ans.back().second++; } if (x != 1) ans.push_back({x, 1}); return ans; } map<ll, ll> factor_map(ull x) { map<ll, ll> ans; for (ll i = 2; i * i <= x; i++) if (x % i == 0) { ans[i] = 1; while ((x /= i) % i == 0) ans[i]++; } if (x != 1) ans[x] = 1; return ans; } vector<uint> divisor(uint x) { vector<uint> ans; for (uint i = 1; i * i <= x; i++) if (x % i == 0) ans.push_back(i); rrep(ans.size() - (ans.back() * ans.back() == x)) ans.push_back(x / ans[i]); return ans; } template <class T> unordered_map<T, ll> press(vector<T> &a) { auto b = a; sort(all(b)); b.erase(unique(all(b)), b.end()); unordered_map<T, ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; } template <class T> map<T, ll> press_map(vector<T> &a) { auto b = a; sort(all(b)); b.erase(unique(all(b)), b.end()); map<T, ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; } int scan() { return getchar(); } void scan(int &a) { scanf("%d", &a); } void scan(unsigned &a) { scanf("%u", &a); } void scan(long &a) { scanf("%ld", &a); } void scan(long long &a) { scanf("%lld", &a); } void scan(unsigned long long &a) { scanf("%llu", &a); } void scan(char &a) { do { a = getchar(); } while (a == ' ' || a == '\n'); } void scan(float &a) { scanf("%f", &a); } void scan(double &a) { scanf("%lf", &a); } void scan(long double &a) { scanf("%Lf", &a); } void scan(vector<bool> &a) { for (unsigned i = 0; i < a.size(); i++) { int b; scan(b); a[i] = b; } } void scan(char a[]) { scanf("%s", a); } void scan(string &a) { cin >> a; } template <class T> void scan(vector<T> &); template <class T, size_t size> void scan(array<T, size> &); template <class T, class L> void scan(pair<T, L> &); template <class T, size_t size> void scan(T (&)[size]); template <class T> void scan(vector<T> &a) { for (auto &&i : a) scan(i); } template <class T> void scan(deque<T> &a) { for (auto &&i : a) scan(i); } template <class T, size_t size> void scan(array<T, size> &a) { for (auto &&i : a) scan(i); } template <class T, class L> void scan(pair<T, L> &p) { scan(p.first); scan(p.second); } template <class T, size_t size> void scan(T (&a)[size]) { for (auto &&i : a) scan(i); } template <class T> void scan(T &a) { cin >> a; } void in() {} template <class Head, class... Tail> void in(Head &head, Tail &...tail) { scan(head); in(tail...); } void print() { putchar(' '); } void print(bool a) { printf("%d", a); } void print(int a) { printf("%d", a); } void print(unsigned a) { printf("%u", a); } void print(long a) { printf("%ld", a); } void print(long long a) { printf("%lld", a); } void print(unsigned long long a) { printf("%llu", a); } void print(char a) { printf("%c", a); } void print(char a[]) { printf("%s", a); } void print(const char a[]) { printf("%s", a); } void print(float a) { printf("%.15f", a); } void print(double a) { printf("%.15f", a); } void print(long double a) { printf("%.15Lf", a); } void print(const string &a) { for (auto &&i : a) print(i); } template <class T> void print(const vector<T> &); template <class T, size_t size> void print(const array<T, size> &); template <class T, class L> void print(const pair<T, L> &p); template <class T, size_t size> void print(const T (&)[size]); template <class T> void print(const vector<T> &a) { if (a.empty()) return; print(a[0]); for (auto i = a.begin(); ++i != a.end();) { putchar(' '); print(*i); } } template <class T> void print(const deque<T> &a) { if (a.empty()) return; print(a[0]); for (auto i = a.begin(); ++i != a.end();) { putchar(' '); print(*i); } } template <class T, size_t size> void print(const array<T, size> &a) { print(a[0]); for (auto i = a.begin(); ++i != a.end();) { putchar(' '); print(*i); } } template <class T, class L> void print(const pair<T, L> &p) { print(p.first); putchar(' '); print(p.second); } template <class T, size_t size> void print(const T (&a)[size]) { print(a[0]); for (auto i = a; ++i != end(a);) { putchar(' '); print(*i); } } template <class T> void print(const T &a) { cout << a; } int out() { putchar('\n'); return 0; } template <class T> int out(const T &t) { print(t); putchar('\n'); return 0; } template <class Head, class... Tail> int out(const Head &head, const Tail &...tail) { print(head); putchar(' '); out(tail...); return 0; } #ifdef DEBUG inline ll __lg(ull __n) { return sizeof(ull) * __CHAR_BIT__ - 1 - __builtin_clzll(__n); } #define debug(...) \ { \ print(#__VA_ARGS__); \ print(":"); \ out(__VA_ARGS__); \ } #else #define debug(...) void(0) #endif int first(bool i = true) { return out(i ? "first" : "second"); } int yes(bool i = true) { return out(i ? "yes" : "no"); } int Yes(bool i = true) { return out(i ? "Yes" : "No"); } int No() { return out("No"); } int YES(bool i = true) { return out(i ? "YES" : "NO"); } int NO() { return out("NO"); } int Yay(bool i = true) { return out(i ? "Yay!" : ":("); } int possible(bool i = true) { return out(i ? "possible" : "impossible"); } int Possible(bool i = true) { return out(i ? "Possible" : "Impossible"); } int POSSIBLE(bool i = true) { return out(i ? "POSSIBLE" : "IMPOSSIBLE"); } void Case(ll i) { printf("Case #%lld: ", i); } vector<pll> add(const vector<pll> &a, pll val) { vector<pll> ans; pll min = {-LINF, -LINF}; ll at1 = 0, at2 = 0; auto add = [&](pll x) { if (ans.empty()) { ans.push_back(x); return; } if (ans.back().second == x.second) chmax(ans.back().first, x.first); elif (ans.back().first < x.first) ans.push_back(x); }; while (at2 < a.size()) { if (at1 == a.size()) { add({a[at2].first + val.first, a[at2].second + val.second}); at2++; continue; } if (a[at1].second < a[at2].second + val.second) add(a[at1++]); else { add({a[at2].first + val.first, a[at2].second + val.second}); at2++; } } return ans; } signed main() { LL(n); VEC(pll, a, n); a.insert(a.begin(), pll{}); vec(vector<pll>, b, 1 << 9); b[0].push_back(pll{}); rep(i, 1, 1 << 9) if (i <= n) b[i] = add(b[i >> 1], a[i]); LL(q); rep(q) { LL(v, l); ll bit = __lg(v); ll cen = v >> (bit + 1) / 2; vector<pll> c(1); while (v > cen) { c = add(c, a[v]); v >>= 1; } ll ans = 0; ll at = b[cen].size() - 1; each(i, c) { if (i.second > l) break; while (i.second + b[cen][at].second > l) at--; chmax(ans, i.first + b[cen][at].first); } out(ans); } }
replace
388
389
388
389
0
p02648
C++
Time Limit Exceeded
#include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <algorithm> #include <bitset> #include <chrono> #include <functional> #include <iostream> #include <limits> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <vector> #define LOG(FMT...) fprintf(stderr, FMT) using namespace std; typedef long long ll; typedef unsigned long long ull; // mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); template <class T> istream &operator>>(istream &is, vector<T> &v) { for (T &x : v) is >> x; return is; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { if (!v.empty()) { os << v.front(); for (int i = 1; i < v.size(); ++i) os << ' ' << v[i]; } return os; } int main() { #ifdef ELEGIA freopen("test.in", "r", stdin); int nol_cl = clock(); #endif ios::sync_with_stdio(false); cin.tie(nullptr); const int L = 100000; int n; cin >> n; vector<int> v(n + 1), w(n + 1); for (int i = 1; i <= n; ++i) cin >> v[i] >> w[i]; int b = sqrt(n); vector<vector<ll>> dp(b + 1, vector<ll>(L + 1)); for (int i = 1; i <= b; ++i) { dp[i] = dp[i >> 1]; for (int j = w[i]; j <= L; ++j) dp[i][j] = max(dp[i][j], dp[i >> 1][j - w[i]] + v[i]); } int q; cin >> q; while (q--) { int u, l; cin >> u >> l; vector<pair<int, int>> th; while (u > b) { th.emplace_back(v[u], w[u]); u >>= 1; } ll ans = 0; function<void(int, int, ll)> dfs = [&](int k, int wt, ll vt) { if (k == th.size()) { ans = max(ans, dp[u][l - wt] + vt); return; } if (wt + th[k].second <= l) dfs(k + 1, wt + th[k].second, vt + th[k].first); dfs(k + 1, wt, vt); }; dfs(0, 0, 0); cout << ans << '\n'; } #ifdef ELEGIA LOG("Time: %dms\n", int((clock() - nol_cl) / (double)CLOCKS_PER_SEC * 1000)); #endif return 0; }
#include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <algorithm> #include <bitset> #include <chrono> #include <functional> #include <iostream> #include <limits> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <vector> #define LOG(FMT...) fprintf(stderr, FMT) using namespace std; typedef long long ll; typedef unsigned long long ull; // mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); template <class T> istream &operator>>(istream &is, vector<T> &v) { for (T &x : v) is >> x; return is; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { if (!v.empty()) { os << v.front(); for (int i = 1; i < v.size(); ++i) os << ' ' << v[i]; } return os; } int main() { #ifdef ELEGIA freopen("test.in", "r", stdin); int nol_cl = clock(); #endif ios::sync_with_stdio(false); cin.tie(nullptr); const int L = 100000; int n; cin >> n; vector<int> v(n + 1), w(n + 1); for (int i = 1; i <= n; ++i) cin >> v[i] >> w[i]; int b = min(1 << 10, n); vector<vector<ll>> dp(b + 1, vector<ll>(L + 1)); for (int i = 1; i <= b; ++i) { dp[i] = dp[i >> 1]; for (int j = w[i]; j <= L; ++j) dp[i][j] = max(dp[i][j], dp[i >> 1][j - w[i]] + v[i]); } int q; cin >> q; while (q--) { int u, l; cin >> u >> l; vector<pair<int, int>> th; while (u > b) { th.emplace_back(v[u], w[u]); u >>= 1; } ll ans = 0; function<void(int, int, ll)> dfs = [&](int k, int wt, ll vt) { if (k == th.size()) { ans = max(ans, dp[u][l - wt] + vt); return; } if (wt + th[k].second <= l) dfs(k + 1, wt + th[k].second, vt + th[k].first); dfs(k + 1, wt, vt); }; dfs(0, 0, 0); cout << ans << '\n'; } #ifdef ELEGIA LOG("Time: %dms\n", int((clock() - nol_cl) / (double)CLOCKS_PER_SEC * 1000)); #endif return 0; }
replace
59
60
59
60
TLE
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef unsigned long long ull; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<double, double> pdd; // typedef vector<vector<ll>> Graph; const ll mod = 1e9 + 7; // const ll mod = 998244353; #define REP(i, n) for (ll i = 0; i < (ll)n; i++) #define dump(x) cerr << #x << " = " << (x) << endl; #define spa << " " << #define fi first #define se second template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template <class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return 1; } return 0; } template <class S, class T> ostream &operator<<(ostream &os, const pair<S, T> v) { os << "(" << v.first << ", " << v.second << ")"; return os; } template <class T> ostream &operator<<(ostream &os, const vector<T> v) { for (int i = 0; i < (int)v.size(); i++) { if (i > 0) { os << " "; } os << v[i]; } return os; } template <class T> ostream &operator<<(ostream &os, const vector<vector<T>> v) { for (int i = 0; i < (int)v.size(); i++) { if (i > 0) { os << endl; } os << v[i]; } return os; } template <typename T> void debug(vector<vector<T>> &v, ll h, ll w) { for (ll i = 0; i < h; i++) { cerr << v[i][0]; for (ll j = 1; j < w; j++) cerr spa v[i][j]; cerr << endl; } }; template <typename T> void debug(vector<T> &v, ll n) { if (n != 0) cerr << v[0]; for (ll i = 1; i < n; i++) cerr spa v[i]; cerr << endl; }; string num2bit(ll num, ll len) { string bit = ""; REP(i, len) { bit += char('0' + (num >> i & 1)); } return bit; } int main() { cin.tie(0); ios::sync_with_stdio(false); ll N; cin >> N; vector<int> V(N + 1), W(N + 1); REP(i, N) cin >> V[i + 1] >> W[i + 1]; const ll K = 9; const ll H = (1ll << K); const ll LMA = 100005; vector<vector<int>> dp(H, vector<int>(LMA, 0)); REP(i, H) { REP(j, 2) { if (i == 0 and j == 0) continue; ll ni = 2 * i + j; if (ni >= H or ni > N) continue; REP(k, LMA) { chmax(dp[ni][k], dp[i][k]); if (k + W[ni] < LMA) chmax(dp[ni][k + W[ni]], dp[i][k] + V[ni]); } } } // debug(dp, 5, 10); ll Q; cin >> Q; while (Q--) { ll v, L; cin >> v >> L; vector<pll> reku; reku.push_back({0, 0}); while (v >= H) { ll sz = reku.size(); REP(i, sz) { pll y; y.first = reku[i].first + V[v]; y.second = reku[i].second + W[v]; reku.push_back(y); } v /= 2; } ll ma = 0; for (auto x : reku) { chmax(ma, x.first + dp[v][L - x.second]); } cout << ma << "\n"; } return 0; }
#include <bits/stdc++.h> using namespace std; typedef unsigned long long ull; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<double, double> pdd; // typedef vector<vector<ll>> Graph; const ll mod = 1e9 + 7; // const ll mod = 998244353; #define REP(i, n) for (ll i = 0; i < (ll)n; i++) #define dump(x) cerr << #x << " = " << (x) << endl; #define spa << " " << #define fi first #define se second template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template <class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return 1; } return 0; } template <class S, class T> ostream &operator<<(ostream &os, const pair<S, T> v) { os << "(" << v.first << ", " << v.second << ")"; return os; } template <class T> ostream &operator<<(ostream &os, const vector<T> v) { for (int i = 0; i < (int)v.size(); i++) { if (i > 0) { os << " "; } os << v[i]; } return os; } template <class T> ostream &operator<<(ostream &os, const vector<vector<T>> v) { for (int i = 0; i < (int)v.size(); i++) { if (i > 0) { os << endl; } os << v[i]; } return os; } template <typename T> void debug(vector<vector<T>> &v, ll h, ll w) { for (ll i = 0; i < h; i++) { cerr << v[i][0]; for (ll j = 1; j < w; j++) cerr spa v[i][j]; cerr << endl; } }; template <typename T> void debug(vector<T> &v, ll n) { if (n != 0) cerr << v[0]; for (ll i = 1; i < n; i++) cerr spa v[i]; cerr << endl; }; string num2bit(ll num, ll len) { string bit = ""; REP(i, len) { bit += char('0' + (num >> i & 1)); } return bit; } int main() { cin.tie(0); ios::sync_with_stdio(false); ll N; cin >> N; vector<int> V(N + 1), W(N + 1); REP(i, N) cin >> V[i + 1] >> W[i + 1]; const ll K = 9; const ll H = (1ll << K); const ll LMA = 100005; vector<vector<int>> dp(H, vector<int>(LMA, 0)); REP(i, H) { REP(j, 2) { if (i == 0 and j == 0) continue; ll ni = 2 * i + j; if (ni >= H or ni > N) continue; REP(k, LMA) { chmax(dp[ni][k], dp[i][k]); if (k + W[ni] < LMA) chmax(dp[ni][k + W[ni]], dp[i][k] + V[ni]); } } } // debug(dp, 5, 10); ll Q; cin >> Q; while (Q--) { ll v, L; cin >> v >> L; vector<pll> reku; reku.push_back({0, 0}); while (v >= H) { ll sz = reku.size(); REP(i, sz) { pll y; y.first = reku[i].first + V[v]; y.second = reku[i].second + W[v]; reku.push_back(y); } v /= 2; } ll ma = 0; for (auto x : reku) { if (L - x.second >= 0) chmax(ma, x.first + dp[v][L - x.second]); } cout << ma << "\n"; } return 0; }
replace
132
133
132
134
-6
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
p02648
C++
Time Limit Exceeded
#include <algorithm> #include <array> #include <bitset> #include <cassert> #include <cmath> #include <complex> #include <cstdint> #include <deque> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <regex> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> using namespace std; using ll = long long; using ull = unsigned long long; namespace utils { #define ALL(x) begin(x), end(x) #define RALL(x) rbegin(x), rend(x) template <class T, class Compare> using p_queue = priority_queue<T, vector<T>, Compare>; template <class T> using min_queue = p_queue<T, greater<T>>; template <class T> using max_queue = p_queue<T, less<T>>; template <class T> inline bool UPMIN(T &X, const T &A) { if (X > A) { X = A; return true; } return false; } template <class T> inline bool UPMAX(T &X, const T &A) { if (X < A) { X = A; return true; } return false; } template <class T> vector<T> VEC(int n, T t) { return vector<T>(n, t); } template <class... Ts> auto VEC(int n, Ts... ts) { return vector<decltype(VEC(ts...))>(n, VEC(ts...)); } template <class S, class T> istream &operator>>(istream &is, tuple<S, T> &t) { return is >> get<0>(t) >> get<1>(t); } template <class S, class T, class U> istream &operator>>(istream &is, tuple<S, T, U> &t) { return is >> get<0>(t) >> get<1>(t) >> get<2>(t); } template <class S, class T> ostream &operator<<(ostream &os, const tuple<S, T> &t) { return os << get<0>(t) << ' ' << get<1>(t); } template <class S, class T, class U> ostream &operator<<(ostream &os, const tuple<S, T, U> &t) { return os << get<0>(t) << ' ' << get<1>(t) << ' ' << get<2>(t); } template <class T> istream &operator>>(istream &is, vector<T> &v) { for (auto &&x : v) { is >> x; } return is; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { auto p = v.begin(); assert(p != v.end()); os << *p++; while (p != v.end()) { os << ' ' << *p++; } return os; } template <class T> ostream &operator<<(ostream &os, const vector<vector<T>> &v) { auto p = v.begin(); assert(p != v.end()); os << *p++; while (p != v.end()) { os << '\n' << *p++; } return os; } template <class... Ts> ostream &operator<<(ostream &os, const vector<tuple<Ts...>> &v) { auto p = v.begin(); assert(p != v.end()); os << *p++; while (p != v.end()) { os << '\n' << *p++; } return os; } constexpr long long INFLL = 1'000'000'000'000'000'000ll; constexpr int INF = 1'000'000'000; constexpr double PI = 3.14'159'265'358'973; constexpr double EPS = 1e-10; } // namespace utils using namespace utils; class solver { istream &is; ostream &os; public: solver(istream &I, ostream &O) : is(I), os(O) {} int N; vector<tuple<ll, ll>> VW; vector<ll> ans; vector<vector<ll>> dp; bool input() { is >> N; VW.resize(N); is >> VW; dp.resize(513, VEC(100'010, 0ll)); return !!is; } void dfs_knop(int v, int p) { if (v > 512) return; if (v > N) return; ll val, wei; tie(val, wei) = VW[v - 1]; for (ll w = 0; w < dp[v].size(); ++w) { dp[v][w] = dp[p][w]; if (w - wei >= 0) { UPMAX(dp[v][w], dp[p][w - wei] + val); } if (w > 0) { UPMAX(dp[v][w], dp[v][w - 1]); } } // end i dfs_knop(2 * v, v); dfs_knop(2 * v + 1, v); } ll calc(int v, ll l) const { vector<tuple<ll, ll>> items; while (v > 2) { items.emplace_back(VW[v - 1]); v /= 2; } ll mx = dp[v][l]; int f = 1 << items.size(); for (int i = 1; i < f; ++i) { ll vs, ws; vs = ws = 0; for (int k = 0; k < items.size(); ++k) { if (i & (1 << k)) { vs += get<0>(items[k]); ws += get<1>(items[k]); } } // end k if (l - ws >= 0) UPMAX(mx, dp[v][l - ws] + vs); } // end i return mx; } void run(); }; int main(int argc, char *argv[]) { cin.tie(nullptr); ios::sync_with_stdio(false); cout << setprecision(16) << scientific; #ifdef XELMH string test_cases = "test_D.txt"; cerr << test_cases << " -->" << endl; auto fs = fstream(test_cases, fstream::in); int loop = 0; while (fs) { loop++; cout << '#' << loop << "#------\n"; solver(fs, cout).run(); } if (loop <= 1) { cout << "===" << endl; while (cin) solver(cin, cout).run(); } #else solver(cin, cout).run(); #endif return 0; } void solver::run() { if (!input()) return; dfs_knop(1, 0); int Q; is >> Q; for (int i = 0; i < Q; ++i) { ll v, l; is >> v >> l; cout << calc(v, l) << '\n'; } // end i }
#include <algorithm> #include <array> #include <bitset> #include <cassert> #include <cmath> #include <complex> #include <cstdint> #include <deque> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <regex> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> using namespace std; using ll = long long; using ull = unsigned long long; namespace utils { #define ALL(x) begin(x), end(x) #define RALL(x) rbegin(x), rend(x) template <class T, class Compare> using p_queue = priority_queue<T, vector<T>, Compare>; template <class T> using min_queue = p_queue<T, greater<T>>; template <class T> using max_queue = p_queue<T, less<T>>; template <class T> inline bool UPMIN(T &X, const T &A) { if (X > A) { X = A; return true; } return false; } template <class T> inline bool UPMAX(T &X, const T &A) { if (X < A) { X = A; return true; } return false; } template <class T> vector<T> VEC(int n, T t) { return vector<T>(n, t); } template <class... Ts> auto VEC(int n, Ts... ts) { return vector<decltype(VEC(ts...))>(n, VEC(ts...)); } template <class S, class T> istream &operator>>(istream &is, tuple<S, T> &t) { return is >> get<0>(t) >> get<1>(t); } template <class S, class T, class U> istream &operator>>(istream &is, tuple<S, T, U> &t) { return is >> get<0>(t) >> get<1>(t) >> get<2>(t); } template <class S, class T> ostream &operator<<(ostream &os, const tuple<S, T> &t) { return os << get<0>(t) << ' ' << get<1>(t); } template <class S, class T, class U> ostream &operator<<(ostream &os, const tuple<S, T, U> &t) { return os << get<0>(t) << ' ' << get<1>(t) << ' ' << get<2>(t); } template <class T> istream &operator>>(istream &is, vector<T> &v) { for (auto &&x : v) { is >> x; } return is; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { auto p = v.begin(); assert(p != v.end()); os << *p++; while (p != v.end()) { os << ' ' << *p++; } return os; } template <class T> ostream &operator<<(ostream &os, const vector<vector<T>> &v) { auto p = v.begin(); assert(p != v.end()); os << *p++; while (p != v.end()) { os << '\n' << *p++; } return os; } template <class... Ts> ostream &operator<<(ostream &os, const vector<tuple<Ts...>> &v) { auto p = v.begin(); assert(p != v.end()); os << *p++; while (p != v.end()) { os << '\n' << *p++; } return os; } constexpr long long INFLL = 1'000'000'000'000'000'000ll; constexpr int INF = 1'000'000'000; constexpr double PI = 3.14'159'265'358'973; constexpr double EPS = 1e-10; } // namespace utils using namespace utils; class solver { istream &is; ostream &os; public: solver(istream &I, ostream &O) : is(I), os(O) {} int N; vector<tuple<ll, ll>> VW; vector<ll> ans; vector<vector<ll>> dp; bool input() { is >> N; VW.resize(N); is >> VW; dp.resize(513, VEC(100'010, 0ll)); return !!is; } void dfs_knop(int v, int p) { if (v > 512) return; if (v > N) return; ll val, wei; tie(val, wei) = VW[v - 1]; for (ll w = 0; w < dp[v].size(); ++w) { dp[v][w] = dp[p][w]; if (w - wei >= 0) { UPMAX(dp[v][w], dp[p][w - wei] + val); } if (w > 0) { UPMAX(dp[v][w], dp[v][w - 1]); } } // end i dfs_knop(2 * v, v); dfs_knop(2 * v + 1, v); } ll calc(int v, ll l) const { vector<tuple<ll, ll>> items; while (v > 512) { items.emplace_back(VW[v - 1]); v /= 2; } ll mx = dp[v][l]; int f = 1 << items.size(); for (int i = 1; i < f; ++i) { ll vs, ws; vs = ws = 0; for (int k = 0; k < items.size(); ++k) { if (i & (1 << k)) { vs += get<0>(items[k]); ws += get<1>(items[k]); } } // end k if (l - ws >= 0) UPMAX(mx, dp[v][l - ws] + vs); } // end i return mx; } void run(); }; int main(int argc, char *argv[]) { cin.tie(nullptr); ios::sync_with_stdio(false); cout << setprecision(16) << scientific; #ifdef XELMH string test_cases = "test_D.txt"; cerr << test_cases << " -->" << endl; auto fs = fstream(test_cases, fstream::in); int loop = 0; while (fs) { loop++; cout << '#' << loop << "#------\n"; solver(fs, cout).run(); } if (loop <= 1) { cout << "===" << endl; while (cin) solver(cin, cout).run(); } #else solver(cin, cout).run(); #endif return 0; } void solver::run() { if (!input()) return; dfs_knop(1, 0); int Q; is >> Q; for (int i = 0; i < Q; ++i) { ll v, l; is >> v >> l; cout << calc(v, l) << '\n'; } // end i }
replace
168
169
168
169
TLE
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; using ll = long long; #define ALL(obj) (obj).begin(), (obj).end() #define SPEED \ cin.tie(0); \ ios::sync_with_stdio(false); template <class T> using PQ = priority_queue<T>; template <class T> using PQR = priority_queue<T, vector<T>, greater<T>>; constexpr long long MOD = (long long)1e9 + 7; constexpr long long MOD2 = 998244353; constexpr long long HIGHINF = (long long)1e18; constexpr long long LOWINF = (long long)1e15; constexpr long double PI = 3.1415926535897932384626433L; template <class T> void chmax(T &a, const T b) { a = max(a, b); } template <class T> void chmin(T &a, const T b) { a = min(a, b); } void YN(bool flg) { cout << (flg ? "YES" : "NO") << endl; } void Yn(bool flg) { cout << (flg ? "Yes" : "No") << endl; } void yn(bool flg) { cout << (flg ? "yes" : "no") << endl; } int main() { SPEED int N; cin >> N; vector<int> V(N + 1), W(N + 1); for (int i = 1; i <= N; ++i) cin >> V[i] >> W[i]; // O(Q) int nl = 1 << 9, nr = 1 << 9, L_max = 100001; vector<int> msb(nl, 0); for (int i = 1; i < nl; ++i) msb[i] = 31 - __builtin_clz(i); vector<int> bit_w_dp(nl, 0); vector<int> bit_v_dp(nl, 0); vector<vector<int>> dp(nl, vector<int>(L_max, 0)); // 前計算 for (int n = 1; n < min(nl, N + 1); ++n) { int k = 2 * n; vector<int> l; while (k /= 2) l.push_back(k); int sz = l.size(); // bit全探索 for (int i = 1; i < (1 << sz); ++i) { bit_w_dp[i] = bit_w_dp[i ^ (1 << msb[i])] + W[l[msb[i]]]; bit_v_dp[i] = bit_v_dp[i ^ (1 << msb[i])] + V[l[msb[i]]]; chmax(dp[n][bit_w_dp[i]], bit_v_dp[i]); } // 累積max for (int i = 1; i < L_max; ++i) { chmax(dp[n][i], dp[n][i - 1]); } } int Q; cin >> Q; string ans_str = ""; // クエリ while (Q--) { int p, L; cin >> p >> L; vector<int> r; int k = 2 * p, l = 0; while (k /= 2) { if (k < nl) chmax(l, k); else r.push_back(k); } int sz = r.size(), ans = dp[l][L]; // bit全探索 for (int i = 1; i < (1 << sz); ++i) { bit_w_dp[i] = bit_w_dp[i ^ (1 << msb[i])] + W[r[msb[i]]]; bit_v_dp[i] = bit_v_dp[i ^ (1 << msb[i])] + V[r[msb[i]]]; if (bit_w_dp[i] <= L) chmax(ans, dp[l][L - bit_w_dp[i]] + bit_v_dp[i]); } ans_str += to_string(ans) + "\n"; } cout << ans_str; return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; #define ALL(obj) (obj).begin(), (obj).end() #define SPEED \ cin.tie(0); \ ios::sync_with_stdio(false); template <class T> using PQ = priority_queue<T>; template <class T> using PQR = priority_queue<T, vector<T>, greater<T>>; constexpr long long MOD = (long long)1e9 + 7; constexpr long long MOD2 = 998244353; constexpr long long HIGHINF = (long long)1e18; constexpr long long LOWINF = (long long)1e15; constexpr long double PI = 3.1415926535897932384626433L; template <class T> void chmax(T &a, const T b) { a = max(a, b); } template <class T> void chmin(T &a, const T b) { a = min(a, b); } void YN(bool flg) { cout << (flg ? "YES" : "NO") << endl; } void Yn(bool flg) { cout << (flg ? "Yes" : "No") << endl; } void yn(bool flg) { cout << (flg ? "yes" : "no") << endl; } int main() { SPEED int N; cin >> N; vector<int> V(N + 1), W(N + 1); for (int i = 1; i <= N; ++i) cin >> V[i] >> W[i]; // O(Q) int nl = 1 << 9, nr = 1 << 9, L_max = 100001; vector<int> msb(nl, 0); for (int i = 1; i < nl; ++i) msb[i] = 31 - __builtin_clz(i); vector<int> bit_w_dp(nl, 0); vector<int> bit_v_dp(nl, 0); vector<vector<int>> dp(nl, vector<int>(L_max, 0)); // 前計算 for (int n = 1; n < min(nl, N + 1); ++n) { int k = 2 * n; vector<int> l; while (k /= 2) l.push_back(k); int sz = l.size(); // bit全探索 for (int i = 1; i < (1 << sz); ++i) { bit_w_dp[i] = bit_w_dp[i ^ (1 << msb[i])] + W[l[msb[i]]]; bit_v_dp[i] = bit_v_dp[i ^ (1 << msb[i])] + V[l[msb[i]]]; if (bit_w_dp[i] <= L_max) chmax(dp[n][bit_w_dp[i]], bit_v_dp[i]); } // 累積max for (int i = 1; i < L_max; ++i) { chmax(dp[n][i], dp[n][i - 1]); } } int Q; cin >> Q; string ans_str = ""; // クエリ while (Q--) { int p, L; cin >> p >> L; vector<int> r; int k = 2 * p, l = 0; while (k /= 2) { if (k < nl) chmax(l, k); else r.push_back(k); } int sz = r.size(), ans = dp[l][L]; // bit全探索 for (int i = 1; i < (1 << sz); ++i) { bit_w_dp[i] = bit_w_dp[i ^ (1 << msb[i])] + W[r[msb[i]]]; bit_v_dp[i] = bit_v_dp[i ^ (1 << msb[i])] + V[r[msb[i]]]; if (bit_w_dp[i] <= L) chmax(ans, dp[l][L - bit_w_dp[i]] + bit_v_dp[i]); } ans_str += to_string(ans) + "\n"; } cout << ans_str; return 0; }
replace
52
53
52
54
-6
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5; int n, pa[333333], v[333333], w[333333], ans[333333], x, y, cur[333333]; int cv[33], cw[33], cnt, sumv[11111], sumw[11111], fun[333333], q; bool con[333333]; vector<pair<int, int>> que[333333]; void proq(int x) { int xx = x; if (que[x].empty()) return; cnt = 0; bool flg = 0; while (x) { if (con[x]) { flg = 1; break; } cv[cnt] = v[x]; cw[cnt] = w[x]; cnt++; x = pa[x]; } x = xx; int id, ww, mx; for (int i = 1; i < (1 << cnt); i++) { int cp = fun[i & (-i)], msk = i ^ (i & (-i)); sumv[i] = sumv[msk] + cv[cp]; sumw[i] = sumw[msk] + cw[cp]; } if (!flg) { for (int i = 0; i < que[x].size(); i++) { ww = que[x][i].first; id = que[x][i].second; mx = 0; for (int j = 0; j < (1 << cnt); j++) { if (sumw[j] <= ww) mx = max(mx, sumv[j]); } ans[id] = mx; } } else { for (int i = 0; i < que[x].size(); i++) { ww = que[x][i].first; id = que[x][i].second; mx = 0; for (int j = 0; j < (1 << cnt); j++) { if (sumw[j] <= ww) mx = max(mx, sumv[j] + cur[ww - sumw[j]]); } ans[id] = mx; } } } void upd(int x) { con[x] = 1; cnt = 0; while (x) { cv[cnt] = v[x]; cw[cnt] = w[x]; cnt++; x = pa[x]; } memset(cur, 0, sizeof(cur)); for (int i = 1; i < (1 << cnt); i++) { int cp = fun[i & (-i)], msk = i ^ (i & (-i)); sumv[i] = sumv[msk] + cv[cp]; sumw[i] = sumw[msk] + cw[cp]; } for (int i = 0; i < (1 << cnt); i++) { if (sumw[i] <= maxn) cur[sumw[i]] = max(cur[sumw[i]], sumv[i]); } for (int i = 1; i <= maxn; i++) cur[i] = max(cur[i], cur[i - 1]); } void dfs(int i, int dep) { proq(i); if (dep == 2) upd(i); if (i * 2 <= n) dfs(i * 2, dep + 1); if (i * 2 + 1 <= n) dfs(i * 2 + 1, dep + 1); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) pa[i] = i >> 1; for (int i = 0; i <= 18; i++) fun[1 << i] = i; for (int i = 1; i <= n; i++) { scanf("%d%d", &v[i], &w[i]); } scanf("%d", &q); for (int i = 1; i <= q; i++) { scanf("%d%d", &x, &y); que[x].push_back(make_pair(y, i)); } dfs(1, 1); for (int i = 1; i <= q; i++) printf("%d\n", ans[i]); return 0; }
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5; int n, pa[333333], v[333333], w[333333], ans[333333], x, y, cur[333333]; int cv[33], cw[33], cnt, sumv[11111], sumw[11111], fun[333333], q; bool con[333333]; vector<pair<int, int>> que[333333]; void proq(int x) { int xx = x; if (que[x].empty()) return; cnt = 0; bool flg = 0; while (x) { if (con[x]) { flg = 1; break; } cv[cnt] = v[x]; cw[cnt] = w[x]; cnt++; x = pa[x]; } x = xx; int id, ww, mx; for (int i = 1; i < (1 << cnt); i++) { int cp = fun[i & (-i)], msk = i ^ (i & (-i)); sumv[i] = sumv[msk] + cv[cp]; sumw[i] = sumw[msk] + cw[cp]; } if (!flg) { for (int i = 0; i < que[x].size(); i++) { ww = que[x][i].first; id = que[x][i].second; mx = 0; for (int j = 0; j < (1 << cnt); j++) { if (sumw[j] <= ww) mx = max(mx, sumv[j]); } ans[id] = mx; } } else { for (int i = 0; i < que[x].size(); i++) { ww = que[x][i].first; id = que[x][i].second; mx = 0; for (int j = 0; j < (1 << cnt); j++) { if (sumw[j] <= ww) mx = max(mx, sumv[j] + cur[ww - sumw[j]]); } ans[id] = mx; } } } void upd(int x) { con[x] = 1; cnt = 0; while (x) { cv[cnt] = v[x]; cw[cnt] = w[x]; cnt++; x = pa[x]; } memset(cur, 0, sizeof(cur)); for (int i = 1; i < (1 << cnt); i++) { int cp = fun[i & (-i)], msk = i ^ (i & (-i)); sumv[i] = sumv[msk] + cv[cp]; sumw[i] = sumw[msk] + cw[cp]; } for (int i = 0; i < (1 << cnt); i++) { if (sumw[i] <= maxn) cur[sumw[i]] = max(cur[sumw[i]], sumv[i]); } for (int i = 1; i <= maxn; i++) cur[i] = max(cur[i], cur[i - 1]); } void dfs(int i, int dep) { proq(i); if (dep == 10) upd(i); if (i * 2 <= n) dfs(i * 2, dep + 1); if (i * 2 + 1 <= n) dfs(i * 2 + 1, dep + 1); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) pa[i] = i >> 1; for (int i = 0; i <= 18; i++) fun[1 << i] = i; for (int i = 1; i <= n; i++) { scanf("%d%d", &v[i], &w[i]); } scanf("%d", &q); for (int i = 1; i <= q; i++) { scanf("%d%d", &x, &y); que[x].push_back(make_pair(y, i)); } dfs(1, 1); for (int i = 1; i <= q; i++) printf("%d\n", ans[i]); return 0; }
replace
78
79
78
79
TLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; #define rep(i, n) for (int i = 0; i < int(n); ++i) #define all(a) (a).begin(), (a).end() typedef long long ll; #define rep1(i, n) for (int i = 1; i <= int(n); ++i) #define lb(s, x) (lower_bound(all(s), x) - s.begin()) using P = pair<ll, ll>; #define w first #define v second vector<P> all_enumerate(vector<P> vp, ll W, bool need_sort) { int N = vp.size(); vector<P> dp; for (int mask = 0; mask < (1 << N); mask++) { ll sumV = 0, sumW = 0; for (int i = 0; i < N; i++) { if (mask & (1 << i)) { sumV += vp[i].v; sumW += vp[i].w; } } if (sumW <= W) { dp.push_back({sumW, sumV}); } } if (!need_sort) return dp; // V降順 sort(dp.begin(), dp.end(), [](P a, P b) { return a.v != b.v ? a.v > b.v : a.w < b.w; }); vector<P> res; int w_border = W + 1; for (P s : dp) { if (w_border > s.w) { w_border = s.w; res.push_back(s); } } // V昇順 & W昇順 reverse(res.begin(), res.end()); return res; } int main(void) { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector<int> v(n + 1), w(n + 1); rep1(i, n) { cin >> v[i] >> w[i]; } int H2 = log2(n) / 2; vector<vector<P>> dp((1 << H2) + 1); for (int i = 1; i < (1 << H2); i++) { if (i > n) break; vector<P> vp; int x = i; while (x) { vp.push_back({w[x], v[x]}); x /= 2; } dp[i] = all_enumerate(vp, 100000LL, true); } int Q; cin >> Q; rep(q, Q) { int x, L; cin >> x >> L; vector<P> vp; while ((1 << H2) <= x) { vp.push_back({w[x], v[x]}); x /= 2; } vector<P> dp1 = dp[x]; vector<P> dp2 = all_enumerate(vp, L, false); ll max_v = 0; for (P p : dp2) { int pos = lb(dp1, P({L - p.w + 1, 0LL})) - 1; if (pos < 0) { if (p.w <= L) { max_v = max(max_v, p.v); } } else { if (p.w + dp1[pos].w <= L) { max_v = max(max_v, p.v + dp1[pos].v); } } } cout << max_v << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; #define rep(i, n) for (int i = 0; i < int(n); ++i) #define all(a) (a).begin(), (a).end() typedef long long ll; #define rep1(i, n) for (int i = 1; i <= int(n); ++i) #define lb(s, x) (lower_bound(all(s), x) - s.begin()) using P = pair<ll, ll>; #define w first #define v second vector<P> all_enumerate(vector<P> vp, ll W, bool need_sort) { int N = vp.size(); vector<P> dp; for (int mask = 0; mask < (1 << N); mask++) { ll sumV = 0, sumW = 0; for (int i = 0; i < N; i++) { if (mask & (1 << i)) { sumV += vp[i].v; sumW += vp[i].w; } } if (sumW <= W) { dp.push_back({sumW, sumV}); } } if (!need_sort) return dp; // V降順 sort(dp.begin(), dp.end(), [](P a, P b) { return a.v != b.v ? a.v > b.v : a.w < b.w; }); vector<P> res; int w_border = W + 1; for (P s : dp) { if (w_border > s.w) { w_border = s.w; res.push_back(s); } } // V昇順 & W昇順 reverse(res.begin(), res.end()); return res; } int main(void) { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector<int> v(n + 1), w(n + 1); rep1(i, n) { cin >> v[i] >> w[i]; } int H2 = log2(n) / 2 + 3; vector<vector<P>> dp((1 << H2) + 1); for (int i = 1; i < (1 << H2); i++) { if (i > n) break; vector<P> vp; int x = i; while (x) { vp.push_back({w[x], v[x]}); x /= 2; } dp[i] = all_enumerate(vp, 100000LL, true); } int Q; cin >> Q; rep(q, Q) { int x, L; cin >> x >> L; vector<P> vp; while ((1 << H2) <= x) { vp.push_back({w[x], v[x]}); x /= 2; } vector<P> dp1 = dp[x]; vector<P> dp2 = all_enumerate(vp, L, false); ll max_v = 0; for (P p : dp2) { int pos = lb(dp1, P({L - p.w + 1, 0LL})) - 1; if (pos < 0) { if (p.w <= L) { max_v = max(max_v, p.v); } } else { if (p.w + dp1[pos].w <= L) { max_v = max(max_v, p.v + dp1[pos].v); } } } cout << max_v << endl; } return 0; }
replace
52
53
52
53
TLE
p02648
C++
Memory Limit Exceeded
const int isDebugMode = 0; #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<long long, long long> P; struct edge { long long to, cost; }; const int inf = 1 << 27; const long long INF = 1LL << 60; const int COMBMAX = 1001001; const long long MOD = 1000000007; const long long dy[] = {-1, 0, 0, 1}; const long long dx[] = {0, -1, 1, 0}; string abc = "abcdefghijklmnopqrstuvwxyz"; #define rep(i, n) for (int i = 0; i < (n); ++i) #define eachdo(v, e) for (const auto &e : (v)) #define all(v) (v).begin(), (v).end() #define lower_index(v, e) \ (long long)distance((v).begin(), lower_bound((v).begin(), (v).end(), e)) #define upper_index(v, e) \ (long long)distance((v).begin(), upper_bound((v).begin(), (v).end(), e)) long long mpow(long long a, long long n, long long mod = MOD) { long long res = 1; while (n > 0) { if (n & 1) res = res * a % mod; a = a * a % mod; n >>= 1; } return res; } void pt() { cout << endl; return; } template <class Head> void pt(Head &&head) { cout << head; pt(); return; } template <class Head, class... Tail> void pt(Head &&head, Tail &&...tail) { cout << head << " "; pt(forward<Tail>(tail)...); } void dpt() { if (!isDebugMode) return; cout << endl; return; } template <class Head> void dpt(Head &&head) { if (!isDebugMode) return; cout << head; pt(); return; } template <class Head, class... Tail> void dpt(Head &&head, Tail &&...tail) { if (!isDebugMode) return; cout << head << " "; pt(forward<Tail>(tail)...); } template <class T> void debug(T v) { if (!isDebugMode) return; rep(i, v.size()) cout << v[i] << " "; cout << endl; } template <class T> void debug2(T v) { if (!isDebugMode) return; rep(i, v.size()) { rep(j, v[i].size()) cout << v[i][j] << " "; cout << endl; } } template <class T1, class T2> inline bool chmin(T1 &a, T2 b) { if (a > b) { a = b; return true; } return false; } template <class T1, class T2> inline bool chmax(T1 &a, T2 b) { if (a < b) { a = b; return true; } return false; } template <class T1, class T2> long long gcd(T1 a, T2 b) { return a % b ? gcd(b, a % b) : b; } template <class T1, class T2> void reduce(T1 &a, T2 &b) { ll g = gcd(a, b); a /= g; b /= g; return; } bool valid(long long H, long long W, long long h, long long w) { return 0 <= h && h < H && 0 <= w && w < W; } const int MAX_DEPTH = 12; const int MAX_L = 100100; int main() { int N; cin >> N; vector<int> val(N), wet(N); rep(i, N) cin >> val[i] >> wet[i]; int restore = min(N, 1 << MAX_DEPTH); dpt(restore); vector<vector<int>> dp(restore, vector<int>(MAX_L + 1, 0)); // case i = 0 rep(j, MAX_L + 1) { if (wet[0] <= j) dp[0][j] = val[0]; } for (int i = 1; i < restore; i++) { rep(j, MAX_L + 1) { if (j > 0) dp[i][j] = dp[i][j - 1]; chmax(dp[i][j], dp[(i - 1) >> 1][j]); if (0 <= j - wet[i]) chmax(dp[i][j], dp[(i - 1) >> 1][j - wet[i]] + val[i]); } } int Q; cin >> Q; vector<pair<int, int>> queries(Q); vector<int> anss; rep(i, Q) cin >> queries[i].first >> queries[i].second; for (const auto &query : queries) { int node = query.first - 1; int L = query.second; if (node < restore) { anss.push_back(dp[node][L]); continue; } int ans = 0; vector<pair<int, int>> list; while (restore <= node) { list.push_back(make_pair(wet[node], val[node])); node = (node - 1) >> 1; } int listSize = list.size(); int listcom = 1 << listSize; rep(i, listcom) { int com_wet = 0; int com_val = 0; rep(j, listSize) { if (i >> j & 1) { com_wet += list[j].first; com_val += list[j].second; } } if (L < com_wet) continue; chmax(ans, com_val + dp[node][L - com_wet]); } anss.push_back(ans); } rep(i, Q) pt(anss[i]); return 0; }
const int isDebugMode = 0; #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<long long, long long> P; struct edge { long long to, cost; }; const int inf = 1 << 27; const long long INF = 1LL << 60; const int COMBMAX = 1001001; const long long MOD = 1000000007; const long long dy[] = {-1, 0, 0, 1}; const long long dx[] = {0, -1, 1, 0}; string abc = "abcdefghijklmnopqrstuvwxyz"; #define rep(i, n) for (int i = 0; i < (n); ++i) #define eachdo(v, e) for (const auto &e : (v)) #define all(v) (v).begin(), (v).end() #define lower_index(v, e) \ (long long)distance((v).begin(), lower_bound((v).begin(), (v).end(), e)) #define upper_index(v, e) \ (long long)distance((v).begin(), upper_bound((v).begin(), (v).end(), e)) long long mpow(long long a, long long n, long long mod = MOD) { long long res = 1; while (n > 0) { if (n & 1) res = res * a % mod; a = a * a % mod; n >>= 1; } return res; } void pt() { cout << endl; return; } template <class Head> void pt(Head &&head) { cout << head; pt(); return; } template <class Head, class... Tail> void pt(Head &&head, Tail &&...tail) { cout << head << " "; pt(forward<Tail>(tail)...); } void dpt() { if (!isDebugMode) return; cout << endl; return; } template <class Head> void dpt(Head &&head) { if (!isDebugMode) return; cout << head; pt(); return; } template <class Head, class... Tail> void dpt(Head &&head, Tail &&...tail) { if (!isDebugMode) return; cout << head << " "; pt(forward<Tail>(tail)...); } template <class T> void debug(T v) { if (!isDebugMode) return; rep(i, v.size()) cout << v[i] << " "; cout << endl; } template <class T> void debug2(T v) { if (!isDebugMode) return; rep(i, v.size()) { rep(j, v[i].size()) cout << v[i][j] << " "; cout << endl; } } template <class T1, class T2> inline bool chmin(T1 &a, T2 b) { if (a > b) { a = b; return true; } return false; } template <class T1, class T2> inline bool chmax(T1 &a, T2 b) { if (a < b) { a = b; return true; } return false; } template <class T1, class T2> long long gcd(T1 a, T2 b) { return a % b ? gcd(b, a % b) : b; } template <class T1, class T2> void reduce(T1 &a, T2 &b) { ll g = gcd(a, b); a /= g; b /= g; return; } bool valid(long long H, long long W, long long h, long long w) { return 0 <= h && h < H && 0 <= w && w < W; } const int MAX_DEPTH = 11; const int MAX_L = 100100; int main() { int N; cin >> N; vector<int> val(N), wet(N); rep(i, N) cin >> val[i] >> wet[i]; int restore = min(N, 1 << MAX_DEPTH); dpt(restore); vector<vector<int>> dp(restore, vector<int>(MAX_L + 1, 0)); // case i = 0 rep(j, MAX_L + 1) { if (wet[0] <= j) dp[0][j] = val[0]; } for (int i = 1; i < restore; i++) { rep(j, MAX_L + 1) { if (j > 0) dp[i][j] = dp[i][j - 1]; chmax(dp[i][j], dp[(i - 1) >> 1][j]); if (0 <= j - wet[i]) chmax(dp[i][j], dp[(i - 1) >> 1][j - wet[i]] + val[i]); } } int Q; cin >> Q; vector<pair<int, int>> queries(Q); vector<int> anss; rep(i, Q) cin >> queries[i].first >> queries[i].second; for (const auto &query : queries) { int node = query.first - 1; int L = query.second; if (node < restore) { anss.push_back(dp[node][L]); continue; } int ans = 0; vector<pair<int, int>> list; while (restore <= node) { list.push_back(make_pair(wet[node], val[node])); node = (node - 1) >> 1; } int listSize = list.size(); int listcom = 1 << listSize; rep(i, listcom) { int com_wet = 0; int com_val = 0; rep(j, listSize) { if (i >> j & 1) { com_wet += list[j].first; com_val += list[j].second; } } if (L < com_wet) continue; chmax(ans, com_val + dp[node][L - com_wet]); } anss.push_back(ans); } rep(i, Q) pt(anss[i]); return 0; }
replace
105
106
105
106
MLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> #define reg register typedef long long ll; using namespace std; namespace IO { char buf[1 << 15], *S, *T; inline char gc() { if (S == T) { T = (S = buf) + fread(buf, 1, 1 << 15, stdin); if (S == T) return EOF; } return *S++; } inline int read() { reg int x; reg char c; for (; (c = gc()) < '0' || c > '9';) ; for (x = c ^ '0'; (c = gc()) >= '0' && c <= '9'; x = x * 10 + c - '0') ; return x; } const int _outlim = 1 << 20; char outbuf[_outlim + 5]; int cnt; inline void pc(char c) { outbuf[cnt++] = c; if (cnt == _outlim) fwrite(outbuf, 1, cnt, stdout), cnt = 0; } inline void write(int x) { if (x > 9) write(x / 10); pc(x % 10 ^ '0'); } inline void end() { if (cnt) fwrite(outbuf, 1, cnt, stdout); fclose(stdin); fclose(stdout); } } // namespace IO using IO::pc; using IO::read; using IO::write; const int MN = 2 << 18 | 5; const int MM = 65; int n, m, V[MN], W[MN], v[25], w[25]; int f1[MM], f2[MM], f3[MM], g1[MM], g2[MM], g3[MM], id1[MM], id2[MM], id3[MM]; int main() { freopen("t.in", "r", stdin); freopen("t.out", "w", stdout); n = read(); for (reg int i = 1; i <= n; i++) V[i] = read(), W[i] = read(); m = read(); while (m--) { static int x, y, tot, lmid, rmid, cnt1, cnt2, cnt3, i, j, k, U, res, cost, Ans; x = read(); y = read(); tot = 0; while (x) { if (W[x] <= y) v[++tot] = V[x], w[tot] = W[x]; x /= 2; } lmid = tot / 3, rmid = tot * 2 / 3, cnt1 = cnt2 = cnt3 = 0; for (i = 0, U = 1 << lmid; i < U; i++) { res = 0, cost = 0; for (j = 1; cost <= y && j <= lmid; j++) if ((i >> (j - 1)) & 1) res += v[j], cost += w[j]; if (cost <= y) f1[++cnt1] = res, g1[cnt1] = cost; } for (i = 0, U = 1 << (rmid - lmid); i < U; i++) { res = 0, cost = 0; for (j = lmid + 1; cost <= y && j <= rmid; j++) if ((i >> (j - lmid - 1)) & 1) res += v[j], cost += w[j]; if (cost <= y) f2[++cnt2] = res, g2[cnt2] = cost; } for (i = 0, U = 1 << (tot - rmid); i < U; i++) { res = 0, cost = 0; for (j = rmid + 1; cost <= y && j <= tot; j++) if ((i >> (j - rmid - 1)) & 1) res += v[j], cost += w[j]; if (cost <= y) f3[++cnt3] = res, g3[cnt3] = cost; } for (i = 1; i <= cnt1; i++) id1[i] = i; for (i = 1; i <= cnt2; i++) id2[i] = i; for (i = 1; i <= cnt3; i++) id3[i] = i; sort(id1 + 1, id1 + 1 + cnt1, [](int a, int b) { return g1[a] < g1[b]; }); sort(id2 + 1, id2 + 1 + cnt2, [](int a, int b) { return g2[a] < g2[b]; }); sort(id3 + 1, id3 + 1 + cnt3, [](int a, int b) { return g3[a] < g3[b]; }); Ans = 0; for (i = 1; i <= cnt3; i++) f3[id3[i]] = max(f3[id3[i]], f3[id3[i - 1]]); for (i = 1; i <= cnt1; i++) for (j = 1, k = cnt3; j <= cnt2; j++) { while (k && g1[id1[i]] + g2[id2[j]] + g3[id3[k]] > y) k--; if (!k) break; Ans = max(Ans, f1[id1[i]] + f2[id2[j]] + f3[id3[k]]); } write(Ans); pc('\n'); } IO::end(); return 0; }
#include <bits/stdc++.h> #define reg register typedef long long ll; using namespace std; namespace IO { char buf[1 << 15], *S, *T; inline char gc() { if (S == T) { T = (S = buf) + fread(buf, 1, 1 << 15, stdin); if (S == T) return EOF; } return *S++; } inline int read() { reg int x; reg char c; for (; (c = gc()) < '0' || c > '9';) ; for (x = c ^ '0'; (c = gc()) >= '0' && c <= '9'; x = x * 10 + c - '0') ; return x; } const int _outlim = 1 << 20; char outbuf[_outlim + 5]; int cnt; inline void pc(char c) { outbuf[cnt++] = c; if (cnt == _outlim) fwrite(outbuf, 1, cnt, stdout), cnt = 0; } inline void write(int x) { if (x > 9) write(x / 10); pc(x % 10 ^ '0'); } inline void end() { if (cnt) fwrite(outbuf, 1, cnt, stdout); fclose(stdin); fclose(stdout); } } // namespace IO using IO::pc; using IO::read; using IO::write; const int MN = 2 << 18 | 5; const int MM = 65; int n, m, V[MN], W[MN], v[25], w[25]; int f1[MM], f2[MM], f3[MM], g1[MM], g2[MM], g3[MM], id1[MM], id2[MM], id3[MM]; int main() { n = read(); for (reg int i = 1; i <= n; i++) V[i] = read(), W[i] = read(); m = read(); while (m--) { static int x, y, tot, lmid, rmid, cnt1, cnt2, cnt3, i, j, k, U, res, cost, Ans; x = read(); y = read(); tot = 0; while (x) { if (W[x] <= y) v[++tot] = V[x], w[tot] = W[x]; x /= 2; } lmid = tot / 3, rmid = tot * 2 / 3, cnt1 = cnt2 = cnt3 = 0; for (i = 0, U = 1 << lmid; i < U; i++) { res = 0, cost = 0; for (j = 1; cost <= y && j <= lmid; j++) if ((i >> (j - 1)) & 1) res += v[j], cost += w[j]; if (cost <= y) f1[++cnt1] = res, g1[cnt1] = cost; } for (i = 0, U = 1 << (rmid - lmid); i < U; i++) { res = 0, cost = 0; for (j = lmid + 1; cost <= y && j <= rmid; j++) if ((i >> (j - lmid - 1)) & 1) res += v[j], cost += w[j]; if (cost <= y) f2[++cnt2] = res, g2[cnt2] = cost; } for (i = 0, U = 1 << (tot - rmid); i < U; i++) { res = 0, cost = 0; for (j = rmid + 1; cost <= y && j <= tot; j++) if ((i >> (j - rmid - 1)) & 1) res += v[j], cost += w[j]; if (cost <= y) f3[++cnt3] = res, g3[cnt3] = cost; } for (i = 1; i <= cnt1; i++) id1[i] = i; for (i = 1; i <= cnt2; i++) id2[i] = i; for (i = 1; i <= cnt3; i++) id3[i] = i; sort(id1 + 1, id1 + 1 + cnt1, [](int a, int b) { return g1[a] < g1[b]; }); sort(id2 + 1, id2 + 1 + cnt2, [](int a, int b) { return g2[a] < g2[b]; }); sort(id3 + 1, id3 + 1 + cnt3, [](int a, int b) { return g3[a] < g3[b]; }); Ans = 0; for (i = 1; i <= cnt3; i++) f3[id3[i]] = max(f3[id3[i]], f3[id3[i - 1]]); for (i = 1; i <= cnt1; i++) for (j = 1, k = cnt3; j <= cnt2; j++) { while (k && g1[id1[i]] + g2[id2[j]] + g3[id3[k]] > y) k--; if (!k) break; Ans = max(Ans, f1[id1[i]] + f2[id2[j]] + f3[id3[k]]); } write(Ans); pc('\n'); } IO::end(); return 0; }
delete
51
53
51
51
TLE
p02648
C++
Runtime Error
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <stack> #include <string> #include <time.h> #include <vector> #define int long long #define double long double #define rep(i, n) for (int i = 0; i < n; i++) #define REP(i, n) for (int i = 1; i <= n; i++) #define ggr \ getchar(); \ getchar(); \ return 0; #define prique priority_queue constexpr auto mod = 1000000007; #define inf 1e15 #define key 1e9 using namespace std; typedef pair<int, int> P; template <class T> inline void chmax(T &a, T b) { a = std::max(a, b); } template <class T> inline void chmin(T &a, T b) { a = std::min(a, b); } // combination(Nが小さい時はこれを使う const int MAX = 330000; int fac[MAX], finv[MAX], inv[MAX]; // テーブルを作る前処理 void COMinit() { fac[0] = fac[1] = 1; finv[0] = finv[1] = 1; inv[1] = 1; for (int i = 2; i < MAX; i++) { fac[i] = fac[i - 1] * i % mod; inv[i] = mod - inv[mod % i] * (mod / i) % mod; finv[i] = finv[i - 1] * inv[i] % mod; } } // 二項係数計算 long long COMB(int n, int k) { if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * (finv[k] * finv[n - k] % mod) % mod; } bool prime(int n) { int cnt = 0; for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) cnt++; } if (cnt != 1) return false; else return n != 1; } int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } int lcm(int x, int y) { return x / gcd(x, y) * y; } // 繰り返し二乗法(Nが大きい時の場合のcombination) int mod_pow(int x, int y, int m) { int res = 1; while (y) { if (y & 1) { res = res * x % m; } x = x * x % m; y >>= 1; } return res; } int kai(int x, int y) { int res = 1; for (int i = x - y + 1; i <= x; i++) { res *= (i % mod); res %= mod; } return res; } int comb(int x, int y) { if (y > x) return 0; return kai(x, y) * mod_pow(kai(y, y), mod - 2, mod) % mod; } // UnionFind class UnionFind { protected: int *par, *rank, *size; public: UnionFind(unsigned int size) { par = new int[size]; rank = new int[size]; this->size = new int[size]; rep(i, size) { par[i] = i; rank[i] = 0; this->size[i] = 1; } } int find(int n) { if (par[n] == n) return n; return par[n] = find(par[n]); } void unite(int n, int m) { n = find(n); m = find(m); if (n == m) return; if (rank[n] < rank[m]) { par[n] = m; size[m] += size[n]; } else { par[m] = n; size[n] += size[m]; if (rank[n] == rank[m]) rank[n]++; } } bool same(int n, int m) { return find(n) == find(m); } int getsize(int n) { return size[find(n)]; } }; int dight(int n) { int ans = 1; while (n >= 10) { n /= 10; ans++; } return ans; } int dight_sum(int n) { int sum = 0; rep(i, 20) sum += (n % (int)pow(10, i + 1)) / (pow(10, i)); return sum; } int dight_min(int n) { int ans = 9; while (n >= 10) { ans = min(ans, n % 10); n /= 10; } ans = min(ans, n); return ans; } int dight_max(int n) { int ans = 0; while (n >= 10) { ans = max(ans, n % 10); n /= 10; } ans = max(ans, n); return ans; } int n, q; int v[270000], w[270000]; int dp[520][200000]; int s[114514], l[114514]; signed main() { cin >> n; rep(i, n) cin >> v[i] >> w[i]; cin >> q; rep(i, q) cin >> s[i] >> l[i]; dp[1][w[0]] = v[0]; for (int i = 1; i <= min(n / 2, (int)(pow(2, 8) - 1)); i++) { for (int j = 0; j <= 100000; j++) { chmax(dp[i * 2][j], dp[i][j]); chmax(dp[i * 2 + 1][j], dp[i][j]); chmax(dp[i * 2][j + w[i * 2 - 1]], dp[i][j] + v[i * 2 - 1]); chmax(dp[i * 2 + 1][j + w[i * 2]], dp[i][j] + v[i * 2]); } } for (int i = 1; i <= min(n, (int)(pow(2, 9) - 1)); i++) { for (int j = 1; j <= 100000; j++) { dp[i][j] = max(dp[i][j], dp[i][j - 1]); } } rep(i, q) { int ans = 0; vector<int> memo; int vv = s[i]; while (vv >= pow(2, 9)) { memo.push_back(vv); vv /= 2; } int nn = memo.size(); rep(j, (1 << nn)) { int cnt1 = 0, cnt2 = 0; rep(k, nn) { if ((j >> k) & 1) { cnt1 += v[memo[j]]; cnt2 += w[memo[j]]; } } if (l[i] >= cnt2) chmax(ans, dp[vv][l[i] - cnt2] + cnt1); } cout << ans << endl; } ggr }
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <stack> #include <string> #include <time.h> #include <vector> #define int long long #define double long double #define rep(i, n) for (int i = 0; i < n; i++) #define REP(i, n) for (int i = 1; i <= n; i++) #define ggr \ getchar(); \ getchar(); \ return 0; #define prique priority_queue constexpr auto mod = 1000000007; #define inf 1e15 #define key 1e9 using namespace std; typedef pair<int, int> P; template <class T> inline void chmax(T &a, T b) { a = std::max(a, b); } template <class T> inline void chmin(T &a, T b) { a = std::min(a, b); } // combination(Nが小さい時はこれを使う const int MAX = 330000; int fac[MAX], finv[MAX], inv[MAX]; // テーブルを作る前処理 void COMinit() { fac[0] = fac[1] = 1; finv[0] = finv[1] = 1; inv[1] = 1; for (int i = 2; i < MAX; i++) { fac[i] = fac[i - 1] * i % mod; inv[i] = mod - inv[mod % i] * (mod / i) % mod; finv[i] = finv[i - 1] * inv[i] % mod; } } // 二項係数計算 long long COMB(int n, int k) { if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * (finv[k] * finv[n - k] % mod) % mod; } bool prime(int n) { int cnt = 0; for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) cnt++; } if (cnt != 1) return false; else return n != 1; } int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } int lcm(int x, int y) { return x / gcd(x, y) * y; } // 繰り返し二乗法(Nが大きい時の場合のcombination) int mod_pow(int x, int y, int m) { int res = 1; while (y) { if (y & 1) { res = res * x % m; } x = x * x % m; y >>= 1; } return res; } int kai(int x, int y) { int res = 1; for (int i = x - y + 1; i <= x; i++) { res *= (i % mod); res %= mod; } return res; } int comb(int x, int y) { if (y > x) return 0; return kai(x, y) * mod_pow(kai(y, y), mod - 2, mod) % mod; } // UnionFind class UnionFind { protected: int *par, *rank, *size; public: UnionFind(unsigned int size) { par = new int[size]; rank = new int[size]; this->size = new int[size]; rep(i, size) { par[i] = i; rank[i] = 0; this->size[i] = 1; } } int find(int n) { if (par[n] == n) return n; return par[n] = find(par[n]); } void unite(int n, int m) { n = find(n); m = find(m); if (n == m) return; if (rank[n] < rank[m]) { par[n] = m; size[m] += size[n]; } else { par[m] = n; size[n] += size[m]; if (rank[n] == rank[m]) rank[n]++; } } bool same(int n, int m) { return find(n) == find(m); } int getsize(int n) { return size[find(n)]; } }; int dight(int n) { int ans = 1; while (n >= 10) { n /= 10; ans++; } return ans; } int dight_sum(int n) { int sum = 0; rep(i, 20) sum += (n % (int)pow(10, i + 1)) / (pow(10, i)); return sum; } int dight_min(int n) { int ans = 9; while (n >= 10) { ans = min(ans, n % 10); n /= 10; } ans = min(ans, n); return ans; } int dight_max(int n) { int ans = 0; while (n >= 10) { ans = max(ans, n % 10); n /= 10; } ans = max(ans, n); return ans; } int n, q; int v[270000], w[270000]; int dp[520][200000]; int s[114514], l[114514]; signed main() { cin >> n; rep(i, n) cin >> v[i] >> w[i]; cin >> q; rep(i, q) cin >> s[i] >> l[i]; dp[1][w[0]] = v[0]; for (int i = 1; i <= min(n / 2, (int)(pow(2, 8) - 1)); i++) { for (int j = 0; j <= 100000; j++) { chmax(dp[i * 2][j], dp[i][j]); chmax(dp[i * 2 + 1][j], dp[i][j]); chmax(dp[i * 2][j + w[i * 2 - 1]], dp[i][j] + v[i * 2 - 1]); chmax(dp[i * 2 + 1][j + w[i * 2]], dp[i][j] + v[i * 2]); } } for (int i = 1; i <= min(n, (int)(pow(2, 9) - 1)); i++) { for (int j = 1; j <= 100000; j++) { dp[i][j] = max(dp[i][j], dp[i][j - 1]); } } rep(i, q) { int ans = 0; vector<int> memo; int vv = s[i]; while (vv >= pow(2, 9)) { memo.push_back(vv); vv /= 2; } int nn = memo.size(); rep(j, (1 << nn)) { int cnt1 = 0, cnt2 = 0; rep(k, nn) { if ((j >> k) & 1) { cnt1 += v[memo[k] - 1]; cnt2 += w[memo[k] - 1]; } } if (l[i] >= cnt2) chmax(ans, dp[vv][l[i] - cnt2] + cnt1); } cout << ans << endl; } ggr }
replace
198
200
198
200
-11
p02648
C++
Time Limit Exceeded
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <vector> using namespace std; using ll = long long; int ipow(int a, int b) { int r = 1; while (b >= 1) { if (b % 2 == 1) r *= a; b /= 2; a *= a; } return r; } int main() { int N; cin >> N; vector<int> V, W; for (int i = 1; i < N + 1; i++) { int v, w; cin >> v >> w; V.push_back(v); W.push_back(w); } vector<int> qV, qL; int Q; cin >> Q; int maxL = 0; for (int i = 0; i < Q; i++) { int v, L; cin >> v >> L; maxL = max(maxL, L); v--; qV.push_back(v); qL.push_back(L); } vector<vector<int>> dp(min(N, 256), vector<int>(maxL + 1, -1)); for (int i = 0; i < dp.size(); i++) { for (int j = 0; j <= maxL; j++) { if (i == 0) { dp[i][j] = W[0] <= j ? V[0] : 0; // cout<<dp[i][j]<<" "; continue; } dp[i][j] = max(dp[i][j], dp[(i + 1) / 2 - 1][j]); dp[i][j] = max(dp[i][j], j - W[i] >= 0 ? dp[(i + 1) / 2 - 1][j - W[i]] + V[i] : -1); // cout<<dp[i][j]<<" "; } // cout<<endl; } for (int q = 0; q < Q; q++) { int v = qV[q]; int l = qL[q]; if (v < dp.size()) { // cout<<"!!"<<endl; cout << dp[v][l] << endl; continue; } int P = v; vector<int> road; while (P >= dp.size()) { road.push_back(P); P = (P + 1) / 2 - 1; } int res = 0; // cout<<road.size()<<" "<<ipow(2,road.size())<<endl; for (int i = 0; i < ipow(2, road.size()); i++) { int val = 0; int wei = 0; for (int j = 0; j < road.size(); j++) { if ((i >> j) & 1) { val += V[road[j]]; wei += W[road[j]]; } } if (wei > l) continue; val += dp[P][l - wei]; res = max(res, val); } cout << res << endl; } }
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <vector> using namespace std; using ll = long long; int ipow(int a, int b) { int r = 1; while (b >= 1) { if (b % 2 == 1) r *= a; b /= 2; a *= a; } return r; } int main() { int N; cin >> N; vector<int> V, W; for (int i = 1; i < N + 1; i++) { int v, w; cin >> v >> w; V.push_back(v); W.push_back(w); } vector<int> qV, qL; int Q; cin >> Q; int maxL = 0; for (int i = 0; i < Q; i++) { int v, L; cin >> v >> L; maxL = max(maxL, L); v--; qV.push_back(v); qL.push_back(L); } vector<vector<int>> dp(min(N, 700), vector<int>(maxL + 1, -1)); for (int i = 0; i < dp.size(); i++) { for (int j = 0; j <= maxL; j++) { if (i == 0) { dp[i][j] = W[0] <= j ? V[0] : 0; // cout<<dp[i][j]<<" "; continue; } dp[i][j] = max(dp[i][j], dp[(i + 1) / 2 - 1][j]); dp[i][j] = max(dp[i][j], j - W[i] >= 0 ? dp[(i + 1) / 2 - 1][j - W[i]] + V[i] : -1); // cout<<dp[i][j]<<" "; } // cout<<endl; } for (int q = 0; q < Q; q++) { int v = qV[q]; int l = qL[q]; if (v < dp.size()) { // cout<<"!!"<<endl; cout << dp[v][l] << endl; continue; } int P = v; vector<int> road; while (P >= dp.size()) { road.push_back(P); P = (P + 1) / 2 - 1; } int res = 0; // cout<<road.size()<<" "<<ipow(2,road.size())<<endl; for (int i = 0; i < ipow(2, road.size()); i++) { int val = 0; int wei = 0; for (int j = 0; j < road.size(); j++) { if ((i >> j) & 1) { val += V[road[j]]; wei += W[road[j]]; } } if (wei > l) continue; val += dp[P][l - wei]; res = max(res, val); } cout << res << endl; } }
replace
41
42
41
42
TLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> #define endl "\n" using namespace std; typedef long long ll; typedef pair<ll, ll> l_l; typedef pair<int, int> i_i; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; } const long long INF = 1e18; // const ll mod = 1000000007; ll N; vector<ll> V, W; ll K = 9; vector<l_l> mid[1 << 18]; vector<l_l> f(vector<l_l> a) { vector<l_l> tmp; int n = a.size(); for (int i = 0; i < (1 << n); i++) { l_l now; for (int j = 0; j < n; j++) { if (!(i & (1 << j))) continue; now.first += a[j].second; now.second += a[j].first; } tmp.push_back(now); } sort(tmp.begin(), tmp.end(), [](l_l a, l_l b) { if (a.first != b.first) return a.first < b.first; return a.second > b.second; }); vector<l_l> ret; for (auto a : tmp) { if (ret.size() and ret.back().second >= a.second) continue; ret.push_back(a); } return ret; } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> N; V.resize(N + 1); W.resize(N + 1); for (int i = 1; i <= N; i++) { cin >> V[i] >> W[i]; } for (int i = 1; i <= N; i++) { if (i >= (1 << (K - 1)) and i < (1 << (K))) { // cerr << "---" << i << "---" << endl; vector<l_l> v; ll copy = i; while (copy != 0) { v.push_back({V[copy], W[copy]}); copy /= 2; } mid[i] = f(v); for (auto tmp : mid[i]) { // cerr << tmp.first << " " << tmp.second << endl; } } } int Q; cin >> Q; while (Q--) { ll x, L; cin >> x >> L; if (x < (1 << K)) { ll copy = x; vector<l_l> v; while (copy != 0) { v.push_back({V[copy], W[copy]}); copy /= 2; } vector<l_l> w = f(v); ll ans = 0; for (auto tmp : w) { if (tmp.first <= L) chmax(ans, tmp.second); } cout << ans << endl; } else { ll copy = x; vector<l_l> v; while (copy >= (1 << K)) { v.push_back({V[copy], W[copy]}); copy /= 2; } auto w = f(v); auto q = mid[copy]; ll ans = 0; for (auto tmp : w) { l_l s = {L - tmp.first + 1, -INF}; auto itr = lower_bound(q.begin(), q.end(), s); if (itr == q.begin()) continue; itr--; chmax(ans, tmp.second + (*itr).second); } cout << ans << endl; } } return 0; }
#include <bits/stdc++.h> #define endl "\n" using namespace std; typedef long long ll; typedef pair<ll, ll> l_l; typedef pair<int, int> i_i; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; } const long long INF = 1e18; // const ll mod = 1000000007; ll N; vector<ll> V, W; ll K = 10; vector<l_l> mid[1 << 18]; vector<l_l> f(vector<l_l> a) { vector<l_l> tmp; int n = a.size(); for (int i = 0; i < (1 << n); i++) { l_l now; for (int j = 0; j < n; j++) { if (!(i & (1 << j))) continue; now.first += a[j].second; now.second += a[j].first; } tmp.push_back(now); } sort(tmp.begin(), tmp.end(), [](l_l a, l_l b) { if (a.first != b.first) return a.first < b.first; return a.second > b.second; }); vector<l_l> ret; for (auto a : tmp) { if (ret.size() and ret.back().second >= a.second) continue; ret.push_back(a); } return ret; } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> N; V.resize(N + 1); W.resize(N + 1); for (int i = 1; i <= N; i++) { cin >> V[i] >> W[i]; } for (int i = 1; i <= N; i++) { if (i >= (1 << (K - 1)) and i < (1 << (K))) { // cerr << "---" << i << "---" << endl; vector<l_l> v; ll copy = i; while (copy != 0) { v.push_back({V[copy], W[copy]}); copy /= 2; } mid[i] = f(v); for (auto tmp : mid[i]) { // cerr << tmp.first << " " << tmp.second << endl; } } } int Q; cin >> Q; while (Q--) { ll x, L; cin >> x >> L; if (x < (1 << K)) { ll copy = x; vector<l_l> v; while (copy != 0) { v.push_back({V[copy], W[copy]}); copy /= 2; } vector<l_l> w = f(v); ll ans = 0; for (auto tmp : w) { if (tmp.first <= L) chmax(ans, tmp.second); } cout << ans << endl; } else { ll copy = x; vector<l_l> v; while (copy >= (1 << K)) { v.push_back({V[copy], W[copy]}); copy /= 2; } auto w = f(v); auto q = mid[copy]; ll ans = 0; for (auto tmp : w) { l_l s = {L - tmp.first + 1, -INF}; auto itr = lower_bound(q.begin(), q.end(), s); if (itr == q.begin()) continue; itr--; chmax(ans, tmp.second + (*itr).second); } cout << ans << endl; } } return 0; }
replace
26
27
26
27
TLE
p02648
C++
Memory Limit Exceeded
/*temp*/ // // // // // #undef _DEBUG // #pragma GCC optimize("Ofast") // 不動小数点の計算高速化 // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") // #include <boost/multiprecision/cpp_int.hpp> #ifdef _DEBUG #include "template.h" #else #if __cplusplus >= 201703L /*Atcoderでしか使えない(c++17 && このテンプレートが使えるならAtcoder)*/ #include <boost/sort/pdqsort/pdqsort.hpp> #define fast_sort boost::sort::pdqsort #endif #endif #ifndef _DEBUG #ifndef UNTITLED15_TEMPLATE_H #define UNTITLED15_TEMPLATE_H #ifdef _DEBUG #include "bits_stdc++.h" #else #include <bits/stdc++.h> #endif #ifndef fast_sort #define fast_sort sort #endif // #define use_pq #define use_for #define use_for_each #define use_sort #define use_fill #define use_rand #define use_mgr #define use_rui #define use_compress // // // // // // #define use_pbds #ifdef use_pbds #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> template <class T, class U, class W, class X> auto count(__gnu_pbds::gp_hash_table<T, U, W> &a, X k) { return a.find(k) != a.end(); } #endif using namespace std; using namespace std::chrono; /*@formatter:off*/ #define ll long long using sig_dou = double; // マクロ省略形 関数等 #define arsz(a) (sizeof(a) / sizeof(a[0])) #define sz(a) ((ll)(a).size()) #define mp make_pair #define mt make_tuple #define pb pop_back #define pf push_front #define eb emplace_back #define ALL(a) (a).begin(), (a).end() #define RALL(a) (a).rbegin(), (a).rend() template <class T, class U> auto max(T a, U b) { return a > b ? a : b; } template <class T, class U> auto min(T a, U b) { return a < b ? a : b; } // optional<T>について下でオーバーロード(nullopt_tを左辺右辺について単位元として扱う) template <class T, class U> bool chma(T &a, const U &b) { if (a < b) { a = b; return true; } return false; } template <class T, class U> bool chmi(T &a, const U &b) { if (b < a) { a = b; return true; } return false; } // メタ系 meta template <typename T, typename U = typename T::value_type> std::true_type value_type_tester(signed); template <typename T> std::false_type value_type_tester(long); template <typename T> struct has_value_type : decltype(value_type_tester<T>(0)) {}; // A<T>でTを返す template <class T> using decl_t = typename T::value_type; // A<B<.....T>>でTを返す template <class T, bool end = !has_value_type<T>::value> struct decl2_ { typedef T type; }; template <class T> struct decl2_<T, false> { typedef typename decl2_<decl_t<T>>::type type; }; template <class T> using decl2_t = typename decl2_<T>::type; // #define decl_max(a, b) decltype(max(MAX<decltype(a)>(), MAX<decltype(b)>())) #define is_same2(T, U) is_same<T, U>::value template <class T> struct is_vector : std::false_type {}; template <class T> struct is_vector<std::vector<T>> : std::true_type {}; // 大きい型を返す max_type<int, char>::type // todo mintがlong long より小さいと判定されるためバグる template <class T1, class T2, bool t1_bigger = (sizeof(T1) > sizeof(T2))> struct max_type { typedef T1 type; }; template <class T1, class T2> struct max_type<T1, T2, false> { typedef T2 type; }; template <class T> struct vec_rank : integral_constant<int, 0> {}; template <class T> struct vec_rank<vector<T>> : integral_constant<int, vec_rank<T>{} + 1> {}; // N個のTを並べたtupleを返す // tuple_n<3, int>::type tuple<int, int, int> template <size_t N, class T, class... Arg> struct tuple_n { typedef typename tuple_n<N - 1, T, T, Arg...>::type type; }; template <class T, class... Arg> struct tuple_n<0, T, Arg...> { typedef tuple<Arg...> type; }; struct dummy_t1 {}; struct dummy_t2 {}; struct dummy_t3 {}; struct dummy_t4 {}; struct dummy_t5 {}; struct dummy_t6 {}; // template<class T, require(is_integral<T>::value)>など #define require_t(bo) enable_if_t<bo> * = nullptr // 複数でオーバーロードする場合、引数が同じだとうまくいかないため // require_arg(bool, dummy_t1) // require_arg(bool, dummy_t2)等とする #define require_arg1(bo) enable_if_t<bo> * = nullptr #define require_arg2(bo, dummy_type) enable_if_t<bo, dummy_type> * = nullptr #define require_arg(...) \ over2(__VA_ARGS__, require_arg2, require_arg1)(__VA_ARGS__) //->//enable_if_tのtを書き忘れそうだから #define require_ret(bo, ret_type) enable_if_t<bo, ret_type> #define int long long // todo 消したら動かない intの代わりにsignedを使う auto start_time = system_clock::now(); auto past_time = system_clock::now(); #define debugName(VariableName) #VariableName // 最大引数がN #define over2(o1, o2, name, ...) name #define over3(o1, o2, o3, name, ...) name #define over4(o1, o2, o3, o4, name, ...) name #define over5(o1, o2, o3, o4, o5, name, ...) name #define over6(o1, o2, o3, o4, o5, o6, name, ...) name #define over7(o1, o2, o3, o4, o5, o6, o7, name, ...) name #define over8(o1, o2, o3, o4, o5, o6, o7, o8, name, ...) name #define over9(o1, o2, o3, o4, o5, o6, o7, o8, o9, name, ...) name #define over10(o1, o2, o3, o4, o5, o6, o7, o8, o9, o10, name, ...) name #ifdef _DEBUG string message; string res_mes; bool was_deb = false; [[noreturn]] void my_exit(signed e = 0) { if (was_deb && sz(res_mes)) { cerr << "result = " << endl << res_mes << endl; } if (sz(message)) { cerr << "****************************" << endl; cerr << "Note." << endl; cerr << message << endl; cerr << "****************************" << endl; } exit(e); } #define exit my_exit #endif void assert2(bool b, const string &s = "") { if (!b) { cerr << s << endl; exit(1); /*assert(0);*/ } } // my_nulloptをあらゆる操作の単位元的な物として扱う // vectorの参照外時に返したり、右辺値として渡されたときに何もしないなど struct my_nullopt_t { } my_nullopt; #define nullopt_t my_nullopt_t #define nullopt my_nullopt /*@formatter:off*/ // 値が無いときは、setを使わない限り代入できない //=を使っても無視される template <class T> struct my_optional { private: bool is_null; T v; public: typedef T value_type; my_optional() : is_null(true) {} my_optional(const nullopt_t &) : is_null(true) {} my_optional(const T &v) : v(v), is_null(false) {} bool has_value() const { return !is_null; } T &value() { static string mes = "optional has no value"; assert2(!is_null, mes); return v; } const T &value() const { static string mes = "optional has no value"; assert2(!is_null, mes); return v; } void set(const T &nv) { is_null = false; v = nv; } template <class U> void operator=(const U &v) { set(v); // null状態でも代入出来るようにした // if (has_value())value() = v; else return; } template <class U> void operator=(const my_optional<U> &v) { if (/*has_value() && */ v.has_value()) (*this) = v; else return; } /*@formatter:off*/ void reset() { is_null = true; } void operator=(const nullopt_t &) { reset(); } template <require_t(!is_same2(T, bool))> explicit operator bool() { return !is_null; } // nullの時はエラー operator T &() { return value(); } operator const T &() const { return value(); } my_optional<T> operator++() { if (this->has_value()) { this->value()++; return *this; } else { return *this; } } my_optional<T> operator++(signed) { if (this->has_value()) { auto tem = *this; this->value()++; return tem; } else { return *this; } } my_optional<T> operator--() { if (this->has_value()) { this->value()--; return *this; } else { return *this; } } my_optional<T> operator--(signed) { if (this->has_value()) { auto tem = *this; this->value()--; return tem; } else { return *this; } } }; template <class T> istream &operator>>(istream &iss, my_optional<T> &v) { T val; iss >> val; v.set(val); return iss; } #define optional my_optional template <class T> using opt = my_optional<T>; // template<class T, class A = std::allocator<T>> struct debtor : std::vector<T, // A> { template <class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>>> struct o_map : std::map<Key, optional<T>, Compare, Allocator> { optional<T> emp; o_map() : std::map<Key, optional<T>, Compare, Allocator>() {} auto operator()(const nullopt_t &) { return nullopt; } optional<T> &operator()(const optional<Key> &k) { if (k.has_value()) { return std::map<Key, optional<T>, Compare, Allocator>::operator[]( k.value()); } else { emp.reset(); return emp; } } optional<T> &operator()(const Key &k) { auto &v = std::map<Key, optional<T>, Compare, Allocator>::operator[](k); if (v.has_value()) return v; else { v.set(0); return v; } } template <class U> void operator[](U) { static string mes = "s_map cant []"; assert2(0, mes); } }; // 以下、空のoptionalをnulloptと書く // ov[-1(参照外)] でnulloptを返す // ov[nullopt] で nulloptをかえす template <class T> struct ov { optional<T> emp; vector<optional<T>> v; ov(int i = 0, T val = 0) : v(i, val) {} template <class U> ov(const U &rhs) { v.resize(sz(rhs)); for (int i = 0; i < sz(rhs); i++) v[i].set(rhs[i]); } optional<T> &operator()(int i) { if (i < 0 || sz(v) <= i) { emp.reset(); return emp; } else { return v[i]; } } optional<T> &operator()(const nullopt_t &) { return operator()(-1); } optional<T> &operator()(const optional<T> &i) { if (i.has_value()) return operator()(i.value()); else { return operator()(-1); } } /*@formatter:off*/ }; template <class T> string deb_tos(const ov<T> &v) { return deb_tos(v.v); } // vectorに対しての処理は.vを呼ぶ template <class T> class ovv { optional<T> emp; public: vector<vector<optional<T>>> v; ovv(int i = 0, int j = 0, T val = 0) : v(i, vector<optional<T>>(j, val)) {} ovv(const vector<vector<T>> &S) { v.resize(S.size()); for (int h = 0; h < sz(S); h++) { v[h].resize(sz(S[h])); for (int w = 0; w < sz(S[h]); w++) { v[h][w].set(S[h][w]); } } } optional<T> &operator()(int i, int j) { if (i < 0 || j < 0 || sz(v) <= i || sz(v[i]) <= j) { emp.reset(); return emp; } else { return v[i][j]; } } // 再帰ver 遅いと思う // optional<T>& gets(optional<T>& v){return v;} // template<class V, class H, class... U> optional<T>& gets(V& v, H i, U... // tail){ if constexpr(is_same2(H, nullopt_t))return // operator()(-1,-1); else if constexpr(is_same2(H, optional<int>)){ // if(i.has_value())return gets(v[(int)i], tail...); else return // operator()(-1,-1); }else if constexpr(is_integral<H>::value){ // return gets(v[(int)i], tail...); }else{ assert(0); // return emp; } } #if __cplusplus >= 201703L // if constexprバージョン 上が遅かったらこれで template <class U, class V> optional<T> &operator()(const U &i, const V &j) { /*駄目な場合を除外*/ if constexpr (is_same2(U, nullopt_t) || is_same2(U, nullopt_t)) { return operator()(-1, -1); /* o, o*/ } else if constexpr (is_same2(U, optional<int>) && is_same2(V, optional<int>)) { return operator()(i.has_value() ? (int)i : -1, j.has_value() ? (int)j : -1); /* o, x*/ } else if constexpr (is_same2(U, optional<int>)) { return operator()(i.has_value() ? (int)i : -1, (int)j); /* x, o*/ } else if constexpr (is_same2(V, optional<int>)) { return operator()((int)i, j.has_value() ? (int)j : -1); /* x, x*/ } else { return operator()((int)i, (int)j); } } #endif operator const vector<vector<optional<T>>> &() { return v; } }; template <class T> istream &operator>>(istream &iss, ovv<T> &a) { for (int h = 0; h < sz(a); h++) { for (int w = 0; w < sz(a[h]); w++) { iss >> a.v[h][w]; } } return iss; } template <class T> ostream &operator<<(ostream &os, ovv<T> &a) { os << a.v; return os; } template <class T> string deb_tos(const ovv<T> &v) { return deb_tos(v.v); } template <class T> struct ov3 { optional<T> emp; vector<vector<vector<optional<T>>>> v; ov3(int i, int j, int k, T val = 0) : v(i, vector<vector<optional<T>>>(j, vector<optional<T>>(k, val))) {} optional<T> &operator()(int i, int j, int k) { if (i < 0 || j < 0 || sz(v) <= i || sz(v[i]) <= j) { if (k < 0 || sz(v[i][j]) <= k) { emp.reset(); return emp; } } return v[i][j][k]; } private: #if __cplusplus >= 201703L // 再帰ver 遅いと思う template <class V, class H> optional<T> &gets(V &nowv, H i) { if constexpr (is_same2(H, nullopt_t)) { emp.reset(); return emp; } else if constexpr (is_same2(H, optional<int>)) { if (i.has_value()) { return nowv[(int)i]; } else { emp.reset(); return emp; } } else if constexpr (is_integral<H>::value) { return nowv[(int)i]; } else { static string mes = "ov3 error not index"; assert2(0, mes); emp.reset(); return emp; } } // todo const &消した template <class V, class H, class... U> optional<T> &gets(V &nowv, H i, U... tail) { if constexpr (is_same2(H, nullopt_t)) { emp.reset(); return emp; } else if constexpr (is_same2(H, optional<int>)) { if (i.has_value()) { return gets(nowv[(int)i], tail...); } else { emp.reset(); return emp; } } else if constexpr (is_integral<H>::value) { return gets(nowv[(int)i], tail...); } else { static string mes = "ov3 error not index"; assert2(0, mes); emp.reset(); return emp; } } #endif public: template <class U, class V, class W> optional<T> &operator()(U i, V j, W k) { return gets(v, i, j, k); } /*@formatter:off*/ }; template <class T> string deb_tos(const ov3<T> &v) { return deb_tos(v.v); } // nullopt_t // 優先順位 // null, [opt, tem] // + と += は違う意味を持つ // val+=null : val // val+null : null // //+は途中計算 //+=は最終的に格納したい値にだけ持たせる //+=がvoidを返すのは、途中計算で使うのを抑制するため // nulloptを考慮する際、計算途中では+を使ってnulloptを作り // 格納する際は+=で無効にする必要がある // 演算子== // optional<int>(10) == 10 // 全ての型に対応させ、value_typeが等しいかを見るようにするのもありかも // null同士を比較する状況はおかしいのではないか bool operator==(const nullopt_t &, const nullopt_t &) { assert2(0, "nul == null cant hikaku"); return false; } template <class T> bool operator==(const nullopt_t &, const T &) { return false; } template <class T> bool operator!=(const nullopt_t &, const T &) { return true; } template <class T> bool operator==(const T &, const nullopt_t &) { return false; } template <class T> bool operator!=(const T &, const nullopt_t &) { return true; } // nullを nullopt_t &operator+(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator-(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator*(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator/(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator+=(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator-=(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator*=(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator/=(const nullopt_t &, const nullopt_t &) { return nullopt; } template <class ANY> nullopt_t operator+(const nullopt_t &, const ANY &) { return nullopt; } template <class ANY> nullopt_t operator-(const nullopt_t &, const ANY &) { return nullopt; } template <class ANY> nullopt_t operator*(const nullopt_t &, const ANY &) { return nullopt; } template <class ANY> nullopt_t operator/(const nullopt_t &, const ANY &) { return nullopt; } template <class ANY> nullopt_t operator+(const ANY &, const nullopt_t &) { return nullopt; } template <class ANY> nullopt_t operator-(const ANY &, const nullopt_t &) { return nullopt; } template <class ANY> nullopt_t operator*(const ANY &, const nullopt_t &) { return nullopt; } template <class ANY> nullopt_t operator/(const ANY &, const nullopt_t &) { return nullopt; } template <class ANY> void operator+=(nullopt_t &, const ANY &) {} template <class ANY> void operator-=(nullopt_t &, const ANY &) {} template <class ANY> void operator*=(nullopt_t &, const ANY &) {} template <class ANY> void operator/=(nullopt_t &, const ANY &) {} template <class ANY> void operator+=(ANY &, const nullopt_t &) {} template <class ANY> void operator-=(ANY &, const nullopt_t &) {} template <class ANY> void operator*=(ANY &, const nullopt_t &) {} template <class ANY> void operator/=(ANY &, const nullopt_t &) {} template <class T> struct is_optional : false_type {}; template <class T> struct is_optional<optional<T>> : true_type {}; template <class T, class U> true_type both_optional(optional<T> t, optional<U> u); false_type both_optional(...); template <class T, class U> class opt_check : public decltype(both_optional(declval<T>(), declval<U>())) {}; // optionalは同じ型同士しか足せない //(o, t), (t, o), (o, o) #define opt_tem(op) \ template <class O, class O_ret = decltype(declval<O>() op declval<O>())> \ optional<O_ret> operator op(const optional<O> &opt1, \ const optional<O> &opt2) { \ if (!opt1.has_value() || !opt2.has_value()) { \ return optional<O_ret>(); \ } else { \ return optional<O_ret>(opt1.value() op opt2.value()); \ } \ } \ template <class O, class T, \ class O_ret = decltype(declval<O>() op declval<O>())> \ auto operator op(const optional<O> &opt, const T &tem) \ ->require_ret(!(opt_check<optional<O>, T>::value), optional<O_ret>) { \ if (!opt.has_value()) { \ return optional<O_ret>(); \ } else { \ return optional<O_ret>(opt.value() op tem); \ } \ } \ template <class O, class T, \ class O_ret = decltype(declval<O>() op declval<O>())> \ auto operator op(const T &tem, const optional<O> &opt) \ ->require_ret(!(opt_check<optional<O>, T>::value), optional<O_ret>) { \ if (!opt.has_value()) { \ return optional<O_ret>(); \ } else { \ return optional<O_ret>(opt.value() op tem); \ } \ } /*@formatter:off*/ opt_tem(+) opt_tem(-) opt_tem(*) opt_tem(/) // 比較はoptional<bool>を返す opt_tem(<) opt_tem(>) opt_tem(<=) opt_tem(>=) /*@formatter:on*/ /*@formatter:off*/ template <class O, class T> bool operator==(const optional<O> &opt, const T &tem) { if (opt.has_value()) { return opt.value() == tem; } else return nullopt == tem; } template <class O, class T> bool operator!=(const optional<O> &opt, const T &tem) { if (opt.has_value()) { return opt.value() != tem; } else return nullopt != tem; } template <class O, class T> bool operator==(const T &tem, const optional<O> &opt) { if (opt.has_value()) { return opt.value() == tem; } else return nullopt == tem; } template <class O, class T> bool operator!=(const T &tem, const optional<O> &opt) { if (opt.has_value()) { return opt.value() != tem; } else return nullopt != tem; } template <class O> bool operator==(const optional<O> &opt1, const optional<O> &opt2) { if (opt1.has_value() != opt2.has_value()) { return false; } else if (opt1.has_value()) { return opt1.value() == opt2.value(); } else { return nullopt == nullopt; } } template <class O> bool operator!=(const optional<O> &opt1, const optional<O> &opt2) { return !(opt1 == opt2); } //(a+=null) != (a=a+null) // a null template <class T, class O> void operator+=(T &tem, const optional<O> &opt) { if (opt.has_value()) { tem += opt.value(); } } template <class T, class O> void operator-=(T &tem, const optional<O> &opt) { if (opt.has_value()) { tem -= opt.value(); } } template <class T, class O> void operator*=(T &tem, const optional<O> &opt) { if (opt.has_value()) { tem *= opt.value(); } } template <class T, class O> void operator/=(T &tem, const optional<O> &opt) { if (opt.has_value()) { tem /= opt.value(); } } template <class T, class O> void operator+=(optional<O> &opt, const T &tem) { if (opt.has_value()) { opt.value() += tem; } } template <class T, class O> void operator-=(optional<O> &opt, const T &tem) { if (opt.has_value()) { opt.value() -= tem; } } template <class T, class O> void operator*=(optional<O> &opt, const T &tem) { if (opt.has_value()) { opt.value() *= tem; } } template <class T, class O> void operator/=(optional<O> &opt, const T &tem) { if (opt.has_value()) { opt.value() /= tem; } } // template <class Ol, class Or> void operator+=(optional<Ol> &opl, const optional<Or> &opr) { if (opr.has_value()) { return opl += opr.value(); } } template <class Ol, class Or> void operator-=(optional<Ol> &opl, const optional<Or> &opr) { if (opr.has_value()) { return opl -= opr.value(); } } template <class Ol, class Or> void operator*=(optional<Ol> &opl, const optional<Or> &opr) { if (opr.has_value()) { return opl *= opr.value(); } } template <class Ol, class Or> void operator/=(optional<Ol> &opl, const optional<Or> &opr) { if (opr.has_value()) { return opl /= opr.value(); } } /*@formatter:off*/ template <class U> auto max(const nullopt_t &, const U &val) { return val; } template <class U> auto max(const U &val, const nullopt_t &) { return val; } template <class U> auto min(const nullopt_t &, const U &val) { return val; } template <class U> auto min(const U &val, const nullopt_t &) { return val; } template <class T, class U> auto max(const optional<T> &opt, const U &val) { if (opt.has_value()) return max(opt.value(), val); else return val; } template <class T, class U> auto max(const U &val, const optional<T> &opt) { if (opt.has_value()) return max(opt.value(), val); else return val; } template <class T, class U> auto min(const optional<T> &opt, const U &val) { if (opt.has_value()) return min(opt.value(), val); else return val; } template <class T, class U> auto min(const U &val, const optional<T> &opt) { if (opt.has_value()) return min(opt.value(), val); else return val; } // null , optional, T bool chma(nullopt_t &, const nullopt_t &) { return false; } template <class T> bool chma(T &opt, const nullopt_t &) { return false; } template <class T> bool chma(nullopt_t &, const T &opt) { return false; } template <class T> bool chma(optional<T> &olv, const optional<T> &orv) { if (orv.has_value()) { return chma(olv, orv.value()); } else return false; } template <class T, class U> bool chma(optional<T> &opt, const U &rhs) { if (opt.has_value()) { return chma(opt.value(), rhs); } else return false; } template <class T, class U> bool chma(T &lhs, const optional<U> &opt) { if (opt.has_value()) { return chma(lhs, opt.value()); } else return false; } bool chmi(nullopt_t &, const nullopt_t &) { return false; } template <class T> bool chmi(T &opt, const nullopt_t &) { return false; } template <class T> bool chmi(nullopt_t &, const T &opt) { return false; } template <class T> bool chmi(optional<T> &olv, const optional<T> &orv) { if (orv.has_value()) { return chmi(olv, orv.value()); } else return false; } template <class T, class U> bool chmi(optional<T> &opt, const U &rhs) { if (opt.has_value()) { return chmi(opt.value(), rhs); } else return false; } template <class T, class U> bool chmi(T &lhs, const optional<U> &opt) { if (opt.has_value()) { return chmi(lhs, opt.value()); } else return false; } template <class T> ostream &operator<<(ostream &os, optional<T> p) { if (p.has_value()) os << p.value(); else os << "e"; return os; } template <class T> using opt = my_optional<T>; struct xorshift { /*@formatter:on*/ static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } /*@formatter:off*/ size_t operator()(const uint64_t &x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } size_t operator()(const std::pair<ll, ll> &x) const { ll v = ((x.first) << 32) | x.second; static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(v + FIXED_RANDOM); } template <class T, class U> size_t operator()(const std::pair<T, U> &x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); uint64_t hasx = splitmix64(x.first); uint64_t hasy = splitmix64(x.second + FIXED_RANDOM); return hasx ^ hasy; } template <class T> size_t operator()(const vector<T> &x) const { uint64_t has = 0; static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); uint64_t rv = splitmix64(FIXED_RANDOM); for (int i = 0; i < sz(x); i++) { uint64_t v = splitmix64(x[i] + rv); has ^= v; rv = splitmix64(rv); } return has; } }; #ifdef _DEBUG // #define use_debtor // template<class T, class U, class X> auto count(unordered_map<T, U> &a, X k) { // return a.find(k) != a.end(); } #ifdef use_debtor // https://marycore.jp/prog/cpp/class-extension-methods/ 違うかも template <class T, class A = std::allocator<T>> struct debtor : std::vector<T, A> { using std::vector<T, A>::vector; template <class U> int deb_v(U a, int v) { return v; } template <class U> int deb_v(debtor<U> &a, int v = 0) { cerr << a.size() << " "; return deb_v(a.at(0), v + 1); } template <class U> void deb_o(U a) { cerr << a << " "; } template <class U> void deb_o(debtor<U> &a) { for (int i = 0; i < min((int)a.size(), 15ll); i++) { deb_o(a[i]); } if ((int)a.size() > 15) { cerr << "..."; } cerr << endl; } typename std::vector<T>::reference my_at(typename std::vector<T>::size_type n, vector<int> &ind) { if (n < 0 || n >= (int)this->size()) { int siz = (int)this->size(); cerr << "vector size = "; int dim = deb_v((*this)); cerr << endl; ind.push_back(n); cerr << "out index at "; for (auto &&i : ind) { cerr << i << " "; } cerr << endl; cerr << endl; if (dim <= 2) { deb_o((*this)); } exit(0); } return this->at(n); } typename std::vector<T>::reference operator[](typename std::vector<T>::size_type n) { if (n < 0 || n >= (int)this->size()) { int siz = (int)this->size(); cerr << "vector size = "; int dim = deb_v((*this)); cerr << endl; cerr << "out index at " << n << endl; cerr << endl; if (dim <= 2) { deb_o((*this)); } exit(0); } return this->at(n); } }; #define vector debtor #endif #ifdef use_pbds template <class T> struct my_pbds_tree { set<T> s; auto begin() { return s.begin(); } auto end() { return s.end(); } auto rbegin() { return s.rbegin(); } auto rend() { return s.rend(); } auto empty() { return s.empty(); } auto size() { return s.size(); } void clear() { s.clear(); } template <class U> void insert(U v) { s.insert(v); } template <class U> void operator+=(U v) { insert(v); } template <class F> auto erase(F v) { return s.erase(v); } template <class U> auto find(U v) { return s.find(v); } template <class U> auto lower_bound(U v) { return s.lower_bound(v); } template <class U> auto upper_bound(U v) { return s.upper_bound(v); } auto find_by_order(ll k) { auto it = s.begin(); for (ll i = 0; i < k; i++) it++; return it; } auto order_of_key(ll v) { auto it = s.begin(); ll i = 0; for (; it != s.end() && *it < v; i++) it++; return i; } }; #define pbds(T) my_pbds_tree<T> #endif // 区間削除は出来ない // gp_hash_tableでcountを使えないようにするため template <class K, class V> using umap_f = unordered_map<K, V>; #else #define endl '\n' // umapはunorderd_mapになる // umapiはgp_hash_table // find_by_order(k) k番目のイテレーター // order_of_key(k) k以上が前から何番目か #define pbds(U) \ __gnu_pbds::tree<U, __gnu_pbds::null_type, less<U>, __gnu_pbds::rb_tree_tag, \ __gnu_pbds::tree_order_statistics_node_update> template <class K, class V> struct umap_f : public __gnu_pbds::gp_hash_table<K, V, xorshift> { int count(const K &k) { return this->find(k) != this->end(); } }; #endif #define umapi unordered_map<ll, ll> #define umapp unordered_map<P, ll> #define umappp unordered_map<P, P> #define umapu unordered_map<uint64_t, ll> #define umapip unordered_map<ll, P> template <class T, class U, class X> auto count(unordered_map<T, U> &a, X k) { return a.find(k) != a.end(); } /*@formatter:off*/ #ifdef use_pbds template <class U, class L> void operator+=( __gnu_pbds::tree<U, __gnu_pbds::null_type, less<U>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> &s, L v) { s.insert(v); } #endif // 衝突対策 #define ws ws_ typedef tuple<ll, ll, ll> T; typedef tuple<ll, ll, ll, ll> F; // T mt(ll a, ll b, ll c) { return T(a, b, c); } // F mf(ll a, ll b, ll c, ll d) { return F(a, b, c, d); } // 関数内をまとめる // 初期値l=-1, r=-1 void set_lr12(int &l, int &r, int n) { /*r==-1*/ if (r == -1) { if (l == -1) { l = 0; r = n; } else { r = l; l = 0; } } } //@マクロ省略系 型,構造 // using で元のdoubleを同時に使えるはず #define double_big #ifdef double_big #define double long double // #define pow powl #endif using dou = double; /*@formatter:off*/ template <class T> T MAX() { return numeric_limits<T>::max(); } template <class T> T MIN() { return numeric_limits<T>::min(); } constexpr ll inf = (ll)1e9 + 100; constexpr ll linf = (ll)1e18 + 100; constexpr dou dinf = (dou)linf * linf; constexpr char infc = '{'; const string infs = "{"; template <class T> T INF() { return MAX<T>() / 2; } template <> signed INF() { return inf; } template <> ll INF() { return linf; } template <> double INF() { return dinf; } template <> char INF() { return infc; } template <> string INF() { return infs; } const double eps = 1e-9; // #define use_epsdou #ifdef use_epsdou // 基本コメントアウト struct epsdou { double v; epsdou(double v = 0) : v(v) {} template <class T> epsdou &operator+=(T b) { v += (double)b; return (*this); } template <class T> epsdou &operator-=(T b) { v -= (double)b; return (*this); } template <class T> epsdou &operator*=(T b) { v *= (double)b; return (*this); } template <class T> epsdou &operator/=(T b) { v /= (double)b; return (*this); } epsdou operator+(epsdou b) { return v + (double)b; } epsdou operator-(epsdou b) { return v - (double)b; } epsdou operator*(epsdou b) { return v * (double)b; } epsdou operator/(epsdou b) { return v / (double)b; } epsdou operator-() const { return epsdou(-v); } template <class T> bool operator<(T b) { return v < (double)b; } template <class T> bool operator>(T b) { auto r = (double)b; return v > (double)b; } template <class T> bool operator==(T b) { return fabs(v - (double)b) <= eps; } template <class T> bool operator<=(T b) { return v < (double)b || fabs(v - b) <= eps; } template <class T> bool operator>=(T b) { return v > (double)b || fabs(v - b) <= eps; } operator double() { return v; } }; template <> epsdou MAX() { return MAX<double>(); } template <> epsdou MIN() { return MIN<double>(); } // priqrity_queue等で使うのに必要 bool operator<(const epsdou &a, const epsdou &b) { return a.v < b.v; } bool operator>(const epsdou &a, const epsdou &b) { return a.v > b.v; } istream &operator>>(istream &iss, epsdou &a) { iss >> a.v; return iss; } ostream &operator<<(ostream &os, epsdou &a) { os << a.v; return os; } #define eps_conr_t(o) \ template <class T> epsdou operator o(T a, epsdou b) { return (dou)a o b.v; } #define eps_conl_t(o) \ template <class T> epsdou operator o(epsdou a, T b) { return a.v o(dou) b; } eps_conl_t(+) eps_conl_t(-) eps_conl_t(*) eps_conl_t(/) eps_conr_t(+) eps_conr_t(-) eps_conr_t(*) eps_conr_t(/) // template<class U> epsdou max(epsdou a, U b){return a.v>b ? a.v: b;} // template<class U> epsdou max(U a, epsdou b){return a>b.v ? a: b.v;} // template<class U> epsdou min(epsdou a, U b){return a.v<b ? a.v: b;} // template<class U> epsdou min(U a, epsdou b){return a<b.v ? a: b.v;} #undef double #define double epsdou #undef dou #define dou epsdou #endif template <class T = int, class A, class B = int> T my_pow(A a, B b = 2) { if (b < 0) return (T)1 / my_pow<T>(a, -b); #if __cplusplus >= 201703L if constexpr (is_floating_point<T>::value) { return pow((T)a, (T)b); } else if constexpr (is_floating_point<A>::value) { assert2( 0, "pow <not dou>(dou, )"); /*return 0;しない方がコンパイル前に(voidを受け取るので)エラーが出ていいかも*/ } else if constexpr (is_floating_point<B>::value) { assert2( 0, "pow <not dou>(, dou)"); /*return 0;しない方がコンパイル前に(voidを受け取るので)エラーが出ていいかも*/ } else { #endif T ret = 1; T bek = a; while (b) { if (b & 1) ret *= bek; bek *= bek; b >>= 1; } return ret; #if __cplusplus >= 201703L } #endif } #define pow my_pow #define ull unsigned long long using itn = int; using str = string; using bo = bool; #define au auto using P = pair<ll, ll>; #define fi first #define se second #define beg begin #define rbeg rbegin #define con continue #define bre break #define brk break #define is == #define el else #define elf else if #define upd update #define sstream stringstream #define maxq 1 #define minq -1 #define ZERO(a) memset(a, 0, sizeof(a)) #define MINUS(a) memset(a, 0xff, sizeof(a)) #define MALLOC(type, len) (type *)malloc((len) * sizeof(type)) #define lam1(ret) [&](auto &&v) { return ret; } #define lam2(v, ret) [&](auto &&v) { return ret; } #define lam(...) over2(__VA_ARGS__, lam2, lam1)(__VA_ARGS__) #define lamr(right) [&](auto &&p) { return p right; } #define unique(v) v.erase(unique(v.begin(), v.end()), v.end()); // マクロ省略系 コンテナ using vi = vector<ll>; using vb = vector<bool>; using vs = vector<string>; using vd = vector<double>; using vc = vector<char>; using vp = vector<P>; using vt = vector<T>; // #define V vector #define vvt0(t) vector<vector<t>> #define vvt1(t, a) vector<vector<t>> a #define vvt2(t, a, b) vector<vector<t>> a(b) #define vvt3(t, a, b, c) vector<vector<t>> a(b, vector<t>(c)) #define vvt4(t, a, b, c, d) vector<vector<t>> a(b, vector<t>(c, d)) #define vv(type, ...) \ over4(__VA_ARGS__, vvt4, vvt3, vvt2, vvt1, vvt0)(type, __VA_ARGS__) #define vvi(...) vv(ll, __VA_ARGS__) #define vvb(...) vv(bool, __VA_ARGS__) #define vvs(...) vv(string, __VA_ARGS__) #define vvd(...) vv(double, __VA_ARGS__) #define vvc(...) vv(char, __VA_ARGS__) #define vvp(...) vv(P, __VA_ARGS__) #define vvt(...) vv(T, __VA_ARGS__) // optional #define vvoi(...) vv(optional<ll>, __VA_ARGS__) template <typename T> vector<T> make_v(size_t a) { return vector<T>(a); } template <typename T, typename... Ts> auto make_v(size_t a, Ts... ts) { return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...)); } #define vni(name, ...) auto name = make_v<ll>(__VA_ARGS__) #define vnb(name, ...) auto name = make_v<bool>(__VA_ARGS__) #define vns(name, ...) auto name = make_v<string>(__VA_ARGS__) #define vnd(name, ...) auto name = make_v<double>(__VA_ARGS__) #define vnc(name, ...) auto name = make_v<char>(__VA_ARGS__) #define vnp(name, ...) auto name = make_v<P>(__VA_ARGS__) #define vn(type, name, ...) auto name = make_v<type>(__VA_ARGS__) #define PQ priority_queue<ll, vector<ll>, greater<ll>> #define tos to_string using mapi = map<ll, ll>; using mapp = map<P, ll>; using mapd = map<dou, ll>; using mapc = map<char, ll>; using maps = map<str, ll>; using seti = set<ll>; using setp = set<P>; using setd = set<dou>; using setc = set<char>; using sets = set<str>; using qui = queue<ll>; #define uset unordered_set #define useti unordered_set<ll, xorshift> #define mset multiset #define mseti multiset<ll> #define umap unordered_map #define mmap multimap // 初期化子を与える template <template <class...> class MAP, class K, class V, class... A> struct init_map : public MAP<K, V, A...> { V init_value; init_map(V init_value = 0) : MAP<K, V, A...>(), init_value(init_value) {} V &operator[](const K &k) { if (MAP<K, V, A...>::count(k) == 0) { return MAP<K, V, A...>::operator[](k) = init_value; } return MAP<K, V, A...>::operator[](k); } }; template <class... A> using map2 = init_map<map, A...>; template <class... A> using umap2 = init_map<umap, A...>; template <class... A> using umap_f2 = init_map<umap_f, A...>; // 任意のマクロサポート用 使う度に初期化する //todo これを消す int index_, v1_, v2_, v3_; /*@formatter:off*/ string to_string(char c) { string ret = ""; ret += c; return ret; } template <class T> class pq_min_max { vector<T> d; void make_heap() { for (int i = d.size(); i--;) { if (i & 1 && d[i - 1] < d[i]) swap(d[i - 1], d[i]); int k = down(i); up(k, i); } } inline int parent(int k) const { return ((k >> 1) - 1) & ~1; } int down(int k) { int n = d.size(); if (k & 1) { /* min heap*/ while (2 * k + 1 < n) { int c = 2 * k + 3; if (n <= c || d[c - 2] < d[c]) c -= 2; if (c < n && d[c] < d[k]) { swap(d[k], d[c]); k = c; } else break; } } else { /* max heap*/ while (2 * k + 2 < n) { int c = 2 * k + 4; if (n <= c || d[c] < d[c - 2]) c -= 2; if (c < n && d[k] < d[c]) { swap(d[k], d[c]); k = c; } else break; } } return k; } int up(int k, int root = 1) { if ((k | 1) < (int)d.size() && d[k & ~1] < d[k | 1]) { swap(d[k & ~1], d[k | 1]); k ^= 1; } int p; while (root < k && d[p = parent(k)] < d[k]) { /*max heap*/ swap(d[p], d[k]); k = p; } while (root < k && d[k] < d[p = parent(k) | 1]) { /* min heap*/ swap(d[p], d[k]); k = p; } return k; } public: pq_min_max() {} pq_min_max(const vector<T> &d_) : d(d_) { make_heap(); } template <class Iter> pq_min_max(Iter first, Iter last) : d(first, last) { make_heap(); } void operator+=(const T &x) { int k = d.size(); d.push_back(x); up(k); } void pop_min() { if (d.size() < 3u) { d.pop_back(); } else { swap(d[1], d.back()); d.pop_back(); int k = down(1); up(k); } } void pop_max() { if (d.size() < 2u) { d.pop_back(); } else { swap(d[0], d.back()); d.pop_back(); int k = down(0); up(k); } } const T &get_min() const { return d.size() < 2u ? d[0] : d[1]; } const T &get_max() const { return d[0]; } int size() const { return d.size(); } bool empty() const { return d.empty(); } }; // 小さいほうからM個取得するpq template <class T> struct helper_pq_size { pq_min_max<T> q; T su = 0; int max_size = 0; helper_pq_size() {} helper_pq_size(int max_size) : max_size(max_size) {} void clear() { q = pq_min_max<T>(); su = 0; } void operator+=(T v) { su += v; q += (v); if (sz(q) > max_size) { su -= q.get_max(); q.pop_max(); } } T sum() { return su; } T top() { return q.get_min(); } void pop() { su -= q.get_min(); q.pop_min(); } T poll() { T ret = q.get_min(); su -= ret; q.pop_min(); return ret; } ll size() { return q.size(); } }; // 大きいほうからM個取得するpq template <class T> struct helper_pqg_size { pq_min_max<T> q; T su = 0; int max_size = 0; helper_pqg_size() {} helper_pqg_size(int max_size) : max_size(max_size) {} void clear() { q = pq_min_max<T>(); su = 0; } void operator+=(T v) { su += v; q += (v); if (sz(q) > max_size) { su -= q.get_min(); q.pop_min(); } } T sum() { return su; } T top() { return q.get_max(); } void pop() { su -= q.get_max(); q.pop_max(); } T poll() { T ret = q.get_max(); su -= ret; q.pop_min(); return ret; } ll size() { return q.size(); } }; ; template <class T, class Container = vector<T>, class Compare = std::less<typename Container::value_type>> struct helper_pqg { priority_queue<T, Container, Compare> q; /*小さい順*/ T su = 0; helper_pqg() {} void clear() { q = priority_queue<T, vector<T>, greater<T>>(); su = 0; } void operator+=(T v) { su += v; q.push(v); } T sum() { return su; } T top() { return q.top(); } void pop() { su -= q.top(); q.pop(); } T poll() { T ret = q.top(); su -= ret; q.pop(); return ret; } ll size() { return q.size(); } }; template <class T> using helper_pq = helper_pqg<T, vector<T>, greater<T>>; #if __cplusplus >= 201703L // 小さいほうからsize個残る // Tがoptionalなら空の時nullを返す template <class T> struct pq { helper_pq<T> a_q; /*大きい順*/ helper_pq_size<T> b_q; /*大きい順*/ bool aquery; T su = 0; pq(int size = inf) { aquery = size == inf; if (!aquery) { b_q = helper_pq_size<T>(size); } } void clear() { if (aquery) a_q.clear(); else b_q.clear(); } void operator+=(T v) { if (aquery) a_q += v; else b_q += v; } // optionalなら空の時nullを返す T top() { if constexpr (is_optional<T>::value) { if (aquery) { if (sz(a_q) == 0) return T(); return a_q.top(); } else { if (sz(b_q) == 0) return T(); return b_q.top(); } } else { if (aquery) return a_q.top(); else return b_q.top(); } } T sum() { if (aquery) return a_q.sum(); else return b_q.sum(); } // optionalなら空の時何もしない void pop() { if constexpr (is_optional<T>::value) { if (aquery) { if (sz(a_q)) a_q.pop(); } else { if (sz(b_q)) b_q.pop(); } } else { if (aquery) a_q.pop(); else b_q.pop(); } } /*T*/ T poll() { if constexpr (is_optional<T>::value) { if (aquery) { if (sz(a_q) == 0) return T(); return a_q.poll(); } else { if (sz(b_q) == 0) return T(); return b_q.poll(); } } else { if (aquery) return a_q.poll(); else return b_q.poll(); } } ll size() { if (aquery) return a_q.size(); else return b_q.size(); } /*@formatter:off*/ }; template <class T> struct pqg { helper_pqg<T> a_q; /*大きい順*/ helper_pqg_size<T> b_q; /*大きい順*/ bool aquery; T su = 0; pqg(int size = inf) { aquery = size == inf; if (!aquery) { b_q = helper_pqg_size<T>(size); } } void clear() { if (aquery) a_q.clear(); else b_q.clear(); } void operator+=(T v) { if (aquery) a_q += v; else b_q += v; } T sum() { if (aquery) return a_q.sum(); else return b_q.sum(); } T top() { if (aquery) return a_q.top(); else return b_q.top(); } void pop() { if (aquery) a_q.pop(); else b_q.pop(); } T poll() { if (aquery) return a_q.poll(); else return b_q.poll(); } ll size() { if (aquery) return a_q.size(); else return b_q.size(); } }; #else // 小さいほうからsize個残る template <class T> struct pq { helper_pq<T> a_q; /*大きい順*/ helper_pq_size<T> b_q; /*大きい順*/ bool aquery; T su = 0; pq(int size = inf) { aquery = size == inf; if (!aquery) { b_q = helper_pq_size<T>(size); } } void clear() { if (aquery) a_q.clear(); else b_q.clear(); } void operator+=(T v) { if (aquery) a_q += v; else b_q += v; } T sum() { if (aquery) return a_q.sum(); else return b_q.sum(); } T top() { if (aquery) return a_q.top(); else return b_q.top(); } void pop() { if (aquery) a_q.pop(); else b_q.pop(); } T poll() { if (aquery) return a_q.poll(); else return b_q.poll(); } ll size() { if (aquery) return a_q.size(); else return b_q.size(); } }; // 大きいほうからsize個残る template <class T> struct pqg { helper_pqg<T> a_q; /*大きい順*/ helper_pqg_size<T> b_q; /*大きい順*/ bool aquery; T su = 0; pqg(int size = inf) { aquery = size == inf; if (!aquery) { b_q = helper_pqg_size<T>(size); } } void clear() { if (aquery) a_q.clear(); else b_q.clear(); } void operator+=(T v) { if (aquery) a_q += v; else b_q += v; } T sum() { if (aquery) return a_q.sum(); else return b_q.sum(); } T top() { if (aquery) return a_q.top(); else return b_q.top(); } void pop() { if (aquery) a_q.pop(); else b_q.pop(); } T poll() { if (aquery) return a_q.poll(); else return b_q.poll(); } ll size() { if (aquery) return a_q.size(); else return b_q.size(); } }; #endif #define pqi pq<ll> #define pqgi pqg<ll> template <class T> string deb_tos(pq<T> &q) { vector<T> res; auto temq = q; while (sz(temq)) res.push_back(temq.top()), temq.pop(); stringstream ss; ss << res; return ss.str(); } template <class T> string deb_tos(pqg<T> &q) { vector<T> res; auto temq = q; while (sz(temq)) res.push_back(temq.top()), temq.pop(); stringstream ss; ss << res; return ss.str(); } /*@formatter:off*/ // マクロ 繰り返し // ↓@オーバーロード隔離 // todo 使わないもの非表示 #define rep1(n) for (ll rep1i = 0, rep1lim = n; rep1i < rep1lim; ++rep1i) #define rep2(i, n) for (ll i = 0, rep2lim = n; i < rep2lim; ++i) #define rep3(i, m, n) for (ll i = m, rep3lim = n; i < rep3lim; ++i) #define rep4(i, m, n, ad) for (ll i = m, rep4lim = n; i < rep4lim; i += ad) // 逆順 閉区間 #define rer2(i, n) for (ll i = n; i >= 0; i--) #define rer3(i, m, n) for (ll i = m, rer3lim = n; i >= rer3lim; i--) #define rer4(i, m, n, dec) for (ll i = m, rer4lim = n; i >= rer4lim; i -= dec) #ifdef use_for // ループを一つにまとめないとフォーマットで汚くなるため #define nex_ind1(i) i++ #define nex_ind2(i, j, J) \ i = (j + 1 == J) ? i + 1 : i, j = (j + 1 == J ? 0 : j + 1) #define nex_ind3(i, j, k, J, K) \ i = (j + 1 == J && k + 1 == K) ? i + 1 : i, \ j = (k + 1 == K) ? (j + 1 == J ? 0 : j + 1) : j, \ k = (k + 1 == K ? 0 : k + 1) #define nex_ind4(i, j, k, l, J, K, L) \ i = (j + 1 == J && k + 1 == K && l + 1 == L) ? i + 1 : i, \ j = (k + 1 == K && l + 1 == L) ? (j + 1 == J ? 0 : j + 1) : j, \ k = (l + 1 == L ? (k + 1 == K ? 0 : k + 1) : k), l = l + 1 == L ? 0 : l + 1 #define nex_ind5(i, j, k, l, m, J, K, L, M) \ i = (j + 1 == J && k + 1 == K && l + 1 == L && m + 1 == M) ? i + 1 : i, \ j = (k + 1 == K && l + 1 == L && m + 1 == M) ? (j + 1 == J ? 0 : j + 1) : j, \ k = (l + 1 == L && m + 1 == M ? (k + 1 == K ? 0 : k + 1) : k), \ l = m + 1 == M ? l + 1 == L ? 0 : l + 1 : l, m = m + 1 == M ? 0 : m + 1 #define repss2(i, I) for (int i = 0; i < I; i++) #define repss4(i, j, I, J) \ for (int i = (J ? 0 : I), j = 0; i < I; nex_ind2(i, j, J)) #define repss6(i, j, k, I, J, K) \ for (int i = (J && K ? 0 : I), j = 0, k = 0; i < I; nex_ind3(i, j, k, J, K)) #define repss8(i, j, k, l, I, J, K, L) \ for (int i = (J && K && L ? 0 : I), j = 0, k = 0, l = 0; i < I; \ nex_ind4(i, j, k, l, J, K, L)) #define repss10(i, j, k, l, m, I, J, K, L, M) \ for (int i = (J && K && L && M ? 0 : I), j = 0, k = 0, l = 0, m = 0; i < I; \ nex_ind5(i, j, k, l, m, J, K, L, M)) // i,j,k...をnまで見る #define reps2(i, n) repss2(i, n) #define reps3(i, j, n) repss4(i, j, n, n) #define reps4(i, j, k, n) repss6(i, j, k, n, n, n) #define reps5(i, j, k, l, n) repss8(i, j, k, l, n, n, n, n) template <class T> void nex_repv2(int &i, int &j, int &I, int &J, vector<vector<T>> &s) { while (1) { j++; if (j >= J) { j = 0; i++; if (i < I) { J = (int)s[i].size(); } } if (i >= I || J) return; } } template <class T> void nex_repv3(int &i, int &j, int &k, int &I, int &J, int &K, vector<vector<vector<T>>> &s) { while (1) { k++; if (k >= K) { k = 0; j++; if (j >= J) { j = 0; i++; if (i >= I) return; } } J = (int)s[i].size(); K = (int)s[i][j].size(); if (J && K) return; } } #define repv_2(i, a) repss2(i, sz(a)) // 正方形である必要はない // 直前を持つのとどっちが早いか #define repv_3(i, j, a) \ for (int repvI = (int)a.size(), repvJ = (int)a[0].size(), i = 0, j = 0; \ i < repvI; nex_repv2(i, j, repvI, repvJ, a)) // 箱状になっている事が要求される つまり[i] 次元目の要素数は一定 #define repv_4(i, j, k, a) \ for (int repvI = (int)a.size(), repvJ = (int)a[0].size(), \ repvK = (int)a[0][0].size(), i = 0, j = 0, k = 0; \ i < repvI; nex_repv3(i, j, k, repvI, repvJ, repvK, a)) #define repv_5(i, j, k, l, a) \ repss8(i, j, k, l, sz(a), sz(a[0]), sz(a[0][0]), sz(a[0][0][0])) #define repv_6(i, j, k, l, m, a) \ repss10(i, j, k, l, m, sz(a), sz(a[0]), sz(a[0][0]), sz(a[0][0][0]), \ sz(a[0][0][0][0])) #endif template <typename T> struct has_rbegin_rend { private: template <typename U> static auto check(U &&obj) -> decltype(std::rbegin(obj), std::rend(obj), std::true_type{}); static std::false_type check(...); public: static constexpr bool value = decltype(check(std::declval<T>()))::value; }; template <typename T> constexpr bool has_rbegin_rend_v = has_rbegin_rend<T>::value; template <typename Iterator> class Range { public: Range(Iterator &&begin, Iterator &&end) noexcept : m_begin(std::forward<Iterator>(begin)), m_end(std::forward<Iterator>(end)) {} Iterator begin() const noexcept { return m_begin; } Iterator end() const noexcept { return m_end; } private: const Iterator m_begin; const Iterator m_end; }; template <typename Iterator> static inline Range<Iterator> makeRange(Iterator &&begin, Iterator &&end) noexcept { return Range<Iterator>{std::forward<Iterator>(begin), std::forward<Iterator>(end)}; } template <typename T> static inline decltype(auto) makeReversedRange(const std::initializer_list<T> &iniList) noexcept { return makeRange(std::rbegin(iniList), std::rend(iniList)); } template <typename T, typename std::enable_if_t<has_rbegin_rend_v<T>, std::nullptr_t> = nullptr> static inline decltype(auto) makeReversedRange(T &&c) noexcept { return makeRange(std::rbegin(c), std::rend(c)); } /* rbegin(), rend()を持たないものはこっちに分岐させて,エラーメッセージを少なくする*/ template <typename T, typename std::enable_if<!has_rbegin_rend<T>::value, std::nullptr_t>::type = nullptr> static inline void makeReversedRange(T &&) noexcept { static_assert(has_rbegin_rend<T>::value, "Specified argument doesn't have reverse iterator."); } // #define use_for #define form3(k, v, st) for (auto &&[k, v] : st) #define form4(k, v, st, r) \ for (auto &&[k, v] : range(st.begin(), st.lower_bound(r))) #define form5(k, v, st, l, r) \ for (auto &&[k, v] : range(st.lower_bound(l), st.lower_bound(r))) #define form(...) over5(__VA_ARGS__, form5, form4, form3)(__VA_ARGS__) #define forrm1(st) \ for (auto &&forrm_it = st.rbegin(); forrm_it != st.rend(); ++forrm_it) #define forrm3(k, v, st) \ for (auto &&forrm_it = st.rbegin(); forrm_it != st.rend(); ++forrm_it) // 向こう側で // ++itか it = st.erase(it)とする #define fors1(st) for (auto &&it = st.begin(); it != st.end();) #define fors2(v, st) for (auto &&it = st.begin(); it != st.end();) #define fors3(v, st, r) \ for (auto &&it = st.begin(); it != st.end() && (*it) < r;) #define fors4(v, st, l, r) \ for (auto &&it = st.lower_bound(l); it != st.end() && (*it) < r;) #ifdef use_for #define forslr3(st, a, b) \ for (auto &&forslr_it = st.begin(); forslr_it != st.end(); ++forslr_it) #define forslr4(v, st, a, b) \ for (auto &&forslr_it = st.begin(); forslr_it != st.end(); ++forslr_it) #define forslr5(v, st, r, a, b) \ for (auto &&forslr_it = st.begin(); \ forslr_it != st.end() && (*forslr_it) < r; ++forslr_it) #define forslr6(v, st, l, r, a, b) \ for (auto &&forslr_it = st.lower_bound(l); \ forslr_it != st.end() && (*forslr_it) < r; ++forslr_it) #define fora_f_init_2(a, A) ; #define fora_f_init_3(fora_f_i, a, A) auto &&a = A[fora_f_i]; #define fora_f_init_4(a, b, A, B) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; #define fora_f_init_5(fora_f_i, a, b, A, B) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; #define fora_f_init_6(a, b, c, A, B, C) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; \ auto &&c = C[fora_f_i]; #define fora_f_init_7(fora_f_i, a, b, c, A, B, C) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; \ auto &&c = C[fora_f_i]; #define fora_f_init_8(a, b, c, d, A, B, C, D) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; \ auto &&c = C[fora_f_i]; \ auto &&d = D[fora_f_i]; #define fora_f_init_9(fora_f_i, a, b, c, d, A, B, C, D) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; \ auto &&c = C[fora_f_i]; \ auto &&d = D[fora_f_i]; #define fora_f_init(...) \ over9(__VA_ARGS__, fora_f_init_9, fora_f_init_8, fora_f_init_7, \ fora_f_init_6, fora_f_init_5, fora_f_init_4, fora_f_init_3, \ fora_f_init_2)(__VA_ARGS__) #define forr_init_2(a, A) auto &&a = A[forr_i]; #define forr_init_3(forr_i, a, A) auto &&a = A[forr_i]; #define forr_init_4(a, b, A, B) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; #define forr_init_5(forr_i, a, b, A, B) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; #define forr_init_6(a, b, c, A, B, C) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; \ auto &&c = C[forr_i]; #define forr_init_7(forr_i, a, b, c, A, B, C) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; \ auto &&c = C[forr_i]; #define forr_init_8(a, b, c, d, A, B, C, D) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; \ auto &&c = C[forr_i]; \ auto &&d = D[forr_i]; #define forr_init_9(forr_i, a, b, c, d, A, B, C, D) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; \ auto &&c = C[forr_i]; \ auto &&d = D[forr_i]; #define forr_init(...) \ over9(__VA_ARGS__, forr_init_9, forr_init_8, forr_init_7, forr_init_6, \ forr_init_5, forr_init_4, forr_init_3, forr_init_2)(__VA_ARGS__) #define forp_init3(k, v, S) \ auto &&k = S[forp_i].first; \ auto &&v = S[forp_i].second; #define forp_init4(forp_i, k, v, S) \ auto &&k = S[forp_i].first; \ auto &&v = S[forp_i].second; #define forp_init(...) \ over4(__VA_ARGS__, forp_init4, forp_init3, forp_init2, \ forp_init1)(__VA_ARGS__) #define forrm_init(k, v, ...) \ auto &&k = (*forrm_it).fi; \ auto &&v = (*forrm_it).se; #define fors_init(v, ...) auto &&v = (*it); #define forlr_init(a, A, ngl, ngr) \ auto a = A[forlr_i]; \ auto prev = forlr_i ? A[forlr_i - 1] : ngl; \ auto next = forlr_i + 1 < rep2lim ? A[forlr_i + 1] : ngr; #define forslr_init4(a, A, ngl, ngr) \ auto a = (*forslr_it); \ auto prev = (forslr_it != A.begin()) ? (*std::prev(forslr_it)) : ngl; \ auto next = (forslr_it != std::prev(A.end())) ? (*std::next(forslr_it)) : ngr; #define forslr_init5(a, A, r, ngl, ngr) \ auto a = (*forslr_it); \ auto prev = (forslr_it != A.begin()) ? (*std::prev(forslr_it)) : ngl; \ auto next = (forslr_it != std::prev(A.end())) ? (*std::next(forslr_it)) : ngr; #define forslr_init6(a, A, l, r, ngl, ngr) \ auto a = (*forslr_it); \ auto prev = (forslr_it != A.begin()) ? (*std::prev(forslr_it)) : ngl; \ auto next = (forslr_it != std::prev(A.end())) ? (*std::next(forslr_it)) : ngr; #define forslr_init(...) \ over6(__VA_ARGS__, forslr_init6, forslr_init5, forslr_init4)(__VA_ARGS__); // こうしないとmapがおかしくなる #define fora_f_2(a, A) for (auto &&a : A) #define fora_f_3(fora_f_i, a, A) rep(fora_f_i, sz(A)) #define fora_f_4(a, b, A, B) rep(fora_f_i, sz(A)) #define fora_f_5(fora_f_i, a, b, A, B) rep(fora_f_i, sz(A)) #define fora_f_6(a, b, c, A, B, C) rep(fora_f_i, sz(A)) #define fora_f_7(fora_f_i, a, b, c, A, B, C) rep(fora_f_i, sz(A)) #define fora_f_8(a, b, c, d, A, B, C, D) rep(fora_f_i, sz(A)) #define fora_f_9(fora_f_i, a, b, c, d, A, B, C, D) rep(fora_f_i, sz(A)) #define forr_2(a, A) rer(forr_i, sz(A) - 1) #define forr_3(forr_i, a, A) rer(forr_i, sz(A) - 1) #define forr_4(a, b, A, B) rer(forr_i, sz(A) - 1) #define forr_5(forr_i, a, b, A, B) rer(forr_i, sz(A) - 1) #define forr_6(a, b, c, A, B, C) rer(forr_i, sz(A) - 1) #define forr_7(forr_i, a, b, c, A, B, C) rer(forr_i, sz(A) - 1) #define forr_8(a, b, c, d, A, B, C, D) rer(forr_i, sz(A) - 1) #define forr_9(forr_i, a, b, c, d, A, B, C, D) rer(forr_i, sz(A) - 1) #endif // ↑@オーバーロード隔離 // rep系はインデックス、for系は中身 #define rep(...) over4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__) #define rer(...) over4(__VA_ARGS__, rer4, rer3, rer2, )(__VA_ARGS__) // 自分込みで残りがREM以上の間ループを回す #define rem(i, N, REM) for (int i = 0; i < N - REM + 1; i++) // char用のrep #define repc(i, m, n) for (char i = m, repc3lim = n; i < repc3lim; ++i) // i,j,k...をnまで見る #define reps(...) over5(__VA_ARGS__, reps5, reps4, reps3, reps2, )(__VA_ARGS__) #define repss(...) \ over10(__VA_ARGS__, repss10, a, repss8, a, repss6, a, repss4, a, \ repss2)(__VA_ARGS__) // vectorのindexを走査する // repv(i,j,vvi) #define repv(...) \ over6(__VA_ARGS__, repv_6, repv_5, repv_4, repv_3, repv_2, )(__VA_ARGS__) #define rerv(i, A) for (int i = sz(A) - 1; i >= 0; i--) // repvn(dp) nは次元 #define repv1(a) repv(i, a) #define repv2(a) repv(i, j, a) #define repv3(a) repv(i, j, k, a) #define repv4(a) repv(i, j, k, l, a) #ifdef use_for #define fora_f(...) \ over9(__VA_ARGS__, fora_f_9, fora_f_8, fora_f_7, fora_f_6, fora_f_5, \ fora_f_4, fora_f_3, fora_f_2)(__VA_ARGS__) #endif #define forr(...) \ over9(__VA_ARGS__, forr_9, forr_8, forr_7, forr_6, forr_5, forr_4, forr_3, \ forr_2)(__VA_ARGS__) // 0~N-2まで見る #define forar_init(v, rv, A) \ auto &&v = A[forar_i]; \ auto &&rv = A[forar_i + 1]; #define forar(v, rv, A) rep(forar_i, sz(A) - 1) #if __cplusplus >= 201703L template <size_t M_SZ, bool indexed, class Iterator, class T, class U = T, class V = T, class W = T> class ite_vec_merge : public Iterator { std::size_t i = 0; vector<T> &A; vector<U> &B; vector<V> &C; vector<W> &D; public: ite_vec_merge(Iterator ita, vector<T> &A) : Iterator(ita), A(A), B(A), C(A), D(A) {} ite_vec_merge(Iterator ita, vector<T> &A, vector<U> &B) : Iterator(ita), A(A), B(B), C(A), D(A) {} ite_vec_merge(Iterator ita, vector<T> &A, vector<U> &B, vector<V> &C) : Iterator(ita), A(A), B(B), C(C), D(A) {} ite_vec_merge(Iterator ita, vector<T> &A, vector<U> &B, vector<V> &C, vector<W> &D) : Iterator(ita), A(A), B(B), C(C), D(D) {} auto &operator++() { ++i; this->Iterator::operator++(); return *this; } auto operator*() const noexcept { if constexpr (!indexed && M_SZ == 1) { return tuple<T &>(A[i]); } else if constexpr (!indexed && M_SZ == 2) { return tuple<T &, U &>(A[i], B[i]); } else if constexpr (!indexed && M_SZ == 3) { return tuple<T &, U &, V &>(A[i], B[i], C[i]); } else if constexpr (!indexed && M_SZ == 4) { return tuple<T &, U &, V &, W &>(A[i], B[i], C[i], D[i]); } else if constexpr (indexed && M_SZ == 1) { return tuple<int, T &>(i, A[i]); } else if constexpr (indexed && M_SZ == 2) { return tuple<int, T &, U &>(i, A[i], B[i]); } else if constexpr (indexed && M_SZ == 3) { return tuple<int, T &, U &, V &>(i, A[i], B[i], C[i]); } else if constexpr (indexed && M_SZ == 4) { return tuple<int, T &, U &, V &, W &>(i, A[i], B[i], C[i], D[i]); } else { assert(0); return tuple<int>(i); } } }; template <size_t M_SZ, bool indexed, class T, class U = T, class V = T, class W = T> class vec_merge { vector<T> &a; vector<U> &b; vector<V> &c; vector<W> &d; public: vec_merge(vector<T> &a) : a(a), b(a), c(a), d(a) {} vec_merge(vector<T> &a, vector<U> &b) : a(a), b(b), c(a), d(a) {} vec_merge(vector<T> &a, vector<U> &b, vector<V> &c) : a(a), b(b), c(c), d(a) {} vec_merge(vector<T> &a, vector<U> &b, vector<V> &c, vector<W> &d) : a(a), b(b), c(c), d(d) {} auto begin() const { if constexpr (M_SZ == 1) { return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a}; } else if constexpr (M_SZ == 2) { return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a, b}; } else if constexpr (M_SZ == 3) { return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a, b, c}; } else if constexpr (M_SZ == 4) { return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a, b, c, d}; } else { assert(0); return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a}; } } auto end() const { if constexpr (M_SZ == 1) { return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a}; } else if constexpr (M_SZ == 2) { return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a, b}; } else if constexpr (M_SZ == 3) { return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a, b, c}; } else if constexpr (M_SZ == 4) { return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a, b, c, d}; } else { assert(0); return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a}; } } }; #endif #define fora_2(a, A) for (auto &&a : A) #if __cplusplus >= 201703L #define fora_3(i, a, A) \ for (auto [i, a] : vec_merge<1, true, decl_t<decltype(A)>>(A)) #define fora_4(a, b, A, B) \ for (auto [a, b] : \ vec_merge<2, false, decl_t<decltype(A)>, decl_t<decltype(B)>>(A, B)) #define fora_5(i, a, b, A, B) \ for (auto [i, a, b] : \ vec_merge<2, true, decl_t<decltype(A)>, decl_t<decltype(B)>>(A, B)) #define fora_6(a, b, c, A, B, C) \ for (auto [a, b, c] : \ vec_merge<3, false, decl_t<decltype(A)>, decl_t<decltype(B)>, \ decl_t<decltype(C)>>(A, B, C)) #define fora_7(i, a, b, c, A, B, C) \ for (auto [i, a, b, c] : \ vec_merge<3, true, decl_t<decltype(A)>, decl_t<decltype(B)>, \ decl_t<decltype(C)>>(A, B, C)) #define fora_8(a, b, c, d, A, B, C, D) \ for (auto [a, b, c, d] : \ vec_merge<4, false, decl_t<decltype(A)>, decl_t<decltype(B)>, \ decl_t<decltype(C)>, decl_t<decltype(D)>>(A, B, C, D)) #define fora_9(i, a, b, c, d, A, B, C, D) \ for (auto [i, a, b, c, d] : \ vec_merge<4, true, decl_t<decltype(A)>, decl_t<decltype(B)>, \ decl_t<decltype(C)>, decl_t<decltype(D)>>(A, B, C, D)) #endif // 構造化束縛ver // 1e5要素で40ms程度 // 遅いときはfora_fを使う #define fora(...) \ over9(__VA_ARGS__, fora_9, fora_8, fora_7, fora_6, fora_5, fora_4, fora_3, \ fora_2)(__VA_ARGS__) // #define forr(v, a) for(auto&& v : makeReversedRange(a)) // 参照を取らない /*@formatter:off*/ #ifdef use_for template <class U> vector<U> to1d(vector<U> &a) { return a; } template <class U> auto to1d(vector<vector<U>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) res.push_back(a2); return res; } template <class U> vector<U> to1d(vector<vector<vector<U>>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) for (auto &&a3 : a2) res.push_back(a3); return res; } template <class U> vector<U> to1d(vector<vector<vector<vector<U>>>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) for (auto &&a3 : a2) for (auto &&a4 : a3) res.push_back(a4); return res; } template <class U> vector<U> to1d(vector<vector<vector<vector<vector<U>>>>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) for (auto &&a3 : a2) for (auto &&a4 : a3) for (auto &&a5 : a4) res.push_back(a5); return res; } template <class U> vector<U> to1d(vector<vector<vector<vector<vector<vector<U>>>>>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) for (auto &&a3 : a2) for (auto &&a4 : a3) for (auto &&a5 : a4) for (auto &&a6 : a5) res.push_back(a6); return res; } #define forv(a, b) for (auto a : to1d(b)) // インデックスを前後含めて走査 #define ring(i, s, len) \ for (int i = s, prev = (s == 0) ? len - 1 : s - 1, \ next = (s == len - 1) ? 0 : s + 1, cou = 0; \ cou < len; \ cou++, prev = i, i = next, next = (next == len - 1) ? 0 : next + 1) // 値と前後を見る #define ringv(v, d) \ index_ = 0; \ for (auto prev = d[sz(d) - 1], next = (int)d.size() > 1 ? d[1] : d[0], \ v = d[0]; \ index_ < sz(d); index_++, prev = v, v = next, \ next = (index_ >= sz(d) - 1 ? d[0] : d[index_ + 1])) // 左右をnext prevで見る 0の左と nの右 #define forlr(v, d, banpei_l, banpei_r) rep(forlr_i, sz(d)) #endif #define forrm(...) \ over5(__VA_ARGS__, forrm5, forrm4, forrm3, forrm2, forrm1)(__VA_ARGS__) #define fors(...) over4(__VA_ARGS__, fors4, fors3, fors2, fors1)(__VA_ARGS__) #define forslr(...) \ over6(__VA_ARGS__, forslr6, forslr5, forslr4, forslr3)(__VA_ARGS__) #define forp3(k, v, st) rep(forp_i, sz(st)) #define forp4(forp_i, k, v, st) rep(forp_i, sz(st)) #define forp(...) over4(__VA_ARGS__, forp4, forp3)(__VA_ARGS__) // to_vec(rep(i, N))のように使い // iが走査した値を持つvectorを返す #define to_vec2(type, my_for) \ [&]() { \ vector<type> ret; \ my_for { ret.push_back(i); } \ return ret; \ }() #define to_vec1(my_for) to_vec2(int, my_for) #define to_vec(...) over2(__VA_ARGS__, to_vec2, to_vec1)(__VA_ARGS__) // マクロ 定数 #define k3 1010 #define k4 10101 #define k5 101010 #define k6 1010101 #define k7 10101010 const double PI = 3.1415926535897932384626433832795029L; constexpr bool ev(ll a) { return !(a & 1); } constexpr bool od(ll a) { return (a & 1); } //@拡張系 こう出来るべきというもの // 埋め込み 存在を意識せずに機能を増やされているもの namespace std { template <> class hash<std::pair<signed, signed>> { public: size_t operator()(const std::pair<signed, signed> &x) const { return hash<ll>()(((ll)x.first << 32) | x.second); } }; template <> class hash<std::pair<ll, ll>> { public : /*大きいllが渡されると、<<32でオーバーフローするがとりあえず問題ないと判断*/ size_t operator()(const std::pair<ll, ll> &x) const { return hash<ll>()(((ll)x.first << 32) | x.second); } }; } // namespace std // stream まとめ /*@formatter:off*/ istream &operator>>(istream &iss, P &a) { iss >> a.first >> a.second; return iss; } template <typename T> istream &operator>>(istream &iss, vector<T> &vec_) { for (T &x : vec_) iss >> x; return iss; } template <class T, class U> ostream &operator<<(ostream &os, pair<T, U> p) { os << p.fi << " " << p.se; return os; } ostream &operator<<(ostream &os, T p) { os << get<0>(p) << " " << get<1>(p) << " " << get<2>(p); return os; } ostream &operator<<(ostream &os, F p) { os << get<0>(p) << " " << get<1>(p) << " " << get<2>(p) << " " << get<3>(p); return os; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec_) { for (ll i = 0; i < vec_.size(); ++i) os << vec_[i] << (i + 1 == vec_.size() ? "" : " "); return os; } template <typename T> ostream &operator<<(ostream &os, const vector<vector<T>> &vec_) { for (ll i = 0; i < vec_.size(); ++i) { for (ll j = 0; j < vec_[i].size(); ++j) { os << vec_[i][j] << " "; } os << endl; } return os; } template <typename T, typename U> ostream &operator<<(ostream &os, const map<T, U> &m) { os << endl; for (auto &&v : m) os << v << endl; return os; } template <typename T, typename U> ostream &operator<<(ostream &os, const unordered_map<T, U> &m) { os << endl; for (auto &&v : m) os << v << endl; return os; } template <typename T, typename U> string deb_tos(const unordered_map<T, U> &m) { map<T, U> a; for (auto &&v : m) { a[v.first] = v.second; } stringstream ss; ss << a; return ss.str(); } template <class T> ostream &operator<<(ostream &os, const set<T> &s) { fora(v, s) { os << v << " "; } return os; } template <class T> ostream &operator<<(ostream &os, const mset<T> &s) { fora(v, s) { os << v << " "; } return os; } template <class T> ostream &operator<<(ostream &os, const deque<T> &a) { fora(v, a) { os << v << " "; } return os; } ostream &operator<<(ostream &os, const vector<vector<char>> &vec_) { rep(h, sz(vec_)) { rep(w, sz(vec_[0])) { os << vec_[h][w]; } os << endl; } return os; } ostream &operator<<(ostream &os, const vector<vector<my_optional<char>>> &vec_) { rep(h, sz(vec_)) { rep(w, sz(vec_[0])) { os << vec_[h][w]; } os << endl; } return os; } // tuple "," 区切り #if __cplusplus >= 201703L template <class Tuple, size_t... Indicies> void helper_os_tuple(ostream &os, const Tuple &tup, index_sequence<Indicies...>) { stringstream ss; auto f = [&](auto a) { ss << ", " << a; }; (..., f(get<Indicies>(tup))); os << ss.str().substr(2); } template <class... T> ostream &operator<<(ostream &os, const tuple<T...> &tup) { helper_os_tuple(os, tup, index_sequence_for<T...>{}); return os; } #endif template <class T> struct range_now { int l; vector<T> A; range_now(vector<T> &&A, int l) : A(A), l(l) {} }; /*@formatter:off*/ // template<class T,class U>ostream &operator<<(ostream &os, vector<pair<T,U>>& // a) {fora_f(v,a)os<<v<<endl;return os;} template <typename W, typename H> void resize(W &vec_, const H head) { vec_.resize(head); } template <typename W, typename H, typename... T> void resize(W &vec_, const H &head, const T... tail) { vec_.resize(head); for (auto &v : vec_) resize(v, tail...); } // #define use_for_each //_each _all_of _any_of _none_of _find_if _rfind_if // _contains _count_if _erase_if _entry_if #ifdef use_for_each // todo Atcoderの過去問がc++17に対応したら #if __cplusplus >= 201703L // for_each以外はconst & (呼び出し側のラムダも) template <typename T, typename F> bool all_of2(const T &v, F f) { if constexpr (has_value_type<T>::value) { for (auto &&v_ : v) { if (!all_of2(v_, f)) return false; } return true; } else { return f(v); } } template <typename T, typename F> bool any_of2(const T &v, F f) { if constexpr (has_value_type<T>::value) { for (auto &&v_ : v) { if (any_of2(v_, f)) return true; } return false; } else { return f(v); } } template <typename T, typename F> bool none_of2(const T &v, F f) { return all_of2(v, [&](auto a) { return !f(a); }); } /*@formatter:off*/ // 存在しない場合 // 1次元 Nを返す // 多次元-1を返す template <typename T, typename F> ll find_if2(const vector<T> &v, F f) { rep(i, sz(v)) { if (f(v[i])) return i; } return sz(v); } template <typename T, typename F> tuple<int, int> find_if2(const vector<vector<T>> &v, F f) { rep(i, sz(v)) { rep(j, sz(v[i])) { if (f(v[i][j])) { return tuple<int, int>(i, j); } } } return tuple<int, int>(-1, -1); } template <typename T, typename F> auto find_if2(const vector<vector<vector<T>>> &v, F f) { rep(i, sz(v)) { if (auto ret = find_if2(v[i], f); get<0>(ret) != -1) { return tuple_cat(tuple<int>(i), ret); } } auto bad = tuple_cat(tuple<int>(-1), find_if2(v[0], f)); return bad; } template <class T, class F> auto find_if2(const range_now<T> &v, F f) { return find_if2(v.A, f) + v.l; } // 存在しない場合 // 1次元 -1を返す // 多次元-1を返す template <typename T, typename F> ll rfind_if2(const vector<T> &v, F f) { rer(i, sz(v) - 1) { if (f(v[i])) return i; } return -1; } template <typename T, typename F> tuple<int, int> rfind_if2(const vector<vector<T>> &v, F f) { rer(i, sz(v) - 1) { rer(j, sz(v[i]) - 1) { if (f(v[i][j])) { return tuple<int, int>(i, j); } } } return tuple<int, int>(-1, -1); } template <typename T, typename F> auto rfind_if2(const vector<vector<vector<T>>> &v, F f) { rer(i, sz(v) - 1) { if (auto ret = rfind_if2(v[i], f); get<0>(ret) != -1) { return tuple_cat(tuple<int>(i), ret); } } auto bad = tuple_cat(tuple<int>(-1), rfind_if2(v[0], f)); return bad; } // todo まとめられそう string,vector全般 template <class T> bool contains(const string &s, const T &v) { return s.find(v) != string::npos; } template <typename T> bool contains(const vector<T> &v, const T &val) { return std::find(v.begin(), v.end(), val) != v.end(); } template <typename T, typename F> bool contains_if2(const vector<T> &v, F f) { return find_if(v.begin(), v.end(), f) != v.end(); } template <typename T, typename F> ll count_if2(const T &v, F f) { if constexpr (has_value_type<T>::value) { ll ret = 0; for (auto &&v_ : v) { ret += count_if2(v_, f); } return ret; } else { return f(v); } } template <typename T, typename F> void for_each2(T &a, F f) { if constexpr (has_value_type<T>::value) { for (auto &&v_ : a) for_each2(v_, f); } else { f(a); } } #else template <typename T, typename F> bool all_of2(const T &v, F f) { return f(v); } template <typename T, typename F> bool all_of2(const vector<T> &v, F f) { rep(i, sz(v)) { if (!all_of2(v[i], f)) return false; } return true; } template <typename T, typename F> bool any_of2(const T &v, F f) { return f(v); } template <typename T, typename F> bool any_of2(const vector<T> &v, F f) { rep(i, sz(v)) { if (any_of2(v[i], f)) return true; } return false; } template <typename T, typename F> bool none_of2(const T &v, F f) { return f(v); } template <typename T, typename F> bool none_of2(const vector<T> &v, F f) { rep(i, sz(v)) { if (none_of2(v[i], f)) return false; } return true; } template <typename T, typename F> bool find_if2(const T &v, F f) { return f(v); } template <typename T, typename F> ll find_if2(const vector<T> &v, F f) { rep(i, sz(v)) { if (find_if2(v[i], f)) return i; } return sz(v); } template <typename T, typename F> bool rfind_if2(const T &v, F f) { return f(v); } template <typename T, typename F> ll rfind_if2(const vector<T> &v, F f) { rer(i, sz(v) - 1) { if (rfind_if2(v[i], f)) return i; } return -1; } template <class T> bool contains(const string &s, const T &v) { return s.find(v) != string::npos; } template <typename T> bool contains(const vector<T> &v, const T &val) { return std::find(v.begin(), v.end(), val) != v.end(); } template <typename T, typename F> bool contains_if2(const vector<T> &v, F f) { return find_if(v.begin(), v.end(), f) != v.end(); } template <typename T, typename F> ll count_if2(const T &v, F f) { return f(v); } template <typename T, typename F> ll count_if2(const vector<T> &vec_, F f) { ll ret = 0; fora(v, vec_) { ret += count_if2(v, f); } return ret; } template <typename T, typename F> void for_each2(T &a, F f) { f(a); } template <typename T, typename F> void for_each2(vector<T> &a, F f) { for (auto &&v_ : a) for_each2(v_, f); } #endif template <typename W> ll count_od(const vector<W> &a) { return count_if2(a, [](ll v) { return v & 1; }); } template <typename W> ll count_ev(const vector<W> &a) { return count_if2(a, [](ll v) { return !(v & 1); }); } // 削除した後のvectorを返す template <typename T, typename F> vector<T> erase_if2(const vector<T> &v, F f) { vector<T> nv; rep(i, sz(v)) { if (!f(v[i])) { nv.push_back(v[i]); } } return nv; } template <typename T, typename F> vector<vector<T>> erase_if2(const vector<vector<T>> &v, F f) { vector<vector<T>> res; rep(i, sz(v)) { res[i] = erase_if2(v[i], f); } return res; } template <typename T, typename F> vector<T> entry_if2(const vector<T> &v, F f) { vector<T> nv; rep(i, sz(v)) { if (f(v[i])) { nv.push_back(v[i]); } } return nv; } template <typename T, typename F> vector<vector<T>> entry_if2(const vector<vector<T>> &v, F f) { vector<vector<T>> res; rep(i, sz(v)) { res[i] = entry_if2(v[i], f); } return res; } template <typename T, typename F> ll l_rfind_if(const vector<T> &v, F f) { rer(i, sz(v) - 1) { if (f(v[i])) return i; } return -1; } template <typename T, typename F> bool l_contains_if(const vector<T> &v, F f) { rer(i, sz(v) - 1) { if (f(v[i])) return true; } return false; } template <class A, class B, class C> auto t_all_of(A a, B b, C c) { return std::all_of(a, b, c); } template <class A, class B, class C> auto t_any_of(A a, B b, C c) { return std::any_of(a, b, c); } template <class A, class B, class C> auto t_none_of(A a, B b, C c) { return std::none_of(a, b, c); } template <class A, class B, class C> auto t_find_if(A a, B b, C c) { return std::find_if(a, b, c); } template <class A, class B, class C> auto t_count_if(A a, B b, C c) { return std::count_if(a, b, c); } #define all_of_s__2(a, right) (t_all_of(ALL(a), lamr(right))) #define all_of_s__3(a, v, siki) (t_all_of(ALL(a), [&](auto v) { return siki; })) #define all_of_s(...) over3(__VA_ARGS__, all_of_s__3, all_of_s__2)(__VA_ARGS__) // all_of(A, %2); // all_of(A, a, a%2); #define all_of__2(a, right) all_of2(a, lamr(right)) #define all_of__3(a, v, siki) all_of2(a, [&](auto v) { return siki; }) #define all_of(...) over3(__VA_ARGS__, all_of__3, all_of__2)(__VA_ARGS__) #define all_of_f(a, f) all_of2(a, f) #define any_of_s__2(a, right) (t_any_of(ALL(a), lamr(right))) #define any_of_s__3(a, v, siki) (t_any_of(ALL(a), [&](auto v) { return siki; })) #define any_of_s(...) over3(__VA_ARGS__, any_of_s__3, any_of_s__2)(__VA_ARGS__) #define any_of__2(a, right) any_of2(a, lamr(right)) #define any_of__3(a, v, siki) any_of2(a, [&](auto v) { return siki; }) #define any_of(...) over3(__VA_ARGS__, any_of__3, any_of__2)(__VA_ARGS__) #define any_of_f(a, f) any_of2(a, f) #define none_of_s__2(a, right) (t_none_of(ALL(a), lamr(right))) #define none_of_s__3(a, v, siki) \ (t_none_of(ALL(a), [&](auto v) { return siki; })) #define none_of_s(...) \ over3(__VA_ARGS__, none_of_s__3, none_of_s__2)(__VA_ARGS__) #define none_of__2(a, right) none_of2(a, lamr(right)) #define none_of__3(a, v, siki) none_of2(a, [&](auto v) { return siki; }) #define none_of(...) over3(__VA_ARGS__, none_of__3, none_of__2)(__VA_ARGS__) #define none_of_f(a, f) none_of2(a, f) #define find_if_s__2(a, right) (t_find_if(ALL(a), lamr(right)) - a.begin()) #define find_if_s__3(a, v, siki) \ (t_find_if(ALL(a), [&](auto v) { return siki; }) - a.begin()) #define find_if_s(...) \ over3(__VA_ARGS__, find_if_s__3, find_if_s__2)(__VA_ARGS__) #define find_if__2(a, right) find_if2(a, lamr(right)) #define find_if__3(a, v, siki) find_if2(a, [&](auto v) { return siki; }) #define find_if__4(a, l, v, siki) \ (find_if2(decltype(a)(a.begin() + l, a.end()), \ [&](auto v) { return siki; }) + \ l) #define find_if(...) \ over4(__VA_ARGS__, find_if__4, find_if__3, find_if__2)(__VA_ARGS__) #define find_if_f(a, f) find_if2(a, f) #define rfind_if_s__2(a, right) l_rfind_if(a, lamr(right)) #define rfind_if_s__3(a, v, siki) l_rfind_if(a, [&](auto v) { return siki; }) #define rfind_if_s(...) \ over3(__VA_ARGS__, rfind_if_s__3, rfind_if_s__2)(__VA_ARGS__) #define rfind_if__2(a, right) rfind_if2(a, lamr(right)) #define rfind_if__3(a, v, siki) rfind_if2(a, [&](auto v) { return siki; }) #define rfind_if(...) over3(__VA_ARGS__, rfind_if__3, rfind_if__2)(__VA_ARGS__) #define rfind_if_f(a, f) rfind_if2(a, f) #define contains_if_s__2(a, right) l_contains_if(a, lamr(right)) #define contains_if_s__3(a, v, siki) \ l_contains_if(a, [&](auto v) { return siki; }) #define contains_if_s(...) \ over3(__VA_ARGS__, contains_if_s__3, contains_if_s__2)(__VA_ARGS__) #define contains_if__2(a, right) contains_if2(a, lamr(right)) #define contains_if__3(a, v, siki) contains_if2(a, [&](auto v) { return siki; }) #define contains_if(...) \ over3(__VA_ARGS__, contains_if__3, contains_if__2)(__VA_ARGS__) #define contains_if_f(a, f) contains_if2(a, f) #define count_if_s__2(a, right) (t_count_if(ALL(a), lamr(right))) #define count_if_s__3(a, v, siki) \ (t_count_if(ALL(a), [&](auto v) { return siki; })) #define count_if_s(...) \ over3(__VA_ARGS__, count_if_s__3, count_if_s__2)(__VA_ARGS__) #define count_if__2(a, right) count_if2(a, lamr(right)) #define count_if__3(a, v, siki) count_if2(a, [&](auto v) { return siki; }) #define count_if(...) over3(__VA_ARGS__, count_if__3, count_if__2)(__VA_ARGS__) #define count_if_f(a, f) count_if2(a, f) // vector<vi>で、viに対して操作 #define for_each_s__2(a, right) \ do { \ fora(v, a) { v right; } \ } while (0) #define for_each_s__3(a, v, shori) \ do { \ fora(v, a) { shori; } \ } while (0) #define for_each_s(...) \ over3(__VA_ARGS__, for_each_s__3, for_each_s__2)(__VA_ARGS__) // vector<vi>で、intに対して操作 #define for_each__2(a, right) for_each2(a, lamr(right)) #define for_each__3(a, v, shori) for_each2(a, [&](auto &v) { shori; }) #define for_each(...) over3(__VA_ARGS__, for_each__3, for_each__2)(__VA_ARGS__) #define for_each_f(a, f) for_each2(a, f); template <class T, class F> vector<T> help_for_eached(const vector<T> &A, F f) { vector<T> ret = A; for_each(ret, v, f(v)); return ret; } #define for_eached__2(a, right) help_for_eached(a, lamr(right)) #define for_eached__3(a, v, shori) help_for_eached(a, lam(v, shori)) #define for_eached(...) \ over3(__VA_ARGS__, for_eached__3, for_eached__2)(__VA_ARGS__) #define for_eached_f(a, f) for_eached2(a, f); #define each for_each #define eached for_eached // #define erase_if_s__2(a, right) l_erase_if2(a,lamr(right)) // #define erase_if_s__3(a, v, siki) l_erase_if2(a,[&](auto v){return siki;}) // #define erase_if_s(...) // over3(__VA_ARGS__,erase_if_s__3,erase_if_s__2)(__VA_ARGS__) #define erase_if__2(a, right) erase_if2(a, lamr(right)) #define erase_if__3(a, v, siki) erase_if2(a, [&](auto v) { return siki; }) #define erase_if(...) over3(__VA_ARGS__, erase_if__3, erase_if__2)(__VA_ARGS__) #define erase_if_f(a, f) erase_if2(a, f) // #define entry_if_s__2(a, right) l_entry_if2(a,lamr(right)) // #define entry_if_s__3(a, v, siki) l_entry_if2(a,[&](auto v){return siki;}) // #define entry_if_s(...) // over3(__VA_ARGS__,entry_if_s__3,entry_if_s__2)(__VA_ARGS__) #define entry_if__2(a, right) entry_if2(a, lamr(right)) #define entry_if__3(a, v, siki) entry_if2(a, [&](auto v) { return siki; }) #define entry_if(...) over3(__VA_ARGS__, entry_if__3, entry_if__2)(__VA_ARGS__) #define entry_if_f(a, f) entry_if2(a, f) #endif // 機能削除 todo // string.replace()は長さを指定するため、間違えやすい /*@formatter:off*/ void replace(str &a, char key, char v) { replace(ALL(a), key, v); } template <class T, class U> void my_replace(T &s, int l, int r, const U &t) { s.replace(l, r - l, t); } #define replace my_replace template <class T, class U, class W> void replace(vector<W> &a, T key, U v) { rep(i, sz(a)) if (a[i] == key) a[i] = v; } template <class T, class U, class W> void replace(vector<vector<W>> &A, T key, U v) { rep(i, sz(A)) replace(A[i], key, v); } void replace(str &a, char key, str v) { if (v == "") a.erase(remove(ALL(a), key), a.end()); } // keyと同じかどうか01で置き換える template <class T, class U> void replace(vector<T> &a, U k) { rep(i, sz(a)) a[i] = a[i] == k; } template <class T, class U> void replace(vector<vector<T>> &a, U k) { rep(i, sz(a)) rep(j, sz(a[0])) a[i][j] = a[i][j] == k; } void replace(str &a) { int dec = 0; if ('a' <= a[0] && a[0] <= 'z') dec = 'a'; if ('A' <= a[0] && a[0] <= 'Z') dec = 'A'; fora(v, a) { v -= dec; } } void replace(string &a, char key) { string res; for (auto c : a) { if (c != key) res.push_back(c); } swap(a, res); } void replace(str &a, str key, str v) { stringstream t; ll kn = sz(key); std::string::size_type Pos(a.find(key)); ll l = 0; while (Pos != std::string::npos) { t << a.substr(l, Pos - l); t << v; l = Pos + kn; Pos = a.find(key, Pos + kn); } t << a.substr(l, sz(a) - l); a = t.str(); } template <class T> bool is_permutation(vector<T> &a, vector<T> &b) { return is_permutation(ALL(a), ALL(b)); } template <class T> bool next_permutation(vector<T> &a) { return next_permutation(ALL(a)); } vi iota(ll s, ll len) { vi ve(len); iota(ALL(ve), s); return ve; } //[iterator, iterator)等と渡す // vectorに変換もできる #if __cplusplus >= 201703L template <class I, class J> struct body_range { I itl; J itr; body_range(I it, J end) : itl(it), itr(end) {} I begin() { return itl; } I end() { return itr; } // 毎回コピーする operator vector<typename I::value_type>() { return vector<typename I::value_type>(itl, itr); } }; template <class I, class J, require_t(is_integral_v<I>)> vector<int> range(I l, J r) { return iota(l, r - l); } template <class I, require_t(is_integral_v<I>)> vector<int> range(I r) { return iota(0, r); } template <class I, require_t(!is_integral_v<I>)> auto range(I itl, I itr) { return body_range(itl, itr); } #endif /*@formatter:off*/ // tuple<vecs...> = take_vt(vt) #if __cplusplus >= 201703L template <class Tup_l, class Tup_r, size_t... Indicies> auto helper_take_vector_tuple(Tup_l &res, const Tup_r &rhs, index_sequence<Indicies...>) { (..., get<Indicies>(res).emplace_back(get<Indicies>(rhs))); } template <class... T> auto take_vector_tuple(const vector<tuple<T...>> &elems) { tuple<vector<T>...> res; for (auto &&elem : elems) { helper_take_vector_tuple(res, elem, index_sequence_for<T...>{}); } return res; } // tie_vt(A,B,C) = vt; template <class... T> struct tie_vector_tuple { tuple<vector<T> &...> v; tie_vector_tuple(vector<T> &...args) : v(args...) {} template <class Tup, size_t... Indicies> void helper_emplace(int i, Tup &rhs, index_sequence<Indicies...>) { (..., (get<Indicies>(v).emplace_back(get<Indicies>(rhs)))); } template <size_t... Indicies> void clear(index_sequence<Indicies...>) { (..., (get<Indicies>(v).clear())); } void operator=(vector<tuple<T...>> &rhs) { clear(index_sequence_for<T...>{}); rep(i, sz(rhs)) { helper_emplace(i, rhs[i], index_sequence_for<T...>{}); } } }; /*@formatter:off*/ // vt = make_vt(A, B, C) template <class H, class... T> auto make_vector_tuple(const vector<H> &head, const vector<T> &...tails) { vector<tuple<H, T...>> res; rep(i, sz(head)) { res.emplace_back(head[i], tails[i]...); } return res; } #endif /*@formatter:off*/ #define mvt make_vector_tuple #define tie_vt tie_vector_tuple #define make_vt make_vector_tuple #define take_vt take_vector_tuple /*@formatter:off*/ // 基本ソート@0 template <class T> void sort(vector<T> &a, int l = -1, int r = -1) { set_lr12(l, r, sz(a)); fast_sort(a.begin() + l, a.begin() + r); } template <class T> void rsort(vector<T> &a, int l = -1, int r = -1) { set_lr12(l, r, sz(a)); fast_sort(a.begin() + l, a.begin() + r, greater<T>()); }; // f(tup)の大きさでソート template <class U, class F> void sort(vector<U> &a, F f) { fast_sort(ALL(a), [&](U l, U r) { return f(l) < f(r); }); }; template <class U, class F> void rsort(vector<U> &a, F f) { fast_sort(ALL(a), [&](U l, U r) { return f(l) > f(r); }); }; enum tuple_comparator { /*tcom_less = 1728, tcom_greater = 1729, */ fisi = 0, fisd, fdsi, fdsd, sifi, sifd, sdfi, sdfd, fisiti, fisitd, fisdti, fisdtd, fdsiti, fdsitd, fdsdti, fdsdtd, fitisi, fitisd, fitdsi, fitdsd, fdtisi, fdtisd, fdtdsi, fdtdsd, sifiti, sifitd, sifdti, sifdtd, sdfiti, sdfitd, sdfdti, sdfdtd, sitifi, sitifd, sitdfi, sitdfd, sdtifi, sdtifd, sdtdfi, sdfdfd, tifisi, tifisd, tifdsi, tifdsd, tdfisi, tdfisd, tdfdsi, tdfdsd, tisifi, tisifd, tisdfi, tisdfd, tdsifi, tdsifd, tdsdfi, tdsdfd }; // todo 短くする #define set_4(i0, i1, o0, o1) \ [&](U l, U r) { \ return get<i0>(l) != get<i0>(r) ? get<i0>(l) o0 get<i0>(r) \ : get<i1>(l) o1 get<i1>(r); \ } #define set_6(i0, i1, i2, o0, o1, o2) \ [&](U l, U r) { \ return get<i0>(l) != get<i0>(r) ? get<i0>(l) o0 get<i0>(r) \ : get<i1>(l) != get<i1>(r) ? get<i1>(l) o1 get<i1>(r) \ : get<i2>(l) o2 get<i2>(r); \ } // functionを返すため少し遅い todo #if __cplusplus >= 201703L template <class... T, class U = tuple<T...>> function<bool(U, U)> get_function2(const vector<tuple<T...>> &a, tuple_comparator Compare) { if constexpr (sizeof...(T) >= 2) { int type = Compare; if (type == 0) return set_4(0, 1, <, <); if (type == 1) return set_4(0, 1, <, >); if (type == 2) return set_4(0, 1, >, <); if (type == 3) return set_4(0, 1, >, >); if (type == 4) return set_4(1, 0, <, <); if (type == 5) return set_4(1, 0, <, >); if (type == 6) return set_4(1, 0, >, <); if (type == 7) return set_4(1, 0, >, >); } if constexpr (sizeof...(T) >= 3) { int type = Compare - 8; if (type == 0) return set_6(0, 1, 2, <, <, <); else if (type == 1) return set_6(0, 1, 2, <, <, >); else if (type == 2) return set_6(0, 1, 2, <, >, <); else if (type == 3) return set_6(0, 1, 2, <, >, >); else if (type == 4) return set_6(0, 1, 2, >, <, <); else if (type == 5) return set_6(0, 1, 2, >, <, >); else if (type == 6) return set_6(0, 1, 2, >, >, <); else if (type == 7) return set_6(0, 1, 2, >, >, >); else if (type == 8) return set_6(0, 2, 1, <, <, <); else if (type == 9) return set_6(0, 2, 1, <, <, >); else if (type == 10) return set_6(0, 2, 1, <, >, <); else if (type == 11) return set_6(0, 2, 1, <, >, >); else if (type == 12) return set_6(0, 2, 1, >, <, <); else if (type == 13) return set_6(0, 2, 1, >, <, >); else if (type == 14) return set_6(0, 2, 1, >, >, <); else if (type == 15) return set_6(0, 2, 1, >, >, >); else if (type == 16) return set_6(1, 0, 2, <, <, <); else if (type == 17) return set_6(1, 0, 2, <, <, >); else if (type == 18) return set_6(1, 0, 2, <, >, <); else if (type == 19) return set_6(1, 0, 2, <, >, >); else if (type == 20) return set_6(1, 0, 2, >, <, <); else if (type == 21) return set_6(1, 0, 2, >, <, >); else if (type == 22) return set_6(1, 0, 2, >, >, <); else if (type == 23) return set_6(1, 0, 2, >, >, >); else if (type == 24) return set_6(1, 2, 0, <, <, <); else if (type == 25) return set_6(1, 2, 0, <, <, >); else if (type == 26) return set_6(1, 2, 0, <, >, <); else if (type == 27) return set_6(1, 2, 0, <, >, >); else if (type == 28) return set_6(1, 2, 0, >, <, <); else if (type == 29) return set_6(1, 2, 0, >, <, >); else if (type == 30) return set_6(1, 2, 0, >, >, <); else if (type == 31) return set_6(1, 2, 0, >, >, >); else if (type == 32) return set_6(2, 0, 1, <, <, <); else if (type == 33) return set_6(2, 0, 1, <, <, >); else if (type == 34) return set_6(2, 0, 1, <, >, <); else if (type == 35) return set_6(2, 0, 1, <, >, >); else if (type == 36) return set_6(2, 0, 1, >, <, <); else if (type == 37) return set_6(2, 0, 1, >, <, >); else if (type == 38) return set_6(2, 0, 1, >, >, <); else if (type == 39) return set_6(2, 0, 1, >, >, >); else if (type == 40) return set_6(2, 1, 0, <, <, <); else if (type == 41) return set_6(2, 1, 0, <, <, >); else if (type == 42) return set_6(2, 1, 0, <, >, <); else if (type == 43) return set_6(2, 1, 0, <, >, >); else if (type == 44) return set_6(2, 1, 0, >, <, <); else if (type == 45) return set_6(2, 1, 0, >, <, >); else if (type == 46) return set_6(2, 1, 0, >, >, <); else if (type == 47) return set_6(2, 1, 0, >, >, >); } return [&](U l, U r) { return true; }; } template <class... T> void sort(vector<tuple<T...>> &a, tuple_comparator Compare) { auto f = get_function2(a, Compare); fast_sort(ALL(a), f); } #endif /*@formatter:off*/ #undef set_4 #undef set_6 #if __cplusplus >= 201703L // sort_tuple template <class H1, class H2, class... T> void sortt(vector<H1> &head1, vector<H2> &head2, vector<T> &...tails) { auto vec_t = make_vt(head1, head2, tails...); sort(vec_t); tie_vt(head1, head2, tails...) = vec_t; } template <class H1, class H2, class... T> void rsortt(vector<H1> &head1, vector<H2> &head2, vector<T> &...tails) { auto vec_t = make_vt(head1, head2, tails...); rsort(vec_t); tie_vt(head1, head2, tails...) = vec_t; } template <class F, class... T> void helper_sortt_f(F f, vector<T> &...a) { auto z = make_vt(a...); sort(z, f); tie_vt(a...) = z; } template <class F, class... T> void helper_rsortt_f(F f, vector<T> &...a) { auto z = make_vt(a...); rsort(z, f); tie_vt(a...) = z; } // sortt(a,b,c,d, f)まで対応-> template <class A, class B, class F, require_t(!is_vector<F>::value)> void sortt(vector<A> &a, vector<B> &b, F f) { helper_sortt_f(f, a, b); } template <class A, class B, class F, require_t(!is_vector<F>::value)> void rsortt(vector<A> &a, vector<B> &b, F f) { helper_rsortt_f(f, a, b); } template <class A, class B, class C, class F, require_t(!is_vector<F>::value)> void sortt(vector<A> &a, vector<B> &b, vector<C> &c, F f) { helper_sortt_f(f, a, b, c); } template <class A, class B, class C, class F, require_t(!is_vector<F>::value)> void rsortt(vector<A> &a, vector<B> &b, vector<C> &c, F f) { helper_rsortt_f(f, a, b, c); } template <class A, class B, class C, class D, class F, require_t(!is_vector<F>::value)> void sortt(vector<A> &a, vector<B> &b, vector<C> &c, vector<D> &d, F f) { helper_sortt_f(f, a, b, c, d); } template <class A, class B, class C, class D, class F, require_t(!is_vector<F>::value)> void rsortt(vector<A> &a, vector<B> &b, vector<C> &c, vector<D> &d, F f) { helper_rsortt_f(f, a, b, c, d); } // sort_tuple f } #endif /*@formatter:off*/ // 任意引数は取らない template <class T> vi sorti(const vector<T> &a) { auto b = a; vi ind = iota(0, sz(b)); sortt(b, ind); return ind; } template <class T> vi rsorti(const vector<T> &a) { auto b = a; vi ind = iota(0, sz(b)); rsortt(b, ind); return ind; } #if __cplusplus >= 201703L template <class T, class F> vi sorti(const vector<T> &a, F f) { vi ind = iota(0, sz(a)); if constexpr (is_same_v<F, tuple_comparator>) { auto f2 = get_function2(a, f); auto g = [&](int i, int j) { return f2(a[i], a[j]); }; fast_sort(ALL(ind), g); } else { auto g = [&](int i) { return f(a[i]); }; sort(ind, g); } return ind; } template <class T, class F, require_t(is_function_v<F>)> vi rsorti(const vector<T> &a, F f) { vi ind = iota(0, sz(a)); auto g = [&](int i) { return f(a[i]); }; rsort(ind, g); return ind; } // 任意引数にfを渡したい場合は (make_vt(a, b, c), f) template <class H, class... Ts> vi sortti(vector<H> head, vector<Ts>... tails) { vi ind = iota(0, sz(head)); auto vec = make_vt(head, tails..., ind); sort(vec); auto rets = take_vt(vec); return get<sizeof...(tails) + 1>(rets); } template <class H, class... Ts> vi rsortti(vector<H> head, vector<Ts>... tails) { vi ind = iota(0, sz(head)); auto vec = make_vt(head, tails..., ind); rsort(vec); auto rets = take_vt(vec); return get<sizeof...(tails) + 1>(rets); } #endif /*@formatter:off*/ //@5 void sort(string &a) { sort(ALL(a)); } void rsort(string &a) { sort(RALL(a)); } void sort(int &a, int &b) { if (a > b) swap(a, b); } void sort(int &a, int &b, int &c) { sort(a, b); sort(a, c); sort(b, c); } void rsort(int &a, int &b) { if (a < b) swap(a, b); } void rsort(int &a, int &b, int &c) { rsort(a, b); rsort(a, c); rsort(b, c); } template <class... T, class U> auto sorted(U head, T... a) { sort(head, a...); return head; } template <class... T, class U> auto rsorted(U head, T... a) { rsort(head, a...); return head; } template <class T> bool includes(vector<T> &a, vector<T> &b) { vi c = a; vi d = b; sort(c); sort(d); return includes(ALL(c), ALL(d)); } template <class T> bool distinct(const vector<T> &A) { if ((int)(A).size() == 1) return true; if ((int)(A).size() == 2) return A[0] != A[1]; if ((int)(A).size() == 3) return (A[0] != A[1] && A[1] != A[2] && A[0] != A[2]); auto B = A; sort(B); int N = (B.size()); unique(B); return N == (int)(B.size()); } template <class H, class... T> bool distinct(const H &a, const T &...b) { return distinct(vector<H>{a, b...}); } /*@formatter:off*/ template <class T, class U> void inc(pair<T, U> &a, U v = 1) { a.first += v, a.second += v; } template <class T, class U> void inc(T &a, U v = 1) { a += v; } template <class T, class U = int> void inc(vector<T> &a, U v = 1) { for (auto &u : a) inc(u, v); } template <class T, class U> void dec(T &a, U v = 1) { a -= v; } template <class T, class U = int> void dec(vector<T> &a, U v = 1) { for (auto &u : a) dec(u, v); } template <class U> void dec(string &a, U v = 1) { for (auto &u : a) dec(u, v); } template <class T, class U, class W> void dec(vector<T> &a, vector<U> &b, W v = 1) { for (auto &u : a) dec(u, v); for (auto &u : b) dec(u, v); } template <class T, class U, class W> void dec(vector<T> &a, vector<U> &b, vector<W> &c) { for (auto &u : a) dec(u, 1); for (auto &u : b) dec(u, 1); for (auto &u : c) dec(u, 1); } bool ins(ll h, ll w, ll H, ll W) { return h >= 0 && w >= 0 && h < H && w < W; } bool san(ll l, ll v, ll r) { return l <= v && v < r; } template <class T> bool ins(vector<T> &a, ll i, ll j = 0) { return san(0, i, sz(a)) && san(0, j, sz(a)); } #define inside ins ll u0(ll a) { return a < 0 ? 0 : a; } template <class T> vector<T> u0(vector<T> &a) { vector<T> ret = a; fora(v, ret) { v = u(v); } return ret; } // todo 名前 bool d_(int a, int b) { if (b == 0) return false; return (a % b) == 0; } // エラー void ole() { #ifdef _DEBUG cerr << "ole" << endl; exit(0); #endif string a = "a"; rep(i, 30) a += a; rep(i, 1 << 17) cout << a << endl; cout << "OLE 出力長制限超過" << endl; exit(0); } void re(string s = "") { cerr << s << endl; assert(0 == 1); exit(0); } void tle() { while (inf) cout << inf << endl; } //@汎用便利関数 入力 ll in() { ll ret; cin >> ret; return ret; } template <class T> T in() { T ret; cin >> ret; return ret; } string sin() { string ret; cin >> ret; return ret; } template <class T> void in(T &head) { cin >> head; } template <class T, class... U> void in(T &head, U &...tail) { cin >> head; in(tail...); } // value_typeを持つ場合呼べる // len回要素を追加する template <class Iterable, class T = typename Iterable::value_type> Iterable tin(int len) { Iterable ret; T tem; while (len--) { cin >> tem; ret += tem; } return ret; } template <class T> T tin() { T ret; cin >> ret; return ret; } template <class T> T tind(int len = 0) { auto ret = tin<T>(len); dec(ret, 1); return ret; } #define din_t2(type, a) \ type a; \ cin >> a #define din_t3(type, a, b) \ type a, b; \ cin >> a >> b #define din_t4(type, a, b, c) \ type a, b, c; \ cin >> a >> b >> c #define din_t5(type, a, b, c, d) \ type a, b, c, d; \ cin >> a >> b >> c >> d #define din_t6(type, a, b, c, d, e) \ type a, b, c, d, e; \ cin >> a >> b >> c >> d >> e #define din_t7(type, a, b, c, d, e, f) \ type a, b, c, d, e, f; \ cin >> a >> b >> c >> d >> e >> f #define din_t(...) \ over7(__VA_ARGS__, din_t7, din_t6, din_t5, din_t4, din_t3, \ din_t2)(__VA_ARGS__) #define din(...) din_t(int, __VA_ARGS__) #define d_in #define dsig(...) din_t(signed, __VA_ARGS__) #define dst(...) din_t(string, __VA_ARGS__) #define dstr dst #define d_str dst #define dcha(...) din_t(char, __VA_ARGS__) #define dchar dcha #define ddou(...) din_t(double, __VA_ARGS__) #define din1d(a) \ din_t2(int, a); \ a-- #define din2d(a, b) \ din_t3(int, a, b); \ a--, b-- #define din3d(a, b, c) \ din_t4(int, a, b, c); \ a--, b--, c-- #define din4d(a, b, c, d) \ din_t5(int, a, b, c, d); \ a--, b--, c--, d-- #define dind(...) over4(__VA_ARGS__, din4d, din3d, din2d, din1d)(__VA_ARGS__) /*@formatter:off*/ #ifdef _DEBUG template <class T> void err2(T &&head) { cerr << head; } template <class T, class... U> void err2(T &&head, U &&...tail) { cerr << head << " "; err2(tail...); } template <class T, class... U> void err(T &&head, U &&...tail) { cerr << head << " "; err2(tail...); cerr << "" << endl; } template <class T> void err(T &&head) { cerr << head << endl; } void err() { cerr << "" << endl; } // debで出力する最大長 constexpr int DEB_LEN = 20; constexpr int DEB_LEN_H = 12; string deb_tos(const int &v) { if (abs(v) == inf || abs(v) == linf) return "e"; else return to_string(v); } template <class T> string deb_tos(const T &a) { stringstream ss; ss << a; return ss.str(); } string deb_tos(const P &p) { stringstream ss; ss << "{"; ss << p.fi; ss << ", "; ss << p.se; ss << "}"; return ss.str(); } #ifdef use_epsdou string deb_tos(const epsdou &a) { return deb_tos(a.v); } #endif template <class T> string deb_tos(const optional<T> &a) { if (a.has_value()) { return deb_tos(a.value()); } else return "e"; } template <class T> string deb_tos(const vector<T> &a, ll W = inf) { stringstream ss; if (W == inf) W = min(sz(a), DEB_LEN); if (sz(a) == 0) return ss.str(); rep(i, W) { ss << deb_tos(a[i]); if (typeid(a[i]) == typeid(P)) { ss << endl; } else { ss << " "; } } return ss.str(); } template <class T> string deb_tos(const vector<vector<T>> &a, vi H, vi W, int key = -1) { stringstream ss; ss << endl; vi lens(sz(W)); fora(h, H) { rep(wi, sz(W)) { if (sz(a[h]) <= W[wi]) break; lens[wi] = max(lens[wi], sz(deb_tos(a[h][W[wi]])) + 1); lens[wi] = max(lens[wi], sz(deb_tos(W[wi])) + 1); } } if (key == -1) ss << " *|"; else ss << " " << key << "|"; int wi = 0; fora(w, W) { ss << std::right << std::setw(lens[wi]) << w; wi++; } ss << "" << endl; rep(i, sz(W)) rep(lens[i]) ss << "_"; rep(i, 3) ss << "_"; ss << "" << endl; fora(h, H) { ss << std::right << std::setw(2) << h << "|"; int wi = 0; fora(w, W) { if (sz(a[h]) <= w) break; ss << std::right << std::setw(lens[wi]) << deb_tos(a[h][w]); wi++; } ss << "" << endl; } return ss.str(); } template <class T> string deb_tos(const vector<vector<T>> &a, ll H = inf, ll W = inf, int key = -1) { H = (H != inf) ? H : min({H, sz(a), DEB_LEN_H}); W = min({W, sz(a[0]), DEB_LEN_H}); vi hs, ws; rep(h, H) { hs.push_back(h); } rep(w, W) { ws.push_back(w); } return deb_tos(a, hs, ws, key); } template <class T> string deb_tos(const vector<vector<vector<T>>> &a, ll H = inf) { stringstream ss; if (H == inf) H = DEB_LEN_H; H = min(H, sz(a)); rep(i, H) { ss << endl; ss << deb_tos(a[i], inf, inf, i); } return ss.str(); } template <class T> string deb_tos(vector<set<T>> &a, ll H = inf, ll W = inf, int key = -1) { vector<vector<T>> b(sz(a)); rep(i, sz(a)) { fora(v, a[i]) { b[i].push_back(v); } } return deb_tos(b, H, W, key); } template <class T, size_t A> string deb_tos(T (&a)[A]) { return deb_tos(vector<T>(begin(a), end(a))); } template <class T, size_t A, size_t B> string deb_tos(T (&a)[A][B]) { return deb_tos(vector<vector<T>>(begin(a), end(a))); } template <class T, size_t A, size_t B, size_t C> string deb_tos(T (&a)[A][B][C]) { return deb_tos(vector<vector<vector<T>>>(begin(a), end(a))); } /*@formatter:off*/ template <class T> void out2(T head) { cout << head; res_mes += deb_tos(head); } template <class T, class... U> void out2(T head, U... tail) { cout << head << " "; res_mes += deb_tos(head) + " "; out2(tail...); } template <class T, class... U> void out(T head, U... tail) { cout << head << " "; res_mes += deb_tos(head) + " "; out2(tail...); cout << "" << endl; res_mes += "\n"; } template <class T> void out(T head) { cout << head << endl; res_mes += deb_tos(head) + "\n"; } void out() { cout << "" << endl; } #else #define err(...) ; template <class T> void out2(T &&head) { cout << head; } template <class T, class... U> void out2(T &&head, U &&...tail) { cout << head << " "; out2(tail...); } template <class T, class... U> void out(T &&head, U &&...tail) { cout << head << " "; out2(tail...); cout << "" << endl; } template <class T> void out(T &&head) { cout << head << endl; } void out() { cout << "" << endl; } #endif template <class H, class... T> void outl(const vector<H> &h, const vector<T> &...t) { rep(i, sz(h)) out(h[i], t[i]...); } // テーブルをスペースなしで出力 template <class T> void outt(vector<vector<T>> &a) { rep(i, sz(a)) { rep(j, sz(a[i])) { cout << a[i][j]; } cout << endl; } } // int型をbit表記で出力 void outb(int a) { cout << bitset<20>(a) << endl; } /*@formatter:off*/ template <class T> void na(vector<T> &a, ll n) { a.resize(n); rep(i, n) cin >> a[i]; } template <class T> void na(set<T> &a, ll n) { rep(i, n) a.insert(in()); } #define dna(a, n) \ vi a; \ na(a, n); /*nを複数使うと n==in()の時バグる事に注意*/ #define dnad(a, n) \ vi a; \ nad(a, n); template <class T> void nao(vector<T> &a, ll n) { a.resize(n + 1); a[0] = 0; rep(i, n) cin >> a[i + 1]; } template <class T> void naod(vector<T> &a, ll n) { a.resize(n + 1); a[0] = 0; rep(i, n) cin >> a[i + 1], a[i + 1]--; } template <class T> void nad(vector<T> &a, ll n) { a.resize(n); rep(i, n) cin >> a[i], a[i]--; } template <class T> void nad(set<T> &a, ll n) { rep(i, n) a.insert(in() - 1); } template <class T, class U> void na2(vector<T> &a, vector<U> &b, ll n) { a.resize(n); b.resize(n); rep(i, n) cin >> a[i] >> b[i]; } template <class T, class U> void na2(set<T> &a, set<U> &b, ll n) { rep(i, n) { a.insert(in()); b.insert(in()); } } #define dna2(a, b, n) \ vi a, b; \ na2(a, b, n); template <class T, class U> void nao2(vector<T> &a, vector<U> &b, ll n) { a.resize(n + 1); b.resize(n + 1); a[0] = b[0] = 0; rep(i, n) cin >> a[i + 1] >> b[i + 1]; } #define dnao2(a, b, n) \ vi a, b; \ nao2(a, b, n); template <class T, class U> void na2d(vector<T> &a, vector<U> &b, ll n) { a.resize(n); b.resize(n); rep(i, n) cin >> a[i] >> b[i], a[i]--, b[i]--; } #define dna2d(a, b, n) \ vi a, b; \ na2d(a, b, n); template <class T, class U, class W> void na3(vector<T> &a, vector<U> &b, vector<W> &c, ll n) { a.resize(n); b.resize(n); c.resize(n); rep(i, n) cin >> a[i] >> b[i] >> c[i]; } #define dna3(a, b, c, n) \ vi a, b, c; \ na3(a, b, c, n); template <class T, class U, class W> void na3d(vector<T> &a, vector<U> &b, vector<W> &c, ll n) { a.resize(n); b.resize(n); c.resize(n); rep(i, n) cin >> a[i] >> b[i] >> c[i], a[i]--, b[i]--, c[i]--; } #define dna3d(a, b, c, n) \ vi a, b, c; \ na3d(a, b, c, n); template <class T, class U, class W, class X> void na4(vector<T> &a, vector<U> &b, vector<W> &c, vector<X> &d, ll n) { a.resize(n); b.resize(n); c.resize(n); d.resize(n); rep(i, n) cin >> a[i] >> b[i] >> c[i] >> d[i]; } #define dna4(a, b, c, d, n) \ vi a, b, c, d; \ na4(a, b, c, d, n); #define dna4d(a, b, c, d, n) \ vi a, b, c, d; \ na4d(a, b, c, d, n); #define nt(a, h, w) \ resize(a, h, w); \ rep(nthi, h) rep(ntwi, w) cin >> a[nthi][ntwi]; #define ntd(a, h, w) \ resize(a, h, w); \ rep(ntdhi, h) rep(ntdwi, w) cin >> a[ntdhi][ntdwi], a[ntdhi][ntdwi]--; #define ntp(a, h, w) \ resize(a, h + 2, w + 2); \ fill(a, '#'); \ rep(ntphi, 1, h + 1) rep(ntpwi, 1, w + 1) cin >> a[ntphi][ntpwi]; #define dnt(S, h, w) \ vvi(S, h, w); \ nt(S, h, w); #define dntc(S, h, w) \ vvc(S, h, w); \ nt(S, h, w); #define dnts(S, h, w) \ vvs(S, h, w); \ nt(S, h, w); // デバッグ #define sp << " " << /*@formatter:off*/ #define deb1(x) debugName(x) << " = " << deb_tos(x) #define deb_2(x, ...) deb1(x) << ", " << deb1(__VA_ARGS__) #define deb_3(x, ...) deb1(x) << ", " << deb_2(__VA_ARGS__) #define deb_4(x, ...) deb1(x) << ", " << deb_3(__VA_ARGS__) #define deb5(x, ...) deb1(x) << ", " << deb_4(__VA_ARGS__) #define deb6(x, ...) deb1(x) << ", " << deb5(__VA_ARGS__) // #define deb7(x, ...) deb1(x) <<", "<< deb6(__VA_ARGS__) // #define deb8(x, ...) deb1(x) <<", "<< deb7(__VA_ARGS__) // #define deb9(x, ...) deb1(x) <<", "<< deb8(__VA_ARGS__) // #define deb10(x, ...) deb1(x) <<", "<< deb9(__VA_ARGS__) /*@formatter:off*/ #ifdef _DEBUG #define deb(...) \ do { \ was_deb = true; \ cerr << over10(__VA_ARGS__, deb10, deb9, deb8, deb7, deb6, deb5, deb_4, \ deb_3, deb_2, deb1)(__VA_ARGS__) \ << endl; \ } while (0) void print_n_base(int x, int base) { string S; while (x) { S += (char)('0' + x % base); x /= base; } cerr << S << endl; } template <class T> void print_n_base(vector<T> X, int base) { cerr << endl; for (auto &&x : X) { print_n_base(x, base); } cerr << endl; } // n進数 #define deb2(x) \ was_deb = true; \ cerr << debugName(x) << " = "; \ print_n_base(x, 2); #define deb3(x) \ was_deb = true; \ cerr << debugName(x) << " = "; \ print_n_base(x, 3); #define deb4(x) \ was_deb = true; \ cerr << debugName(x) << " = "; \ print_n_base(x, 4); #define deb_ex_deb(x, len) debugName(x) << " = " << deb_tos(x, len) #define call_deb_ex_deb(x, len) deb_ex_deb(x, len) // 要素が存在する行だけ出力(vvt) #define deb_ex(v) \ do { \ int N = sz(v); \ int s = N; \ int t = 0; \ rep(i, N) { \ if (sz(v[i])) { \ chmi(s, i); \ chma(t, i); \ } \ } \ auto ex_v = sub(v, s, N); \ str S = deb_tos(ex_v, sz(ex_v)); \ debugName(v); \ cerr << " = " << endl; \ cerr << S << endl; \ } while (0); #define debi(A) \ { \ int len = min(sz(A), 20); \ was_deb = true; \ cerr << debugName(A) << " = " << endl; \ rep(i, len) cerr << std::right \ << std::setw((int)(sz(tos(A[i])) + (i ? 1 : 0))) \ << (i % 10); \ cerr << endl; \ rep(i, len) cerr << std::right \ << std::setw((int)(sz(tos(A[i])) + (i ? 1 : 0))) << A[i]; \ cerr << endl; \ } template <class T, class F> string deb_tos_f(vector<T> &A, F f) { vi I; rep(i, sz(A)) { if (f(A[i])) I.push_back(i); } was_deb = true; stringstream ss; fora(ii, i, I) ss << std::right << std::setw( (int)(max(sz(tos(A[i])), sz(tos(i))) + (ii ? 1 : 0))) << i; ss << endl; fora(ii, i, I) ss << std::right << std::setw( (int)(max(sz(tos(A[i])), sz(tos(i))) + (ii ? 1 : 0))) << A[i]; return ss.str(); } template <class T, class F> string deb_tos_f(vector<vector<T>> &a, F f, int key = -1) { vi hs, ws_; int H = sz(a), W = sz(a[0]); vi exh(H), exw(W); rep(h, H) { rep(w, W) { if (f(a[h][w])) { exh[h] = true; exw[w] = true; } } } rep(h, H) if (exh[h]) hs.push_back(h); rep(w, W) if (exw[w]) ws_.push_back(w); return deb_tos(a, hs, ws_, key); } template <class T, class F> string deb_tos_f(vector<vector<vector<T>>> &a, F f) { stringstream ss; int H = sz(a); if (sz(a) == 0) return ss.str(); int cou = 0; rep(i, H) { if (any_of(a[i], v, f(v))) { ss << deb_tos_f(a[i], f, i); cou++; } if (cou > 50) break; } ss << "" << endl; return ss.str(); } #define debf_normal(tab, f) \ do { \ cerr << debugName(tab) << " = " << endl; \ cerr << deb_tos_f(tab, f) << endl; \ } while (0); #define debf2(tab, siki_r) debf_normal(tab, lamr(siki_r)) #define debf3(tab, v, siki) debf_normal(tab, lam(siki)) // S, sikir // S, v, siki #define debf(...) over3(__VA_ARGS__, debf3, debf2, debf1)(__VA_ARGS__) #else #define deb(...) ; #define deb2(...) ; #define deb3(...) ; #define deb4(...) ; #define deb_ex(...) ; #define debf(...) ; #define debi(...) ; #endif #define debugline(x) \ cerr << x << " " \ << "(L:" << __LINE__ << ")" << '\n' /*@formatter:off*/ using u32 = unsigned; using u64 = unsigned long long; using u128 = __uint128_t; using bint = __int128; std::ostream &operator<<(std::ostream &dest, __int128_t value) { std::ostream::sentry s(dest); if (s) { __uint128_t tmp = value < 0 ? -value : value; char buffer[128]; char *d = std::end(buffer); do { --d; *d = "0123456789"[tmp % 10]; tmp /= 10; } while (tmp != 0); if (value < 0) { --d; *d = '-'; } ll len = std::end(buffer) - d; if (dest.rdbuf()->sputn(d, len) != len) { dest.setstate(std::ios_base::badbit); } } return dest; } __int128 to_bint(string &s) { __int128 ret = 0; for (ll i = 0; i < (ll)s.length(); ++i) if ('0' <= s[i] && s[i] <= '9') ret = 10 * ret + s[i] - '0'; return ret; } void operator>>(istream &iss, bint &v) { string S; iss >> S; v = 0; rep(i, sz(S)) { v *= 10; v += S[i] - '0'; } } // 便利関数 /*@formatter:off*/ // テスト用 #define rand xor128_ unsigned long xor128_(void) { static unsigned long x = 123456789, y = 362436069, z = 521288629, w = 88675123; unsigned long t; t = (x ^ (x << 11)); x = y; y = z; z = w; return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))); } char ranc() { return (char)('a' + rand() % 26); } ll rand(ll min, ll max) { assert(min <= max); if (min >= 0 && max >= 0) { return rand() % (max + 1 - min) + min; } else if (max < 0) { return -rand(-max, -min); } else { if (rand() % 2) { return rand(0, max); } else { return -rand(0, -min); } } } ll rand(ll max) { return rand(0, max); } template <class T> T rand(vector<T> &A) { return A[rand(sz(A) - 1)]; } // 重複することがある template <class T> vector<T> ranv(vector<T> &A, int N) { vector<T> ret(N); rep(i, N) { ret[i] = rand(A); } return ret; } template <class T> vector<T> ranv_unique(vector<T> &A, int N) { vector<T> ret(N); umapi was; rep(j, N) { int i; while (1) { i = rand(sz(A) - 1); if (was.find(i) == was.end()) break; } ret[j] = A[i]; was[i] = 1; } return ret; } vi ranv(ll n, ll min, ll max) { vi v(n); rep(i, n) v[i] = rand(min, max); return v; } /*@formatter:off*/ #ifdef _DEBUG bool timeup(int time) { static bool never = true; if (never) message += "may timeup, because slow"; never = false; auto end_time = system_clock::now(); auto part = duration_cast<milliseconds>(end_time - start_time); auto lim = milliseconds(time); return part >= lim; } #else bool timeup(int time) { auto end_time = system_clock::now(); auto part = duration_cast<milliseconds>(end_time - start_time); auto lim = milliseconds(time); return part >= lim; } #endif void set_time() { past_time = system_clock::now(); } // MS型(millisecqnds)で返る // set_timeをしてからの時間 auto calc_time_milli() { auto now = system_clock::now(); auto part = duration_cast<milliseconds>(now - past_time); return part; } auto calc_time_micro() { auto now = system_clock::now(); auto part = duration_cast<microseconds>(now - past_time); return part; } auto calc_time_nano() { auto now = system_clock::now(); auto part = duration_cast<nanoseconds>(now - past_time); return part; } bool calc_time(int zikan) { return calc_time_micro() >= microseconds(zikan); } using MS = std::chrono::microseconds; int div(microseconds a, microseconds b) { return a / b; } int div(nanoseconds a, nanoseconds b) { if (b < nanoseconds(1)) { return a / nanoseconds(1); } int v = a / b; return v; } // set_time(); // rep(i,lim)shori // lim*=time_nanbai(); // rep(i,lim)shoriと使う // 全体でmilliかかっていいときにlimを何倍してもう一回できるかを返す int time_nanbai(int milli) { auto dec = duration_cast<nanoseconds>(past_time - start_time); auto part = calc_time_nano(); auto can_time = nanoseconds(milli * 1000 * 1000); can_time -= part; can_time -= dec; return div(can_time, part); } /*@formatter:off*/ // #define use_rand #ifdef use_rand str ransu(ll n) { str s; rep(i, n) s += (char)rand('A', 'Z'); return s; } str ransl(ll n) { str s; rep(i, n) s += (char)rand('a', 'z'); return s; } // 単調増加 vi ranvinc(ll n, ll min, ll max) { vi v(n); bool bad = 1; while (bad) { bad = 0; v.resize(n); rep(i, n) { if (i && min > max - v[i - 1]) { bad = 1; break; } if (i) v[i] = v[i - 1] + rand(min, max - v[i - 1]); else v[i] = rand(min, max); } } return v; } // 便利 汎用 #endif void ranvlr(ll n, ll min, ll max, vi &l, vi &r) { l.resize(n); r.resize(n); rep(i, n) { l[i] = rand(min, max); r[i] = l[i] + rand(0, max - l[i]); } } template <class Iterable, class T = typename Iterable::value_type> vector<pair<T, int>> run_length(const Iterable &a) { vector<pair<T, int>> ret; ret.eb(a[0], 1); rep(i, 1, sz(a)) { if (ret.back().fi == a[i]) { ret.back().se++; } else { ret.eb(a[i], 1); } } return ret; } /*@formatter:off*/ // #define use_mgr //_goldd _goldt #ifdef use_mgr //->[i, f(i)] template <class T, class U, class F> auto mgr(T ok, U ng, const F &f, require_arg(is_integral<T>::value &&is_integral<U>::value)) { auto mid = (ok + ng); if (ok < ng) while (ng - ok > 1) { mid = (ok + ng) >> 1; if (f(mid)) ok = mid; else ng = mid; } else while (ok - ng > 1) { mid = (ok + ng) >> 1; if (f(mid)) ok = mid; else ng = mid; } return ok; } //[l, r)の中で,f(i)がtrueとなる範囲を返す okはそこに含まれる template <class F> P mgr_range(int l, int r, F f, int ok) { if (f(ok) == 0) { out("f(ok) must true"); re(); } return mp(mgr(ok, l - 1, f), mgr(ok, r, f) + 1); } template <class F> auto mgrd(dou ok, dou ng, F f, int kai = 100) { if (ok < ng) rep(i, kai) { dou mid = (ok + ng) / 2; if (f(mid)) ok = mid; else ng = mid; } else rep(i, kai) { dou mid = (ok + ng) / 2; if (f(mid)) ok = mid; else ng = mid; } return ok; } template <class F> dou mgrd_time(dou ok, dou ng, F f, int time = 1980) { bool han = true; if (ok < ng) while (1) { dou mid = (ok + ng) / 2; if (f(mid)) ok = mid, han = true; else ng = mid, han = false; deb(mid, han); if (timeup(time)) { break; } } else while (1) { dou mid = (ok + ng) / 2; if (f(mid)) ok = mid, han = true; else ng = mid, han = false; deb(mid, han); if (timeup(time)) { break; } } return ok; } // todo 減らす template <class F> auto goldd_l(ll left, ll right, F calc) { double GRATIO = 1.6180339887498948482045868343656; ll lm = left + (ll)((right - left) / (GRATIO + 1.0)); ll rm = lm + (ll)((right - lm) / (GRATIO + 1.0)); ll fl = calc(lm); ll fr = calc(rm); while (right - left > 10) { if (fl < fr) { right = rm; rm = lm; fr = fl; lm = left + (ll)((right - left) / (GRATIO + 1.0)); fl = calc(lm); } else { left = lm; lm = rm; fl = fr; rm = lm + (ll)((right - lm) / (GRATIO + 1.0)); fr = calc(rm); } } ll minScore = MAX<ll>(); ll resIndex = left; for (ll i = left; i < right + 1; ++i) { ll score = calc(i); if (minScore > score) { minScore = score; resIndex = i; } } return make_tuple(resIndex, calc(resIndex)); } template <class F> auto goldt_l(ll left, ll right, F calc) { double GRATIO = 1.6180339887498948482045868343656; ll lm = left + (ll)((right - left) / (GRATIO + 1.0)); ll rm = lm + (ll)((right - lm) / (GRATIO + 1.0)); ll fl = calc(lm); ll fr = calc(rm); while (right - left > 10) { if (fl > fr) { right = rm; rm = lm; fr = fl; lm = left + (ll)((right - left) / (GRATIO + 1.0)); fl = calc(lm); } else { left = lm; lm = rm; fl = fr; rm = lm + (ll)((right - lm) / (GRATIO + 1.0)); fr = calc(rm); } } if (left > right) { ll l = left; left = right; right = l; } ll maxScore = MIN<ll>(); ll resIndex = left; for (ll i = left; i < right + 1; ++i) { ll score = calc(i); if (maxScore < score) { maxScore = score; resIndex = i; } } return make_tuple(resIndex, calc(resIndex)); } /*loopは200にすればおそらく大丈夫 余裕なら300に*/ template <class F> auto goldd_d(dou left, dou right, F calc, ll loop = 200) { dou GRATIO = 1.6180339887498948482045868343656; dou lm = left + ((right - left) / (GRATIO + 1.0)); dou rm = lm + ((right - lm) / (GRATIO + 1.0)); dou fl = calc(lm); dou fr = calc(rm); /*200にすればおそらく大丈夫*/ /*余裕なら300に*/ ll k = 141; loop++; while (--loop) { if (fl < fr) { right = rm; rm = lm; fr = fl; lm = left + ((right - left) / (GRATIO + 1.0)); fl = calc(lm); } else { left = lm; lm = rm; fl = fr; rm = lm + ((right - lm) / (GRATIO + 1.0)); fr = calc(rm); } } return make_tuple(left, calc(left)); } template <class F> auto goldt_d(dou left, dou right, F calc, ll loop = 200) { double GRATIO = 1.6180339887498948482045868343656; dou lm = left + ((right - left) / (GRATIO + 1.0)); dou rm = lm + ((right - lm) / (GRATIO + 1.0)); dou fl = calc(lm); dou fr = calc(rm); loop++; while (--loop) { if (fl > fr) { right = rm; rm = lm; fr = fl; lm = left + ((right - left) / (GRATIO + 1.0)); fl = calc(lm); } else { left = lm; lm = rm; fl = fr; rm = lm + ((right - lm) / (GRATIO + 1.0)); fr = calc(rm); } } return make_tuple(left, calc(left)); } // l ~ rを複数の区間に分割し、極致を与えるiを返す time-20 msまで探索 template <class F> auto goldd_ls(ll l, ll r, F calc, ll time = 2000) { auto lim = milliseconds(time - 20); ll mini = 0, minv = MAX<ll>(); /*区間をk分割する*/ rep(k, 1, inf) { auto s = system_clock::now(); ll haba = (r - l + k) / k; /*((r-l+1) + k-1) /k*/ ll nl = l; ll nr = l + haba; rep(i, k) { ll ni = goldd_l(nl, nr, calc); if (chmi(minv, calc(ni))) mini = ni; nl = nr; nr = nl + haba; } auto end = system_clock::now(); auto part = duration_cast<milliseconds>(end - s); auto elapsed = duration_cast<milliseconds>(end - start_time); if (elapsed + part * 2 >= lim) { break; } } return make_tuple(mini, calc(mini)); } template <class F> auto goldt_ls(ll l, ll r, F calc, ll time = 2000) { auto lim = milliseconds(time - 20); ll maxi = 0, maxv = MIN<ll>(); /*区間をk分割する*/ rep(k, 1, inf) { auto s = system_clock::now(); ll haba = (r - l + k) / k; /*((r-l+1) + k-1) /k*/ ll nl = l; ll nr = l + haba; rep(i, k) { ll ni = goldt_l(nl, nr, calc); if (chma(maxv, calc(ni))) maxi = ni; nl = nr; nr = nl + haba; } auto end = system_clock::now(); auto part = duration_cast<milliseconds>(end - s); auto elapsed = duration_cast<milliseconds>(end - start_time); if (elapsed + part * 2 >= lim) { break; } } return make_tuple(maxi, calc(maxi)); } template <class F> auto goldd_d_s(dou l, dou r, F calc, ll time = 2000) { /*20ms余裕を持つ*/ auto lim = milliseconds(time - 20); dou mini = 0, minv = MAX<dou>(); /*区間をk分割する*/ rep(k, 1, inf) { auto s = system_clock::now(); dou haba = (r - l) / k; dou nl = l; dou nr = l + haba; rep(i, k) { dou ni = goldd_d(nl, nr, calc); if (chmi(minv, calc(ni))) mini = ni; nl = nr; nr = nl + haba; } auto end = system_clock::now(); auto part = duration_cast<milliseconds>(end - s); auto elapsed = duration_cast<milliseconds>(end - start_time); if (elapsed + part * 2 >= lim) { break; } } return make_tuple(mini, calc(mini)); } template <class F> auto goldt_d_s(dou l, dou r, F calc, ll time = 2000) { /*20ms余裕を残している*/ auto lim = milliseconds(time - 20); dou maxi = 0, maxv = MIN<dou>(); /*区間をk分割する*/ rep(k, 1, inf) { auto s = system_clock::now(); dou haba = (r - l) / k; dou nl = l; dou nr = l + haba; rep(i, k) { dou ni = goldt_d(nl, nr, calc); if (chma(maxv, calc(ni))) maxi = ni; nl = nr; nr = nl + haba; } auto end = system_clock::now(); auto part = duration_cast<milliseconds>(end - s); auto elapsed = duration_cast<milliseconds>(end - start_time); if (elapsed + part * 2 >= lim) { break; } } return make_tuple(maxi, calc(maxi)); } #endif // strを整数として比較 string smax(str &a, str b) { if (sz(a) < sz(b)) { return b; } else if (sz(a) > sz(b)) { return a; } else if (a < b) return b; else return a; } // strを整数として比較 string smin(str &a, str b) { if (sz(a) > sz(b)) { return b; } else if (sz(a) < sz(b)) { return a; } else if (a > b) return b; else return a; } // エラー-1 template <typename W, typename T> ll find(vector<W> &a, int l, const T key) { rep(i, l, sz(a)) if (a[i] == key) return i; return -1; } template <typename W, typename T> ll find(vector<W> &a, const T key) { rep(i, sz(a)) if (a[i] == key) return i; return -1; } template <typename W, typename T> P find(vector<vector<W>> &a, const T key) { rep(i, sz(a)) rep(j, sz(a[0])) if (a[i][j] == key) return mp(i, j); return mp(-1, -1); } // getid(find())を返す 1次元にする template <typename W, typename T> int findi(vector<vector<W>> &a, const T key) { rep(i, sz(a)) rep(j, sz(a[0])) if (a[i][j] == key) return i * sz(a[0]) + j; return -1; } template <typename W, typename U> tuple<int, int, int> find(vector<vector<vector<W>>> &a, const U key) { rep(i, sz(a)) rep(j, sz(a[0])) rep(k, sz(a[0][0])) if (a[i][j][k] == key) return tuple<int, int, int>(i, j, k); return tuple<int, int, int>(-1, -1, -1); } // 無ければ-1 int find(string &s, const string key) { int klen = sz(key); rep(i, sz(s) - klen + 1) { if (s[i] != key[0]) continue; if (s.substr(i, klen) == key) { return i; } } return -1; } int find(string &s, int l, const string key) { int klen = sz(key); rep(i, l, sz(s) - klen + 1) { if (s[i] != key[0]) continue; if (s.substr(i, klen) == key) { return i; } } return -1; } int find(string &s, const char key) { rep(i, sz(s)) { if (s[i] == key) return i; } return -1; } int find(string &s, int l, const char key) { rep(i, l, sz(s)) { if (s[i] == key) return i; } return -1; } // N箇所について右のkeyの場所を返す template <typename W, typename T> vi finds(const W &a, const T &key) { int n = sz(a); vi rpos(n, -1); rer(i, n - 1) { if (i < n - 1) { rpos[i] = rpos[i + 1]; } if (a[i] == key) rpos[i] = i; } return rpos; } template <typename W, typename T> vi rfinds(const W &a, const T &key) { int n = sz(a); vi lpos(n, -1); rep(i, n) { if (i > 0) { lpos[i] = lpos[i - 1]; } if (a[i] == key) lpos[i] = i; } return lpos; } // todoz #if __cplusplus >= 201703L template <typename W, typename T, class Iterable = typename W::value_type> ll count(const W &a, const T &k) { return count_if(a, == k); } template <typename W, class Iterable = typename W::value_type> vi count(const W &a) { vi res; for_each(a, v, if (sz(res) <= (int)v) res.resize((int)v + 1); res[v]++;); return res; } #else ll count(const string &S, const char &c) { int res = 0; fora(s, S) { res += s == c; } return res; } #endif ll count(const str &a, const str &k) { ll ret = 0, len = k.length(); auto pos = a.find(k); while (pos != string::npos) pos = a.find(k, pos + len), ++ret; return ret; } /*@formatter:off*/ //'a' = 'A' = 0 として集計 既に-'a'されていても動く vi count(str &a, int l, int r) { vi cou(26); char c = 'a'; if ('A' <= a[l] && a[l] <= 'Z') c = 'A'; if ('a' <= a[l] && a[l] <= 'z') c = 'a'; else c = 0; rep(i, l, r)++ cou[a[i] - c]; return cou; } #define couif count_if // algorythm ll rev(ll a) { ll res = 0; while (a) { res *= 10; res += a % 10; a /= 10; } return res; } template <class T> auto rev(const vector<T> &a) { auto b = a; reverse(ALL(b)); return b; } /* \反転 */ template <class U> auto rev(vector<vector<U>> &a) { vector<vector<U>> b(sz(a[0]), vector<U>(sz(a))); rep(h, sz(a)) rep(w, sz(a[0])) b[w][h] = a[h][w]; return b; } /* |反転 */ template <class U> auto revw(vector<vector<U>> &a) { vector<vector<U>> b(sz(a), vector<U>(sz(a[0]))); int W = sz(a[0]); rep(h, sz(a)) rep(w, sz(a[0])) { b[h][W - 1 - w] = a[h][w]; } return b; } /* ー反転 */ template <class U> auto revh(vector<vector<U>> &a) { vector<vector<U>> b(sz(a), vector<U>(sz(a[0]))); int H = sz(a); rep(h, sz(a)) rep(w, sz(a[0])) { b[H - 1 - h][w] = a[h][w]; } return b; } /* /反転 */ template <class U> auto revr(vector<vector<U>> &a) { vector<vector<U>> b(sz(a[0]), vector<U>(sz(a))); int H = sz(a); int W = sz(a[0]); rep(h, sz(a)) rep(w, sz(a[0])) b[w][h] = a[H - 1 - h][W - 1 - w]; return b; } auto rev(const string &a) { string b = a; reverse(ALL(b)); return b; } template <class T> auto rev(const T &v, int i) { return v[sz(v) - 1 - i]; } int rev(int N, int i) { return N - 1 - i; } constexpr ll p10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000ll, 100000000000ll, 1000000000000ll, 10000000000000ll, 100000000000000ll, 1000000000000000ll, 10000000000000000ll, 100000000000000000ll, 1000000000000000000ll}; // 0は0桁 ll keta(ll v, int if_zero_res) { if (!v) return if_zero_res; if (v < p10[9]) { if (v < p10[4]) { if (v < p10[2]) { if (v < p10[1]) { if (v < p10[0]) return 0; else return 1; } else return 2; } else { if (v < p10[3]) return 3; else return 4; } } else { if (v < p10[7]) { if (v < p10[5]) return 5; else if (v < p10[6]) return 6; else return 7; } else { if (v < p10[8]) return 8; else return 9; } } } else { if (v < p10[13]) { if (v < p10[11]) { if (v < p10[10]) return 10; else return 11; } else { if (v < p10[12]) return 12; else return 13; } } else { if (v < p10[15]) { if (v < p10[14]) return 14; else return 15; } else { if (v < p10[17]) { if (v < p10[16]) return 16; else return 17; } else { if (v < p10[18]) return 18; else return 19; } } } } } #if __cplusplus >= 201703L ll getr(ll a, ll keta) { return (a / pow<ll>(10, keta)) % 10; } #else ll getr(ll a, ll keta) { return (a / (int)pow(10, keta)) % 10; } #endif // 上から何桁目か ll getl(ll a, ll ket) { int sketa = keta(a, 1); return getr(a, sketa - 1 - ket); } ll dsum(ll v, ll sin = 10) { ll ret = 0; for (; v; v /= sin) ret += v % sin; return ret; } ll mask10(ll v) { return p10[v] - 1; } // 変換系 template <class T, class U> auto to_v1(vector<reference_wrapper<U>> &ret, vector<T> &A) { rep(i, sz(A)) ret.push_back(A[i]); return ret; } template <class T, class U> auto to_v1(vector<reference_wrapper<U>> &ret, vector<vector<T>> &A) { rep(i, sz(A)) to_v1(ret, A[i]); return ret; } // 参照付きで1次元に起こす template <class T> auto to_v1(vector<vector<T>> &A) { vector<reference_wrapper<decl2_t<decltype(A)>>> ret; rep(i, sz(A)) to_v1(ret, A[i]); return ret; } //[v] := iとなるようなvectorを返す // 存在しない物は-1 // 空でも動く(なぜか) template <class T> auto keys(const T &a) { vector<decltype((a.begin())->fi)> res; for (auto &&k : a) res.push_back(k.fi); return res; } template <class T> auto values(const T &a) { vector<decltype((a.begin())->se)> res; for (auto &&k : a) res.push_back(k.se); return res; } // todo 可変長で template <class T> constexpr T min(T a, T b, T c) { return a >= b ? b >= c ? c : b : a >= c ? c : a; } template <class T> constexpr T max(T a, T b, T c) { return a <= b ? b <= c ? c : b : a <= c ? c : a; } // 1次元のコンテナ template <class T> int mini(const vector<T> &a) { return min_element(ALL(a)) - a.begin(); } template <class T> int maxi(const vector<T> &a) { return max_element(ALL(a)) - a.begin(); } template <class T> T sum(const T &A) { return A; } template <class T> T sum(const vector<T> &A, int l = -1, int r = -1) { T s = 0; set_lr12(l, r, sz(A)); rep(i, l, r) s += sum(A[i]); return s; } // 1次元のIterableに使える template <class T, require_t(!has_value_type<T>::value)> T min(T &a) { return a; } template <class V, require_t(has_value_type<V>::value)> auto min(V &a, ll s = -1, ll n = -1) { using Ret_t = decl2_t<V>; auto ret = MAX<Ret_t>(); set_lr12(s, n, sz(a)); if (s == n) { return INF<Ret_t>(); } else { rep(i, s, n) { ret = min(ret, min(a[i])); } return ret; } } template <class T, require_t(!has_value_type<T>::value)> T max(T &a) { return a; } template <class V, require_t(has_value_type<V>::value)> auto max(V &a, ll s = -1, ll n = -1) { using Ret_t = decl2_t<V>; auto ret = MIN<Ret_t>(); set_lr12(s, n, sz(a)); if (s == n) { return -INF<Ret_t>(); } else { rep(i, s, n) { ret = max(ret, max(a[i])); } return ret; } } template <class T> T mul(vector<T> &v, ll t = inf) { T ret = v[0]; rep(i, 1, min(t, sz(v))) ret *= v[i]; return ret; } // template<class T, class U, class... W> auto sumn(vector<T> &v, U head, W... // tail) { auto ret = sum(v[0], tail...); rep(i, 1, min(sz(v), head))ret // += sum(v[i], tail...); return ret;} indexを持つvectorを返す /*@formatter:off*/ template <typename W, typename T> void fill(W &xx, const T vall) { xx = vall; } template <typename W, typename T> void fill(vector<W> &vecc, const T vall) { for (auto &&vx : vecc) fill(vx, vall); } template <typename W, typename T> void fill(vector<W> &xx, const T v, ll len) { rep(i, len) xx[i] = v; } template <typename W, typename T> void fill(vector<W> &xx, const T v, int s, ll t) { rep(i, s, t) xx[i] = v; } template <typename W, typename T> void fill(vector<vector<W>> &xx, T v, int sh, int th, int sw, int tw) { rep(h, sh, th) rep(w, sw, tw) xx[h][w] = v; } // #define use_fill //_sum _array _max _min #ifdef use_fill template <typename A, size_t N, typename T> void fill(A (&a)[N], const T &v) { rep(i, N) { fill(a[i], v); } } template <class T, class U> void fill(vector<T> &a, const vi &ind, U val) { fora(v, ind) { a[v] = val; } } template <typename A, size_t N> auto sum(A (&a)[N], int l = -1, int r = -1) { set_lr12(l, r, N); auto res = sum(a[l]); if (l == r) { return res - res; } rep(i, l + 1, r) res += sum(a[i]); return res; } template <typename A, size_t N> auto max(A (&a)[N], int l = -1, int r = -1) { set_lr12(l, r, N); auto res = max(a[l]); if (l == r) { return -INF<decltype(res)>(); } rep(i, l + 1, r) res = max(res, max(a[i])); return res; } template <typename A, size_t N> auto min(A (&a)[N], int l = -1, int r = -1) { set_lr12(l, r, N); auto res = min(a[l]); if (l == r) { return INF<decltype(res)>(); } rep(i, l + 1, r) res = min(res, min(a[i])); return res; } #endif vi inds_(vi &a) { int n = max(a) + 1; vi ret(n, -1); rep(i, sz(a)) { assert(ret[a[i]] == -1); ret[a[i]] = i; } return ret; } void clear(PQ &q) { q = PQ(); } void clear(priority_queue<int> &q) { q = priority_queue<int>(); } template <class T> void clear(queue<T> &q) { while (q.size()) q.pop(); } // template<class T> T *negarr(ll size) { T *body = (T *) malloc((size * 2 + // 1) * sizeof(T)); return body + size;} template<class T> T *negarr2(ll h, // ll w) { double **dummy1 = new double *[2 * h + 1]; double *dummy2 = new // double[(2 * h + 1) * (2 * w + 1)]; dummy1[0] = dummy2 + w; for (ll i = // 1; i <= 2 * h + 1; ++i) { dummy1[i] = dummy1[i - 1] + 2 * w + 1; } double // **a = dummy1 + h; return a;} template <class T> struct ruiC { vector<T> rui; ruiC(vector<T> &ru) : rui(ru) {} /*先頭0*/ ruiC() : rui(1, 0) {} T operator()(ll l, ll r) { if (l > r) { cerr << "ruic "; deb(l, r); assert(0); } return rui[r] - rui[l]; } T operator()(int r = inf) { return operator()(0, min(r, sz(rui) - 1)); } /*ruiv[]をruic[]に変えた際意味が変わるのがまずいため()と統一*/ /*単体iを返す 累積でないことに注意(seg木との統一でこうしている)*/ // T operator[](ll i) { return rui[i + 1] - rui[i]; } T operator[](ll i) { return rui[i]; } /*0から順に追加される必要がある*/ void operator+=(T v) { rui.push_back(rui.back() + v); } void add(int i, T v) { if (sz(rui) - 1 != i) ole(); operator+=(v); } T back() { return rui.back(); } ll size() { return rui.size(); } auto begin() { return rui.begin(); } auto end() { return rui.end(); } }; template <class T> string deb_tos(const ruiC<T> &a) { return deb_tos(a.rui); } template <class T> ostream &operator<<(ostream &os, ruiC<T> a) { fora(v, a.rui) { os << v << " "; } return os; } template <class T> vector<T> ruiv(const vector<T> &a) { vector<T> ret(a.size() + 1); rep(i, a.size()) ret[i + 1] = ret[i] + a[i]; return ret; } template <class T> ruiC<T> ruic(const vector<T> &a) { vector<T> ret = ruiv(a); return ruiC<T>(ret); } template <class T> ruiC<T> ruic() { return ruiC<T>(); } // imoは0-indexed // ruiは1-indexed template <class T> vector<T> imo(const vector<T> &v) { vector<T> ret = v; rep(i, sz(ret) - 1) ret[i + 1] += ret[i]; return ret; } // #define use_rui //_imo _ruic _ruiv #ifdef use_rui // kと同じものの数 template <class T, class U> vi imo(const vector<T> &a, U k) { vi equ(sz(a)); rep(i, sz(a)) { equ[i] = a[i] == k; } return imo(equ); } template <class T> vector<T> imox(const vector<T> &v) { vector<T> ret = v; rep(i, sz(ret) - 1) ret[i + 1] ^= ret[i]; return ret; } // 漸化的に最小を持つ template <class T> vector<T> imi(const vector<T> &v) { vector<T> ret = v; rep(i, sz(ret) - 1) chmi(ret[i + 1], ret[i]); return ret; } template <class T> vector<T> ima(const vector<T> &v) { vector<T> ret = v; rep(i, sz(ret) - 1) chma(ret[i + 1], ret[i]); return ret; } template <class T> vector<T> rimi(const vector<T> &v) { vector<T> ret = v; rer(i, sz(ret) - 1, 1) chmi(ret[i - 1], ret[i]); return ret; } template <class T> vector<T> rima(const vector<T> &v) { vector<T> ret = v; rer(i, sz(ret) - 1, 1) chma(ret[i - 1], ret[i]); return ret; } template <class T> struct ruimax { template <typename Monoid> struct SegmentTree { /*pairで処理*/ int sz; vector<Monoid> seg; const Monoid M1 = mp(MIN<T>(), -1); Monoid f(Monoid a, Monoid b) { return max(a, b); } void build(vector<T> &a) { int n = sz(a); sz = 1; while (sz < n) sz <<= 1; seg.assign(2 * sz, M1); rep(i, n) { seg[i + sz] = mp(a[i], i); } for (int k = sz - 1; k > 0; k--) { seg[k] = f(seg[k << 1], seg[(k << 1) | 1]); } } Monoid query(int a, int b) { Monoid L = M1, R = M1; for (a += sz, b += sz; a < b; a >>= 1, b >>= 1) { if (a & 1) L = f(L, seg[a++]); if (b & 1) R = f(seg[--b], R); } return f(L, R); } Monoid operator[](const int &k) const { return seg[k + sz]; } }; private: vector<T> ve; SegmentTree<pair<T, int>> seg; vector<T> rv; vector<int> ri; bool build = false; public: int n; ruimax(vector<T> &a) : ve(a), n(sz(a)) { int index = -1; T ma = MIN<T>(); rv.resize(n + 1); ri.resize(n + 1); rv[0] = -INF<T>(); ri[0] = -1; rep(i, n) { if (chma(ma, a[i])) { index = i; } rv[i + 1] = ma; ri[i + 1] = index; } } T operator()(int l, int r) { if (!(l <= r && 0 <= l && r <= n)) { deb(l, r, n); assert(0); } if (l == 0) { return rv[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).first; } } T operator()(int r = inf) { return operator()(0, min(r, n)); } T operator[](int r) { return operator()(0, r); } T getv(int l, int r) { return operator()(l, r); } T getv(int r = inf) { return getv(0, min(r, n)); }; int geti(int l, int r) { assert(l <= r && 0 <= l && r <= n); if (l == 0) { return ri[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).second; } } int geti(int r = inf) { return geti(0, min(r, n)); }; auto begin() { return rv.begin(); } auto end() { return rv.end(); } }; template <class T> struct ruimin { template <typename Monoid> struct SegmentTree { /*pairで処理*/ int sz; vector<Monoid> seg; const Monoid M1 = mp(MAX<T>(), -1); Monoid f(Monoid a, Monoid b) { return min(a, b); } void build(vector<T> &a) { int n = sz(a); sz = 1; while (sz < n) sz <<= 1; seg.assign(2 * sz, M1); rep(i, n) { seg[i + sz] = mp(a[i], i); } for (int k = sz - 1; k > 0; k--) { seg[k] = f(seg[k << 1], seg[(k << 1) | 1]); } } Monoid query(int a, int b) { Monoid L = M1, R = M1; for (a += sz, b += sz; a < b; a >>= 1, b >>= 1) { if (a & 1) L = f(L, seg[a++]); if (b & 1) R = f(seg[--b], R); } return f(L, R); } Monoid operator[](const int &k) const { return seg[k + sz]; } }; private: vector<T> ve; SegmentTree<pair<T, int>> seg; vector<T> rv; vector<int> ri; bool build = false; int n; public: ruimin(vector<T> &a) : ve(a), n(sz(a)) { int index = -1; T mi = MAX<T>(); rv.resize(n + 1); ri.resize(n + 1); rv[0] = INF<T>(); ri[0] = -1; rep(i, n) { if (chmi(mi, a[i])) { index = i; } rv[i + 1] = mi; ri[i + 1] = index; } } T operator()(int l, int r) { assert(l <= r && 0 <= l && r <= n); if (l == 0) { return rv[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).first; } } T operator()(int r = inf) { return operator()(0, min(r, n)); } T operator[](int r) { return operator()(0, r); } T getv(int l, int r) { return operator()(l, r); } T getv(int r = inf) { return getv(0, min(r, n)); }; int geti(int l, int r) { { assert(l <= r && 0 <= l && r <= n); if (l == 0) { return ri[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).second; } } assert(l <= r && 0 <= l && r <= n); if (l == 0) { return ri[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).second; } } int geti(int r = inf) { return geti(0, min(r, n)); }; auto begin() { return rv.begin(); } auto end() { return rv.end(); } }; /*@formatter:off*/ vvi() ruib(vi &a) { vvi(res, 61, sz(a) + 1); rep(k, 61) { rep(i, sz(a)) { res[k][i + 1] = res[k][i] + ((a[i] >> k) & 1); } } return res; } vector<ruiC<int>> ruibc(vi &a) { vector<ruiC<int>> ret(61); vvi(res, 61, sz(a)); rep(k, 61) { rep(i, sz(a)) { res[k][i] = (a[i] >> k) & 1; } ret[k] = ruic(res[k]); } return ret; } // kと同じものの数 template <class T, class U> vi ruiv(T &a, U k) { vi ret(a.size() + 1); rep(i, a.size()) ret[i + 1] = ret[i] + (a[i] == k); return ret; } template <class T, class U> ruiC<ll> ruic(T &a, U k) { vi ret = ruiv(a, k); return ruiC<ll>(ret); } template <class T> struct ruiC2 { int H; vector<ruiC<T>> rui; ruiC<T> dummy; // 変なのをよばれたときはこれを返す//todo ruiC2(const vector<vector<T>> &ru) : rui(sz(ru)), H(sz(ru)) { for (int h = 0; h < H; h++) { if (sz(ru[h]) == 0) continue; if (sz(dummy) == 1) dummy = ruic(vector<T>(sz(ru[h]))); rui[h] = ruic(ru[h]); } } // WについてHを返す vector<T> operator()(ll l, ll r) { if (l > r) { cerr << "ruic "; deb(l, r); assert(0); } vector<T> res(H); for (int h = 0; h < H; h++) res[h] = rui[h](l, r); return res; } // HについてWを返す ruiC<T> &operator[](ll h) { #ifdef _DEBUG if (h >= H) { message += "warning ruiC h >= H"; } #endif if (h >= H || sz(rui[h]) == 1) return dummy; else return rui[h]; } /*@formatter:off*/ // vector<T> operator()(int r) { return operator()(0, r); } /*ruiv[]をruic[]に変えた際意味が変わるのがまずいため()と統一*/ /*単体iを返す 累積でないことに注意(seg木との統一でこうしている)*/ // T operator[](ll i) { return rui[i + 1] - rui[i]; } /*0から順に追加される必要がある*/ // T back() { return rui.back(); } // ll size() { return rui.size(); } // auto begin(){return rui.begin();} // auto end(){return rui.end();} }; template <class T, class U> ruiC<ll> ruicou(vector<T> &a, U b) { vi cou(sz(a)); rep(i, sz(a)) { cou[i] = a[i] == b; } return ruic(cou); } // メモリは形式によらず(26*N) // rui(l,r)でvector(26文字について, l~rのcの個数) // rui[h] ruic()を返す // 添え字は'a', 'A'のまま扱う // (予め-='a','A'されているものが渡されたらそれに従う) template <typename Iterable, class is_Iterable = typename Iterable::value_type> ruiC2<ll> ruicou(const Iterable &a) { int H = max(a) + 1; vvi(cou, H); rep(i, sz(a)) { if (sz(cou[a[i]]) == 0) cou[a[i]].resize(sz(a)); cou[a[i]][i] = 1; } return ruiC2<ll>(cou); } /*@formatter:off*/ // h query template <class T> vector<T> imoh(vector<vector<T>> &v, int w) { vector<T> ret(sz(v)); rep(h, sz(ret)) { ret[h] = v[h][w]; } rep(i, sz(ret) - 1) { ret[i + 1] += ret[i]; } return ret; } template <class T> vector<T> ruih(vector<vector<T>> &v, int w) { vector<T> ret(sz(v) + 1); rep(h, sz(v)) { ret[h + 1] = v[h][w]; } rep(i, sz(v)) { ret[i + 1] += ret[i]; } return ret; } template <class T> ruiC<T> ruihc(vector<vector<T>> &a, int w) { vector<T> ret = ruih(a, w); return ruiC<T>(ret); } // xor template <class T> struct ruixC { vector<T> rui; ruixC(vector<T> &ru) : rui(ru) {} T operator()(ll l, ll r) { if (l > r) { cerr << "ruiXc "; deb(l, r); assert(0); } return rui[r] ^ rui[l]; } T operator[](ll i) { return rui[i]; } T back() { return rui.back(); } ll size() { return rui.size(); } }; template <class T> vector<T> ruix(vector<T> &a) { vector<T> ret(a.size() + 1); rep(i, a.size()) ret[i + 1] = ret[i] ^ a[i]; return ret; } template <class T> ruixC<ll> ruixc(vector<T> &a) { vi ret = ruix(a); return ruixC<ll>(ret); } // 差分を返す(累積を取ると元に戻る) // 101なら // 1111を返す // 元の配列で[l, r)へのxorは //[l]と[r]へのxorになる https://atcoder.jp/contests/abc155/tasks/abc155_f vi ruix_diff(vi &A) { int N = sz(A); assert(N); vi res(N + 1); res[0] = A[0]; rep(i, 1, N) { res[i] = A[i - 1] ^ A[i]; } res[N] = A[N - 1]; return res; } template <class T> vector<T> ruim(vector<T> &a) { vector<T> res(a.size() + 1, 1); rep(i, a.size()) res[i + 1] = res[i] * a[i]; return res; } // 漸化的に最小を1indexで持つ template <class T> vector<T> ruimi(vector<T> &a) { ll n = sz(a); vector<T> ret(n + 1); rep(i, 1, n) { ret[i] = a[i - 1]; chmi(ret[i + 1], ret[i]); } return ret; } // template<class T> T *rrui(vector<T> &a) { // 右から左にかけての半開区間 (-1 n-1] template <class T> struct rruiC { vector<T> rui; int n; rruiC(vector<T> &a) : n(sz(a)) { rui.resize(n + 1); rer(i, n - 1) { rui[i] = rui[i + 1] + a[i]; } } /*[r l)*/ T operator()(int r, int l) { r++; l++; assert(l <= r && l >= 0 && r <= n); return rui[l] - rui[r]; } T operator()(int l) { return operator()(n - 1, l); } T operator[](int i) { return operator()(i); } }; template <class T> ostream &operator<<(ostream &os, rruiC<T> a) { fora(v, a.rui) { os << v << " "; } return os; } template <class T> string deb_tos(rruiC<T> &a) { return deb_tos(a.rui); } #define rrui rruic template <class T> rruiC<T> rruic(vector<T> &a) { return rruiC<T>(a); } // 掛け算 template <class T> struct ruimulC { vector<T> rv; int n; ruimulC(vector<T> &a) : rv(a), n(sz(a)) { rv.resize(n + 1); rv[0] = 1; rep(i, n) { rv[i + 1] = a[i] * rv[i]; } } ruimulC() : n(0) { rv.resize(n + 1); rv[0] = 1; } void operator+=(T v) { rv.push_back(rv.back() * v); n++; } T operator()(int l, int r) { assert(l <= r && 0 <= l && r <= n); return rv[r] / rv[l]; } T operator()(int r = inf) { return operator()(0, min(r, n)); } T operator[](int r) { return operator()(0, r); } auto begin() { return rv.begin(); } auto end() { return rv.end(); } }; template <class T> ruimulC<T> ruimul(vector<T> &a) { return ruimulC<T>(a); } template <class T> ruimulC<T> ruimul() { vector<T> a; return ruimulC<T>(a); } template <class T> T *rruim(vector<T> &a) { ll len = a.size(); T *body = (T *)malloc((len + 1) * sizeof(T)); T *res = body + 1; res[len - 1] = 1; rer(i, len - 1) res[i - 1] = res[i] * a[i]; return res; } template <class T, class U, class W> T lowerBound(ruiC<T> &a, U v, W banpei) { return lowerBound(a.rui, v, banpei); } template <class T, class U, class W> T upperBound(ruiC<T> &a, U v, W banpei) { return upperBound(a.rui, v, banpei); } template <class T, class U, class W> T rlowerBound(ruiC<T> &a, U v, W banpei) { return rlowerBound(a.rui, v, banpei); } template <class T, class U, class W> T rupperBound(ruiC<T> &a, U v, W banpei) { return rupperBound(a.rui, v, banpei); } #endif constexpr bool bget(ll m, ll keta) { #ifdef _DEBUG assert(keta <= 62); // オーバーフロー 1^62までしか扱えない #endif return (m >> keta) & 1; } // bget(n)次元 // NならN-1まで vector<vi> bget2(vi &a, int keta_size) { vvi(res, keta_size, sz(a)); rep(k, keta_size) { rep(i, sz(a)) { res[k][i] = bget(a[i], k); } } return res; } vi bget1(vi &a, int keta) { vi res(sz(a)); rep(i, sz(a)) { res[i] = bget(a[i], keta); } return res; } #if __cplusplus >= 201703L ll bget(ll m, ll keta, ll sinsuu) { m /= pow<ll>(sinsuu, keta); return m % sinsuu; } #else ll bget(ll m, ll keta, ll sinsuu) { m /= (ll)pow(sinsuu, keta); return m % sinsuu; } #endif constexpr ll bit(ll n) { #ifdef _DEBUG assert(n <= 62); // オーバーフロー 1^62までしか扱えない #endif return (1LL << (n)); } #if __cplusplus >= 201703L ll bit(ll n, ll sinsuu) { return pow<ll>(sinsuu, n); } #else ll bit(ll n, ll sinsuu) { return (ll)pow(sinsuu, n); } #endif ll mask(ll n) { return (1ll << n) - 1; } // aをbitに置きなおす //{0, 2} -> 101 ll bit(const vi &a) { int m = 0; for (auto &&v : a) m |= bit(v); return m; } //{1, 1, 0} -> 011 // bitsetに置き換える感覚 i が立っていたら i bit目を立てる ll bit_bool(vi &a) { int m = 0; rep(i, sz(a)) if (a[i]) m |= bit(i); return m; } #define bcou __builtin_popcountll // 最下位ビット ll lbit(ll n) { assert(n); return n & -n; } ll lbiti(ll n) { assert(n); return log2(n & -n); } // 最上位ビット ll hbit(ll n) { assert(n); n |= (n >> 1); n |= (n >> 2); n |= (n >> 4); n |= (n >> 8); n |= (n >> 16); n |= (n >> 32); return n - (n >> 1); } ll hbiti(ll n) { assert(n); return log2(hbit(n)); } // ll hbitk(ll n) { ll k = 0; rer(i, 5) { ll a = k + (1ll << i); ll // b = 1ll << a; if (b <= n)k += 1ll << i; } return k;} // 初期化は0を渡す ll nextComb(ll &mask, ll n, ll r) { if (!mask) return mask = (1LL << r) - 1; ll x = mask & -mask; /*最下位の1*/ ll y = mask + x; /*連続した下の1を繰り上がらせる*/ ll res = ((mask & ~y) / x >> 1) | y; if (bget(res, n)) return mask = 0; else return mask = res; } // n桁以下でビットがr個立っているもののvectorを返す vi bitCombList(ll n, ll r) { vi res; ll m = 0; while (nextComb(m, n, r)) { res.push_back(m); } return res; } /*over*/ #define forbit1_2(i, mas) \ for (int forbitj = !mas ? 0 : lbit(mas), forbitm = mas, \ i = !mas ? 0 : log2(forbitj); \ forbitm; forbitm = forbitm ^ forbitj, \ forbitj = !forbitm ? 1 : lbit(forbitm), i = log2(forbitj)) /*over*/ #define forbit1_3(i, N, mas) \ for (int forbitj = !mas ? 0 : lbit(mas), forbitm = mas, \ i = !mas ? 0 : log2(forbitj); \ forbitm && i < N; forbitm = forbitm ^ forbitj, \ forbitj = !forbitm ? 1 : lbit(forbitm), i = log2(forbitj)) // masの立ってるindexを見る // i, [N], mas #define forbit1(...) over3(__VA_ARGS__, forbit1_3, forbit1_2)(__VA_ARGS__) // masが立っていないindexを見る // i, N, mas #define forbit0(i, N, mas) forbit1(i, (mask(N) & (~(mas)))) // forsubをスニペットして使う // Mの部分集合(0,M含む)を見る 3^sz(S)個ある #define forsub_all(m, M) for (int m = M; m != -1; m = m == 0 ? -1 : (m - 1) & M) // BASE進数 template <size_t BASE> class base_num { int v; public: base_num(int v = 0) : v(v){}; int operator[](int i) { return bget(v, i, BASE); } void operator++() { v++; } void operator++(signed) { v++; } operator int() { return v; } }; #define base3(mas, lim, BASE) for (base_num<BASE> mas; mas < lim; mas++) #define base2(mas, lim) base3(mas, lim, 2) #define base(...) over3(__VA_ARGS__, base3, base2, base1)(__VA_ARGS__) // aにある物をtrueとする vb bool_(vi a, int n) { vb ret(max(max(a) + 1, n)); rep(i, sz(a)) ret[a[i]] = true; return ret; } char itoal(ll i) { return 'a' + i; } char itoaL(ll i) { return 'A' + i; } ll altoi(char c) { if ('A' <= c && c <= 'Z') return c - 'A'; return c - 'a'; } ll ctoi(char c) { return c - '0'; } char itoc(ll i) { return i + '0'; } ll vtoi(vi &v) { ll res = 0; if (sz(v) > 18) { debugline("vtoi"); deb(sz(v)); ole(); } rep(i, sz(v)) { res *= 10; res += v[i]; } return res; } vi itov(ll i) { vi res; while (i) { res.push_back(i % 10); i /= 10; } res = rev(res); return res; } vi stov(string &a) { ll n = sz(a); vi ret(n); rep(i, n) { ret[i] = a[i] - '0'; } return ret; } // 基準を満たさないものは0になる vi stov(string &a, char one) { ll n = sz(a); vi ret(n); rep(i, n) ret[i] = a[i] == one; return ret; } vector<vector<ll>> ctoi(vector<vector<char>> s, char c) { ll n = sz(s), m = sz(s[0]); vector<vector<ll>> res(n, vector<ll>(m)); rep(i, n) rep(j, m) res[i][j] = s[i][j] == c; return res; } // #define use_compress //[i] := vを返す // aは0~n-1で置き換えられる vi compress(vi &a) { vi b; ll len = a.size(); for (ll i = 0; i < len; ++i) { b.push_back(a[i]); } sort(b); unique(b); for (ll i = 0; i < len; ++i) { a[i] = lower_bound(ALL(b), a[i]) - b.begin(); } ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } #ifdef use_compress // ind[i] := i番目に小さい数 // map[v] := vは何番目に小さいか vi compress(vi &a, umapi &map) { vi b; ll len = a.size(); for (ll i = 0; i < len; ++i) { b.push_back(a[i]); } sort(b); unique(b); for (ll i = 0; i < len; ++i) { ll v = a[i]; a[i] = lower_bound(ALL(b), a[i]) - b.begin(); map[v] = a[i]; } ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } vi compress(vi &a, vi &r) { vi b; ll len = a.size(); fora(v, a) { b.push_back(v); } fora(v, r) { b.push_back(v); } sort(b); unique(b); for (ll i = 0; i < len; ++i) a[i] = lower_bound(ALL(b), a[i]) - b.begin(); for (ll i = 0; i < sz(r); ++i) r[i] = lower_bound(ALL(b), r[i]) - b.begin(); ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } vi compress(vi &a, vi &r, vi &s) { vi b; ll len = a.size(); fora(v, a) { b.push_back(v); } fora(v, r) { b.push_back(v); } fora(v, s) { b.push_back(v); } sort(b); unique(b); for (ll i = 0; i < len; ++i) a[i] = lower_bound(ALL(b), a[i]) - b.begin(); for (ll i = 0; i < sz(r); ++i) r[i] = lower_bound(ALL(b), r[i]) - b.begin(); for (ll i = 0; i < sz(s); ++i) r[i] = lower_bound(ALL(b), s[i]) - b.begin(); ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } vi compress(vector<vi> &a) { vi b; fora(vv, a) { fora(v, vv) { b.push_back(v); } } sort(b); unique(b); fora(vv, a) { fora(v, vv) { v = lower_bound(ALL(b), v) - b.begin(); } } ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } vi compress(vector<vector<vi>> &a) { vi b; fora(vvv, a) { fora(vv, vvv) { fora(v, vv) { b.push_back(v); } } } sort(b); unique(b); fora(vvv, a) { fora(vv, vvv) { fora(v, vv) { v = lower_bound(ALL(b), v) - b.begin(); } } } ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } void compress(ll a[], ll len) { vi b; for (ll i = 0; i < len; ++i) { b.push_back(a[i]); } sort(b); unique(b); for (ll i = 0; i < len; ++i) { a[i] = lower_bound(ALL(b), a[i]) - b.begin(); } } #endif // 要素が見つからなかったときに困る #define binarySearch(a, v) (binary_search(ALL(a), v)) #define lowerIndex(a, v) (lower_bound(ALL(a), v) - a.begin()) #define upperIndex(a, v) (upper_bound(ALL(a), v) - a.begin()) #define rlowerIndex(a, v) (upper_bound(ALL(a), v) - a.begin() - 1) #define rupperIndex(a, v) (lower_bound(ALL(a), v) - a.begin() - 1) template <class T, class U, class W> T lowerBound(vector<T> &a, U v, W banpei) { auto it = lower_bound(a.begin(), a.end(), v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T upperBound(vector<T> &a, U v, W banpei) { auto it = upper_bound(a.begin(), a.end(), v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T rlowerBound(vector<T> &a, U v, W banpei) { auto it = upper_bound(a.begin(), a.end(), v); if (it == a.begin()) return banpei; else { return *(--it); } } template <class T, class U, class W> T rupperBound(vector<T> &a, U v, W banpei) { auto it = lower_bound(a.begin(), a.end(), v); if (it == a.begin()) return banpei; else { return *(--it); } } // todo 消せないか template <class T, class U, class W> T lowerBound(set<T> &a, U v, W banpei) { auto it = a.lower_bound(v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T upperBound(set<T> &a, U v, W banpei) { auto it = a.upper_bound(v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T rlowerBound(set<T> &a, U v, W banpei) { auto it = a.upper_bound(v); if (it == a.begin()) return banpei; else { return *(--it); } } template <class T, class U, class W> T rupperBound(set<T> &a, U v, W banpei) { auto it = a.lower_bound(v); if (it == a.begin()) return banpei; else { return *(--it); } } template <class T, class U, class W> T lowerBound(mset<T> &a, U v, W banpei) { auto it = a.lower_bound(v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T upperBound(mset<T> &a, U v, W banpei) { auto it = a.upper_bound(v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T rlowerBound(mset<T> &a, U v, W banpei) { auto it = a.upper_bound(v); if (it == a.begin()) return banpei; else { return *(--it); } } template <class T, class U, class W> T rupperBound(mset<T> &a, U v, W banpei) { auto it = a.lower_bound(v); if (it == a.begin()) return banpei; else { return *(--it); } } #define next2(a) next(next(a)) #define prev2(a) prev(prev(a)) // 狭義の単調増加列 長さを返す template <class T> int lis(vector<T> &a) { int n = sz(a); vi tail(n + 1, MAX<T>()); rep(i, n) { int id = lowerIndex(tail, a[i]); /**/ tail[id] = a[i]; } return lowerIndex(tail, MAX<T>()); } template <class T> int lis_eq(vector<T> &a) { int n = sz(a); vi tail(n + 1, MAX<T>()); rep(i, n) { int id = upperIndex(tail, a[i]); /**/ tail[id] = a[i]; } return lowerIndex(tail, MAX<T>()); } // iteratorを返す // valueが1以上の物を返す 0は見つけ次第削除 // vを減らす場合 (*it).se--でいい template <class T, class U, class V> auto lower_map(map<T, U> &m, V k) { auto ret = m.lower_bound(k); while (ret != m.end() && (*ret).second == 0) { ret = m.erase(ret); } return ret; } template <class T, class U, class V> auto upper_map(map<T, U> &m, V k) { auto ret = m.upper_bound(k); while (ret != m.end() && (*ret).second == 0) { ret = m.erase(ret); } return ret; } // 存在しなければエラー template <class T, class U, class V> auto rlower_map(map<T, U> &m, V k) { auto ret = upper_map(m, k); assert(ret != m.begin()); ret--; while (1) { if ((*ret).second != 0) break; assert(ret != m.begin()); auto next = ret; --next; m.erase(ret); ret = next; } return ret; } template <class T, class U, class V> auto rupper_map(map<T, U> &m, V k) { auto ret = lower_map(m, k); assert(ret != m.begin()); ret--; while (1) { if ((*ret).second != 0) break; assert(ret != m.begin()); auto next = ret; --next; m.erase(ret); ret = next; } return ret; } template <class... T> void fin(T... s) { out(s...); exit(0); } // 便利 数学 math // sub ⊂ top bool subset(int sub, int top) { return (sub & top) == sub; } //-180 ~ 180 degree double atand(double h, double w) { return atan2(h, w) / PI * 180; } //% -mの場合、最小の正の数を返す ll mod(ll a, ll m) { if (m < 0) m *= -1; return (a % m + m) % m; } // ll pow(ll a) { return a * a; }; template <class T> T fact(int v) { static vector<T> fact(2, 1); if (sz(fact) <= v) { rep(i, sz(fact), v + 1) { fact.emplace_back(fact.back() * i); } } return fact[v]; } ll comi(ll n, ll r) { assert(n < 100); static vvi(pas, 100, 100); if (pas[0][0]) return pas[n][r]; pas[0][0] = 1; rep(i, 1, 100) { pas[i][0] = 1; rep(j, 1, i + 1) pas[i][j] = pas[i - 1][j - 1] + pas[i - 1][j]; } return pas[n][r]; } // 二項係数の偶奇を返す int com_mod2(int n, int r) { return n == (r | (n - r)); } double comd2(ll n, ll r) { static vvd(comb, 2020, 2020); if (comb[0][0] == 0) { comb[0][0] = 1; rep(i, 2000) { comb[i + 1][0] = 1; rep(j, 1, i + 2) { comb[i + 1][j] = comb[i][j] + comb[i][j - 1]; } } } return comb[n][r]; } double comd(int n, int r) { if (r < 0 || r > n) return 0; if (n < 2020) return comd2(n, r); static vd fact(2, 1); if (sz(fact) <= n) { rep(i, sz(fact), n + 1) { fact.push_back(fact.back() * i); } } return fact[n] / fact[n - r] / fact[r]; } #define gcd my_gcd template <class T, class U, class V = typename max_type<T, U>::type> V gcd(T a_, U b_) { V a = a_; V b = b_; while (b) a %= b, swap(a, b); return abs(a); } template <class T> T gcd(const vector<T> &b) { T res = b[0]; rep(i, 1, sz(b)) res = gcd(b[i], res); return res; } #define lcm my_lcm ll lcm(ll a, ll b) { return a / gcd(a, b) * b; } ll lcm(vi a) { ll res = a[0]; rep(i, 1, sz(a)) res = lcm(a[i], res); return res; } ll ceil(ll a, ll b) { if (b == 0) { debugline("ceil"); deb(a, b); ole(); return -1; } else if (a < 0) { return 0; } else { return (a + b - 1) / b; } } #define hypot my_hypot double hypot(double dx, double dy) { return std::sqrt(dx * dx + dy * dy); } ll sig0(int t) { return t <= 0 ? 0 : ((1 + t) * t) >> 1; } bint sig0(bint t) { return t <= 0 ? 0 : ((1 + t) * t) >> 1; } // ll sig(ll s, ll t) { return ((s + t) * (t - s + 1)) >> 1; } ll sig(ll s, ll t) { if (s > t) swap(s, t); return sig0(t - s) + s * (t - s + 1); } #define tousa_i tosa_i #define lower_tousa_i lower_tosa_i #define upper_tousa upper_tosa #define upper_tousa_i upper_tosa_i ll tosa_i(ll st, ll ad, ll v) { assert(((v - st) % ad) == 0); return (v - st) / ad; } ll tosa_s(ll st, ll ad, ll len) { return st * len + sig0(len - 1) * ad; } // ax + r (x は非負整数) で表せる整数のうち、v 以上となる最小の整数 ll lower_tosa(ll st, ll ad, ll v) { if (st >= v) return st; return (v - st + ad - 1) / ad * ad + st; } // 第何項か ll lower_tosa_i(ll st, ll ad, ll v) { if (st >= v) return 0; return (v - st + ad - 1) / ad; } ll upper_tosa(ll st, ll ad, ll v) { return lower_tosa(st, ad, v + 1); } ll upper_tosa_i(ll st, ll ad, ll v) { return lower_tosa_i(st, ad, v + 1); } // b * res <= aを満たす [l, r)を返す div P drange_ika(int a, int b) { P null_p = mp(linf, linf); if (b == 0) { if (a >= 0) { return mp(-linf, linf + 1) /*全て*/; } else { return null_p /*無い*/; } } else { if (a >= 0) { if (b > 0) { return mp(-linf, a / b + 1); } else { return mp(-(a / -b), linf + 1); } } else { if (b > 0) { return mp(-linf, -ceil(-a, b) + 1); } else { return mp(ceil(-a, -b), linf + 1); } } } } // v * v >= aとなる最小のvを返す ll sqrt(ll a) { if (a < 0) { debugline("sqrt"); deb(a); ole(); } ll res = (ll)std::sqrt(a); while (res * res < a) ++res; return res; } double log(double e, double x) { return log(x) / log(e); } /*@formatter:off*/ // 機能拡張 #define dtie(a, b) \ int a, b; \ tie(a, b) template <class T, class U> string to_string(T a, U b) { string res = ""; res += a; res += b; return res; } template <class T, class U, class V> string to_string(T a, U b, V c) { string res = ""; res += a; res += b; res += c; return res; } template <class T, class U, class V, class W> string to_string(T a, U b, V c, W d) { string res = ""; res += a; res += b; res += c; res += d; return res; } template <class T, class U, class V, class W, class X> string to_string(T a, U b, V c, W d, X e) { string res = ""; res += a; res += b; res += c; res += d; res += e; return res; } // todo stringもセットで // find_ifはsubrを使う string sub(string &A, int l = -1, int r = -1) { set_lr12(l, r, sz(A)); assert(0 <= l && l <= r && r <= sz(A)); return A.substr(l, r - l); } template <class T> vector<T> sub(const vector<T> &A, int l, int r) { assert(0 <= l && l <= r && r <= sz(A)); vector<T> ret(r - l); std::copy(A.begin() + l, A.begin() + r, ret.begin()); return ret; } template <class T> vector<T> sub(const vector<T> &A, int r) { return sub(A, 0, r); } #if __cplusplus >= 201703L template <class I, require_t(has_value_type<I>::value)> I subn(const I &A, int l, int len) { return sub(A, l, l + len); } #endif template <class T, class F> // sub2で呼ぶ vector<T> sub(const vector<vector<T>> &A, int h, int w, int ah, int aw, F f) { vector<T> res; while (0 <= h && h < sz(A) && 0 <= w && w < sz(A[h]) && f(A[h][w])) { res.emplace_back(A[h][w]); h += ah; w += aw; } return res; } template <class T> vector<T> sub(const vector<vector<T>> &A, int h, int w, int ah, int aw) { return sub(A, h, w, ah, aw, [&](T v) { return true; }); } // range_nowを返す(find_ifでしか使われない) #if __cplusplus >= 201703L template <class T> auto subr(const vector<T> &A, int l) { return range_now(vector<T>(A.begin() + l, A.end()), l); } #endif #define sub25(A, h, w, ah, aw) sub(A, h, w, ah, aw) #define sub26(A, h, w, ah, aw, siki_r) \ sub(A, h, w, ah, aw, [&](auto v) { return v siki_r; }) #define sub27(A, h, w, ah, aw, v, siki) \ sub(A, h, w, ah, aw, [&](auto v) { return siki; }) #define sub2(...) over7(__VA_ARGS__, sub27, sub26, sub25)(__VA_ARGS__) constexpr int bsetlen = 50001; // constexpr int bsetlen = 5050; #define bset bitset<bsetlen> bool operator<(bitset<bsetlen> &a, bitset<bsetlen> &b) { rer(i, bsetlen - 1) { if (a[i] < b[i]) return true; if (a[i] > b[i]) return false; } return false; } bool operator>(bitset<bsetlen> &a, bitset<bsetlen> &b) { rer(i, bsetlen - 1) { if (a[i] > b[i]) return true; if (a[i] < b[i]) return false; } return false; } bool operator<=(bitset<bsetlen> &a, bitset<bsetlen> &b) { rer(i, bsetlen - 1) { if (a[i] < b[i]) return true; if (a[i] > b[i]) return false; } return true; } bool operator>=(bitset<bsetlen> &a, bitset<bsetlen> &b) { rer(i, bsetlen - 1) { if (a[i] > b[i]) return true; if (a[i] < b[i]) return false; } return true; } string operator~(string &a) { string res = a; for (auto &&c : res) { if (c == '0') c = '1'; else if (c == '1') c = '0'; else { cerr << "cant ~" << a << "must bit" << endl; exit(0); } } return res; } ostream &operator<<(ostream &os, bset &a) { bitset<10> b; vi list; rep(i, bsetlen) { if (a[i]) list.push_back(i), b[i] = 1; } os << b << ", " << list; return os; } int hbiti(bset &a) { rer(i, bsetlen) { if (a[i]) return i; } return -1; } #define hk(a, b, c) (a <= b && b < c) // O(N/64) bset nap(bset &a, int v) { bset r = a | a << v; return r; } bset nap(bset &a, bset &v) { bset r = a; rep(i, bsetlen) { if (v[i]) r |= a << i; } return r; } template <class T> int count(set<T> &S, T l, T r) { assert(l < r); auto it = S.lower_bound(l); return it != S.end() && (*it) < r; } // template<class T> void seth(vector<vector<T>> &S, int w, vector<T> &v) // {assert(sz(S) == sz(v));assert(w < sz(S[0]));rep(h, sz(S)) { S[h][w] = v[h]; // }} template <class T> vector<T> geth(vector<vector<T>> &S, int w) { assert(w < sz(S[0])); vector<T> ret(sz(S)); rep(h, sz(S)) { ret[h] = S[h][w]; } return ret; } // vector<bool>[i]は参照を返さないため、こうしないとvb[i] |= // trueがコンパイルエラー vb::reference operator|=(vb::reference a, bool b) { return a = a | b; } vb::reference operator&=(vb::reference a, bool b) { return a = a & b; } template <class T, class U> void operator+=(pair<T, U> &a, pair<T, U> &b) { a.fi += b.fi; a.se += b.se; } template <class T, class U> pair<T, U> operator+(const pair<T, U> &a, const pair<T, U> &b) { return pair<T, U>(a.fi + b.fi, a.se + b.se); } template <class T, class U> pair<T, U> operator-(const pair<T, U> &a, const pair<T, U> &b) { return pair<T, U>(a.fi - b.fi, a.se - b.se); } template <class T, class U> pair<T, U> operator-(const pair<T, U> &a) { return pair<T, U>(-a.first, -a.second); } template <typename CharT, typename Traits, typename Alloc> basic_string<CharT, Traits, Alloc> operator+(const basic_string<CharT, Traits, Alloc> &lhs, const int rhs) { #ifdef _DEBUG static bool was = false; if (!was) message += "str += 65 is 'A' not \"65\" "; was = true; #endif return lhs + (char)rhs; } template <typename CharT, typename Traits, typename Alloc> basic_string<CharT, Traits, Alloc> operator+(const int lhs, const basic_string<CharT, Traits, Alloc> &rhs) { #ifdef _DEBUG static bool was = false; if (!was) message += "str += 65 is 'A' not \"65\" "; was = true; #endif return (char)lhs + rhs; } template <typename CharT, typename Traits, typename Alloc> void operator+=(basic_string<CharT, Traits, Alloc> &lhs, const int rv) { lhs = lhs + rv; } template <typename CharT, typename Traits, typename Alloc> basic_string<CharT, Traits, Alloc> operator+(const basic_string<CharT, Traits, Alloc> &lhs, const signed rv) { const int rv2 = rv; return lhs + rv2; } template <typename CharT, typename Traits, typename Alloc> void operator+=(basic_string<CharT, Traits, Alloc> &lhs, const signed rv) { const int v = rv; lhs += v; } template <typename CharT, typename Traits, typename Alloc> void operator*=(basic_string<CharT, Traits, Alloc> &s, int num) { auto bek = s; s = ""; for (; num; num >>= 1) { if (num & 1) { s += bek; } bek += bek; } } template <class T, class U> void operator+=(queue<T> &a, U v) { a.push(v); } template <class T, class U> void operator+=(deque<T> &a, U v) { a.push_back(v); } template <class T> priority_queue<T, vector<T>, greater<T>> & operator+=(priority_queue<T, vector<T>, greater<T>> &a, vector<T> &v) { fora(d, v) { a.push(d); } return a; } template <class T, class U> priority_queue<T, vector<T>, greater<T>> & operator+=(priority_queue<T, vector<T>, greater<T>> &a, U v) { a.push(v); return a; } template <class T, class U> priority_queue<T> &operator+=(priority_queue<T> &a, U v) { a.push(v); return a; } template <class T> set<T> &operator+=(set<T> &a, vector<T> v) { fora(d, v) { a.insert(d); } return a; } template <class T, class U> auto operator+=(set<T> &a, U v) { return a.insert(v); } template <class T, class U> auto operator-=(set<T> &a, U v) { return a.erase(v); } template <class T, class U> auto operator+=(mset<T> &a, U v) { return a.insert(v); } template <class T, class U> set<T, greater<T>> &operator+=(set<T, greater<T>> &a, U v) { a.insert(v); return a; } template <class T, class U> vector<T> &operator+=(vector<T> &a, U v) { a.push_back(v); return a; } template <class T, class U> vector<T> operator+(U v, const vector<T> &a) { vector<T> ret = a; ret.insert(ret.begin(), v); return ret; } template <class T> vector<T> operator+(const vector<T> &a, const vector<T> &b) { vector<T> ret; ret = a; fora(v, b) { ret += v; } return ret; } template <class T> vector<T> &operator+=(vector<T> &a, const vector<T> &b) { rep(i, sz(b)) { /*こうしないとa+=aで両辺が増え続けてバグる*/ a.push_back(b[i]); } return a; } template <class T, class U> map<T, U> &operator+=(map<T, U> &a, map<T, U> &b) { for (auto &&bv : b) { a[bv.first] += bv.second; } return a; } template <class T, class U> vector<T> operator+(const vector<T> &a, const U &v) { vector<T> ret = a; ret += v; return ret; } template <class T, class U> auto operator+=(uset<T> &a, U v) { return a.insert(v); } template <class T> vector<T> operator%(vector<T> &a, int v) { vi ret(sz(a)); rep(i, sz(a)) { ret[i] = a[i] % v; } return ret; } template <class T> vector<T> operator%=(vector<T> &a, int v) { rep(i, sz(a)) { a[i] %= v; } return a; } vi operator&(vi &a, vi &b) { assert(sz(a) == sz(b)); vi ret(sz(a)); rep(i, sz(a)) { ret[i] = min(a[i], b[i]); } return ret; } template <class T> void operator+=(mset<T> &a, vector<T> &v) { for (auto &&u : v) a.insert(u); } template <class T> void operator+=(set<T> &a, vector<T> &v) { for (auto &&u : v) a.insert(u); } template <class T> void operator+=(vector<T> &a, set<T> &v) { for (auto &&u : v) a.emplace_back(u); } template <class T> void operator+=(vector<T> &a, mset<T> &v) { for (auto &&u : v) a.emplace_back(u); } template <class T> vector<T> &operator-=(vector<T> &a, vector<T> &b) { if (sz(a) != sz(b)) { debugline("vector<T> operator-="); deb(a); deb(b); exit(0); } rep(i, sz(a)) a[i] -= b[i]; return a; } template <class T> vector<T> operator-(vector<T> &a, vector<T> &b) { if (sz(a) != sz(b)) { debugline("vector<T> operator-"); deb(a); deb(b); ole(); } vector<T> res(sz(a)); rep(i, sz(a)) res[i] = a[i] - b[i]; return res; } // template<class T, class U> void operator*=(vector<T> &a, U b) { vector<T> // ta = a; rep(b-1){ a+=ta; }} template <typename T> void erase(T &v, unsigned ll i) { v.erase(v.begin() + i); } template <typename T> void erase(T &v, unsigned ll s, unsigned ll e) { v.erase(v.begin() + s, v.begin() + e); } template <class T, class... I> auto erased(T &v, I... arg) { auto ret = v; erase(ret, arg...); return ret; } template <typename T> void pop_front(vector<T> &v) { erase(v, 0); } template <typename T> void entry(vector<T> &v, unsigned ll s, unsigned ll e) { erase(v, e, sz(v)); erase(v, 0, s); } template <class T, class U> void erase(map<T, U> &m, ll okl, ll ngr) { m.erase(m.lower_bound(okl), m.lower_bound(ngr)); } template <class T> void erase(set<T> &m, ll okl, ll ngr) { m.erase(m.lower_bound(okl), m.lower_bound(ngr)); } template <typename T> void erasen(vector<T> &v, unsigned ll s, unsigned ll n) { v.erase(v.begin() + s, v.begin() + s + n); } template <typename T, typename U> void insert(vector<T> &v, unsigned ll i, U t) { v.insert(v.begin() + i, t); } template <typename T, typename U> void push_front(vector<T> &v, U t) { v.insert(v.begin(), t); } template <typename T, typename U> void insert(vector<T> &v, unsigned ll i, vector<T> list) { for (auto &&va : list) v.insert(v.begin() + i++, va); } vector<string> split(const string &a, const char deli) { string b = a + deli; ll l = 0, r = 0, n = b.size(); vector<string> res; rep(i, n) { if (b[i] == deli) { r = i; if (l < r) res.push_back(b.substr(l, r - l)); l = i + 1; } } return res; } vector<string> split(const string &a, const string deli) { vector<string> res; ll kn = sz(deli); std::string::size_type Pos(a.find(deli)); ll l = 0; while (Pos != std::string::npos) { if (Pos - l) res.push_back(a.substr(l, Pos - l)); l = Pos + kn; Pos = a.find(deli, Pos + kn); } if (sz(a) - l) res.push_back(a.substr(l, sz(a) - l)); return res; } ll stoi(string &s) { return stol(s); } #define assert_yn(yn_v, v) \ ; \ assert(yn_v == 0 || yn_v == v); \ yn_v = v; // 不完全な対策、現状はautohotkeyで対応 int yn_v = 0; void yn(bool a) { assert_yn(yn_v, 1); if (a) cout << "yes" << endl; else cout << "no" << endl; } void fyn(bool a) { assert_yn(yn_v, 1); yn(a); exit(0); } void Yn(bool a) { assert_yn(yn_v, 2); if (a) cout << "Yes" << endl; else cout << "No" << endl; } void fYn(bool a) { assert_yn(yn_v, 2); Yn(a); exit(0); } void YN(bool a) { assert_yn(yn_v, 3); if (a) cout << "YES" << endl; else cout << "NO" << endl; } void fYN(bool a) { assert_yn(yn_v, 3); YN(a); exit(0); } int ab_v = 0; void fAb(bool a) { assert_yn(ab_v, 1); if (a) cout << "Alice" << endl; else cout << "Bob"; } void fAB(bool a) { assert_yn(yn_v, 2); if (a) cout << "ALICE" << endl; else cout << "BOB"; } int pos_v = 0; void Possible(bool a) { assert_yn(pos_v, 1); if (a) cout << "Possible" << endl; else cout << "Impossible" << endl; exit(0); } void POSSIBLE(bool a) { assert_yn(pos_v, 2); if (a) cout << "POSSIBLE" << endl; else cout << "IMPOSSIBLE" << endl; exit(0); } void fPossible(bool a) { assert_yn(pos_v, 1) Possible(a); exit(0); } void fPOSSIBLE(bool a) { assert_yn(pos_v, 2) POSSIBLE(a); exit(0); } template <typename T> class fixed_point : T { public: explicit constexpr fixed_point(T &&t) noexcept : T(std::forward<T>(t)) {} template <typename... Args> constexpr decltype(auto) operator()(Args &&...args) const { return T::operator()(*this, std::forward<Args>(args)...); } }; template <typename T> static inline constexpr decltype(auto) fix(T &&t) noexcept { return fixed_point<T>{std::forward<T>(t)}; } // 未分類 // 0,2,1 1番目と2番目の次元を入れ替える template <class T> auto irekae(vector<vector<vector<T>>> &A, int x, int y, int z) { #define irekae_resize_loop(a, b, c) \ resize(res, a, b, c); \ rep(i, a) rep(j, b) rep(k, c) vector<vector<vector<T>>> res; if (x == 0 && y == 1 && z == 2) { res = A; } else if (x == 0 && y == 2 && z == 1) { irekae_resize_loop(sz(A), sz(A[0][0]), sz(A[0])) { res[i][j][k] = A[i][k][j]; } } else if (x == 1 && y == 0 && z == 2) { irekae_resize_loop(sz(A[0]), sz(A), sz(A[0][0])) { res[i][j][k] = A[j][i][k]; } } else if (x == 1 && y == 2 && z == 0) { irekae_resize_loop(sz(A[0]), sz(A[0][0]), sz(A)) { res[i][j][k] = A[k][i][j]; } } else if (x == 2 && y == 0 && z == 1) { irekae_resize_loop(sz(A[0][0]), sz(A), sz(A[0])) { res[i][j][k] = A[j][k][i]; } } else if (x == 2 && y == 1 && z == 0) { irekae_resize_loop(sz(A[0][0]), sz(A[0]), sz(A)) { res[i][j][k] = A[k][j][i]; } } return res; #undef irekae_resize_loop } template <class T> auto irekae(vector<vector<T>> &A, int i = 1, int j = 0) { vvt(res, sz(A[0]), sz(A)); rep(i, sz(A)) { rep(j, sz(A[0])) { res[j][i] = A[i][j]; } } return res; } // tou分割する template <typename Iterable> vector<Iterable> table(const Iterable &a, int tou = 2) { int N = sz(a); vector<Iterable> res(tou); int hab = N / tou; vi lens(tou, hab); rep(i, N % tou) { lens[tou - 1 - i]++; } int l = 0; rep(i, tou) { int len = lens[i]; int r = l + len; res[i].resize(len); std::copy(a.begin() + l, a.begin() + r, res[i].begin()); l = r; } return res; } // 長さn毎に分割する template <typename Iterable> vector<Iterable> table_n(const Iterable &a, int len) { int N = sz(a); vector<Iterable> res(ceil(N, len)); vi lens(N / len, len); if (N % len) lens.push_back(N % len); int l = 0; rep(i, sz(lens)) { int len = lens[i]; int r = l + len; res[i].resize(len); std::copy(a.begin() + l, a.begin() + r, res[i].begin()); l = r; } return res; } // 縦を返す vi &geth(vvi() & a, int w) { static vi ret; ret.resize(sz(a)); rep(i, sz(a)) { ret[i] = a[i][w]; } return ret; } //@起動時 struct initon { initon() { cin.tie(0); ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(16); srand((unsigned)clock() + (unsigned)time(NULL)); }; } initonv; // #define pre prev // #define nex next // gra mll pr // 上下左右 const string udlr = "udlr"; string UDLR = "UDLR"; // x4と連動 UDLR.find('U') := x4[0] vc atoz = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; vc AtoZ = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; // 右、上が正 constexpr ll h4[] = {1, -1, 0, 0}; constexpr ll w4[] = {0, 0, -1, 1}; constexpr ll h8[] = {0, 1, 0, -1, -1, 1, 1, -1}; constexpr ll w8[] = {1, 0, -1, 0, 1, -1, 1, -1}; int mei_inc(int h, int w, int H, int W, int i) { while (++i < 4) { if (inside(h + h4[i], w + w4[i], H, W)) return i; } return i; } #define mei(nh, nw, h, w) \ for (int i = mei_inc(h, w, H, W, -1), nh = i < 4 ? h + h4[i] : 0, \ nw = i < 4 ? w + w4[i] : 0; \ i < 4; i = mei_inc(h, w, H, W, i), nh = h + h4[i], nw = w + w4[i]) int mei_inc8(int h, int w, int H, int W, int i) { while (++i < 8) { if (inside(h + h8[i], w + w8[i], H, W)) return i; } return i; } #define mei8(nh, nw, h, w) \ for (int i = mei_inc8(h, w, H, W, -1), nh = i < 8 ? h + h8[i] : 0, \ nw = i < 8 ? w + w8[i] : 0; \ i < 8; i = mei_inc8(h, w, H, W, i), nh = h + h8[i], nw = w + w8[i]) int mei_incv(int h, int w, int H, int W, int i, vp &p) { while (++i < sz(p)) { if (inside(h + p[i].fi, w + p[i].se, H, W)) return i; } return i; } #define meiv(nh, nw, h, w, p) \ for (int i = mei_incv(h, w, H, W, -1, p), nh = i < sz(p) ? h + p[i].fi : 0, \ nw = i < sz(p) ? w + p[i].se : 0; \ i < sz(p); \ i = mei_incv(h, w, H, W, i, p), nh = h + p[i].fi, nw = w + p[i].se) // H*Wのグリッドを斜めに分割する // 右上 vector<vp> naname_list_ne(int H, int W) { vector<vp> res(H + W - 1); rep(sh, H) { int sw = 0; res[sh] += mp(sh, sw); int nh = sh; int nw = sw; while (1) { nh--; nw++; if (0 <= nh && nw < W) { res[sh] += mp(nh, nw); } else { break; } } } rep(sw, 1, W) { int sh = H - 1; res[H + sw - 1] += mp(sh, sw); int nh = sh; int nw = sw; while (1) { nh--; nw++; if (0 <= nh && nw < W) { res[H + sw - 1] += mp(nh, nw); } else { break; } } } return res; } // 右下 vector<vp> naname_list_se(int H, int W) { vector<vp> res(H + W - 1); rep(sh, H) { int sw = 0; res[sh] += mp(sh, sw); int nh = sh; int nw = sw; while (1) { nh++; nw++; if (0 <= nh && nh < H && nw < W) { res[sh] += mp(nh, nw); } else { break; } } } rep(sw, 1, W) { int sh = 0; res[H + sw - 1] += mp(sh, sw); int nh = sh; int nw = sw; while (1) { nh++; nw++; if (0 <= nh && nh < H && nw < W) { res[H + sw - 1] += mp(nh, nw); } else { break; } } } return res; } // グラフ内で #undef getid // #define getidとしているため、ここを書き直したらgraphも書き直す #define getid_2(h, w) ((h) * (W) + (w)) #define getid_1(p) ((p).first * W + (p).second) #define getid(...) over2(__VA_ARGS__, getid_2, getid_1)(__VA_ARGS__) #define getp(id) mp((id) / W, (id) % W) #define set_shuffle() \ std::random_device seed_gen; \ std::mt19937 engine(seed_gen()) #define shuffle(a) std::shuffle((a).begin(), (a).end(), engine); // 1980 開始からtime ms経っていたらtrue vb bit_bool(int v, int len) { assert(bit(len) > v); vb ret(len); rep(i, len) { ret[i] = bget(v, i); } return ret; } vi tov(vb &a) { vi ret; rep(i, sz(a)) { if (a[i]) ret.push_back(i); } return ret; } bool kaibun(const str &S) { return S == rev(S); } template <class T> vector<T> repeat(const vector<T> &A, int kaisu) { vector<T> ret; while (kaisu--) { ret += A; } return ret; } #define rge range #define upd update // S[{s, t, d}] #define strs slice_str struct slice_str { string S; slice_str() {} slice_str(const string &S) : S(S) {} slice_str(int len, char c) : S(len, c) {} auto size() { return S.size(); } char &operator[](int p) { return S[p]; } string operator[](initializer_list<int> p) { if (sz(p) == 1) { return S.substr(0, *(p.begin())); } else if (sz(p) == 2) { int l = *(p.begin()); int r = *(next(p.begin())); return S.substr(l, r - l); } else { auto it = p.begin(); int s = *(it++); int t = *(it++); int d = *(it); if (d == -1) { int s_ = sz(S) - s - 1; int t_ = sz(S) - t - 1; return rev(S).substr(s_, t_ - s_); } else if (d < 0) { t = max(-1ll, t); string ret; while (s > t) { ret += S[s]; s += d; } return ret; } else { t = min(sz(S), t); string ret; while (s < t) { ret += S[s]; s += d; } return ret; } } } operator string &() { return S; } template <class T> void operator+=(const T &a) { S += a; } bool operator==(const slice_str &rhs) { return S == rhs.S; } auto pop_back() { return S.pop_back(); } }; ostream &operator<<(ostream &os, const slice_str &a) { os << a.S; return os; } istream &operator>>(istream &iss, slice_str &a) { iss >> a.S; return iss; } template <class T> bool can(const T &v, int i) { return 0 <= i && i < sz(v); } #if __cplusplus >= 201703L // template<class T> auto sum(int a, T v...) {return (v + ... + 0);} #endif #define VEC vector // string.substr()は長さを指定するため、間違えやすい #define substr my_substr #endif /*UNTITLED15_TEMPLATE_H*/ #endif // † ←template終了 /*@formatter:on*/ // vectorで取れる要素数 // bool=> 1e9 * 8.32 // int => 1e8 * 2.6 // ll => 1e8 * 1.3 // 3次元以上取るとメモリがヤバい // static配列を使う vvc(ba); ll N, M, H, W; vi A, B, C; // 14:43 void solve() { in(N); dnao2(Vs, Ws, N); din(Q); int mid_lim = min(bit(11), N + 1); auto get_path = [&](int v) { vi D; D += v; while (v > 1) { v /= 2; D += v; } return D; }; // 1-indexed static int dp_u[bit(11) + 1][k5]; rep(cur, 1, mid_lim) { auto D = get_path(cur); int dn = sz(D); rep(mas, bit(dn)) { int v = 0, w = 0; forbit1(di, mas) { v += Vs[D[di]]; w += Ws[D[di]]; } if (w < k5) chma(dp_u[cur][w], v); } rep(w, k5 - 1) { chma(dp_u[cur][w + 1], dp_u[cur][w]); } } // deb(dp_u); rep(q, Q) { din(v, L); if (v < mid_lim) { out(dp_u[v][L]); continue; } int u_last = 0; vi D; { vi D2 = get_path(v); fora(d, D2) { if (d >= mid_lim) D += d; else { chma(u_last, d); } } } deb(q, D, u_last); int N = sz(D); int max_v = 0; rep(mas, bit(N)) { int v = 0, w = 0; forbit1(di, mas) { v += Vs[D[di]]; w += Ws[D[di]]; } if (w <= L) { chma(max_v, v + dp_u[u_last][L - w]); } } out(max_v); } } auto my(ll n, vi &a) { return 0; } auto sister(ll n, vi &a) { ll ret = 0; return ret; } signed main() { solve(); #define arg n, a #ifdef _DEBUG bool bad = 0; for (ll i = 0, ok = 1; i < k5 && ok; ++i) { ll n = rand(1, 8); vi a = ranv(n, 1, 10); auto myres = my(arg); auto res = sister(arg); ok = myres == res; if (!ok) { out(arg); cerr << "AC : " << res << endl; cerr << "MY : " << myres << endl; bad = 1; break; } } if (!bad) { // solveを書き直す // solveを呼び出す } exit(0); #endif return 0; };
/*temp*/ // // // // // #undef _DEBUG // #pragma GCC optimize("Ofast") // 不動小数点の計算高速化 // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") // #include <boost/multiprecision/cpp_int.hpp> #ifdef _DEBUG #include "template.h" #else #if __cplusplus >= 201703L /*Atcoderでしか使えない(c++17 && このテンプレートが使えるならAtcoder)*/ #include <boost/sort/pdqsort/pdqsort.hpp> #define fast_sort boost::sort::pdqsort #endif #endif #ifndef _DEBUG #ifndef UNTITLED15_TEMPLATE_H #define UNTITLED15_TEMPLATE_H #ifdef _DEBUG #include "bits_stdc++.h" #else #include <bits/stdc++.h> #endif #ifndef fast_sort #define fast_sort sort #endif // #define use_pq #define use_for #define use_for_each #define use_sort #define use_fill #define use_rand #define use_mgr #define use_rui #define use_compress // // // // // // #define use_pbds #ifdef use_pbds #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> template <class T, class U, class W, class X> auto count(__gnu_pbds::gp_hash_table<T, U, W> &a, X k) { return a.find(k) != a.end(); } #endif using namespace std; using namespace std::chrono; /*@formatter:off*/ #define ll long long using sig_dou = double; // マクロ省略形 関数等 #define arsz(a) (sizeof(a) / sizeof(a[0])) #define sz(a) ((ll)(a).size()) #define mp make_pair #define mt make_tuple #define pb pop_back #define pf push_front #define eb emplace_back #define ALL(a) (a).begin(), (a).end() #define RALL(a) (a).rbegin(), (a).rend() template <class T, class U> auto max(T a, U b) { return a > b ? a : b; } template <class T, class U> auto min(T a, U b) { return a < b ? a : b; } // optional<T>について下でオーバーロード(nullopt_tを左辺右辺について単位元として扱う) template <class T, class U> bool chma(T &a, const U &b) { if (a < b) { a = b; return true; } return false; } template <class T, class U> bool chmi(T &a, const U &b) { if (b < a) { a = b; return true; } return false; } // メタ系 meta template <typename T, typename U = typename T::value_type> std::true_type value_type_tester(signed); template <typename T> std::false_type value_type_tester(long); template <typename T> struct has_value_type : decltype(value_type_tester<T>(0)) {}; // A<T>でTを返す template <class T> using decl_t = typename T::value_type; // A<B<.....T>>でTを返す template <class T, bool end = !has_value_type<T>::value> struct decl2_ { typedef T type; }; template <class T> struct decl2_<T, false> { typedef typename decl2_<decl_t<T>>::type type; }; template <class T> using decl2_t = typename decl2_<T>::type; // #define decl_max(a, b) decltype(max(MAX<decltype(a)>(), MAX<decltype(b)>())) #define is_same2(T, U) is_same<T, U>::value template <class T> struct is_vector : std::false_type {}; template <class T> struct is_vector<std::vector<T>> : std::true_type {}; // 大きい型を返す max_type<int, char>::type // todo mintがlong long より小さいと判定されるためバグる template <class T1, class T2, bool t1_bigger = (sizeof(T1) > sizeof(T2))> struct max_type { typedef T1 type; }; template <class T1, class T2> struct max_type<T1, T2, false> { typedef T2 type; }; template <class T> struct vec_rank : integral_constant<int, 0> {}; template <class T> struct vec_rank<vector<T>> : integral_constant<int, vec_rank<T>{} + 1> {}; // N個のTを並べたtupleを返す // tuple_n<3, int>::type tuple<int, int, int> template <size_t N, class T, class... Arg> struct tuple_n { typedef typename tuple_n<N - 1, T, T, Arg...>::type type; }; template <class T, class... Arg> struct tuple_n<0, T, Arg...> { typedef tuple<Arg...> type; }; struct dummy_t1 {}; struct dummy_t2 {}; struct dummy_t3 {}; struct dummy_t4 {}; struct dummy_t5 {}; struct dummy_t6 {}; // template<class T, require(is_integral<T>::value)>など #define require_t(bo) enable_if_t<bo> * = nullptr // 複数でオーバーロードする場合、引数が同じだとうまくいかないため // require_arg(bool, dummy_t1) // require_arg(bool, dummy_t2)等とする #define require_arg1(bo) enable_if_t<bo> * = nullptr #define require_arg2(bo, dummy_type) enable_if_t<bo, dummy_type> * = nullptr #define require_arg(...) \ over2(__VA_ARGS__, require_arg2, require_arg1)(__VA_ARGS__) //->//enable_if_tのtを書き忘れそうだから #define require_ret(bo, ret_type) enable_if_t<bo, ret_type> #define int long long // todo 消したら動かない intの代わりにsignedを使う auto start_time = system_clock::now(); auto past_time = system_clock::now(); #define debugName(VariableName) #VariableName // 最大引数がN #define over2(o1, o2, name, ...) name #define over3(o1, o2, o3, name, ...) name #define over4(o1, o2, o3, o4, name, ...) name #define over5(o1, o2, o3, o4, o5, name, ...) name #define over6(o1, o2, o3, o4, o5, o6, name, ...) name #define over7(o1, o2, o3, o4, o5, o6, o7, name, ...) name #define over8(o1, o2, o3, o4, o5, o6, o7, o8, name, ...) name #define over9(o1, o2, o3, o4, o5, o6, o7, o8, o9, name, ...) name #define over10(o1, o2, o3, o4, o5, o6, o7, o8, o9, o10, name, ...) name #ifdef _DEBUG string message; string res_mes; bool was_deb = false; [[noreturn]] void my_exit(signed e = 0) { if (was_deb && sz(res_mes)) { cerr << "result = " << endl << res_mes << endl; } if (sz(message)) { cerr << "****************************" << endl; cerr << "Note." << endl; cerr << message << endl; cerr << "****************************" << endl; } exit(e); } #define exit my_exit #endif void assert2(bool b, const string &s = "") { if (!b) { cerr << s << endl; exit(1); /*assert(0);*/ } } // my_nulloptをあらゆる操作の単位元的な物として扱う // vectorの参照外時に返したり、右辺値として渡されたときに何もしないなど struct my_nullopt_t { } my_nullopt; #define nullopt_t my_nullopt_t #define nullopt my_nullopt /*@formatter:off*/ // 値が無いときは、setを使わない限り代入できない //=を使っても無視される template <class T> struct my_optional { private: bool is_null; T v; public: typedef T value_type; my_optional() : is_null(true) {} my_optional(const nullopt_t &) : is_null(true) {} my_optional(const T &v) : v(v), is_null(false) {} bool has_value() const { return !is_null; } T &value() { static string mes = "optional has no value"; assert2(!is_null, mes); return v; } const T &value() const { static string mes = "optional has no value"; assert2(!is_null, mes); return v; } void set(const T &nv) { is_null = false; v = nv; } template <class U> void operator=(const U &v) { set(v); // null状態でも代入出来るようにした // if (has_value())value() = v; else return; } template <class U> void operator=(const my_optional<U> &v) { if (/*has_value() && */ v.has_value()) (*this) = v; else return; } /*@formatter:off*/ void reset() { is_null = true; } void operator=(const nullopt_t &) { reset(); } template <require_t(!is_same2(T, bool))> explicit operator bool() { return !is_null; } // nullの時はエラー operator T &() { return value(); } operator const T &() const { return value(); } my_optional<T> operator++() { if (this->has_value()) { this->value()++; return *this; } else { return *this; } } my_optional<T> operator++(signed) { if (this->has_value()) { auto tem = *this; this->value()++; return tem; } else { return *this; } } my_optional<T> operator--() { if (this->has_value()) { this->value()--; return *this; } else { return *this; } } my_optional<T> operator--(signed) { if (this->has_value()) { auto tem = *this; this->value()--; return tem; } else { return *this; } } }; template <class T> istream &operator>>(istream &iss, my_optional<T> &v) { T val; iss >> val; v.set(val); return iss; } #define optional my_optional template <class T> using opt = my_optional<T>; // template<class T, class A = std::allocator<T>> struct debtor : std::vector<T, // A> { template <class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>>> struct o_map : std::map<Key, optional<T>, Compare, Allocator> { optional<T> emp; o_map() : std::map<Key, optional<T>, Compare, Allocator>() {} auto operator()(const nullopt_t &) { return nullopt; } optional<T> &operator()(const optional<Key> &k) { if (k.has_value()) { return std::map<Key, optional<T>, Compare, Allocator>::operator[]( k.value()); } else { emp.reset(); return emp; } } optional<T> &operator()(const Key &k) { auto &v = std::map<Key, optional<T>, Compare, Allocator>::operator[](k); if (v.has_value()) return v; else { v.set(0); return v; } } template <class U> void operator[](U) { static string mes = "s_map cant []"; assert2(0, mes); } }; // 以下、空のoptionalをnulloptと書く // ov[-1(参照外)] でnulloptを返す // ov[nullopt] で nulloptをかえす template <class T> struct ov { optional<T> emp; vector<optional<T>> v; ov(int i = 0, T val = 0) : v(i, val) {} template <class U> ov(const U &rhs) { v.resize(sz(rhs)); for (int i = 0; i < sz(rhs); i++) v[i].set(rhs[i]); } optional<T> &operator()(int i) { if (i < 0 || sz(v) <= i) { emp.reset(); return emp; } else { return v[i]; } } optional<T> &operator()(const nullopt_t &) { return operator()(-1); } optional<T> &operator()(const optional<T> &i) { if (i.has_value()) return operator()(i.value()); else { return operator()(-1); } } /*@formatter:off*/ }; template <class T> string deb_tos(const ov<T> &v) { return deb_tos(v.v); } // vectorに対しての処理は.vを呼ぶ template <class T> class ovv { optional<T> emp; public: vector<vector<optional<T>>> v; ovv(int i = 0, int j = 0, T val = 0) : v(i, vector<optional<T>>(j, val)) {} ovv(const vector<vector<T>> &S) { v.resize(S.size()); for (int h = 0; h < sz(S); h++) { v[h].resize(sz(S[h])); for (int w = 0; w < sz(S[h]); w++) { v[h][w].set(S[h][w]); } } } optional<T> &operator()(int i, int j) { if (i < 0 || j < 0 || sz(v) <= i || sz(v[i]) <= j) { emp.reset(); return emp; } else { return v[i][j]; } } // 再帰ver 遅いと思う // optional<T>& gets(optional<T>& v){return v;} // template<class V, class H, class... U> optional<T>& gets(V& v, H i, U... // tail){ if constexpr(is_same2(H, nullopt_t))return // operator()(-1,-1); else if constexpr(is_same2(H, optional<int>)){ // if(i.has_value())return gets(v[(int)i], tail...); else return // operator()(-1,-1); }else if constexpr(is_integral<H>::value){ // return gets(v[(int)i], tail...); }else{ assert(0); // return emp; } } #if __cplusplus >= 201703L // if constexprバージョン 上が遅かったらこれで template <class U, class V> optional<T> &operator()(const U &i, const V &j) { /*駄目な場合を除外*/ if constexpr (is_same2(U, nullopt_t) || is_same2(U, nullopt_t)) { return operator()(-1, -1); /* o, o*/ } else if constexpr (is_same2(U, optional<int>) && is_same2(V, optional<int>)) { return operator()(i.has_value() ? (int)i : -1, j.has_value() ? (int)j : -1); /* o, x*/ } else if constexpr (is_same2(U, optional<int>)) { return operator()(i.has_value() ? (int)i : -1, (int)j); /* x, o*/ } else if constexpr (is_same2(V, optional<int>)) { return operator()((int)i, j.has_value() ? (int)j : -1); /* x, x*/ } else { return operator()((int)i, (int)j); } } #endif operator const vector<vector<optional<T>>> &() { return v; } }; template <class T> istream &operator>>(istream &iss, ovv<T> &a) { for (int h = 0; h < sz(a); h++) { for (int w = 0; w < sz(a[h]); w++) { iss >> a.v[h][w]; } } return iss; } template <class T> ostream &operator<<(ostream &os, ovv<T> &a) { os << a.v; return os; } template <class T> string deb_tos(const ovv<T> &v) { return deb_tos(v.v); } template <class T> struct ov3 { optional<T> emp; vector<vector<vector<optional<T>>>> v; ov3(int i, int j, int k, T val = 0) : v(i, vector<vector<optional<T>>>(j, vector<optional<T>>(k, val))) {} optional<T> &operator()(int i, int j, int k) { if (i < 0 || j < 0 || sz(v) <= i || sz(v[i]) <= j) { if (k < 0 || sz(v[i][j]) <= k) { emp.reset(); return emp; } } return v[i][j][k]; } private: #if __cplusplus >= 201703L // 再帰ver 遅いと思う template <class V, class H> optional<T> &gets(V &nowv, H i) { if constexpr (is_same2(H, nullopt_t)) { emp.reset(); return emp; } else if constexpr (is_same2(H, optional<int>)) { if (i.has_value()) { return nowv[(int)i]; } else { emp.reset(); return emp; } } else if constexpr (is_integral<H>::value) { return nowv[(int)i]; } else { static string mes = "ov3 error not index"; assert2(0, mes); emp.reset(); return emp; } } // todo const &消した template <class V, class H, class... U> optional<T> &gets(V &nowv, H i, U... tail) { if constexpr (is_same2(H, nullopt_t)) { emp.reset(); return emp; } else if constexpr (is_same2(H, optional<int>)) { if (i.has_value()) { return gets(nowv[(int)i], tail...); } else { emp.reset(); return emp; } } else if constexpr (is_integral<H>::value) { return gets(nowv[(int)i], tail...); } else { static string mes = "ov3 error not index"; assert2(0, mes); emp.reset(); return emp; } } #endif public: template <class U, class V, class W> optional<T> &operator()(U i, V j, W k) { return gets(v, i, j, k); } /*@formatter:off*/ }; template <class T> string deb_tos(const ov3<T> &v) { return deb_tos(v.v); } // nullopt_t // 優先順位 // null, [opt, tem] // + と += は違う意味を持つ // val+=null : val // val+null : null // //+は途中計算 //+=は最終的に格納したい値にだけ持たせる //+=がvoidを返すのは、途中計算で使うのを抑制するため // nulloptを考慮する際、計算途中では+を使ってnulloptを作り // 格納する際は+=で無効にする必要がある // 演算子== // optional<int>(10) == 10 // 全ての型に対応させ、value_typeが等しいかを見るようにするのもありかも // null同士を比較する状況はおかしいのではないか bool operator==(const nullopt_t &, const nullopt_t &) { assert2(0, "nul == null cant hikaku"); return false; } template <class T> bool operator==(const nullopt_t &, const T &) { return false; } template <class T> bool operator!=(const nullopt_t &, const T &) { return true; } template <class T> bool operator==(const T &, const nullopt_t &) { return false; } template <class T> bool operator!=(const T &, const nullopt_t &) { return true; } // nullを nullopt_t &operator+(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator-(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator*(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator/(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator+=(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator-=(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator*=(const nullopt_t &, const nullopt_t &) { return nullopt; } nullopt_t &operator/=(const nullopt_t &, const nullopt_t &) { return nullopt; } template <class ANY> nullopt_t operator+(const nullopt_t &, const ANY &) { return nullopt; } template <class ANY> nullopt_t operator-(const nullopt_t &, const ANY &) { return nullopt; } template <class ANY> nullopt_t operator*(const nullopt_t &, const ANY &) { return nullopt; } template <class ANY> nullopt_t operator/(const nullopt_t &, const ANY &) { return nullopt; } template <class ANY> nullopt_t operator+(const ANY &, const nullopt_t &) { return nullopt; } template <class ANY> nullopt_t operator-(const ANY &, const nullopt_t &) { return nullopt; } template <class ANY> nullopt_t operator*(const ANY &, const nullopt_t &) { return nullopt; } template <class ANY> nullopt_t operator/(const ANY &, const nullopt_t &) { return nullopt; } template <class ANY> void operator+=(nullopt_t &, const ANY &) {} template <class ANY> void operator-=(nullopt_t &, const ANY &) {} template <class ANY> void operator*=(nullopt_t &, const ANY &) {} template <class ANY> void operator/=(nullopt_t &, const ANY &) {} template <class ANY> void operator+=(ANY &, const nullopt_t &) {} template <class ANY> void operator-=(ANY &, const nullopt_t &) {} template <class ANY> void operator*=(ANY &, const nullopt_t &) {} template <class ANY> void operator/=(ANY &, const nullopt_t &) {} template <class T> struct is_optional : false_type {}; template <class T> struct is_optional<optional<T>> : true_type {}; template <class T, class U> true_type both_optional(optional<T> t, optional<U> u); false_type both_optional(...); template <class T, class U> class opt_check : public decltype(both_optional(declval<T>(), declval<U>())) {}; // optionalは同じ型同士しか足せない //(o, t), (t, o), (o, o) #define opt_tem(op) \ template <class O, class O_ret = decltype(declval<O>() op declval<O>())> \ optional<O_ret> operator op(const optional<O> &opt1, \ const optional<O> &opt2) { \ if (!opt1.has_value() || !opt2.has_value()) { \ return optional<O_ret>(); \ } else { \ return optional<O_ret>(opt1.value() op opt2.value()); \ } \ } \ template <class O, class T, \ class O_ret = decltype(declval<O>() op declval<O>())> \ auto operator op(const optional<O> &opt, const T &tem) \ ->require_ret(!(opt_check<optional<O>, T>::value), optional<O_ret>) { \ if (!opt.has_value()) { \ return optional<O_ret>(); \ } else { \ return optional<O_ret>(opt.value() op tem); \ } \ } \ template <class O, class T, \ class O_ret = decltype(declval<O>() op declval<O>())> \ auto operator op(const T &tem, const optional<O> &opt) \ ->require_ret(!(opt_check<optional<O>, T>::value), optional<O_ret>) { \ if (!opt.has_value()) { \ return optional<O_ret>(); \ } else { \ return optional<O_ret>(opt.value() op tem); \ } \ } /*@formatter:off*/ opt_tem(+) opt_tem(-) opt_tem(*) opt_tem(/) // 比較はoptional<bool>を返す opt_tem(<) opt_tem(>) opt_tem(<=) opt_tem(>=) /*@formatter:on*/ /*@formatter:off*/ template <class O, class T> bool operator==(const optional<O> &opt, const T &tem) { if (opt.has_value()) { return opt.value() == tem; } else return nullopt == tem; } template <class O, class T> bool operator!=(const optional<O> &opt, const T &tem) { if (opt.has_value()) { return opt.value() != tem; } else return nullopt != tem; } template <class O, class T> bool operator==(const T &tem, const optional<O> &opt) { if (opt.has_value()) { return opt.value() == tem; } else return nullopt == tem; } template <class O, class T> bool operator!=(const T &tem, const optional<O> &opt) { if (opt.has_value()) { return opt.value() != tem; } else return nullopt != tem; } template <class O> bool operator==(const optional<O> &opt1, const optional<O> &opt2) { if (opt1.has_value() != opt2.has_value()) { return false; } else if (opt1.has_value()) { return opt1.value() == opt2.value(); } else { return nullopt == nullopt; } } template <class O> bool operator!=(const optional<O> &opt1, const optional<O> &opt2) { return !(opt1 == opt2); } //(a+=null) != (a=a+null) // a null template <class T, class O> void operator+=(T &tem, const optional<O> &opt) { if (opt.has_value()) { tem += opt.value(); } } template <class T, class O> void operator-=(T &tem, const optional<O> &opt) { if (opt.has_value()) { tem -= opt.value(); } } template <class T, class O> void operator*=(T &tem, const optional<O> &opt) { if (opt.has_value()) { tem *= opt.value(); } } template <class T, class O> void operator/=(T &tem, const optional<O> &opt) { if (opt.has_value()) { tem /= opt.value(); } } template <class T, class O> void operator+=(optional<O> &opt, const T &tem) { if (opt.has_value()) { opt.value() += tem; } } template <class T, class O> void operator-=(optional<O> &opt, const T &tem) { if (opt.has_value()) { opt.value() -= tem; } } template <class T, class O> void operator*=(optional<O> &opt, const T &tem) { if (opt.has_value()) { opt.value() *= tem; } } template <class T, class O> void operator/=(optional<O> &opt, const T &tem) { if (opt.has_value()) { opt.value() /= tem; } } // template <class Ol, class Or> void operator+=(optional<Ol> &opl, const optional<Or> &opr) { if (opr.has_value()) { return opl += opr.value(); } } template <class Ol, class Or> void operator-=(optional<Ol> &opl, const optional<Or> &opr) { if (opr.has_value()) { return opl -= opr.value(); } } template <class Ol, class Or> void operator*=(optional<Ol> &opl, const optional<Or> &opr) { if (opr.has_value()) { return opl *= opr.value(); } } template <class Ol, class Or> void operator/=(optional<Ol> &opl, const optional<Or> &opr) { if (opr.has_value()) { return opl /= opr.value(); } } /*@formatter:off*/ template <class U> auto max(const nullopt_t &, const U &val) { return val; } template <class U> auto max(const U &val, const nullopt_t &) { return val; } template <class U> auto min(const nullopt_t &, const U &val) { return val; } template <class U> auto min(const U &val, const nullopt_t &) { return val; } template <class T, class U> auto max(const optional<T> &opt, const U &val) { if (opt.has_value()) return max(opt.value(), val); else return val; } template <class T, class U> auto max(const U &val, const optional<T> &opt) { if (opt.has_value()) return max(opt.value(), val); else return val; } template <class T, class U> auto min(const optional<T> &opt, const U &val) { if (opt.has_value()) return min(opt.value(), val); else return val; } template <class T, class U> auto min(const U &val, const optional<T> &opt) { if (opt.has_value()) return min(opt.value(), val); else return val; } // null , optional, T bool chma(nullopt_t &, const nullopt_t &) { return false; } template <class T> bool chma(T &opt, const nullopt_t &) { return false; } template <class T> bool chma(nullopt_t &, const T &opt) { return false; } template <class T> bool chma(optional<T> &olv, const optional<T> &orv) { if (orv.has_value()) { return chma(olv, orv.value()); } else return false; } template <class T, class U> bool chma(optional<T> &opt, const U &rhs) { if (opt.has_value()) { return chma(opt.value(), rhs); } else return false; } template <class T, class U> bool chma(T &lhs, const optional<U> &opt) { if (opt.has_value()) { return chma(lhs, opt.value()); } else return false; } bool chmi(nullopt_t &, const nullopt_t &) { return false; } template <class T> bool chmi(T &opt, const nullopt_t &) { return false; } template <class T> bool chmi(nullopt_t &, const T &opt) { return false; } template <class T> bool chmi(optional<T> &olv, const optional<T> &orv) { if (orv.has_value()) { return chmi(olv, orv.value()); } else return false; } template <class T, class U> bool chmi(optional<T> &opt, const U &rhs) { if (opt.has_value()) { return chmi(opt.value(), rhs); } else return false; } template <class T, class U> bool chmi(T &lhs, const optional<U> &opt) { if (opt.has_value()) { return chmi(lhs, opt.value()); } else return false; } template <class T> ostream &operator<<(ostream &os, optional<T> p) { if (p.has_value()) os << p.value(); else os << "e"; return os; } template <class T> using opt = my_optional<T>; struct xorshift { /*@formatter:on*/ static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } /*@formatter:off*/ size_t operator()(const uint64_t &x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } size_t operator()(const std::pair<ll, ll> &x) const { ll v = ((x.first) << 32) | x.second; static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(v + FIXED_RANDOM); } template <class T, class U> size_t operator()(const std::pair<T, U> &x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); uint64_t hasx = splitmix64(x.first); uint64_t hasy = splitmix64(x.second + FIXED_RANDOM); return hasx ^ hasy; } template <class T> size_t operator()(const vector<T> &x) const { uint64_t has = 0; static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); uint64_t rv = splitmix64(FIXED_RANDOM); for (int i = 0; i < sz(x); i++) { uint64_t v = splitmix64(x[i] + rv); has ^= v; rv = splitmix64(rv); } return has; } }; #ifdef _DEBUG // #define use_debtor // template<class T, class U, class X> auto count(unordered_map<T, U> &a, X k) { // return a.find(k) != a.end(); } #ifdef use_debtor // https://marycore.jp/prog/cpp/class-extension-methods/ 違うかも template <class T, class A = std::allocator<T>> struct debtor : std::vector<T, A> { using std::vector<T, A>::vector; template <class U> int deb_v(U a, int v) { return v; } template <class U> int deb_v(debtor<U> &a, int v = 0) { cerr << a.size() << " "; return deb_v(a.at(0), v + 1); } template <class U> void deb_o(U a) { cerr << a << " "; } template <class U> void deb_o(debtor<U> &a) { for (int i = 0; i < min((int)a.size(), 15ll); i++) { deb_o(a[i]); } if ((int)a.size() > 15) { cerr << "..."; } cerr << endl; } typename std::vector<T>::reference my_at(typename std::vector<T>::size_type n, vector<int> &ind) { if (n < 0 || n >= (int)this->size()) { int siz = (int)this->size(); cerr << "vector size = "; int dim = deb_v((*this)); cerr << endl; ind.push_back(n); cerr << "out index at "; for (auto &&i : ind) { cerr << i << " "; } cerr << endl; cerr << endl; if (dim <= 2) { deb_o((*this)); } exit(0); } return this->at(n); } typename std::vector<T>::reference operator[](typename std::vector<T>::size_type n) { if (n < 0 || n >= (int)this->size()) { int siz = (int)this->size(); cerr << "vector size = "; int dim = deb_v((*this)); cerr << endl; cerr << "out index at " << n << endl; cerr << endl; if (dim <= 2) { deb_o((*this)); } exit(0); } return this->at(n); } }; #define vector debtor #endif #ifdef use_pbds template <class T> struct my_pbds_tree { set<T> s; auto begin() { return s.begin(); } auto end() { return s.end(); } auto rbegin() { return s.rbegin(); } auto rend() { return s.rend(); } auto empty() { return s.empty(); } auto size() { return s.size(); } void clear() { s.clear(); } template <class U> void insert(U v) { s.insert(v); } template <class U> void operator+=(U v) { insert(v); } template <class F> auto erase(F v) { return s.erase(v); } template <class U> auto find(U v) { return s.find(v); } template <class U> auto lower_bound(U v) { return s.lower_bound(v); } template <class U> auto upper_bound(U v) { return s.upper_bound(v); } auto find_by_order(ll k) { auto it = s.begin(); for (ll i = 0; i < k; i++) it++; return it; } auto order_of_key(ll v) { auto it = s.begin(); ll i = 0; for (; it != s.end() && *it < v; i++) it++; return i; } }; #define pbds(T) my_pbds_tree<T> #endif // 区間削除は出来ない // gp_hash_tableでcountを使えないようにするため template <class K, class V> using umap_f = unordered_map<K, V>; #else #define endl '\n' // umapはunorderd_mapになる // umapiはgp_hash_table // find_by_order(k) k番目のイテレーター // order_of_key(k) k以上が前から何番目か #define pbds(U) \ __gnu_pbds::tree<U, __gnu_pbds::null_type, less<U>, __gnu_pbds::rb_tree_tag, \ __gnu_pbds::tree_order_statistics_node_update> template <class K, class V> struct umap_f : public __gnu_pbds::gp_hash_table<K, V, xorshift> { int count(const K &k) { return this->find(k) != this->end(); } }; #endif #define umapi unordered_map<ll, ll> #define umapp unordered_map<P, ll> #define umappp unordered_map<P, P> #define umapu unordered_map<uint64_t, ll> #define umapip unordered_map<ll, P> template <class T, class U, class X> auto count(unordered_map<T, U> &a, X k) { return a.find(k) != a.end(); } /*@formatter:off*/ #ifdef use_pbds template <class U, class L> void operator+=( __gnu_pbds::tree<U, __gnu_pbds::null_type, less<U>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> &s, L v) { s.insert(v); } #endif // 衝突対策 #define ws ws_ typedef tuple<ll, ll, ll> T; typedef tuple<ll, ll, ll, ll> F; // T mt(ll a, ll b, ll c) { return T(a, b, c); } // F mf(ll a, ll b, ll c, ll d) { return F(a, b, c, d); } // 関数内をまとめる // 初期値l=-1, r=-1 void set_lr12(int &l, int &r, int n) { /*r==-1*/ if (r == -1) { if (l == -1) { l = 0; r = n; } else { r = l; l = 0; } } } //@マクロ省略系 型,構造 // using で元のdoubleを同時に使えるはず #define double_big #ifdef double_big #define double long double // #define pow powl #endif using dou = double; /*@formatter:off*/ template <class T> T MAX() { return numeric_limits<T>::max(); } template <class T> T MIN() { return numeric_limits<T>::min(); } constexpr ll inf = (ll)1e9 + 100; constexpr ll linf = (ll)1e18 + 100; constexpr dou dinf = (dou)linf * linf; constexpr char infc = '{'; const string infs = "{"; template <class T> T INF() { return MAX<T>() / 2; } template <> signed INF() { return inf; } template <> ll INF() { return linf; } template <> double INF() { return dinf; } template <> char INF() { return infc; } template <> string INF() { return infs; } const double eps = 1e-9; // #define use_epsdou #ifdef use_epsdou // 基本コメントアウト struct epsdou { double v; epsdou(double v = 0) : v(v) {} template <class T> epsdou &operator+=(T b) { v += (double)b; return (*this); } template <class T> epsdou &operator-=(T b) { v -= (double)b; return (*this); } template <class T> epsdou &operator*=(T b) { v *= (double)b; return (*this); } template <class T> epsdou &operator/=(T b) { v /= (double)b; return (*this); } epsdou operator+(epsdou b) { return v + (double)b; } epsdou operator-(epsdou b) { return v - (double)b; } epsdou operator*(epsdou b) { return v * (double)b; } epsdou operator/(epsdou b) { return v / (double)b; } epsdou operator-() const { return epsdou(-v); } template <class T> bool operator<(T b) { return v < (double)b; } template <class T> bool operator>(T b) { auto r = (double)b; return v > (double)b; } template <class T> bool operator==(T b) { return fabs(v - (double)b) <= eps; } template <class T> bool operator<=(T b) { return v < (double)b || fabs(v - b) <= eps; } template <class T> bool operator>=(T b) { return v > (double)b || fabs(v - b) <= eps; } operator double() { return v; } }; template <> epsdou MAX() { return MAX<double>(); } template <> epsdou MIN() { return MIN<double>(); } // priqrity_queue等で使うのに必要 bool operator<(const epsdou &a, const epsdou &b) { return a.v < b.v; } bool operator>(const epsdou &a, const epsdou &b) { return a.v > b.v; } istream &operator>>(istream &iss, epsdou &a) { iss >> a.v; return iss; } ostream &operator<<(ostream &os, epsdou &a) { os << a.v; return os; } #define eps_conr_t(o) \ template <class T> epsdou operator o(T a, epsdou b) { return (dou)a o b.v; } #define eps_conl_t(o) \ template <class T> epsdou operator o(epsdou a, T b) { return a.v o(dou) b; } eps_conl_t(+) eps_conl_t(-) eps_conl_t(*) eps_conl_t(/) eps_conr_t(+) eps_conr_t(-) eps_conr_t(*) eps_conr_t(/) // template<class U> epsdou max(epsdou a, U b){return a.v>b ? a.v: b;} // template<class U> epsdou max(U a, epsdou b){return a>b.v ? a: b.v;} // template<class U> epsdou min(epsdou a, U b){return a.v<b ? a.v: b;} // template<class U> epsdou min(U a, epsdou b){return a<b.v ? a: b.v;} #undef double #define double epsdou #undef dou #define dou epsdou #endif template <class T = int, class A, class B = int> T my_pow(A a, B b = 2) { if (b < 0) return (T)1 / my_pow<T>(a, -b); #if __cplusplus >= 201703L if constexpr (is_floating_point<T>::value) { return pow((T)a, (T)b); } else if constexpr (is_floating_point<A>::value) { assert2( 0, "pow <not dou>(dou, )"); /*return 0;しない方がコンパイル前に(voidを受け取るので)エラーが出ていいかも*/ } else if constexpr (is_floating_point<B>::value) { assert2( 0, "pow <not dou>(, dou)"); /*return 0;しない方がコンパイル前に(voidを受け取るので)エラーが出ていいかも*/ } else { #endif T ret = 1; T bek = a; while (b) { if (b & 1) ret *= bek; bek *= bek; b >>= 1; } return ret; #if __cplusplus >= 201703L } #endif } #define pow my_pow #define ull unsigned long long using itn = int; using str = string; using bo = bool; #define au auto using P = pair<ll, ll>; #define fi first #define se second #define beg begin #define rbeg rbegin #define con continue #define bre break #define brk break #define is == #define el else #define elf else if #define upd update #define sstream stringstream #define maxq 1 #define minq -1 #define ZERO(a) memset(a, 0, sizeof(a)) #define MINUS(a) memset(a, 0xff, sizeof(a)) #define MALLOC(type, len) (type *)malloc((len) * sizeof(type)) #define lam1(ret) [&](auto &&v) { return ret; } #define lam2(v, ret) [&](auto &&v) { return ret; } #define lam(...) over2(__VA_ARGS__, lam2, lam1)(__VA_ARGS__) #define lamr(right) [&](auto &&p) { return p right; } #define unique(v) v.erase(unique(v.begin(), v.end()), v.end()); // マクロ省略系 コンテナ using vi = vector<ll>; using vb = vector<bool>; using vs = vector<string>; using vd = vector<double>; using vc = vector<char>; using vp = vector<P>; using vt = vector<T>; // #define V vector #define vvt0(t) vector<vector<t>> #define vvt1(t, a) vector<vector<t>> a #define vvt2(t, a, b) vector<vector<t>> a(b) #define vvt3(t, a, b, c) vector<vector<t>> a(b, vector<t>(c)) #define vvt4(t, a, b, c, d) vector<vector<t>> a(b, vector<t>(c, d)) #define vv(type, ...) \ over4(__VA_ARGS__, vvt4, vvt3, vvt2, vvt1, vvt0)(type, __VA_ARGS__) #define vvi(...) vv(ll, __VA_ARGS__) #define vvb(...) vv(bool, __VA_ARGS__) #define vvs(...) vv(string, __VA_ARGS__) #define vvd(...) vv(double, __VA_ARGS__) #define vvc(...) vv(char, __VA_ARGS__) #define vvp(...) vv(P, __VA_ARGS__) #define vvt(...) vv(T, __VA_ARGS__) // optional #define vvoi(...) vv(optional<ll>, __VA_ARGS__) template <typename T> vector<T> make_v(size_t a) { return vector<T>(a); } template <typename T, typename... Ts> auto make_v(size_t a, Ts... ts) { return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...)); } #define vni(name, ...) auto name = make_v<ll>(__VA_ARGS__) #define vnb(name, ...) auto name = make_v<bool>(__VA_ARGS__) #define vns(name, ...) auto name = make_v<string>(__VA_ARGS__) #define vnd(name, ...) auto name = make_v<double>(__VA_ARGS__) #define vnc(name, ...) auto name = make_v<char>(__VA_ARGS__) #define vnp(name, ...) auto name = make_v<P>(__VA_ARGS__) #define vn(type, name, ...) auto name = make_v<type>(__VA_ARGS__) #define PQ priority_queue<ll, vector<ll>, greater<ll>> #define tos to_string using mapi = map<ll, ll>; using mapp = map<P, ll>; using mapd = map<dou, ll>; using mapc = map<char, ll>; using maps = map<str, ll>; using seti = set<ll>; using setp = set<P>; using setd = set<dou>; using setc = set<char>; using sets = set<str>; using qui = queue<ll>; #define uset unordered_set #define useti unordered_set<ll, xorshift> #define mset multiset #define mseti multiset<ll> #define umap unordered_map #define mmap multimap // 初期化子を与える template <template <class...> class MAP, class K, class V, class... A> struct init_map : public MAP<K, V, A...> { V init_value; init_map(V init_value = 0) : MAP<K, V, A...>(), init_value(init_value) {} V &operator[](const K &k) { if (MAP<K, V, A...>::count(k) == 0) { return MAP<K, V, A...>::operator[](k) = init_value; } return MAP<K, V, A...>::operator[](k); } }; template <class... A> using map2 = init_map<map, A...>; template <class... A> using umap2 = init_map<umap, A...>; template <class... A> using umap_f2 = init_map<umap_f, A...>; // 任意のマクロサポート用 使う度に初期化する //todo これを消す int index_, v1_, v2_, v3_; /*@formatter:off*/ string to_string(char c) { string ret = ""; ret += c; return ret; } template <class T> class pq_min_max { vector<T> d; void make_heap() { for (int i = d.size(); i--;) { if (i & 1 && d[i - 1] < d[i]) swap(d[i - 1], d[i]); int k = down(i); up(k, i); } } inline int parent(int k) const { return ((k >> 1) - 1) & ~1; } int down(int k) { int n = d.size(); if (k & 1) { /* min heap*/ while (2 * k + 1 < n) { int c = 2 * k + 3; if (n <= c || d[c - 2] < d[c]) c -= 2; if (c < n && d[c] < d[k]) { swap(d[k], d[c]); k = c; } else break; } } else { /* max heap*/ while (2 * k + 2 < n) { int c = 2 * k + 4; if (n <= c || d[c] < d[c - 2]) c -= 2; if (c < n && d[k] < d[c]) { swap(d[k], d[c]); k = c; } else break; } } return k; } int up(int k, int root = 1) { if ((k | 1) < (int)d.size() && d[k & ~1] < d[k | 1]) { swap(d[k & ~1], d[k | 1]); k ^= 1; } int p; while (root < k && d[p = parent(k)] < d[k]) { /*max heap*/ swap(d[p], d[k]); k = p; } while (root < k && d[k] < d[p = parent(k) | 1]) { /* min heap*/ swap(d[p], d[k]); k = p; } return k; } public: pq_min_max() {} pq_min_max(const vector<T> &d_) : d(d_) { make_heap(); } template <class Iter> pq_min_max(Iter first, Iter last) : d(first, last) { make_heap(); } void operator+=(const T &x) { int k = d.size(); d.push_back(x); up(k); } void pop_min() { if (d.size() < 3u) { d.pop_back(); } else { swap(d[1], d.back()); d.pop_back(); int k = down(1); up(k); } } void pop_max() { if (d.size() < 2u) { d.pop_back(); } else { swap(d[0], d.back()); d.pop_back(); int k = down(0); up(k); } } const T &get_min() const { return d.size() < 2u ? d[0] : d[1]; } const T &get_max() const { return d[0]; } int size() const { return d.size(); } bool empty() const { return d.empty(); } }; // 小さいほうからM個取得するpq template <class T> struct helper_pq_size { pq_min_max<T> q; T su = 0; int max_size = 0; helper_pq_size() {} helper_pq_size(int max_size) : max_size(max_size) {} void clear() { q = pq_min_max<T>(); su = 0; } void operator+=(T v) { su += v; q += (v); if (sz(q) > max_size) { su -= q.get_max(); q.pop_max(); } } T sum() { return su; } T top() { return q.get_min(); } void pop() { su -= q.get_min(); q.pop_min(); } T poll() { T ret = q.get_min(); su -= ret; q.pop_min(); return ret; } ll size() { return q.size(); } }; // 大きいほうからM個取得するpq template <class T> struct helper_pqg_size { pq_min_max<T> q; T su = 0; int max_size = 0; helper_pqg_size() {} helper_pqg_size(int max_size) : max_size(max_size) {} void clear() { q = pq_min_max<T>(); su = 0; } void operator+=(T v) { su += v; q += (v); if (sz(q) > max_size) { su -= q.get_min(); q.pop_min(); } } T sum() { return su; } T top() { return q.get_max(); } void pop() { su -= q.get_max(); q.pop_max(); } T poll() { T ret = q.get_max(); su -= ret; q.pop_min(); return ret; } ll size() { return q.size(); } }; ; template <class T, class Container = vector<T>, class Compare = std::less<typename Container::value_type>> struct helper_pqg { priority_queue<T, Container, Compare> q; /*小さい順*/ T su = 0; helper_pqg() {} void clear() { q = priority_queue<T, vector<T>, greater<T>>(); su = 0; } void operator+=(T v) { su += v; q.push(v); } T sum() { return su; } T top() { return q.top(); } void pop() { su -= q.top(); q.pop(); } T poll() { T ret = q.top(); su -= ret; q.pop(); return ret; } ll size() { return q.size(); } }; template <class T> using helper_pq = helper_pqg<T, vector<T>, greater<T>>; #if __cplusplus >= 201703L // 小さいほうからsize個残る // Tがoptionalなら空の時nullを返す template <class T> struct pq { helper_pq<T> a_q; /*大きい順*/ helper_pq_size<T> b_q; /*大きい順*/ bool aquery; T su = 0; pq(int size = inf) { aquery = size == inf; if (!aquery) { b_q = helper_pq_size<T>(size); } } void clear() { if (aquery) a_q.clear(); else b_q.clear(); } void operator+=(T v) { if (aquery) a_q += v; else b_q += v; } // optionalなら空の時nullを返す T top() { if constexpr (is_optional<T>::value) { if (aquery) { if (sz(a_q) == 0) return T(); return a_q.top(); } else { if (sz(b_q) == 0) return T(); return b_q.top(); } } else { if (aquery) return a_q.top(); else return b_q.top(); } } T sum() { if (aquery) return a_q.sum(); else return b_q.sum(); } // optionalなら空の時何もしない void pop() { if constexpr (is_optional<T>::value) { if (aquery) { if (sz(a_q)) a_q.pop(); } else { if (sz(b_q)) b_q.pop(); } } else { if (aquery) a_q.pop(); else b_q.pop(); } } /*T*/ T poll() { if constexpr (is_optional<T>::value) { if (aquery) { if (sz(a_q) == 0) return T(); return a_q.poll(); } else { if (sz(b_q) == 0) return T(); return b_q.poll(); } } else { if (aquery) return a_q.poll(); else return b_q.poll(); } } ll size() { if (aquery) return a_q.size(); else return b_q.size(); } /*@formatter:off*/ }; template <class T> struct pqg { helper_pqg<T> a_q; /*大きい順*/ helper_pqg_size<T> b_q; /*大きい順*/ bool aquery; T su = 0; pqg(int size = inf) { aquery = size == inf; if (!aquery) { b_q = helper_pqg_size<T>(size); } } void clear() { if (aquery) a_q.clear(); else b_q.clear(); } void operator+=(T v) { if (aquery) a_q += v; else b_q += v; } T sum() { if (aquery) return a_q.sum(); else return b_q.sum(); } T top() { if (aquery) return a_q.top(); else return b_q.top(); } void pop() { if (aquery) a_q.pop(); else b_q.pop(); } T poll() { if (aquery) return a_q.poll(); else return b_q.poll(); } ll size() { if (aquery) return a_q.size(); else return b_q.size(); } }; #else // 小さいほうからsize個残る template <class T> struct pq { helper_pq<T> a_q; /*大きい順*/ helper_pq_size<T> b_q; /*大きい順*/ bool aquery; T su = 0; pq(int size = inf) { aquery = size == inf; if (!aquery) { b_q = helper_pq_size<T>(size); } } void clear() { if (aquery) a_q.clear(); else b_q.clear(); } void operator+=(T v) { if (aquery) a_q += v; else b_q += v; } T sum() { if (aquery) return a_q.sum(); else return b_q.sum(); } T top() { if (aquery) return a_q.top(); else return b_q.top(); } void pop() { if (aquery) a_q.pop(); else b_q.pop(); } T poll() { if (aquery) return a_q.poll(); else return b_q.poll(); } ll size() { if (aquery) return a_q.size(); else return b_q.size(); } }; // 大きいほうからsize個残る template <class T> struct pqg { helper_pqg<T> a_q; /*大きい順*/ helper_pqg_size<T> b_q; /*大きい順*/ bool aquery; T su = 0; pqg(int size = inf) { aquery = size == inf; if (!aquery) { b_q = helper_pqg_size<T>(size); } } void clear() { if (aquery) a_q.clear(); else b_q.clear(); } void operator+=(T v) { if (aquery) a_q += v; else b_q += v; } T sum() { if (aquery) return a_q.sum(); else return b_q.sum(); } T top() { if (aquery) return a_q.top(); else return b_q.top(); } void pop() { if (aquery) a_q.pop(); else b_q.pop(); } T poll() { if (aquery) return a_q.poll(); else return b_q.poll(); } ll size() { if (aquery) return a_q.size(); else return b_q.size(); } }; #endif #define pqi pq<ll> #define pqgi pqg<ll> template <class T> string deb_tos(pq<T> &q) { vector<T> res; auto temq = q; while (sz(temq)) res.push_back(temq.top()), temq.pop(); stringstream ss; ss << res; return ss.str(); } template <class T> string deb_tos(pqg<T> &q) { vector<T> res; auto temq = q; while (sz(temq)) res.push_back(temq.top()), temq.pop(); stringstream ss; ss << res; return ss.str(); } /*@formatter:off*/ // マクロ 繰り返し // ↓@オーバーロード隔離 // todo 使わないもの非表示 #define rep1(n) for (ll rep1i = 0, rep1lim = n; rep1i < rep1lim; ++rep1i) #define rep2(i, n) for (ll i = 0, rep2lim = n; i < rep2lim; ++i) #define rep3(i, m, n) for (ll i = m, rep3lim = n; i < rep3lim; ++i) #define rep4(i, m, n, ad) for (ll i = m, rep4lim = n; i < rep4lim; i += ad) // 逆順 閉区間 #define rer2(i, n) for (ll i = n; i >= 0; i--) #define rer3(i, m, n) for (ll i = m, rer3lim = n; i >= rer3lim; i--) #define rer4(i, m, n, dec) for (ll i = m, rer4lim = n; i >= rer4lim; i -= dec) #ifdef use_for // ループを一つにまとめないとフォーマットで汚くなるため #define nex_ind1(i) i++ #define nex_ind2(i, j, J) \ i = (j + 1 == J) ? i + 1 : i, j = (j + 1 == J ? 0 : j + 1) #define nex_ind3(i, j, k, J, K) \ i = (j + 1 == J && k + 1 == K) ? i + 1 : i, \ j = (k + 1 == K) ? (j + 1 == J ? 0 : j + 1) : j, \ k = (k + 1 == K ? 0 : k + 1) #define nex_ind4(i, j, k, l, J, K, L) \ i = (j + 1 == J && k + 1 == K && l + 1 == L) ? i + 1 : i, \ j = (k + 1 == K && l + 1 == L) ? (j + 1 == J ? 0 : j + 1) : j, \ k = (l + 1 == L ? (k + 1 == K ? 0 : k + 1) : k), l = l + 1 == L ? 0 : l + 1 #define nex_ind5(i, j, k, l, m, J, K, L, M) \ i = (j + 1 == J && k + 1 == K && l + 1 == L && m + 1 == M) ? i + 1 : i, \ j = (k + 1 == K && l + 1 == L && m + 1 == M) ? (j + 1 == J ? 0 : j + 1) : j, \ k = (l + 1 == L && m + 1 == M ? (k + 1 == K ? 0 : k + 1) : k), \ l = m + 1 == M ? l + 1 == L ? 0 : l + 1 : l, m = m + 1 == M ? 0 : m + 1 #define repss2(i, I) for (int i = 0; i < I; i++) #define repss4(i, j, I, J) \ for (int i = (J ? 0 : I), j = 0; i < I; nex_ind2(i, j, J)) #define repss6(i, j, k, I, J, K) \ for (int i = (J && K ? 0 : I), j = 0, k = 0; i < I; nex_ind3(i, j, k, J, K)) #define repss8(i, j, k, l, I, J, K, L) \ for (int i = (J && K && L ? 0 : I), j = 0, k = 0, l = 0; i < I; \ nex_ind4(i, j, k, l, J, K, L)) #define repss10(i, j, k, l, m, I, J, K, L, M) \ for (int i = (J && K && L && M ? 0 : I), j = 0, k = 0, l = 0, m = 0; i < I; \ nex_ind5(i, j, k, l, m, J, K, L, M)) // i,j,k...をnまで見る #define reps2(i, n) repss2(i, n) #define reps3(i, j, n) repss4(i, j, n, n) #define reps4(i, j, k, n) repss6(i, j, k, n, n, n) #define reps5(i, j, k, l, n) repss8(i, j, k, l, n, n, n, n) template <class T> void nex_repv2(int &i, int &j, int &I, int &J, vector<vector<T>> &s) { while (1) { j++; if (j >= J) { j = 0; i++; if (i < I) { J = (int)s[i].size(); } } if (i >= I || J) return; } } template <class T> void nex_repv3(int &i, int &j, int &k, int &I, int &J, int &K, vector<vector<vector<T>>> &s) { while (1) { k++; if (k >= K) { k = 0; j++; if (j >= J) { j = 0; i++; if (i >= I) return; } } J = (int)s[i].size(); K = (int)s[i][j].size(); if (J && K) return; } } #define repv_2(i, a) repss2(i, sz(a)) // 正方形である必要はない // 直前を持つのとどっちが早いか #define repv_3(i, j, a) \ for (int repvI = (int)a.size(), repvJ = (int)a[0].size(), i = 0, j = 0; \ i < repvI; nex_repv2(i, j, repvI, repvJ, a)) // 箱状になっている事が要求される つまり[i] 次元目の要素数は一定 #define repv_4(i, j, k, a) \ for (int repvI = (int)a.size(), repvJ = (int)a[0].size(), \ repvK = (int)a[0][0].size(), i = 0, j = 0, k = 0; \ i < repvI; nex_repv3(i, j, k, repvI, repvJ, repvK, a)) #define repv_5(i, j, k, l, a) \ repss8(i, j, k, l, sz(a), sz(a[0]), sz(a[0][0]), sz(a[0][0][0])) #define repv_6(i, j, k, l, m, a) \ repss10(i, j, k, l, m, sz(a), sz(a[0]), sz(a[0][0]), sz(a[0][0][0]), \ sz(a[0][0][0][0])) #endif template <typename T> struct has_rbegin_rend { private: template <typename U> static auto check(U &&obj) -> decltype(std::rbegin(obj), std::rend(obj), std::true_type{}); static std::false_type check(...); public: static constexpr bool value = decltype(check(std::declval<T>()))::value; }; template <typename T> constexpr bool has_rbegin_rend_v = has_rbegin_rend<T>::value; template <typename Iterator> class Range { public: Range(Iterator &&begin, Iterator &&end) noexcept : m_begin(std::forward<Iterator>(begin)), m_end(std::forward<Iterator>(end)) {} Iterator begin() const noexcept { return m_begin; } Iterator end() const noexcept { return m_end; } private: const Iterator m_begin; const Iterator m_end; }; template <typename Iterator> static inline Range<Iterator> makeRange(Iterator &&begin, Iterator &&end) noexcept { return Range<Iterator>{std::forward<Iterator>(begin), std::forward<Iterator>(end)}; } template <typename T> static inline decltype(auto) makeReversedRange(const std::initializer_list<T> &iniList) noexcept { return makeRange(std::rbegin(iniList), std::rend(iniList)); } template <typename T, typename std::enable_if_t<has_rbegin_rend_v<T>, std::nullptr_t> = nullptr> static inline decltype(auto) makeReversedRange(T &&c) noexcept { return makeRange(std::rbegin(c), std::rend(c)); } /* rbegin(), rend()を持たないものはこっちに分岐させて,エラーメッセージを少なくする*/ template <typename T, typename std::enable_if<!has_rbegin_rend<T>::value, std::nullptr_t>::type = nullptr> static inline void makeReversedRange(T &&) noexcept { static_assert(has_rbegin_rend<T>::value, "Specified argument doesn't have reverse iterator."); } // #define use_for #define form3(k, v, st) for (auto &&[k, v] : st) #define form4(k, v, st, r) \ for (auto &&[k, v] : range(st.begin(), st.lower_bound(r))) #define form5(k, v, st, l, r) \ for (auto &&[k, v] : range(st.lower_bound(l), st.lower_bound(r))) #define form(...) over5(__VA_ARGS__, form5, form4, form3)(__VA_ARGS__) #define forrm1(st) \ for (auto &&forrm_it = st.rbegin(); forrm_it != st.rend(); ++forrm_it) #define forrm3(k, v, st) \ for (auto &&forrm_it = st.rbegin(); forrm_it != st.rend(); ++forrm_it) // 向こう側で // ++itか it = st.erase(it)とする #define fors1(st) for (auto &&it = st.begin(); it != st.end();) #define fors2(v, st) for (auto &&it = st.begin(); it != st.end();) #define fors3(v, st, r) \ for (auto &&it = st.begin(); it != st.end() && (*it) < r;) #define fors4(v, st, l, r) \ for (auto &&it = st.lower_bound(l); it != st.end() && (*it) < r;) #ifdef use_for #define forslr3(st, a, b) \ for (auto &&forslr_it = st.begin(); forslr_it != st.end(); ++forslr_it) #define forslr4(v, st, a, b) \ for (auto &&forslr_it = st.begin(); forslr_it != st.end(); ++forslr_it) #define forslr5(v, st, r, a, b) \ for (auto &&forslr_it = st.begin(); \ forslr_it != st.end() && (*forslr_it) < r; ++forslr_it) #define forslr6(v, st, l, r, a, b) \ for (auto &&forslr_it = st.lower_bound(l); \ forslr_it != st.end() && (*forslr_it) < r; ++forslr_it) #define fora_f_init_2(a, A) ; #define fora_f_init_3(fora_f_i, a, A) auto &&a = A[fora_f_i]; #define fora_f_init_4(a, b, A, B) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; #define fora_f_init_5(fora_f_i, a, b, A, B) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; #define fora_f_init_6(a, b, c, A, B, C) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; \ auto &&c = C[fora_f_i]; #define fora_f_init_7(fora_f_i, a, b, c, A, B, C) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; \ auto &&c = C[fora_f_i]; #define fora_f_init_8(a, b, c, d, A, B, C, D) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; \ auto &&c = C[fora_f_i]; \ auto &&d = D[fora_f_i]; #define fora_f_init_9(fora_f_i, a, b, c, d, A, B, C, D) \ auto &&a = A[fora_f_i]; \ auto &&b = B[fora_f_i]; \ auto &&c = C[fora_f_i]; \ auto &&d = D[fora_f_i]; #define fora_f_init(...) \ over9(__VA_ARGS__, fora_f_init_9, fora_f_init_8, fora_f_init_7, \ fora_f_init_6, fora_f_init_5, fora_f_init_4, fora_f_init_3, \ fora_f_init_2)(__VA_ARGS__) #define forr_init_2(a, A) auto &&a = A[forr_i]; #define forr_init_3(forr_i, a, A) auto &&a = A[forr_i]; #define forr_init_4(a, b, A, B) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; #define forr_init_5(forr_i, a, b, A, B) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; #define forr_init_6(a, b, c, A, B, C) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; \ auto &&c = C[forr_i]; #define forr_init_7(forr_i, a, b, c, A, B, C) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; \ auto &&c = C[forr_i]; #define forr_init_8(a, b, c, d, A, B, C, D) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; \ auto &&c = C[forr_i]; \ auto &&d = D[forr_i]; #define forr_init_9(forr_i, a, b, c, d, A, B, C, D) \ auto &&a = A[forr_i]; \ auto &&b = B[forr_i]; \ auto &&c = C[forr_i]; \ auto &&d = D[forr_i]; #define forr_init(...) \ over9(__VA_ARGS__, forr_init_9, forr_init_8, forr_init_7, forr_init_6, \ forr_init_5, forr_init_4, forr_init_3, forr_init_2)(__VA_ARGS__) #define forp_init3(k, v, S) \ auto &&k = S[forp_i].first; \ auto &&v = S[forp_i].second; #define forp_init4(forp_i, k, v, S) \ auto &&k = S[forp_i].first; \ auto &&v = S[forp_i].second; #define forp_init(...) \ over4(__VA_ARGS__, forp_init4, forp_init3, forp_init2, \ forp_init1)(__VA_ARGS__) #define forrm_init(k, v, ...) \ auto &&k = (*forrm_it).fi; \ auto &&v = (*forrm_it).se; #define fors_init(v, ...) auto &&v = (*it); #define forlr_init(a, A, ngl, ngr) \ auto a = A[forlr_i]; \ auto prev = forlr_i ? A[forlr_i - 1] : ngl; \ auto next = forlr_i + 1 < rep2lim ? A[forlr_i + 1] : ngr; #define forslr_init4(a, A, ngl, ngr) \ auto a = (*forslr_it); \ auto prev = (forslr_it != A.begin()) ? (*std::prev(forslr_it)) : ngl; \ auto next = (forslr_it != std::prev(A.end())) ? (*std::next(forslr_it)) : ngr; #define forslr_init5(a, A, r, ngl, ngr) \ auto a = (*forslr_it); \ auto prev = (forslr_it != A.begin()) ? (*std::prev(forslr_it)) : ngl; \ auto next = (forslr_it != std::prev(A.end())) ? (*std::next(forslr_it)) : ngr; #define forslr_init6(a, A, l, r, ngl, ngr) \ auto a = (*forslr_it); \ auto prev = (forslr_it != A.begin()) ? (*std::prev(forslr_it)) : ngl; \ auto next = (forslr_it != std::prev(A.end())) ? (*std::next(forslr_it)) : ngr; #define forslr_init(...) \ over6(__VA_ARGS__, forslr_init6, forslr_init5, forslr_init4)(__VA_ARGS__); // こうしないとmapがおかしくなる #define fora_f_2(a, A) for (auto &&a : A) #define fora_f_3(fora_f_i, a, A) rep(fora_f_i, sz(A)) #define fora_f_4(a, b, A, B) rep(fora_f_i, sz(A)) #define fora_f_5(fora_f_i, a, b, A, B) rep(fora_f_i, sz(A)) #define fora_f_6(a, b, c, A, B, C) rep(fora_f_i, sz(A)) #define fora_f_7(fora_f_i, a, b, c, A, B, C) rep(fora_f_i, sz(A)) #define fora_f_8(a, b, c, d, A, B, C, D) rep(fora_f_i, sz(A)) #define fora_f_9(fora_f_i, a, b, c, d, A, B, C, D) rep(fora_f_i, sz(A)) #define forr_2(a, A) rer(forr_i, sz(A) - 1) #define forr_3(forr_i, a, A) rer(forr_i, sz(A) - 1) #define forr_4(a, b, A, B) rer(forr_i, sz(A) - 1) #define forr_5(forr_i, a, b, A, B) rer(forr_i, sz(A) - 1) #define forr_6(a, b, c, A, B, C) rer(forr_i, sz(A) - 1) #define forr_7(forr_i, a, b, c, A, B, C) rer(forr_i, sz(A) - 1) #define forr_8(a, b, c, d, A, B, C, D) rer(forr_i, sz(A) - 1) #define forr_9(forr_i, a, b, c, d, A, B, C, D) rer(forr_i, sz(A) - 1) #endif // ↑@オーバーロード隔離 // rep系はインデックス、for系は中身 #define rep(...) over4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__) #define rer(...) over4(__VA_ARGS__, rer4, rer3, rer2, )(__VA_ARGS__) // 自分込みで残りがREM以上の間ループを回す #define rem(i, N, REM) for (int i = 0; i < N - REM + 1; i++) // char用のrep #define repc(i, m, n) for (char i = m, repc3lim = n; i < repc3lim; ++i) // i,j,k...をnまで見る #define reps(...) over5(__VA_ARGS__, reps5, reps4, reps3, reps2, )(__VA_ARGS__) #define repss(...) \ over10(__VA_ARGS__, repss10, a, repss8, a, repss6, a, repss4, a, \ repss2)(__VA_ARGS__) // vectorのindexを走査する // repv(i,j,vvi) #define repv(...) \ over6(__VA_ARGS__, repv_6, repv_5, repv_4, repv_3, repv_2, )(__VA_ARGS__) #define rerv(i, A) for (int i = sz(A) - 1; i >= 0; i--) // repvn(dp) nは次元 #define repv1(a) repv(i, a) #define repv2(a) repv(i, j, a) #define repv3(a) repv(i, j, k, a) #define repv4(a) repv(i, j, k, l, a) #ifdef use_for #define fora_f(...) \ over9(__VA_ARGS__, fora_f_9, fora_f_8, fora_f_7, fora_f_6, fora_f_5, \ fora_f_4, fora_f_3, fora_f_2)(__VA_ARGS__) #endif #define forr(...) \ over9(__VA_ARGS__, forr_9, forr_8, forr_7, forr_6, forr_5, forr_4, forr_3, \ forr_2)(__VA_ARGS__) // 0~N-2まで見る #define forar_init(v, rv, A) \ auto &&v = A[forar_i]; \ auto &&rv = A[forar_i + 1]; #define forar(v, rv, A) rep(forar_i, sz(A) - 1) #if __cplusplus >= 201703L template <size_t M_SZ, bool indexed, class Iterator, class T, class U = T, class V = T, class W = T> class ite_vec_merge : public Iterator { std::size_t i = 0; vector<T> &A; vector<U> &B; vector<V> &C; vector<W> &D; public: ite_vec_merge(Iterator ita, vector<T> &A) : Iterator(ita), A(A), B(A), C(A), D(A) {} ite_vec_merge(Iterator ita, vector<T> &A, vector<U> &B) : Iterator(ita), A(A), B(B), C(A), D(A) {} ite_vec_merge(Iterator ita, vector<T> &A, vector<U> &B, vector<V> &C) : Iterator(ita), A(A), B(B), C(C), D(A) {} ite_vec_merge(Iterator ita, vector<T> &A, vector<U> &B, vector<V> &C, vector<W> &D) : Iterator(ita), A(A), B(B), C(C), D(D) {} auto &operator++() { ++i; this->Iterator::operator++(); return *this; } auto operator*() const noexcept { if constexpr (!indexed && M_SZ == 1) { return tuple<T &>(A[i]); } else if constexpr (!indexed && M_SZ == 2) { return tuple<T &, U &>(A[i], B[i]); } else if constexpr (!indexed && M_SZ == 3) { return tuple<T &, U &, V &>(A[i], B[i], C[i]); } else if constexpr (!indexed && M_SZ == 4) { return tuple<T &, U &, V &, W &>(A[i], B[i], C[i], D[i]); } else if constexpr (indexed && M_SZ == 1) { return tuple<int, T &>(i, A[i]); } else if constexpr (indexed && M_SZ == 2) { return tuple<int, T &, U &>(i, A[i], B[i]); } else if constexpr (indexed && M_SZ == 3) { return tuple<int, T &, U &, V &>(i, A[i], B[i], C[i]); } else if constexpr (indexed && M_SZ == 4) { return tuple<int, T &, U &, V &, W &>(i, A[i], B[i], C[i], D[i]); } else { assert(0); return tuple<int>(i); } } }; template <size_t M_SZ, bool indexed, class T, class U = T, class V = T, class W = T> class vec_merge { vector<T> &a; vector<U> &b; vector<V> &c; vector<W> &d; public: vec_merge(vector<T> &a) : a(a), b(a), c(a), d(a) {} vec_merge(vector<T> &a, vector<U> &b) : a(a), b(b), c(a), d(a) {} vec_merge(vector<T> &a, vector<U> &b, vector<V> &c) : a(a), b(b), c(c), d(a) {} vec_merge(vector<T> &a, vector<U> &b, vector<V> &c, vector<W> &d) : a(a), b(b), c(c), d(d) {} auto begin() const { if constexpr (M_SZ == 1) { return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a}; } else if constexpr (M_SZ == 2) { return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a, b}; } else if constexpr (M_SZ == 3) { return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a, b, c}; } else if constexpr (M_SZ == 4) { return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a, b, c, d}; } else { assert(0); return ite_vec_merge<M_SZ, indexed, decltype(std::begin(a)), T, U, V, W>{ std::begin(a), a}; } } auto end() const { if constexpr (M_SZ == 1) { return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a}; } else if constexpr (M_SZ == 2) { return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a, b}; } else if constexpr (M_SZ == 3) { return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a, b, c}; } else if constexpr (M_SZ == 4) { return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a, b, c, d}; } else { assert(0); return ite_vec_merge<M_SZ, indexed, decltype(std::end(a)), T, U, V, W>{ std::end(a), a}; } } }; #endif #define fora_2(a, A) for (auto &&a : A) #if __cplusplus >= 201703L #define fora_3(i, a, A) \ for (auto [i, a] : vec_merge<1, true, decl_t<decltype(A)>>(A)) #define fora_4(a, b, A, B) \ for (auto [a, b] : \ vec_merge<2, false, decl_t<decltype(A)>, decl_t<decltype(B)>>(A, B)) #define fora_5(i, a, b, A, B) \ for (auto [i, a, b] : \ vec_merge<2, true, decl_t<decltype(A)>, decl_t<decltype(B)>>(A, B)) #define fora_6(a, b, c, A, B, C) \ for (auto [a, b, c] : \ vec_merge<3, false, decl_t<decltype(A)>, decl_t<decltype(B)>, \ decl_t<decltype(C)>>(A, B, C)) #define fora_7(i, a, b, c, A, B, C) \ for (auto [i, a, b, c] : \ vec_merge<3, true, decl_t<decltype(A)>, decl_t<decltype(B)>, \ decl_t<decltype(C)>>(A, B, C)) #define fora_8(a, b, c, d, A, B, C, D) \ for (auto [a, b, c, d] : \ vec_merge<4, false, decl_t<decltype(A)>, decl_t<decltype(B)>, \ decl_t<decltype(C)>, decl_t<decltype(D)>>(A, B, C, D)) #define fora_9(i, a, b, c, d, A, B, C, D) \ for (auto [i, a, b, c, d] : \ vec_merge<4, true, decl_t<decltype(A)>, decl_t<decltype(B)>, \ decl_t<decltype(C)>, decl_t<decltype(D)>>(A, B, C, D)) #endif // 構造化束縛ver // 1e5要素で40ms程度 // 遅いときはfora_fを使う #define fora(...) \ over9(__VA_ARGS__, fora_9, fora_8, fora_7, fora_6, fora_5, fora_4, fora_3, \ fora_2)(__VA_ARGS__) // #define forr(v, a) for(auto&& v : makeReversedRange(a)) // 参照を取らない /*@formatter:off*/ #ifdef use_for template <class U> vector<U> to1d(vector<U> &a) { return a; } template <class U> auto to1d(vector<vector<U>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) res.push_back(a2); return res; } template <class U> vector<U> to1d(vector<vector<vector<U>>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) for (auto &&a3 : a2) res.push_back(a3); return res; } template <class U> vector<U> to1d(vector<vector<vector<vector<U>>>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) for (auto &&a3 : a2) for (auto &&a4 : a3) res.push_back(a4); return res; } template <class U> vector<U> to1d(vector<vector<vector<vector<vector<U>>>>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) for (auto &&a3 : a2) for (auto &&a4 : a3) for (auto &&a5 : a4) res.push_back(a5); return res; } template <class U> vector<U> to1d(vector<vector<vector<vector<vector<vector<U>>>>>> &a) { vector<U> res; for (auto &&a1 : a) for (auto &&a2 : a1) for (auto &&a3 : a2) for (auto &&a4 : a3) for (auto &&a5 : a4) for (auto &&a6 : a5) res.push_back(a6); return res; } #define forv(a, b) for (auto a : to1d(b)) // インデックスを前後含めて走査 #define ring(i, s, len) \ for (int i = s, prev = (s == 0) ? len - 1 : s - 1, \ next = (s == len - 1) ? 0 : s + 1, cou = 0; \ cou < len; \ cou++, prev = i, i = next, next = (next == len - 1) ? 0 : next + 1) // 値と前後を見る #define ringv(v, d) \ index_ = 0; \ for (auto prev = d[sz(d) - 1], next = (int)d.size() > 1 ? d[1] : d[0], \ v = d[0]; \ index_ < sz(d); index_++, prev = v, v = next, \ next = (index_ >= sz(d) - 1 ? d[0] : d[index_ + 1])) // 左右をnext prevで見る 0の左と nの右 #define forlr(v, d, banpei_l, banpei_r) rep(forlr_i, sz(d)) #endif #define forrm(...) \ over5(__VA_ARGS__, forrm5, forrm4, forrm3, forrm2, forrm1)(__VA_ARGS__) #define fors(...) over4(__VA_ARGS__, fors4, fors3, fors2, fors1)(__VA_ARGS__) #define forslr(...) \ over6(__VA_ARGS__, forslr6, forslr5, forslr4, forslr3)(__VA_ARGS__) #define forp3(k, v, st) rep(forp_i, sz(st)) #define forp4(forp_i, k, v, st) rep(forp_i, sz(st)) #define forp(...) over4(__VA_ARGS__, forp4, forp3)(__VA_ARGS__) // to_vec(rep(i, N))のように使い // iが走査した値を持つvectorを返す #define to_vec2(type, my_for) \ [&]() { \ vector<type> ret; \ my_for { ret.push_back(i); } \ return ret; \ }() #define to_vec1(my_for) to_vec2(int, my_for) #define to_vec(...) over2(__VA_ARGS__, to_vec2, to_vec1)(__VA_ARGS__) // マクロ 定数 #define k3 1010 #define k4 10101 #define k5 101010 #define k6 1010101 #define k7 10101010 const double PI = 3.1415926535897932384626433832795029L; constexpr bool ev(ll a) { return !(a & 1); } constexpr bool od(ll a) { return (a & 1); } //@拡張系 こう出来るべきというもの // 埋め込み 存在を意識せずに機能を増やされているもの namespace std { template <> class hash<std::pair<signed, signed>> { public: size_t operator()(const std::pair<signed, signed> &x) const { return hash<ll>()(((ll)x.first << 32) | x.second); } }; template <> class hash<std::pair<ll, ll>> { public : /*大きいllが渡されると、<<32でオーバーフローするがとりあえず問題ないと判断*/ size_t operator()(const std::pair<ll, ll> &x) const { return hash<ll>()(((ll)x.first << 32) | x.second); } }; } // namespace std // stream まとめ /*@formatter:off*/ istream &operator>>(istream &iss, P &a) { iss >> a.first >> a.second; return iss; } template <typename T> istream &operator>>(istream &iss, vector<T> &vec_) { for (T &x : vec_) iss >> x; return iss; } template <class T, class U> ostream &operator<<(ostream &os, pair<T, U> p) { os << p.fi << " " << p.se; return os; } ostream &operator<<(ostream &os, T p) { os << get<0>(p) << " " << get<1>(p) << " " << get<2>(p); return os; } ostream &operator<<(ostream &os, F p) { os << get<0>(p) << " " << get<1>(p) << " " << get<2>(p) << " " << get<3>(p); return os; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec_) { for (ll i = 0; i < vec_.size(); ++i) os << vec_[i] << (i + 1 == vec_.size() ? "" : " "); return os; } template <typename T> ostream &operator<<(ostream &os, const vector<vector<T>> &vec_) { for (ll i = 0; i < vec_.size(); ++i) { for (ll j = 0; j < vec_[i].size(); ++j) { os << vec_[i][j] << " "; } os << endl; } return os; } template <typename T, typename U> ostream &operator<<(ostream &os, const map<T, U> &m) { os << endl; for (auto &&v : m) os << v << endl; return os; } template <typename T, typename U> ostream &operator<<(ostream &os, const unordered_map<T, U> &m) { os << endl; for (auto &&v : m) os << v << endl; return os; } template <typename T, typename U> string deb_tos(const unordered_map<T, U> &m) { map<T, U> a; for (auto &&v : m) { a[v.first] = v.second; } stringstream ss; ss << a; return ss.str(); } template <class T> ostream &operator<<(ostream &os, const set<T> &s) { fora(v, s) { os << v << " "; } return os; } template <class T> ostream &operator<<(ostream &os, const mset<T> &s) { fora(v, s) { os << v << " "; } return os; } template <class T> ostream &operator<<(ostream &os, const deque<T> &a) { fora(v, a) { os << v << " "; } return os; } ostream &operator<<(ostream &os, const vector<vector<char>> &vec_) { rep(h, sz(vec_)) { rep(w, sz(vec_[0])) { os << vec_[h][w]; } os << endl; } return os; } ostream &operator<<(ostream &os, const vector<vector<my_optional<char>>> &vec_) { rep(h, sz(vec_)) { rep(w, sz(vec_[0])) { os << vec_[h][w]; } os << endl; } return os; } // tuple "," 区切り #if __cplusplus >= 201703L template <class Tuple, size_t... Indicies> void helper_os_tuple(ostream &os, const Tuple &tup, index_sequence<Indicies...>) { stringstream ss; auto f = [&](auto a) { ss << ", " << a; }; (..., f(get<Indicies>(tup))); os << ss.str().substr(2); } template <class... T> ostream &operator<<(ostream &os, const tuple<T...> &tup) { helper_os_tuple(os, tup, index_sequence_for<T...>{}); return os; } #endif template <class T> struct range_now { int l; vector<T> A; range_now(vector<T> &&A, int l) : A(A), l(l) {} }; /*@formatter:off*/ // template<class T,class U>ostream &operator<<(ostream &os, vector<pair<T,U>>& // a) {fora_f(v,a)os<<v<<endl;return os;} template <typename W, typename H> void resize(W &vec_, const H head) { vec_.resize(head); } template <typename W, typename H, typename... T> void resize(W &vec_, const H &head, const T... tail) { vec_.resize(head); for (auto &v : vec_) resize(v, tail...); } // #define use_for_each //_each _all_of _any_of _none_of _find_if _rfind_if // _contains _count_if _erase_if _entry_if #ifdef use_for_each // todo Atcoderの過去問がc++17に対応したら #if __cplusplus >= 201703L // for_each以外はconst & (呼び出し側のラムダも) template <typename T, typename F> bool all_of2(const T &v, F f) { if constexpr (has_value_type<T>::value) { for (auto &&v_ : v) { if (!all_of2(v_, f)) return false; } return true; } else { return f(v); } } template <typename T, typename F> bool any_of2(const T &v, F f) { if constexpr (has_value_type<T>::value) { for (auto &&v_ : v) { if (any_of2(v_, f)) return true; } return false; } else { return f(v); } } template <typename T, typename F> bool none_of2(const T &v, F f) { return all_of2(v, [&](auto a) { return !f(a); }); } /*@formatter:off*/ // 存在しない場合 // 1次元 Nを返す // 多次元-1を返す template <typename T, typename F> ll find_if2(const vector<T> &v, F f) { rep(i, sz(v)) { if (f(v[i])) return i; } return sz(v); } template <typename T, typename F> tuple<int, int> find_if2(const vector<vector<T>> &v, F f) { rep(i, sz(v)) { rep(j, sz(v[i])) { if (f(v[i][j])) { return tuple<int, int>(i, j); } } } return tuple<int, int>(-1, -1); } template <typename T, typename F> auto find_if2(const vector<vector<vector<T>>> &v, F f) { rep(i, sz(v)) { if (auto ret = find_if2(v[i], f); get<0>(ret) != -1) { return tuple_cat(tuple<int>(i), ret); } } auto bad = tuple_cat(tuple<int>(-1), find_if2(v[0], f)); return bad; } template <class T, class F> auto find_if2(const range_now<T> &v, F f) { return find_if2(v.A, f) + v.l; } // 存在しない場合 // 1次元 -1を返す // 多次元-1を返す template <typename T, typename F> ll rfind_if2(const vector<T> &v, F f) { rer(i, sz(v) - 1) { if (f(v[i])) return i; } return -1; } template <typename T, typename F> tuple<int, int> rfind_if2(const vector<vector<T>> &v, F f) { rer(i, sz(v) - 1) { rer(j, sz(v[i]) - 1) { if (f(v[i][j])) { return tuple<int, int>(i, j); } } } return tuple<int, int>(-1, -1); } template <typename T, typename F> auto rfind_if2(const vector<vector<vector<T>>> &v, F f) { rer(i, sz(v) - 1) { if (auto ret = rfind_if2(v[i], f); get<0>(ret) != -1) { return tuple_cat(tuple<int>(i), ret); } } auto bad = tuple_cat(tuple<int>(-1), rfind_if2(v[0], f)); return bad; } // todo まとめられそう string,vector全般 template <class T> bool contains(const string &s, const T &v) { return s.find(v) != string::npos; } template <typename T> bool contains(const vector<T> &v, const T &val) { return std::find(v.begin(), v.end(), val) != v.end(); } template <typename T, typename F> bool contains_if2(const vector<T> &v, F f) { return find_if(v.begin(), v.end(), f) != v.end(); } template <typename T, typename F> ll count_if2(const T &v, F f) { if constexpr (has_value_type<T>::value) { ll ret = 0; for (auto &&v_ : v) { ret += count_if2(v_, f); } return ret; } else { return f(v); } } template <typename T, typename F> void for_each2(T &a, F f) { if constexpr (has_value_type<T>::value) { for (auto &&v_ : a) for_each2(v_, f); } else { f(a); } } #else template <typename T, typename F> bool all_of2(const T &v, F f) { return f(v); } template <typename T, typename F> bool all_of2(const vector<T> &v, F f) { rep(i, sz(v)) { if (!all_of2(v[i], f)) return false; } return true; } template <typename T, typename F> bool any_of2(const T &v, F f) { return f(v); } template <typename T, typename F> bool any_of2(const vector<T> &v, F f) { rep(i, sz(v)) { if (any_of2(v[i], f)) return true; } return false; } template <typename T, typename F> bool none_of2(const T &v, F f) { return f(v); } template <typename T, typename F> bool none_of2(const vector<T> &v, F f) { rep(i, sz(v)) { if (none_of2(v[i], f)) return false; } return true; } template <typename T, typename F> bool find_if2(const T &v, F f) { return f(v); } template <typename T, typename F> ll find_if2(const vector<T> &v, F f) { rep(i, sz(v)) { if (find_if2(v[i], f)) return i; } return sz(v); } template <typename T, typename F> bool rfind_if2(const T &v, F f) { return f(v); } template <typename T, typename F> ll rfind_if2(const vector<T> &v, F f) { rer(i, sz(v) - 1) { if (rfind_if2(v[i], f)) return i; } return -1; } template <class T> bool contains(const string &s, const T &v) { return s.find(v) != string::npos; } template <typename T> bool contains(const vector<T> &v, const T &val) { return std::find(v.begin(), v.end(), val) != v.end(); } template <typename T, typename F> bool contains_if2(const vector<T> &v, F f) { return find_if(v.begin(), v.end(), f) != v.end(); } template <typename T, typename F> ll count_if2(const T &v, F f) { return f(v); } template <typename T, typename F> ll count_if2(const vector<T> &vec_, F f) { ll ret = 0; fora(v, vec_) { ret += count_if2(v, f); } return ret; } template <typename T, typename F> void for_each2(T &a, F f) { f(a); } template <typename T, typename F> void for_each2(vector<T> &a, F f) { for (auto &&v_ : a) for_each2(v_, f); } #endif template <typename W> ll count_od(const vector<W> &a) { return count_if2(a, [](ll v) { return v & 1; }); } template <typename W> ll count_ev(const vector<W> &a) { return count_if2(a, [](ll v) { return !(v & 1); }); } // 削除した後のvectorを返す template <typename T, typename F> vector<T> erase_if2(const vector<T> &v, F f) { vector<T> nv; rep(i, sz(v)) { if (!f(v[i])) { nv.push_back(v[i]); } } return nv; } template <typename T, typename F> vector<vector<T>> erase_if2(const vector<vector<T>> &v, F f) { vector<vector<T>> res; rep(i, sz(v)) { res[i] = erase_if2(v[i], f); } return res; } template <typename T, typename F> vector<T> entry_if2(const vector<T> &v, F f) { vector<T> nv; rep(i, sz(v)) { if (f(v[i])) { nv.push_back(v[i]); } } return nv; } template <typename T, typename F> vector<vector<T>> entry_if2(const vector<vector<T>> &v, F f) { vector<vector<T>> res; rep(i, sz(v)) { res[i] = entry_if2(v[i], f); } return res; } template <typename T, typename F> ll l_rfind_if(const vector<T> &v, F f) { rer(i, sz(v) - 1) { if (f(v[i])) return i; } return -1; } template <typename T, typename F> bool l_contains_if(const vector<T> &v, F f) { rer(i, sz(v) - 1) { if (f(v[i])) return true; } return false; } template <class A, class B, class C> auto t_all_of(A a, B b, C c) { return std::all_of(a, b, c); } template <class A, class B, class C> auto t_any_of(A a, B b, C c) { return std::any_of(a, b, c); } template <class A, class B, class C> auto t_none_of(A a, B b, C c) { return std::none_of(a, b, c); } template <class A, class B, class C> auto t_find_if(A a, B b, C c) { return std::find_if(a, b, c); } template <class A, class B, class C> auto t_count_if(A a, B b, C c) { return std::count_if(a, b, c); } #define all_of_s__2(a, right) (t_all_of(ALL(a), lamr(right))) #define all_of_s__3(a, v, siki) (t_all_of(ALL(a), [&](auto v) { return siki; })) #define all_of_s(...) over3(__VA_ARGS__, all_of_s__3, all_of_s__2)(__VA_ARGS__) // all_of(A, %2); // all_of(A, a, a%2); #define all_of__2(a, right) all_of2(a, lamr(right)) #define all_of__3(a, v, siki) all_of2(a, [&](auto v) { return siki; }) #define all_of(...) over3(__VA_ARGS__, all_of__3, all_of__2)(__VA_ARGS__) #define all_of_f(a, f) all_of2(a, f) #define any_of_s__2(a, right) (t_any_of(ALL(a), lamr(right))) #define any_of_s__3(a, v, siki) (t_any_of(ALL(a), [&](auto v) { return siki; })) #define any_of_s(...) over3(__VA_ARGS__, any_of_s__3, any_of_s__2)(__VA_ARGS__) #define any_of__2(a, right) any_of2(a, lamr(right)) #define any_of__3(a, v, siki) any_of2(a, [&](auto v) { return siki; }) #define any_of(...) over3(__VA_ARGS__, any_of__3, any_of__2)(__VA_ARGS__) #define any_of_f(a, f) any_of2(a, f) #define none_of_s__2(a, right) (t_none_of(ALL(a), lamr(right))) #define none_of_s__3(a, v, siki) \ (t_none_of(ALL(a), [&](auto v) { return siki; })) #define none_of_s(...) \ over3(__VA_ARGS__, none_of_s__3, none_of_s__2)(__VA_ARGS__) #define none_of__2(a, right) none_of2(a, lamr(right)) #define none_of__3(a, v, siki) none_of2(a, [&](auto v) { return siki; }) #define none_of(...) over3(__VA_ARGS__, none_of__3, none_of__2)(__VA_ARGS__) #define none_of_f(a, f) none_of2(a, f) #define find_if_s__2(a, right) (t_find_if(ALL(a), lamr(right)) - a.begin()) #define find_if_s__3(a, v, siki) \ (t_find_if(ALL(a), [&](auto v) { return siki; }) - a.begin()) #define find_if_s(...) \ over3(__VA_ARGS__, find_if_s__3, find_if_s__2)(__VA_ARGS__) #define find_if__2(a, right) find_if2(a, lamr(right)) #define find_if__3(a, v, siki) find_if2(a, [&](auto v) { return siki; }) #define find_if__4(a, l, v, siki) \ (find_if2(decltype(a)(a.begin() + l, a.end()), \ [&](auto v) { return siki; }) + \ l) #define find_if(...) \ over4(__VA_ARGS__, find_if__4, find_if__3, find_if__2)(__VA_ARGS__) #define find_if_f(a, f) find_if2(a, f) #define rfind_if_s__2(a, right) l_rfind_if(a, lamr(right)) #define rfind_if_s__3(a, v, siki) l_rfind_if(a, [&](auto v) { return siki; }) #define rfind_if_s(...) \ over3(__VA_ARGS__, rfind_if_s__3, rfind_if_s__2)(__VA_ARGS__) #define rfind_if__2(a, right) rfind_if2(a, lamr(right)) #define rfind_if__3(a, v, siki) rfind_if2(a, [&](auto v) { return siki; }) #define rfind_if(...) over3(__VA_ARGS__, rfind_if__3, rfind_if__2)(__VA_ARGS__) #define rfind_if_f(a, f) rfind_if2(a, f) #define contains_if_s__2(a, right) l_contains_if(a, lamr(right)) #define contains_if_s__3(a, v, siki) \ l_contains_if(a, [&](auto v) { return siki; }) #define contains_if_s(...) \ over3(__VA_ARGS__, contains_if_s__3, contains_if_s__2)(__VA_ARGS__) #define contains_if__2(a, right) contains_if2(a, lamr(right)) #define contains_if__3(a, v, siki) contains_if2(a, [&](auto v) { return siki; }) #define contains_if(...) \ over3(__VA_ARGS__, contains_if__3, contains_if__2)(__VA_ARGS__) #define contains_if_f(a, f) contains_if2(a, f) #define count_if_s__2(a, right) (t_count_if(ALL(a), lamr(right))) #define count_if_s__3(a, v, siki) \ (t_count_if(ALL(a), [&](auto v) { return siki; })) #define count_if_s(...) \ over3(__VA_ARGS__, count_if_s__3, count_if_s__2)(__VA_ARGS__) #define count_if__2(a, right) count_if2(a, lamr(right)) #define count_if__3(a, v, siki) count_if2(a, [&](auto v) { return siki; }) #define count_if(...) over3(__VA_ARGS__, count_if__3, count_if__2)(__VA_ARGS__) #define count_if_f(a, f) count_if2(a, f) // vector<vi>で、viに対して操作 #define for_each_s__2(a, right) \ do { \ fora(v, a) { v right; } \ } while (0) #define for_each_s__3(a, v, shori) \ do { \ fora(v, a) { shori; } \ } while (0) #define for_each_s(...) \ over3(__VA_ARGS__, for_each_s__3, for_each_s__2)(__VA_ARGS__) // vector<vi>で、intに対して操作 #define for_each__2(a, right) for_each2(a, lamr(right)) #define for_each__3(a, v, shori) for_each2(a, [&](auto &v) { shori; }) #define for_each(...) over3(__VA_ARGS__, for_each__3, for_each__2)(__VA_ARGS__) #define for_each_f(a, f) for_each2(a, f); template <class T, class F> vector<T> help_for_eached(const vector<T> &A, F f) { vector<T> ret = A; for_each(ret, v, f(v)); return ret; } #define for_eached__2(a, right) help_for_eached(a, lamr(right)) #define for_eached__3(a, v, shori) help_for_eached(a, lam(v, shori)) #define for_eached(...) \ over3(__VA_ARGS__, for_eached__3, for_eached__2)(__VA_ARGS__) #define for_eached_f(a, f) for_eached2(a, f); #define each for_each #define eached for_eached // #define erase_if_s__2(a, right) l_erase_if2(a,lamr(right)) // #define erase_if_s__3(a, v, siki) l_erase_if2(a,[&](auto v){return siki;}) // #define erase_if_s(...) // over3(__VA_ARGS__,erase_if_s__3,erase_if_s__2)(__VA_ARGS__) #define erase_if__2(a, right) erase_if2(a, lamr(right)) #define erase_if__3(a, v, siki) erase_if2(a, [&](auto v) { return siki; }) #define erase_if(...) over3(__VA_ARGS__, erase_if__3, erase_if__2)(__VA_ARGS__) #define erase_if_f(a, f) erase_if2(a, f) // #define entry_if_s__2(a, right) l_entry_if2(a,lamr(right)) // #define entry_if_s__3(a, v, siki) l_entry_if2(a,[&](auto v){return siki;}) // #define entry_if_s(...) // over3(__VA_ARGS__,entry_if_s__3,entry_if_s__2)(__VA_ARGS__) #define entry_if__2(a, right) entry_if2(a, lamr(right)) #define entry_if__3(a, v, siki) entry_if2(a, [&](auto v) { return siki; }) #define entry_if(...) over3(__VA_ARGS__, entry_if__3, entry_if__2)(__VA_ARGS__) #define entry_if_f(a, f) entry_if2(a, f) #endif // 機能削除 todo // string.replace()は長さを指定するため、間違えやすい /*@formatter:off*/ void replace(str &a, char key, char v) { replace(ALL(a), key, v); } template <class T, class U> void my_replace(T &s, int l, int r, const U &t) { s.replace(l, r - l, t); } #define replace my_replace template <class T, class U, class W> void replace(vector<W> &a, T key, U v) { rep(i, sz(a)) if (a[i] == key) a[i] = v; } template <class T, class U, class W> void replace(vector<vector<W>> &A, T key, U v) { rep(i, sz(A)) replace(A[i], key, v); } void replace(str &a, char key, str v) { if (v == "") a.erase(remove(ALL(a), key), a.end()); } // keyと同じかどうか01で置き換える template <class T, class U> void replace(vector<T> &a, U k) { rep(i, sz(a)) a[i] = a[i] == k; } template <class T, class U> void replace(vector<vector<T>> &a, U k) { rep(i, sz(a)) rep(j, sz(a[0])) a[i][j] = a[i][j] == k; } void replace(str &a) { int dec = 0; if ('a' <= a[0] && a[0] <= 'z') dec = 'a'; if ('A' <= a[0] && a[0] <= 'Z') dec = 'A'; fora(v, a) { v -= dec; } } void replace(string &a, char key) { string res; for (auto c : a) { if (c != key) res.push_back(c); } swap(a, res); } void replace(str &a, str key, str v) { stringstream t; ll kn = sz(key); std::string::size_type Pos(a.find(key)); ll l = 0; while (Pos != std::string::npos) { t << a.substr(l, Pos - l); t << v; l = Pos + kn; Pos = a.find(key, Pos + kn); } t << a.substr(l, sz(a) - l); a = t.str(); } template <class T> bool is_permutation(vector<T> &a, vector<T> &b) { return is_permutation(ALL(a), ALL(b)); } template <class T> bool next_permutation(vector<T> &a) { return next_permutation(ALL(a)); } vi iota(ll s, ll len) { vi ve(len); iota(ALL(ve), s); return ve; } //[iterator, iterator)等と渡す // vectorに変換もできる #if __cplusplus >= 201703L template <class I, class J> struct body_range { I itl; J itr; body_range(I it, J end) : itl(it), itr(end) {} I begin() { return itl; } I end() { return itr; } // 毎回コピーする operator vector<typename I::value_type>() { return vector<typename I::value_type>(itl, itr); } }; template <class I, class J, require_t(is_integral_v<I>)> vector<int> range(I l, J r) { return iota(l, r - l); } template <class I, require_t(is_integral_v<I>)> vector<int> range(I r) { return iota(0, r); } template <class I, require_t(!is_integral_v<I>)> auto range(I itl, I itr) { return body_range(itl, itr); } #endif /*@formatter:off*/ // tuple<vecs...> = take_vt(vt) #if __cplusplus >= 201703L template <class Tup_l, class Tup_r, size_t... Indicies> auto helper_take_vector_tuple(Tup_l &res, const Tup_r &rhs, index_sequence<Indicies...>) { (..., get<Indicies>(res).emplace_back(get<Indicies>(rhs))); } template <class... T> auto take_vector_tuple(const vector<tuple<T...>> &elems) { tuple<vector<T>...> res; for (auto &&elem : elems) { helper_take_vector_tuple(res, elem, index_sequence_for<T...>{}); } return res; } // tie_vt(A,B,C) = vt; template <class... T> struct tie_vector_tuple { tuple<vector<T> &...> v; tie_vector_tuple(vector<T> &...args) : v(args...) {} template <class Tup, size_t... Indicies> void helper_emplace(int i, Tup &rhs, index_sequence<Indicies...>) { (..., (get<Indicies>(v).emplace_back(get<Indicies>(rhs)))); } template <size_t... Indicies> void clear(index_sequence<Indicies...>) { (..., (get<Indicies>(v).clear())); } void operator=(vector<tuple<T...>> &rhs) { clear(index_sequence_for<T...>{}); rep(i, sz(rhs)) { helper_emplace(i, rhs[i], index_sequence_for<T...>{}); } } }; /*@formatter:off*/ // vt = make_vt(A, B, C) template <class H, class... T> auto make_vector_tuple(const vector<H> &head, const vector<T> &...tails) { vector<tuple<H, T...>> res; rep(i, sz(head)) { res.emplace_back(head[i], tails[i]...); } return res; } #endif /*@formatter:off*/ #define mvt make_vector_tuple #define tie_vt tie_vector_tuple #define make_vt make_vector_tuple #define take_vt take_vector_tuple /*@formatter:off*/ // 基本ソート@0 template <class T> void sort(vector<T> &a, int l = -1, int r = -1) { set_lr12(l, r, sz(a)); fast_sort(a.begin() + l, a.begin() + r); } template <class T> void rsort(vector<T> &a, int l = -1, int r = -1) { set_lr12(l, r, sz(a)); fast_sort(a.begin() + l, a.begin() + r, greater<T>()); }; // f(tup)の大きさでソート template <class U, class F> void sort(vector<U> &a, F f) { fast_sort(ALL(a), [&](U l, U r) { return f(l) < f(r); }); }; template <class U, class F> void rsort(vector<U> &a, F f) { fast_sort(ALL(a), [&](U l, U r) { return f(l) > f(r); }); }; enum tuple_comparator { /*tcom_less = 1728, tcom_greater = 1729, */ fisi = 0, fisd, fdsi, fdsd, sifi, sifd, sdfi, sdfd, fisiti, fisitd, fisdti, fisdtd, fdsiti, fdsitd, fdsdti, fdsdtd, fitisi, fitisd, fitdsi, fitdsd, fdtisi, fdtisd, fdtdsi, fdtdsd, sifiti, sifitd, sifdti, sifdtd, sdfiti, sdfitd, sdfdti, sdfdtd, sitifi, sitifd, sitdfi, sitdfd, sdtifi, sdtifd, sdtdfi, sdfdfd, tifisi, tifisd, tifdsi, tifdsd, tdfisi, tdfisd, tdfdsi, tdfdsd, tisifi, tisifd, tisdfi, tisdfd, tdsifi, tdsifd, tdsdfi, tdsdfd }; // todo 短くする #define set_4(i0, i1, o0, o1) \ [&](U l, U r) { \ return get<i0>(l) != get<i0>(r) ? get<i0>(l) o0 get<i0>(r) \ : get<i1>(l) o1 get<i1>(r); \ } #define set_6(i0, i1, i2, o0, o1, o2) \ [&](U l, U r) { \ return get<i0>(l) != get<i0>(r) ? get<i0>(l) o0 get<i0>(r) \ : get<i1>(l) != get<i1>(r) ? get<i1>(l) o1 get<i1>(r) \ : get<i2>(l) o2 get<i2>(r); \ } // functionを返すため少し遅い todo #if __cplusplus >= 201703L template <class... T, class U = tuple<T...>> function<bool(U, U)> get_function2(const vector<tuple<T...>> &a, tuple_comparator Compare) { if constexpr (sizeof...(T) >= 2) { int type = Compare; if (type == 0) return set_4(0, 1, <, <); if (type == 1) return set_4(0, 1, <, >); if (type == 2) return set_4(0, 1, >, <); if (type == 3) return set_4(0, 1, >, >); if (type == 4) return set_4(1, 0, <, <); if (type == 5) return set_4(1, 0, <, >); if (type == 6) return set_4(1, 0, >, <); if (type == 7) return set_4(1, 0, >, >); } if constexpr (sizeof...(T) >= 3) { int type = Compare - 8; if (type == 0) return set_6(0, 1, 2, <, <, <); else if (type == 1) return set_6(0, 1, 2, <, <, >); else if (type == 2) return set_6(0, 1, 2, <, >, <); else if (type == 3) return set_6(0, 1, 2, <, >, >); else if (type == 4) return set_6(0, 1, 2, >, <, <); else if (type == 5) return set_6(0, 1, 2, >, <, >); else if (type == 6) return set_6(0, 1, 2, >, >, <); else if (type == 7) return set_6(0, 1, 2, >, >, >); else if (type == 8) return set_6(0, 2, 1, <, <, <); else if (type == 9) return set_6(0, 2, 1, <, <, >); else if (type == 10) return set_6(0, 2, 1, <, >, <); else if (type == 11) return set_6(0, 2, 1, <, >, >); else if (type == 12) return set_6(0, 2, 1, >, <, <); else if (type == 13) return set_6(0, 2, 1, >, <, >); else if (type == 14) return set_6(0, 2, 1, >, >, <); else if (type == 15) return set_6(0, 2, 1, >, >, >); else if (type == 16) return set_6(1, 0, 2, <, <, <); else if (type == 17) return set_6(1, 0, 2, <, <, >); else if (type == 18) return set_6(1, 0, 2, <, >, <); else if (type == 19) return set_6(1, 0, 2, <, >, >); else if (type == 20) return set_6(1, 0, 2, >, <, <); else if (type == 21) return set_6(1, 0, 2, >, <, >); else if (type == 22) return set_6(1, 0, 2, >, >, <); else if (type == 23) return set_6(1, 0, 2, >, >, >); else if (type == 24) return set_6(1, 2, 0, <, <, <); else if (type == 25) return set_6(1, 2, 0, <, <, >); else if (type == 26) return set_6(1, 2, 0, <, >, <); else if (type == 27) return set_6(1, 2, 0, <, >, >); else if (type == 28) return set_6(1, 2, 0, >, <, <); else if (type == 29) return set_6(1, 2, 0, >, <, >); else if (type == 30) return set_6(1, 2, 0, >, >, <); else if (type == 31) return set_6(1, 2, 0, >, >, >); else if (type == 32) return set_6(2, 0, 1, <, <, <); else if (type == 33) return set_6(2, 0, 1, <, <, >); else if (type == 34) return set_6(2, 0, 1, <, >, <); else if (type == 35) return set_6(2, 0, 1, <, >, >); else if (type == 36) return set_6(2, 0, 1, >, <, <); else if (type == 37) return set_6(2, 0, 1, >, <, >); else if (type == 38) return set_6(2, 0, 1, >, >, <); else if (type == 39) return set_6(2, 0, 1, >, >, >); else if (type == 40) return set_6(2, 1, 0, <, <, <); else if (type == 41) return set_6(2, 1, 0, <, <, >); else if (type == 42) return set_6(2, 1, 0, <, >, <); else if (type == 43) return set_6(2, 1, 0, <, >, >); else if (type == 44) return set_6(2, 1, 0, >, <, <); else if (type == 45) return set_6(2, 1, 0, >, <, >); else if (type == 46) return set_6(2, 1, 0, >, >, <); else if (type == 47) return set_6(2, 1, 0, >, >, >); } return [&](U l, U r) { return true; }; } template <class... T> void sort(vector<tuple<T...>> &a, tuple_comparator Compare) { auto f = get_function2(a, Compare); fast_sort(ALL(a), f); } #endif /*@formatter:off*/ #undef set_4 #undef set_6 #if __cplusplus >= 201703L // sort_tuple template <class H1, class H2, class... T> void sortt(vector<H1> &head1, vector<H2> &head2, vector<T> &...tails) { auto vec_t = make_vt(head1, head2, tails...); sort(vec_t); tie_vt(head1, head2, tails...) = vec_t; } template <class H1, class H2, class... T> void rsortt(vector<H1> &head1, vector<H2> &head2, vector<T> &...tails) { auto vec_t = make_vt(head1, head2, tails...); rsort(vec_t); tie_vt(head1, head2, tails...) = vec_t; } template <class F, class... T> void helper_sortt_f(F f, vector<T> &...a) { auto z = make_vt(a...); sort(z, f); tie_vt(a...) = z; } template <class F, class... T> void helper_rsortt_f(F f, vector<T> &...a) { auto z = make_vt(a...); rsort(z, f); tie_vt(a...) = z; } // sortt(a,b,c,d, f)まで対応-> template <class A, class B, class F, require_t(!is_vector<F>::value)> void sortt(vector<A> &a, vector<B> &b, F f) { helper_sortt_f(f, a, b); } template <class A, class B, class F, require_t(!is_vector<F>::value)> void rsortt(vector<A> &a, vector<B> &b, F f) { helper_rsortt_f(f, a, b); } template <class A, class B, class C, class F, require_t(!is_vector<F>::value)> void sortt(vector<A> &a, vector<B> &b, vector<C> &c, F f) { helper_sortt_f(f, a, b, c); } template <class A, class B, class C, class F, require_t(!is_vector<F>::value)> void rsortt(vector<A> &a, vector<B> &b, vector<C> &c, F f) { helper_rsortt_f(f, a, b, c); } template <class A, class B, class C, class D, class F, require_t(!is_vector<F>::value)> void sortt(vector<A> &a, vector<B> &b, vector<C> &c, vector<D> &d, F f) { helper_sortt_f(f, a, b, c, d); } template <class A, class B, class C, class D, class F, require_t(!is_vector<F>::value)> void rsortt(vector<A> &a, vector<B> &b, vector<C> &c, vector<D> &d, F f) { helper_rsortt_f(f, a, b, c, d); } // sort_tuple f } #endif /*@formatter:off*/ // 任意引数は取らない template <class T> vi sorti(const vector<T> &a) { auto b = a; vi ind = iota(0, sz(b)); sortt(b, ind); return ind; } template <class T> vi rsorti(const vector<T> &a) { auto b = a; vi ind = iota(0, sz(b)); rsortt(b, ind); return ind; } #if __cplusplus >= 201703L template <class T, class F> vi sorti(const vector<T> &a, F f) { vi ind = iota(0, sz(a)); if constexpr (is_same_v<F, tuple_comparator>) { auto f2 = get_function2(a, f); auto g = [&](int i, int j) { return f2(a[i], a[j]); }; fast_sort(ALL(ind), g); } else { auto g = [&](int i) { return f(a[i]); }; sort(ind, g); } return ind; } template <class T, class F, require_t(is_function_v<F>)> vi rsorti(const vector<T> &a, F f) { vi ind = iota(0, sz(a)); auto g = [&](int i) { return f(a[i]); }; rsort(ind, g); return ind; } // 任意引数にfを渡したい場合は (make_vt(a, b, c), f) template <class H, class... Ts> vi sortti(vector<H> head, vector<Ts>... tails) { vi ind = iota(0, sz(head)); auto vec = make_vt(head, tails..., ind); sort(vec); auto rets = take_vt(vec); return get<sizeof...(tails) + 1>(rets); } template <class H, class... Ts> vi rsortti(vector<H> head, vector<Ts>... tails) { vi ind = iota(0, sz(head)); auto vec = make_vt(head, tails..., ind); rsort(vec); auto rets = take_vt(vec); return get<sizeof...(tails) + 1>(rets); } #endif /*@formatter:off*/ //@5 void sort(string &a) { sort(ALL(a)); } void rsort(string &a) { sort(RALL(a)); } void sort(int &a, int &b) { if (a > b) swap(a, b); } void sort(int &a, int &b, int &c) { sort(a, b); sort(a, c); sort(b, c); } void rsort(int &a, int &b) { if (a < b) swap(a, b); } void rsort(int &a, int &b, int &c) { rsort(a, b); rsort(a, c); rsort(b, c); } template <class... T, class U> auto sorted(U head, T... a) { sort(head, a...); return head; } template <class... T, class U> auto rsorted(U head, T... a) { rsort(head, a...); return head; } template <class T> bool includes(vector<T> &a, vector<T> &b) { vi c = a; vi d = b; sort(c); sort(d); return includes(ALL(c), ALL(d)); } template <class T> bool distinct(const vector<T> &A) { if ((int)(A).size() == 1) return true; if ((int)(A).size() == 2) return A[0] != A[1]; if ((int)(A).size() == 3) return (A[0] != A[1] && A[1] != A[2] && A[0] != A[2]); auto B = A; sort(B); int N = (B.size()); unique(B); return N == (int)(B.size()); } template <class H, class... T> bool distinct(const H &a, const T &...b) { return distinct(vector<H>{a, b...}); } /*@formatter:off*/ template <class T, class U> void inc(pair<T, U> &a, U v = 1) { a.first += v, a.second += v; } template <class T, class U> void inc(T &a, U v = 1) { a += v; } template <class T, class U = int> void inc(vector<T> &a, U v = 1) { for (auto &u : a) inc(u, v); } template <class T, class U> void dec(T &a, U v = 1) { a -= v; } template <class T, class U = int> void dec(vector<T> &a, U v = 1) { for (auto &u : a) dec(u, v); } template <class U> void dec(string &a, U v = 1) { for (auto &u : a) dec(u, v); } template <class T, class U, class W> void dec(vector<T> &a, vector<U> &b, W v = 1) { for (auto &u : a) dec(u, v); for (auto &u : b) dec(u, v); } template <class T, class U, class W> void dec(vector<T> &a, vector<U> &b, vector<W> &c) { for (auto &u : a) dec(u, 1); for (auto &u : b) dec(u, 1); for (auto &u : c) dec(u, 1); } bool ins(ll h, ll w, ll H, ll W) { return h >= 0 && w >= 0 && h < H && w < W; } bool san(ll l, ll v, ll r) { return l <= v && v < r; } template <class T> bool ins(vector<T> &a, ll i, ll j = 0) { return san(0, i, sz(a)) && san(0, j, sz(a)); } #define inside ins ll u0(ll a) { return a < 0 ? 0 : a; } template <class T> vector<T> u0(vector<T> &a) { vector<T> ret = a; fora(v, ret) { v = u(v); } return ret; } // todo 名前 bool d_(int a, int b) { if (b == 0) return false; return (a % b) == 0; } // エラー void ole() { #ifdef _DEBUG cerr << "ole" << endl; exit(0); #endif string a = "a"; rep(i, 30) a += a; rep(i, 1 << 17) cout << a << endl; cout << "OLE 出力長制限超過" << endl; exit(0); } void re(string s = "") { cerr << s << endl; assert(0 == 1); exit(0); } void tle() { while (inf) cout << inf << endl; } //@汎用便利関数 入力 ll in() { ll ret; cin >> ret; return ret; } template <class T> T in() { T ret; cin >> ret; return ret; } string sin() { string ret; cin >> ret; return ret; } template <class T> void in(T &head) { cin >> head; } template <class T, class... U> void in(T &head, U &...tail) { cin >> head; in(tail...); } // value_typeを持つ場合呼べる // len回要素を追加する template <class Iterable, class T = typename Iterable::value_type> Iterable tin(int len) { Iterable ret; T tem; while (len--) { cin >> tem; ret += tem; } return ret; } template <class T> T tin() { T ret; cin >> ret; return ret; } template <class T> T tind(int len = 0) { auto ret = tin<T>(len); dec(ret, 1); return ret; } #define din_t2(type, a) \ type a; \ cin >> a #define din_t3(type, a, b) \ type a, b; \ cin >> a >> b #define din_t4(type, a, b, c) \ type a, b, c; \ cin >> a >> b >> c #define din_t5(type, a, b, c, d) \ type a, b, c, d; \ cin >> a >> b >> c >> d #define din_t6(type, a, b, c, d, e) \ type a, b, c, d, e; \ cin >> a >> b >> c >> d >> e #define din_t7(type, a, b, c, d, e, f) \ type a, b, c, d, e, f; \ cin >> a >> b >> c >> d >> e >> f #define din_t(...) \ over7(__VA_ARGS__, din_t7, din_t6, din_t5, din_t4, din_t3, \ din_t2)(__VA_ARGS__) #define din(...) din_t(int, __VA_ARGS__) #define d_in #define dsig(...) din_t(signed, __VA_ARGS__) #define dst(...) din_t(string, __VA_ARGS__) #define dstr dst #define d_str dst #define dcha(...) din_t(char, __VA_ARGS__) #define dchar dcha #define ddou(...) din_t(double, __VA_ARGS__) #define din1d(a) \ din_t2(int, a); \ a-- #define din2d(a, b) \ din_t3(int, a, b); \ a--, b-- #define din3d(a, b, c) \ din_t4(int, a, b, c); \ a--, b--, c-- #define din4d(a, b, c, d) \ din_t5(int, a, b, c, d); \ a--, b--, c--, d-- #define dind(...) over4(__VA_ARGS__, din4d, din3d, din2d, din1d)(__VA_ARGS__) /*@formatter:off*/ #ifdef _DEBUG template <class T> void err2(T &&head) { cerr << head; } template <class T, class... U> void err2(T &&head, U &&...tail) { cerr << head << " "; err2(tail...); } template <class T, class... U> void err(T &&head, U &&...tail) { cerr << head << " "; err2(tail...); cerr << "" << endl; } template <class T> void err(T &&head) { cerr << head << endl; } void err() { cerr << "" << endl; } // debで出力する最大長 constexpr int DEB_LEN = 20; constexpr int DEB_LEN_H = 12; string deb_tos(const int &v) { if (abs(v) == inf || abs(v) == linf) return "e"; else return to_string(v); } template <class T> string deb_tos(const T &a) { stringstream ss; ss << a; return ss.str(); } string deb_tos(const P &p) { stringstream ss; ss << "{"; ss << p.fi; ss << ", "; ss << p.se; ss << "}"; return ss.str(); } #ifdef use_epsdou string deb_tos(const epsdou &a) { return deb_tos(a.v); } #endif template <class T> string deb_tos(const optional<T> &a) { if (a.has_value()) { return deb_tos(a.value()); } else return "e"; } template <class T> string deb_tos(const vector<T> &a, ll W = inf) { stringstream ss; if (W == inf) W = min(sz(a), DEB_LEN); if (sz(a) == 0) return ss.str(); rep(i, W) { ss << deb_tos(a[i]); if (typeid(a[i]) == typeid(P)) { ss << endl; } else { ss << " "; } } return ss.str(); } template <class T> string deb_tos(const vector<vector<T>> &a, vi H, vi W, int key = -1) { stringstream ss; ss << endl; vi lens(sz(W)); fora(h, H) { rep(wi, sz(W)) { if (sz(a[h]) <= W[wi]) break; lens[wi] = max(lens[wi], sz(deb_tos(a[h][W[wi]])) + 1); lens[wi] = max(lens[wi], sz(deb_tos(W[wi])) + 1); } } if (key == -1) ss << " *|"; else ss << " " << key << "|"; int wi = 0; fora(w, W) { ss << std::right << std::setw(lens[wi]) << w; wi++; } ss << "" << endl; rep(i, sz(W)) rep(lens[i]) ss << "_"; rep(i, 3) ss << "_"; ss << "" << endl; fora(h, H) { ss << std::right << std::setw(2) << h << "|"; int wi = 0; fora(w, W) { if (sz(a[h]) <= w) break; ss << std::right << std::setw(lens[wi]) << deb_tos(a[h][w]); wi++; } ss << "" << endl; } return ss.str(); } template <class T> string deb_tos(const vector<vector<T>> &a, ll H = inf, ll W = inf, int key = -1) { H = (H != inf) ? H : min({H, sz(a), DEB_LEN_H}); W = min({W, sz(a[0]), DEB_LEN_H}); vi hs, ws; rep(h, H) { hs.push_back(h); } rep(w, W) { ws.push_back(w); } return deb_tos(a, hs, ws, key); } template <class T> string deb_tos(const vector<vector<vector<T>>> &a, ll H = inf) { stringstream ss; if (H == inf) H = DEB_LEN_H; H = min(H, sz(a)); rep(i, H) { ss << endl; ss << deb_tos(a[i], inf, inf, i); } return ss.str(); } template <class T> string deb_tos(vector<set<T>> &a, ll H = inf, ll W = inf, int key = -1) { vector<vector<T>> b(sz(a)); rep(i, sz(a)) { fora(v, a[i]) { b[i].push_back(v); } } return deb_tos(b, H, W, key); } template <class T, size_t A> string deb_tos(T (&a)[A]) { return deb_tos(vector<T>(begin(a), end(a))); } template <class T, size_t A, size_t B> string deb_tos(T (&a)[A][B]) { return deb_tos(vector<vector<T>>(begin(a), end(a))); } template <class T, size_t A, size_t B, size_t C> string deb_tos(T (&a)[A][B][C]) { return deb_tos(vector<vector<vector<T>>>(begin(a), end(a))); } /*@formatter:off*/ template <class T> void out2(T head) { cout << head; res_mes += deb_tos(head); } template <class T, class... U> void out2(T head, U... tail) { cout << head << " "; res_mes += deb_tos(head) + " "; out2(tail...); } template <class T, class... U> void out(T head, U... tail) { cout << head << " "; res_mes += deb_tos(head) + " "; out2(tail...); cout << "" << endl; res_mes += "\n"; } template <class T> void out(T head) { cout << head << endl; res_mes += deb_tos(head) + "\n"; } void out() { cout << "" << endl; } #else #define err(...) ; template <class T> void out2(T &&head) { cout << head; } template <class T, class... U> void out2(T &&head, U &&...tail) { cout << head << " "; out2(tail...); } template <class T, class... U> void out(T &&head, U &&...tail) { cout << head << " "; out2(tail...); cout << "" << endl; } template <class T> void out(T &&head) { cout << head << endl; } void out() { cout << "" << endl; } #endif template <class H, class... T> void outl(const vector<H> &h, const vector<T> &...t) { rep(i, sz(h)) out(h[i], t[i]...); } // テーブルをスペースなしで出力 template <class T> void outt(vector<vector<T>> &a) { rep(i, sz(a)) { rep(j, sz(a[i])) { cout << a[i][j]; } cout << endl; } } // int型をbit表記で出力 void outb(int a) { cout << bitset<20>(a) << endl; } /*@formatter:off*/ template <class T> void na(vector<T> &a, ll n) { a.resize(n); rep(i, n) cin >> a[i]; } template <class T> void na(set<T> &a, ll n) { rep(i, n) a.insert(in()); } #define dna(a, n) \ vi a; \ na(a, n); /*nを複数使うと n==in()の時バグる事に注意*/ #define dnad(a, n) \ vi a; \ nad(a, n); template <class T> void nao(vector<T> &a, ll n) { a.resize(n + 1); a[0] = 0; rep(i, n) cin >> a[i + 1]; } template <class T> void naod(vector<T> &a, ll n) { a.resize(n + 1); a[0] = 0; rep(i, n) cin >> a[i + 1], a[i + 1]--; } template <class T> void nad(vector<T> &a, ll n) { a.resize(n); rep(i, n) cin >> a[i], a[i]--; } template <class T> void nad(set<T> &a, ll n) { rep(i, n) a.insert(in() - 1); } template <class T, class U> void na2(vector<T> &a, vector<U> &b, ll n) { a.resize(n); b.resize(n); rep(i, n) cin >> a[i] >> b[i]; } template <class T, class U> void na2(set<T> &a, set<U> &b, ll n) { rep(i, n) { a.insert(in()); b.insert(in()); } } #define dna2(a, b, n) \ vi a, b; \ na2(a, b, n); template <class T, class U> void nao2(vector<T> &a, vector<U> &b, ll n) { a.resize(n + 1); b.resize(n + 1); a[0] = b[0] = 0; rep(i, n) cin >> a[i + 1] >> b[i + 1]; } #define dnao2(a, b, n) \ vi a, b; \ nao2(a, b, n); template <class T, class U> void na2d(vector<T> &a, vector<U> &b, ll n) { a.resize(n); b.resize(n); rep(i, n) cin >> a[i] >> b[i], a[i]--, b[i]--; } #define dna2d(a, b, n) \ vi a, b; \ na2d(a, b, n); template <class T, class U, class W> void na3(vector<T> &a, vector<U> &b, vector<W> &c, ll n) { a.resize(n); b.resize(n); c.resize(n); rep(i, n) cin >> a[i] >> b[i] >> c[i]; } #define dna3(a, b, c, n) \ vi a, b, c; \ na3(a, b, c, n); template <class T, class U, class W> void na3d(vector<T> &a, vector<U> &b, vector<W> &c, ll n) { a.resize(n); b.resize(n); c.resize(n); rep(i, n) cin >> a[i] >> b[i] >> c[i], a[i]--, b[i]--, c[i]--; } #define dna3d(a, b, c, n) \ vi a, b, c; \ na3d(a, b, c, n); template <class T, class U, class W, class X> void na4(vector<T> &a, vector<U> &b, vector<W> &c, vector<X> &d, ll n) { a.resize(n); b.resize(n); c.resize(n); d.resize(n); rep(i, n) cin >> a[i] >> b[i] >> c[i] >> d[i]; } #define dna4(a, b, c, d, n) \ vi a, b, c, d; \ na4(a, b, c, d, n); #define dna4d(a, b, c, d, n) \ vi a, b, c, d; \ na4d(a, b, c, d, n); #define nt(a, h, w) \ resize(a, h, w); \ rep(nthi, h) rep(ntwi, w) cin >> a[nthi][ntwi]; #define ntd(a, h, w) \ resize(a, h, w); \ rep(ntdhi, h) rep(ntdwi, w) cin >> a[ntdhi][ntdwi], a[ntdhi][ntdwi]--; #define ntp(a, h, w) \ resize(a, h + 2, w + 2); \ fill(a, '#'); \ rep(ntphi, 1, h + 1) rep(ntpwi, 1, w + 1) cin >> a[ntphi][ntpwi]; #define dnt(S, h, w) \ vvi(S, h, w); \ nt(S, h, w); #define dntc(S, h, w) \ vvc(S, h, w); \ nt(S, h, w); #define dnts(S, h, w) \ vvs(S, h, w); \ nt(S, h, w); // デバッグ #define sp << " " << /*@formatter:off*/ #define deb1(x) debugName(x) << " = " << deb_tos(x) #define deb_2(x, ...) deb1(x) << ", " << deb1(__VA_ARGS__) #define deb_3(x, ...) deb1(x) << ", " << deb_2(__VA_ARGS__) #define deb_4(x, ...) deb1(x) << ", " << deb_3(__VA_ARGS__) #define deb5(x, ...) deb1(x) << ", " << deb_4(__VA_ARGS__) #define deb6(x, ...) deb1(x) << ", " << deb5(__VA_ARGS__) // #define deb7(x, ...) deb1(x) <<", "<< deb6(__VA_ARGS__) // #define deb8(x, ...) deb1(x) <<", "<< deb7(__VA_ARGS__) // #define deb9(x, ...) deb1(x) <<", "<< deb8(__VA_ARGS__) // #define deb10(x, ...) deb1(x) <<", "<< deb9(__VA_ARGS__) /*@formatter:off*/ #ifdef _DEBUG #define deb(...) \ do { \ was_deb = true; \ cerr << over10(__VA_ARGS__, deb10, deb9, deb8, deb7, deb6, deb5, deb_4, \ deb_3, deb_2, deb1)(__VA_ARGS__) \ << endl; \ } while (0) void print_n_base(int x, int base) { string S; while (x) { S += (char)('0' + x % base); x /= base; } cerr << S << endl; } template <class T> void print_n_base(vector<T> X, int base) { cerr << endl; for (auto &&x : X) { print_n_base(x, base); } cerr << endl; } // n進数 #define deb2(x) \ was_deb = true; \ cerr << debugName(x) << " = "; \ print_n_base(x, 2); #define deb3(x) \ was_deb = true; \ cerr << debugName(x) << " = "; \ print_n_base(x, 3); #define deb4(x) \ was_deb = true; \ cerr << debugName(x) << " = "; \ print_n_base(x, 4); #define deb_ex_deb(x, len) debugName(x) << " = " << deb_tos(x, len) #define call_deb_ex_deb(x, len) deb_ex_deb(x, len) // 要素が存在する行だけ出力(vvt) #define deb_ex(v) \ do { \ int N = sz(v); \ int s = N; \ int t = 0; \ rep(i, N) { \ if (sz(v[i])) { \ chmi(s, i); \ chma(t, i); \ } \ } \ auto ex_v = sub(v, s, N); \ str S = deb_tos(ex_v, sz(ex_v)); \ debugName(v); \ cerr << " = " << endl; \ cerr << S << endl; \ } while (0); #define debi(A) \ { \ int len = min(sz(A), 20); \ was_deb = true; \ cerr << debugName(A) << " = " << endl; \ rep(i, len) cerr << std::right \ << std::setw((int)(sz(tos(A[i])) + (i ? 1 : 0))) \ << (i % 10); \ cerr << endl; \ rep(i, len) cerr << std::right \ << std::setw((int)(sz(tos(A[i])) + (i ? 1 : 0))) << A[i]; \ cerr << endl; \ } template <class T, class F> string deb_tos_f(vector<T> &A, F f) { vi I; rep(i, sz(A)) { if (f(A[i])) I.push_back(i); } was_deb = true; stringstream ss; fora(ii, i, I) ss << std::right << std::setw( (int)(max(sz(tos(A[i])), sz(tos(i))) + (ii ? 1 : 0))) << i; ss << endl; fora(ii, i, I) ss << std::right << std::setw( (int)(max(sz(tos(A[i])), sz(tos(i))) + (ii ? 1 : 0))) << A[i]; return ss.str(); } template <class T, class F> string deb_tos_f(vector<vector<T>> &a, F f, int key = -1) { vi hs, ws_; int H = sz(a), W = sz(a[0]); vi exh(H), exw(W); rep(h, H) { rep(w, W) { if (f(a[h][w])) { exh[h] = true; exw[w] = true; } } } rep(h, H) if (exh[h]) hs.push_back(h); rep(w, W) if (exw[w]) ws_.push_back(w); return deb_tos(a, hs, ws_, key); } template <class T, class F> string deb_tos_f(vector<vector<vector<T>>> &a, F f) { stringstream ss; int H = sz(a); if (sz(a) == 0) return ss.str(); int cou = 0; rep(i, H) { if (any_of(a[i], v, f(v))) { ss << deb_tos_f(a[i], f, i); cou++; } if (cou > 50) break; } ss << "" << endl; return ss.str(); } #define debf_normal(tab, f) \ do { \ cerr << debugName(tab) << " = " << endl; \ cerr << deb_tos_f(tab, f) << endl; \ } while (0); #define debf2(tab, siki_r) debf_normal(tab, lamr(siki_r)) #define debf3(tab, v, siki) debf_normal(tab, lam(siki)) // S, sikir // S, v, siki #define debf(...) over3(__VA_ARGS__, debf3, debf2, debf1)(__VA_ARGS__) #else #define deb(...) ; #define deb2(...) ; #define deb3(...) ; #define deb4(...) ; #define deb_ex(...) ; #define debf(...) ; #define debi(...) ; #endif #define debugline(x) \ cerr << x << " " \ << "(L:" << __LINE__ << ")" << '\n' /*@formatter:off*/ using u32 = unsigned; using u64 = unsigned long long; using u128 = __uint128_t; using bint = __int128; std::ostream &operator<<(std::ostream &dest, __int128_t value) { std::ostream::sentry s(dest); if (s) { __uint128_t tmp = value < 0 ? -value : value; char buffer[128]; char *d = std::end(buffer); do { --d; *d = "0123456789"[tmp % 10]; tmp /= 10; } while (tmp != 0); if (value < 0) { --d; *d = '-'; } ll len = std::end(buffer) - d; if (dest.rdbuf()->sputn(d, len) != len) { dest.setstate(std::ios_base::badbit); } } return dest; } __int128 to_bint(string &s) { __int128 ret = 0; for (ll i = 0; i < (ll)s.length(); ++i) if ('0' <= s[i] && s[i] <= '9') ret = 10 * ret + s[i] - '0'; return ret; } void operator>>(istream &iss, bint &v) { string S; iss >> S; v = 0; rep(i, sz(S)) { v *= 10; v += S[i] - '0'; } } // 便利関数 /*@formatter:off*/ // テスト用 #define rand xor128_ unsigned long xor128_(void) { static unsigned long x = 123456789, y = 362436069, z = 521288629, w = 88675123; unsigned long t; t = (x ^ (x << 11)); x = y; y = z; z = w; return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))); } char ranc() { return (char)('a' + rand() % 26); } ll rand(ll min, ll max) { assert(min <= max); if (min >= 0 && max >= 0) { return rand() % (max + 1 - min) + min; } else if (max < 0) { return -rand(-max, -min); } else { if (rand() % 2) { return rand(0, max); } else { return -rand(0, -min); } } } ll rand(ll max) { return rand(0, max); } template <class T> T rand(vector<T> &A) { return A[rand(sz(A) - 1)]; } // 重複することがある template <class T> vector<T> ranv(vector<T> &A, int N) { vector<T> ret(N); rep(i, N) { ret[i] = rand(A); } return ret; } template <class T> vector<T> ranv_unique(vector<T> &A, int N) { vector<T> ret(N); umapi was; rep(j, N) { int i; while (1) { i = rand(sz(A) - 1); if (was.find(i) == was.end()) break; } ret[j] = A[i]; was[i] = 1; } return ret; } vi ranv(ll n, ll min, ll max) { vi v(n); rep(i, n) v[i] = rand(min, max); return v; } /*@formatter:off*/ #ifdef _DEBUG bool timeup(int time) { static bool never = true; if (never) message += "may timeup, because slow"; never = false; auto end_time = system_clock::now(); auto part = duration_cast<milliseconds>(end_time - start_time); auto lim = milliseconds(time); return part >= lim; } #else bool timeup(int time) { auto end_time = system_clock::now(); auto part = duration_cast<milliseconds>(end_time - start_time); auto lim = milliseconds(time); return part >= lim; } #endif void set_time() { past_time = system_clock::now(); } // MS型(millisecqnds)で返る // set_timeをしてからの時間 auto calc_time_milli() { auto now = system_clock::now(); auto part = duration_cast<milliseconds>(now - past_time); return part; } auto calc_time_micro() { auto now = system_clock::now(); auto part = duration_cast<microseconds>(now - past_time); return part; } auto calc_time_nano() { auto now = system_clock::now(); auto part = duration_cast<nanoseconds>(now - past_time); return part; } bool calc_time(int zikan) { return calc_time_micro() >= microseconds(zikan); } using MS = std::chrono::microseconds; int div(microseconds a, microseconds b) { return a / b; } int div(nanoseconds a, nanoseconds b) { if (b < nanoseconds(1)) { return a / nanoseconds(1); } int v = a / b; return v; } // set_time(); // rep(i,lim)shori // lim*=time_nanbai(); // rep(i,lim)shoriと使う // 全体でmilliかかっていいときにlimを何倍してもう一回できるかを返す int time_nanbai(int milli) { auto dec = duration_cast<nanoseconds>(past_time - start_time); auto part = calc_time_nano(); auto can_time = nanoseconds(milli * 1000 * 1000); can_time -= part; can_time -= dec; return div(can_time, part); } /*@formatter:off*/ // #define use_rand #ifdef use_rand str ransu(ll n) { str s; rep(i, n) s += (char)rand('A', 'Z'); return s; } str ransl(ll n) { str s; rep(i, n) s += (char)rand('a', 'z'); return s; } // 単調増加 vi ranvinc(ll n, ll min, ll max) { vi v(n); bool bad = 1; while (bad) { bad = 0; v.resize(n); rep(i, n) { if (i && min > max - v[i - 1]) { bad = 1; break; } if (i) v[i] = v[i - 1] + rand(min, max - v[i - 1]); else v[i] = rand(min, max); } } return v; } // 便利 汎用 #endif void ranvlr(ll n, ll min, ll max, vi &l, vi &r) { l.resize(n); r.resize(n); rep(i, n) { l[i] = rand(min, max); r[i] = l[i] + rand(0, max - l[i]); } } template <class Iterable, class T = typename Iterable::value_type> vector<pair<T, int>> run_length(const Iterable &a) { vector<pair<T, int>> ret; ret.eb(a[0], 1); rep(i, 1, sz(a)) { if (ret.back().fi == a[i]) { ret.back().se++; } else { ret.eb(a[i], 1); } } return ret; } /*@formatter:off*/ // #define use_mgr //_goldd _goldt #ifdef use_mgr //->[i, f(i)] template <class T, class U, class F> auto mgr(T ok, U ng, const F &f, require_arg(is_integral<T>::value &&is_integral<U>::value)) { auto mid = (ok + ng); if (ok < ng) while (ng - ok > 1) { mid = (ok + ng) >> 1; if (f(mid)) ok = mid; else ng = mid; } else while (ok - ng > 1) { mid = (ok + ng) >> 1; if (f(mid)) ok = mid; else ng = mid; } return ok; } //[l, r)の中で,f(i)がtrueとなる範囲を返す okはそこに含まれる template <class F> P mgr_range(int l, int r, F f, int ok) { if (f(ok) == 0) { out("f(ok) must true"); re(); } return mp(mgr(ok, l - 1, f), mgr(ok, r, f) + 1); } template <class F> auto mgrd(dou ok, dou ng, F f, int kai = 100) { if (ok < ng) rep(i, kai) { dou mid = (ok + ng) / 2; if (f(mid)) ok = mid; else ng = mid; } else rep(i, kai) { dou mid = (ok + ng) / 2; if (f(mid)) ok = mid; else ng = mid; } return ok; } template <class F> dou mgrd_time(dou ok, dou ng, F f, int time = 1980) { bool han = true; if (ok < ng) while (1) { dou mid = (ok + ng) / 2; if (f(mid)) ok = mid, han = true; else ng = mid, han = false; deb(mid, han); if (timeup(time)) { break; } } else while (1) { dou mid = (ok + ng) / 2; if (f(mid)) ok = mid, han = true; else ng = mid, han = false; deb(mid, han); if (timeup(time)) { break; } } return ok; } // todo 減らす template <class F> auto goldd_l(ll left, ll right, F calc) { double GRATIO = 1.6180339887498948482045868343656; ll lm = left + (ll)((right - left) / (GRATIO + 1.0)); ll rm = lm + (ll)((right - lm) / (GRATIO + 1.0)); ll fl = calc(lm); ll fr = calc(rm); while (right - left > 10) { if (fl < fr) { right = rm; rm = lm; fr = fl; lm = left + (ll)((right - left) / (GRATIO + 1.0)); fl = calc(lm); } else { left = lm; lm = rm; fl = fr; rm = lm + (ll)((right - lm) / (GRATIO + 1.0)); fr = calc(rm); } } ll minScore = MAX<ll>(); ll resIndex = left; for (ll i = left; i < right + 1; ++i) { ll score = calc(i); if (minScore > score) { minScore = score; resIndex = i; } } return make_tuple(resIndex, calc(resIndex)); } template <class F> auto goldt_l(ll left, ll right, F calc) { double GRATIO = 1.6180339887498948482045868343656; ll lm = left + (ll)((right - left) / (GRATIO + 1.0)); ll rm = lm + (ll)((right - lm) / (GRATIO + 1.0)); ll fl = calc(lm); ll fr = calc(rm); while (right - left > 10) { if (fl > fr) { right = rm; rm = lm; fr = fl; lm = left + (ll)((right - left) / (GRATIO + 1.0)); fl = calc(lm); } else { left = lm; lm = rm; fl = fr; rm = lm + (ll)((right - lm) / (GRATIO + 1.0)); fr = calc(rm); } } if (left > right) { ll l = left; left = right; right = l; } ll maxScore = MIN<ll>(); ll resIndex = left; for (ll i = left; i < right + 1; ++i) { ll score = calc(i); if (maxScore < score) { maxScore = score; resIndex = i; } } return make_tuple(resIndex, calc(resIndex)); } /*loopは200にすればおそらく大丈夫 余裕なら300に*/ template <class F> auto goldd_d(dou left, dou right, F calc, ll loop = 200) { dou GRATIO = 1.6180339887498948482045868343656; dou lm = left + ((right - left) / (GRATIO + 1.0)); dou rm = lm + ((right - lm) / (GRATIO + 1.0)); dou fl = calc(lm); dou fr = calc(rm); /*200にすればおそらく大丈夫*/ /*余裕なら300に*/ ll k = 141; loop++; while (--loop) { if (fl < fr) { right = rm; rm = lm; fr = fl; lm = left + ((right - left) / (GRATIO + 1.0)); fl = calc(lm); } else { left = lm; lm = rm; fl = fr; rm = lm + ((right - lm) / (GRATIO + 1.0)); fr = calc(rm); } } return make_tuple(left, calc(left)); } template <class F> auto goldt_d(dou left, dou right, F calc, ll loop = 200) { double GRATIO = 1.6180339887498948482045868343656; dou lm = left + ((right - left) / (GRATIO + 1.0)); dou rm = lm + ((right - lm) / (GRATIO + 1.0)); dou fl = calc(lm); dou fr = calc(rm); loop++; while (--loop) { if (fl > fr) { right = rm; rm = lm; fr = fl; lm = left + ((right - left) / (GRATIO + 1.0)); fl = calc(lm); } else { left = lm; lm = rm; fl = fr; rm = lm + ((right - lm) / (GRATIO + 1.0)); fr = calc(rm); } } return make_tuple(left, calc(left)); } // l ~ rを複数の区間に分割し、極致を与えるiを返す time-20 msまで探索 template <class F> auto goldd_ls(ll l, ll r, F calc, ll time = 2000) { auto lim = milliseconds(time - 20); ll mini = 0, minv = MAX<ll>(); /*区間をk分割する*/ rep(k, 1, inf) { auto s = system_clock::now(); ll haba = (r - l + k) / k; /*((r-l+1) + k-1) /k*/ ll nl = l; ll nr = l + haba; rep(i, k) { ll ni = goldd_l(nl, nr, calc); if (chmi(minv, calc(ni))) mini = ni; nl = nr; nr = nl + haba; } auto end = system_clock::now(); auto part = duration_cast<milliseconds>(end - s); auto elapsed = duration_cast<milliseconds>(end - start_time); if (elapsed + part * 2 >= lim) { break; } } return make_tuple(mini, calc(mini)); } template <class F> auto goldt_ls(ll l, ll r, F calc, ll time = 2000) { auto lim = milliseconds(time - 20); ll maxi = 0, maxv = MIN<ll>(); /*区間をk分割する*/ rep(k, 1, inf) { auto s = system_clock::now(); ll haba = (r - l + k) / k; /*((r-l+1) + k-1) /k*/ ll nl = l; ll nr = l + haba; rep(i, k) { ll ni = goldt_l(nl, nr, calc); if (chma(maxv, calc(ni))) maxi = ni; nl = nr; nr = nl + haba; } auto end = system_clock::now(); auto part = duration_cast<milliseconds>(end - s); auto elapsed = duration_cast<milliseconds>(end - start_time); if (elapsed + part * 2 >= lim) { break; } } return make_tuple(maxi, calc(maxi)); } template <class F> auto goldd_d_s(dou l, dou r, F calc, ll time = 2000) { /*20ms余裕を持つ*/ auto lim = milliseconds(time - 20); dou mini = 0, minv = MAX<dou>(); /*区間をk分割する*/ rep(k, 1, inf) { auto s = system_clock::now(); dou haba = (r - l) / k; dou nl = l; dou nr = l + haba; rep(i, k) { dou ni = goldd_d(nl, nr, calc); if (chmi(minv, calc(ni))) mini = ni; nl = nr; nr = nl + haba; } auto end = system_clock::now(); auto part = duration_cast<milliseconds>(end - s); auto elapsed = duration_cast<milliseconds>(end - start_time); if (elapsed + part * 2 >= lim) { break; } } return make_tuple(mini, calc(mini)); } template <class F> auto goldt_d_s(dou l, dou r, F calc, ll time = 2000) { /*20ms余裕を残している*/ auto lim = milliseconds(time - 20); dou maxi = 0, maxv = MIN<dou>(); /*区間をk分割する*/ rep(k, 1, inf) { auto s = system_clock::now(); dou haba = (r - l) / k; dou nl = l; dou nr = l + haba; rep(i, k) { dou ni = goldt_d(nl, nr, calc); if (chma(maxv, calc(ni))) maxi = ni; nl = nr; nr = nl + haba; } auto end = system_clock::now(); auto part = duration_cast<milliseconds>(end - s); auto elapsed = duration_cast<milliseconds>(end - start_time); if (elapsed + part * 2 >= lim) { break; } } return make_tuple(maxi, calc(maxi)); } #endif // strを整数として比較 string smax(str &a, str b) { if (sz(a) < sz(b)) { return b; } else if (sz(a) > sz(b)) { return a; } else if (a < b) return b; else return a; } // strを整数として比較 string smin(str &a, str b) { if (sz(a) > sz(b)) { return b; } else if (sz(a) < sz(b)) { return a; } else if (a > b) return b; else return a; } // エラー-1 template <typename W, typename T> ll find(vector<W> &a, int l, const T key) { rep(i, l, sz(a)) if (a[i] == key) return i; return -1; } template <typename W, typename T> ll find(vector<W> &a, const T key) { rep(i, sz(a)) if (a[i] == key) return i; return -1; } template <typename W, typename T> P find(vector<vector<W>> &a, const T key) { rep(i, sz(a)) rep(j, sz(a[0])) if (a[i][j] == key) return mp(i, j); return mp(-1, -1); } // getid(find())を返す 1次元にする template <typename W, typename T> int findi(vector<vector<W>> &a, const T key) { rep(i, sz(a)) rep(j, sz(a[0])) if (a[i][j] == key) return i * sz(a[0]) + j; return -1; } template <typename W, typename U> tuple<int, int, int> find(vector<vector<vector<W>>> &a, const U key) { rep(i, sz(a)) rep(j, sz(a[0])) rep(k, sz(a[0][0])) if (a[i][j][k] == key) return tuple<int, int, int>(i, j, k); return tuple<int, int, int>(-1, -1, -1); } // 無ければ-1 int find(string &s, const string key) { int klen = sz(key); rep(i, sz(s) - klen + 1) { if (s[i] != key[0]) continue; if (s.substr(i, klen) == key) { return i; } } return -1; } int find(string &s, int l, const string key) { int klen = sz(key); rep(i, l, sz(s) - klen + 1) { if (s[i] != key[0]) continue; if (s.substr(i, klen) == key) { return i; } } return -1; } int find(string &s, const char key) { rep(i, sz(s)) { if (s[i] == key) return i; } return -1; } int find(string &s, int l, const char key) { rep(i, l, sz(s)) { if (s[i] == key) return i; } return -1; } // N箇所について右のkeyの場所を返す template <typename W, typename T> vi finds(const W &a, const T &key) { int n = sz(a); vi rpos(n, -1); rer(i, n - 1) { if (i < n - 1) { rpos[i] = rpos[i + 1]; } if (a[i] == key) rpos[i] = i; } return rpos; } template <typename W, typename T> vi rfinds(const W &a, const T &key) { int n = sz(a); vi lpos(n, -1); rep(i, n) { if (i > 0) { lpos[i] = lpos[i - 1]; } if (a[i] == key) lpos[i] = i; } return lpos; } // todoz #if __cplusplus >= 201703L template <typename W, typename T, class Iterable = typename W::value_type> ll count(const W &a, const T &k) { return count_if(a, == k); } template <typename W, class Iterable = typename W::value_type> vi count(const W &a) { vi res; for_each(a, v, if (sz(res) <= (int)v) res.resize((int)v + 1); res[v]++;); return res; } #else ll count(const string &S, const char &c) { int res = 0; fora(s, S) { res += s == c; } return res; } #endif ll count(const str &a, const str &k) { ll ret = 0, len = k.length(); auto pos = a.find(k); while (pos != string::npos) pos = a.find(k, pos + len), ++ret; return ret; } /*@formatter:off*/ //'a' = 'A' = 0 として集計 既に-'a'されていても動く vi count(str &a, int l, int r) { vi cou(26); char c = 'a'; if ('A' <= a[l] && a[l] <= 'Z') c = 'A'; if ('a' <= a[l] && a[l] <= 'z') c = 'a'; else c = 0; rep(i, l, r)++ cou[a[i] - c]; return cou; } #define couif count_if // algorythm ll rev(ll a) { ll res = 0; while (a) { res *= 10; res += a % 10; a /= 10; } return res; } template <class T> auto rev(const vector<T> &a) { auto b = a; reverse(ALL(b)); return b; } /* \反転 */ template <class U> auto rev(vector<vector<U>> &a) { vector<vector<U>> b(sz(a[0]), vector<U>(sz(a))); rep(h, sz(a)) rep(w, sz(a[0])) b[w][h] = a[h][w]; return b; } /* |反転 */ template <class U> auto revw(vector<vector<U>> &a) { vector<vector<U>> b(sz(a), vector<U>(sz(a[0]))); int W = sz(a[0]); rep(h, sz(a)) rep(w, sz(a[0])) { b[h][W - 1 - w] = a[h][w]; } return b; } /* ー反転 */ template <class U> auto revh(vector<vector<U>> &a) { vector<vector<U>> b(sz(a), vector<U>(sz(a[0]))); int H = sz(a); rep(h, sz(a)) rep(w, sz(a[0])) { b[H - 1 - h][w] = a[h][w]; } return b; } /* /反転 */ template <class U> auto revr(vector<vector<U>> &a) { vector<vector<U>> b(sz(a[0]), vector<U>(sz(a))); int H = sz(a); int W = sz(a[0]); rep(h, sz(a)) rep(w, sz(a[0])) b[w][h] = a[H - 1 - h][W - 1 - w]; return b; } auto rev(const string &a) { string b = a; reverse(ALL(b)); return b; } template <class T> auto rev(const T &v, int i) { return v[sz(v) - 1 - i]; } int rev(int N, int i) { return N - 1 - i; } constexpr ll p10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000ll, 100000000000ll, 1000000000000ll, 10000000000000ll, 100000000000000ll, 1000000000000000ll, 10000000000000000ll, 100000000000000000ll, 1000000000000000000ll}; // 0は0桁 ll keta(ll v, int if_zero_res) { if (!v) return if_zero_res; if (v < p10[9]) { if (v < p10[4]) { if (v < p10[2]) { if (v < p10[1]) { if (v < p10[0]) return 0; else return 1; } else return 2; } else { if (v < p10[3]) return 3; else return 4; } } else { if (v < p10[7]) { if (v < p10[5]) return 5; else if (v < p10[6]) return 6; else return 7; } else { if (v < p10[8]) return 8; else return 9; } } } else { if (v < p10[13]) { if (v < p10[11]) { if (v < p10[10]) return 10; else return 11; } else { if (v < p10[12]) return 12; else return 13; } } else { if (v < p10[15]) { if (v < p10[14]) return 14; else return 15; } else { if (v < p10[17]) { if (v < p10[16]) return 16; else return 17; } else { if (v < p10[18]) return 18; else return 19; } } } } } #if __cplusplus >= 201703L ll getr(ll a, ll keta) { return (a / pow<ll>(10, keta)) % 10; } #else ll getr(ll a, ll keta) { return (a / (int)pow(10, keta)) % 10; } #endif // 上から何桁目か ll getl(ll a, ll ket) { int sketa = keta(a, 1); return getr(a, sketa - 1 - ket); } ll dsum(ll v, ll sin = 10) { ll ret = 0; for (; v; v /= sin) ret += v % sin; return ret; } ll mask10(ll v) { return p10[v] - 1; } // 変換系 template <class T, class U> auto to_v1(vector<reference_wrapper<U>> &ret, vector<T> &A) { rep(i, sz(A)) ret.push_back(A[i]); return ret; } template <class T, class U> auto to_v1(vector<reference_wrapper<U>> &ret, vector<vector<T>> &A) { rep(i, sz(A)) to_v1(ret, A[i]); return ret; } // 参照付きで1次元に起こす template <class T> auto to_v1(vector<vector<T>> &A) { vector<reference_wrapper<decl2_t<decltype(A)>>> ret; rep(i, sz(A)) to_v1(ret, A[i]); return ret; } //[v] := iとなるようなvectorを返す // 存在しない物は-1 // 空でも動く(なぜか) template <class T> auto keys(const T &a) { vector<decltype((a.begin())->fi)> res; for (auto &&k : a) res.push_back(k.fi); return res; } template <class T> auto values(const T &a) { vector<decltype((a.begin())->se)> res; for (auto &&k : a) res.push_back(k.se); return res; } // todo 可変長で template <class T> constexpr T min(T a, T b, T c) { return a >= b ? b >= c ? c : b : a >= c ? c : a; } template <class T> constexpr T max(T a, T b, T c) { return a <= b ? b <= c ? c : b : a <= c ? c : a; } // 1次元のコンテナ template <class T> int mini(const vector<T> &a) { return min_element(ALL(a)) - a.begin(); } template <class T> int maxi(const vector<T> &a) { return max_element(ALL(a)) - a.begin(); } template <class T> T sum(const T &A) { return A; } template <class T> T sum(const vector<T> &A, int l = -1, int r = -1) { T s = 0; set_lr12(l, r, sz(A)); rep(i, l, r) s += sum(A[i]); return s; } // 1次元のIterableに使える template <class T, require_t(!has_value_type<T>::value)> T min(T &a) { return a; } template <class V, require_t(has_value_type<V>::value)> auto min(V &a, ll s = -1, ll n = -1) { using Ret_t = decl2_t<V>; auto ret = MAX<Ret_t>(); set_lr12(s, n, sz(a)); if (s == n) { return INF<Ret_t>(); } else { rep(i, s, n) { ret = min(ret, min(a[i])); } return ret; } } template <class T, require_t(!has_value_type<T>::value)> T max(T &a) { return a; } template <class V, require_t(has_value_type<V>::value)> auto max(V &a, ll s = -1, ll n = -1) { using Ret_t = decl2_t<V>; auto ret = MIN<Ret_t>(); set_lr12(s, n, sz(a)); if (s == n) { return -INF<Ret_t>(); } else { rep(i, s, n) { ret = max(ret, max(a[i])); } return ret; } } template <class T> T mul(vector<T> &v, ll t = inf) { T ret = v[0]; rep(i, 1, min(t, sz(v))) ret *= v[i]; return ret; } // template<class T, class U, class... W> auto sumn(vector<T> &v, U head, W... // tail) { auto ret = sum(v[0], tail...); rep(i, 1, min(sz(v), head))ret // += sum(v[i], tail...); return ret;} indexを持つvectorを返す /*@formatter:off*/ template <typename W, typename T> void fill(W &xx, const T vall) { xx = vall; } template <typename W, typename T> void fill(vector<W> &vecc, const T vall) { for (auto &&vx : vecc) fill(vx, vall); } template <typename W, typename T> void fill(vector<W> &xx, const T v, ll len) { rep(i, len) xx[i] = v; } template <typename W, typename T> void fill(vector<W> &xx, const T v, int s, ll t) { rep(i, s, t) xx[i] = v; } template <typename W, typename T> void fill(vector<vector<W>> &xx, T v, int sh, int th, int sw, int tw) { rep(h, sh, th) rep(w, sw, tw) xx[h][w] = v; } // #define use_fill //_sum _array _max _min #ifdef use_fill template <typename A, size_t N, typename T> void fill(A (&a)[N], const T &v) { rep(i, N) { fill(a[i], v); } } template <class T, class U> void fill(vector<T> &a, const vi &ind, U val) { fora(v, ind) { a[v] = val; } } template <typename A, size_t N> auto sum(A (&a)[N], int l = -1, int r = -1) { set_lr12(l, r, N); auto res = sum(a[l]); if (l == r) { return res - res; } rep(i, l + 1, r) res += sum(a[i]); return res; } template <typename A, size_t N> auto max(A (&a)[N], int l = -1, int r = -1) { set_lr12(l, r, N); auto res = max(a[l]); if (l == r) { return -INF<decltype(res)>(); } rep(i, l + 1, r) res = max(res, max(a[i])); return res; } template <typename A, size_t N> auto min(A (&a)[N], int l = -1, int r = -1) { set_lr12(l, r, N); auto res = min(a[l]); if (l == r) { return INF<decltype(res)>(); } rep(i, l + 1, r) res = min(res, min(a[i])); return res; } #endif vi inds_(vi &a) { int n = max(a) + 1; vi ret(n, -1); rep(i, sz(a)) { assert(ret[a[i]] == -1); ret[a[i]] = i; } return ret; } void clear(PQ &q) { q = PQ(); } void clear(priority_queue<int> &q) { q = priority_queue<int>(); } template <class T> void clear(queue<T> &q) { while (q.size()) q.pop(); } // template<class T> T *negarr(ll size) { T *body = (T *) malloc((size * 2 + // 1) * sizeof(T)); return body + size;} template<class T> T *negarr2(ll h, // ll w) { double **dummy1 = new double *[2 * h + 1]; double *dummy2 = new // double[(2 * h + 1) * (2 * w + 1)]; dummy1[0] = dummy2 + w; for (ll i = // 1; i <= 2 * h + 1; ++i) { dummy1[i] = dummy1[i - 1] + 2 * w + 1; } double // **a = dummy1 + h; return a;} template <class T> struct ruiC { vector<T> rui; ruiC(vector<T> &ru) : rui(ru) {} /*先頭0*/ ruiC() : rui(1, 0) {} T operator()(ll l, ll r) { if (l > r) { cerr << "ruic "; deb(l, r); assert(0); } return rui[r] - rui[l]; } T operator()(int r = inf) { return operator()(0, min(r, sz(rui) - 1)); } /*ruiv[]をruic[]に変えた際意味が変わるのがまずいため()と統一*/ /*単体iを返す 累積でないことに注意(seg木との統一でこうしている)*/ // T operator[](ll i) { return rui[i + 1] - rui[i]; } T operator[](ll i) { return rui[i]; } /*0から順に追加される必要がある*/ void operator+=(T v) { rui.push_back(rui.back() + v); } void add(int i, T v) { if (sz(rui) - 1 != i) ole(); operator+=(v); } T back() { return rui.back(); } ll size() { return rui.size(); } auto begin() { return rui.begin(); } auto end() { return rui.end(); } }; template <class T> string deb_tos(const ruiC<T> &a) { return deb_tos(a.rui); } template <class T> ostream &operator<<(ostream &os, ruiC<T> a) { fora(v, a.rui) { os << v << " "; } return os; } template <class T> vector<T> ruiv(const vector<T> &a) { vector<T> ret(a.size() + 1); rep(i, a.size()) ret[i + 1] = ret[i] + a[i]; return ret; } template <class T> ruiC<T> ruic(const vector<T> &a) { vector<T> ret = ruiv(a); return ruiC<T>(ret); } template <class T> ruiC<T> ruic() { return ruiC<T>(); } // imoは0-indexed // ruiは1-indexed template <class T> vector<T> imo(const vector<T> &v) { vector<T> ret = v; rep(i, sz(ret) - 1) ret[i + 1] += ret[i]; return ret; } // #define use_rui //_imo _ruic _ruiv #ifdef use_rui // kと同じものの数 template <class T, class U> vi imo(const vector<T> &a, U k) { vi equ(sz(a)); rep(i, sz(a)) { equ[i] = a[i] == k; } return imo(equ); } template <class T> vector<T> imox(const vector<T> &v) { vector<T> ret = v; rep(i, sz(ret) - 1) ret[i + 1] ^= ret[i]; return ret; } // 漸化的に最小を持つ template <class T> vector<T> imi(const vector<T> &v) { vector<T> ret = v; rep(i, sz(ret) - 1) chmi(ret[i + 1], ret[i]); return ret; } template <class T> vector<T> ima(const vector<T> &v) { vector<T> ret = v; rep(i, sz(ret) - 1) chma(ret[i + 1], ret[i]); return ret; } template <class T> vector<T> rimi(const vector<T> &v) { vector<T> ret = v; rer(i, sz(ret) - 1, 1) chmi(ret[i - 1], ret[i]); return ret; } template <class T> vector<T> rima(const vector<T> &v) { vector<T> ret = v; rer(i, sz(ret) - 1, 1) chma(ret[i - 1], ret[i]); return ret; } template <class T> struct ruimax { template <typename Monoid> struct SegmentTree { /*pairで処理*/ int sz; vector<Monoid> seg; const Monoid M1 = mp(MIN<T>(), -1); Monoid f(Monoid a, Monoid b) { return max(a, b); } void build(vector<T> &a) { int n = sz(a); sz = 1; while (sz < n) sz <<= 1; seg.assign(2 * sz, M1); rep(i, n) { seg[i + sz] = mp(a[i], i); } for (int k = sz - 1; k > 0; k--) { seg[k] = f(seg[k << 1], seg[(k << 1) | 1]); } } Monoid query(int a, int b) { Monoid L = M1, R = M1; for (a += sz, b += sz; a < b; a >>= 1, b >>= 1) { if (a & 1) L = f(L, seg[a++]); if (b & 1) R = f(seg[--b], R); } return f(L, R); } Monoid operator[](const int &k) const { return seg[k + sz]; } }; private: vector<T> ve; SegmentTree<pair<T, int>> seg; vector<T> rv; vector<int> ri; bool build = false; public: int n; ruimax(vector<T> &a) : ve(a), n(sz(a)) { int index = -1; T ma = MIN<T>(); rv.resize(n + 1); ri.resize(n + 1); rv[0] = -INF<T>(); ri[0] = -1; rep(i, n) { if (chma(ma, a[i])) { index = i; } rv[i + 1] = ma; ri[i + 1] = index; } } T operator()(int l, int r) { if (!(l <= r && 0 <= l && r <= n)) { deb(l, r, n); assert(0); } if (l == 0) { return rv[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).first; } } T operator()(int r = inf) { return operator()(0, min(r, n)); } T operator[](int r) { return operator()(0, r); } T getv(int l, int r) { return operator()(l, r); } T getv(int r = inf) { return getv(0, min(r, n)); }; int geti(int l, int r) { assert(l <= r && 0 <= l && r <= n); if (l == 0) { return ri[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).second; } } int geti(int r = inf) { return geti(0, min(r, n)); }; auto begin() { return rv.begin(); } auto end() { return rv.end(); } }; template <class T> struct ruimin { template <typename Monoid> struct SegmentTree { /*pairで処理*/ int sz; vector<Monoid> seg; const Monoid M1 = mp(MAX<T>(), -1); Monoid f(Monoid a, Monoid b) { return min(a, b); } void build(vector<T> &a) { int n = sz(a); sz = 1; while (sz < n) sz <<= 1; seg.assign(2 * sz, M1); rep(i, n) { seg[i + sz] = mp(a[i], i); } for (int k = sz - 1; k > 0; k--) { seg[k] = f(seg[k << 1], seg[(k << 1) | 1]); } } Monoid query(int a, int b) { Monoid L = M1, R = M1; for (a += sz, b += sz; a < b; a >>= 1, b >>= 1) { if (a & 1) L = f(L, seg[a++]); if (b & 1) R = f(seg[--b], R); } return f(L, R); } Monoid operator[](const int &k) const { return seg[k + sz]; } }; private: vector<T> ve; SegmentTree<pair<T, int>> seg; vector<T> rv; vector<int> ri; bool build = false; int n; public: ruimin(vector<T> &a) : ve(a), n(sz(a)) { int index = -1; T mi = MAX<T>(); rv.resize(n + 1); ri.resize(n + 1); rv[0] = INF<T>(); ri[0] = -1; rep(i, n) { if (chmi(mi, a[i])) { index = i; } rv[i + 1] = mi; ri[i + 1] = index; } } T operator()(int l, int r) { assert(l <= r && 0 <= l && r <= n); if (l == 0) { return rv[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).first; } } T operator()(int r = inf) { return operator()(0, min(r, n)); } T operator[](int r) { return operator()(0, r); } T getv(int l, int r) { return operator()(l, r); } T getv(int r = inf) { return getv(0, min(r, n)); }; int geti(int l, int r) { { assert(l <= r && 0 <= l && r <= n); if (l == 0) { return ri[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).second; } } assert(l <= r && 0 <= l && r <= n); if (l == 0) { return ri[r]; } else { if (!build) seg.build(ve), build = true; return seg.query(l, r).second; } } int geti(int r = inf) { return geti(0, min(r, n)); }; auto begin() { return rv.begin(); } auto end() { return rv.end(); } }; /*@formatter:off*/ vvi() ruib(vi &a) { vvi(res, 61, sz(a) + 1); rep(k, 61) { rep(i, sz(a)) { res[k][i + 1] = res[k][i] + ((a[i] >> k) & 1); } } return res; } vector<ruiC<int>> ruibc(vi &a) { vector<ruiC<int>> ret(61); vvi(res, 61, sz(a)); rep(k, 61) { rep(i, sz(a)) { res[k][i] = (a[i] >> k) & 1; } ret[k] = ruic(res[k]); } return ret; } // kと同じものの数 template <class T, class U> vi ruiv(T &a, U k) { vi ret(a.size() + 1); rep(i, a.size()) ret[i + 1] = ret[i] + (a[i] == k); return ret; } template <class T, class U> ruiC<ll> ruic(T &a, U k) { vi ret = ruiv(a, k); return ruiC<ll>(ret); } template <class T> struct ruiC2 { int H; vector<ruiC<T>> rui; ruiC<T> dummy; // 変なのをよばれたときはこれを返す//todo ruiC2(const vector<vector<T>> &ru) : rui(sz(ru)), H(sz(ru)) { for (int h = 0; h < H; h++) { if (sz(ru[h]) == 0) continue; if (sz(dummy) == 1) dummy = ruic(vector<T>(sz(ru[h]))); rui[h] = ruic(ru[h]); } } // WについてHを返す vector<T> operator()(ll l, ll r) { if (l > r) { cerr << "ruic "; deb(l, r); assert(0); } vector<T> res(H); for (int h = 0; h < H; h++) res[h] = rui[h](l, r); return res; } // HについてWを返す ruiC<T> &operator[](ll h) { #ifdef _DEBUG if (h >= H) { message += "warning ruiC h >= H"; } #endif if (h >= H || sz(rui[h]) == 1) return dummy; else return rui[h]; } /*@formatter:off*/ // vector<T> operator()(int r) { return operator()(0, r); } /*ruiv[]をruic[]に変えた際意味が変わるのがまずいため()と統一*/ /*単体iを返す 累積でないことに注意(seg木との統一でこうしている)*/ // T operator[](ll i) { return rui[i + 1] - rui[i]; } /*0から順に追加される必要がある*/ // T back() { return rui.back(); } // ll size() { return rui.size(); } // auto begin(){return rui.begin();} // auto end(){return rui.end();} }; template <class T, class U> ruiC<ll> ruicou(vector<T> &a, U b) { vi cou(sz(a)); rep(i, sz(a)) { cou[i] = a[i] == b; } return ruic(cou); } // メモリは形式によらず(26*N) // rui(l,r)でvector(26文字について, l~rのcの個数) // rui[h] ruic()を返す // 添え字は'a', 'A'のまま扱う // (予め-='a','A'されているものが渡されたらそれに従う) template <typename Iterable, class is_Iterable = typename Iterable::value_type> ruiC2<ll> ruicou(const Iterable &a) { int H = max(a) + 1; vvi(cou, H); rep(i, sz(a)) { if (sz(cou[a[i]]) == 0) cou[a[i]].resize(sz(a)); cou[a[i]][i] = 1; } return ruiC2<ll>(cou); } /*@formatter:off*/ // h query template <class T> vector<T> imoh(vector<vector<T>> &v, int w) { vector<T> ret(sz(v)); rep(h, sz(ret)) { ret[h] = v[h][w]; } rep(i, sz(ret) - 1) { ret[i + 1] += ret[i]; } return ret; } template <class T> vector<T> ruih(vector<vector<T>> &v, int w) { vector<T> ret(sz(v) + 1); rep(h, sz(v)) { ret[h + 1] = v[h][w]; } rep(i, sz(v)) { ret[i + 1] += ret[i]; } return ret; } template <class T> ruiC<T> ruihc(vector<vector<T>> &a, int w) { vector<T> ret = ruih(a, w); return ruiC<T>(ret); } // xor template <class T> struct ruixC { vector<T> rui; ruixC(vector<T> &ru) : rui(ru) {} T operator()(ll l, ll r) { if (l > r) { cerr << "ruiXc "; deb(l, r); assert(0); } return rui[r] ^ rui[l]; } T operator[](ll i) { return rui[i]; } T back() { return rui.back(); } ll size() { return rui.size(); } }; template <class T> vector<T> ruix(vector<T> &a) { vector<T> ret(a.size() + 1); rep(i, a.size()) ret[i + 1] = ret[i] ^ a[i]; return ret; } template <class T> ruixC<ll> ruixc(vector<T> &a) { vi ret = ruix(a); return ruixC<ll>(ret); } // 差分を返す(累積を取ると元に戻る) // 101なら // 1111を返す // 元の配列で[l, r)へのxorは //[l]と[r]へのxorになる https://atcoder.jp/contests/abc155/tasks/abc155_f vi ruix_diff(vi &A) { int N = sz(A); assert(N); vi res(N + 1); res[0] = A[0]; rep(i, 1, N) { res[i] = A[i - 1] ^ A[i]; } res[N] = A[N - 1]; return res; } template <class T> vector<T> ruim(vector<T> &a) { vector<T> res(a.size() + 1, 1); rep(i, a.size()) res[i + 1] = res[i] * a[i]; return res; } // 漸化的に最小を1indexで持つ template <class T> vector<T> ruimi(vector<T> &a) { ll n = sz(a); vector<T> ret(n + 1); rep(i, 1, n) { ret[i] = a[i - 1]; chmi(ret[i + 1], ret[i]); } return ret; } // template<class T> T *rrui(vector<T> &a) { // 右から左にかけての半開区間 (-1 n-1] template <class T> struct rruiC { vector<T> rui; int n; rruiC(vector<T> &a) : n(sz(a)) { rui.resize(n + 1); rer(i, n - 1) { rui[i] = rui[i + 1] + a[i]; } } /*[r l)*/ T operator()(int r, int l) { r++; l++; assert(l <= r && l >= 0 && r <= n); return rui[l] - rui[r]; } T operator()(int l) { return operator()(n - 1, l); } T operator[](int i) { return operator()(i); } }; template <class T> ostream &operator<<(ostream &os, rruiC<T> a) { fora(v, a.rui) { os << v << " "; } return os; } template <class T> string deb_tos(rruiC<T> &a) { return deb_tos(a.rui); } #define rrui rruic template <class T> rruiC<T> rruic(vector<T> &a) { return rruiC<T>(a); } // 掛け算 template <class T> struct ruimulC { vector<T> rv; int n; ruimulC(vector<T> &a) : rv(a), n(sz(a)) { rv.resize(n + 1); rv[0] = 1; rep(i, n) { rv[i + 1] = a[i] * rv[i]; } } ruimulC() : n(0) { rv.resize(n + 1); rv[0] = 1; } void operator+=(T v) { rv.push_back(rv.back() * v); n++; } T operator()(int l, int r) { assert(l <= r && 0 <= l && r <= n); return rv[r] / rv[l]; } T operator()(int r = inf) { return operator()(0, min(r, n)); } T operator[](int r) { return operator()(0, r); } auto begin() { return rv.begin(); } auto end() { return rv.end(); } }; template <class T> ruimulC<T> ruimul(vector<T> &a) { return ruimulC<T>(a); } template <class T> ruimulC<T> ruimul() { vector<T> a; return ruimulC<T>(a); } template <class T> T *rruim(vector<T> &a) { ll len = a.size(); T *body = (T *)malloc((len + 1) * sizeof(T)); T *res = body + 1; res[len - 1] = 1; rer(i, len - 1) res[i - 1] = res[i] * a[i]; return res; } template <class T, class U, class W> T lowerBound(ruiC<T> &a, U v, W banpei) { return lowerBound(a.rui, v, banpei); } template <class T, class U, class W> T upperBound(ruiC<T> &a, U v, W banpei) { return upperBound(a.rui, v, banpei); } template <class T, class U, class W> T rlowerBound(ruiC<T> &a, U v, W banpei) { return rlowerBound(a.rui, v, banpei); } template <class T, class U, class W> T rupperBound(ruiC<T> &a, U v, W banpei) { return rupperBound(a.rui, v, banpei); } #endif constexpr bool bget(ll m, ll keta) { #ifdef _DEBUG assert(keta <= 62); // オーバーフロー 1^62までしか扱えない #endif return (m >> keta) & 1; } // bget(n)次元 // NならN-1まで vector<vi> bget2(vi &a, int keta_size) { vvi(res, keta_size, sz(a)); rep(k, keta_size) { rep(i, sz(a)) { res[k][i] = bget(a[i], k); } } return res; } vi bget1(vi &a, int keta) { vi res(sz(a)); rep(i, sz(a)) { res[i] = bget(a[i], keta); } return res; } #if __cplusplus >= 201703L ll bget(ll m, ll keta, ll sinsuu) { m /= pow<ll>(sinsuu, keta); return m % sinsuu; } #else ll bget(ll m, ll keta, ll sinsuu) { m /= (ll)pow(sinsuu, keta); return m % sinsuu; } #endif constexpr ll bit(ll n) { #ifdef _DEBUG assert(n <= 62); // オーバーフロー 1^62までしか扱えない #endif return (1LL << (n)); } #if __cplusplus >= 201703L ll bit(ll n, ll sinsuu) { return pow<ll>(sinsuu, n); } #else ll bit(ll n, ll sinsuu) { return (ll)pow(sinsuu, n); } #endif ll mask(ll n) { return (1ll << n) - 1; } // aをbitに置きなおす //{0, 2} -> 101 ll bit(const vi &a) { int m = 0; for (auto &&v : a) m |= bit(v); return m; } //{1, 1, 0} -> 011 // bitsetに置き換える感覚 i が立っていたら i bit目を立てる ll bit_bool(vi &a) { int m = 0; rep(i, sz(a)) if (a[i]) m |= bit(i); return m; } #define bcou __builtin_popcountll // 最下位ビット ll lbit(ll n) { assert(n); return n & -n; } ll lbiti(ll n) { assert(n); return log2(n & -n); } // 最上位ビット ll hbit(ll n) { assert(n); n |= (n >> 1); n |= (n >> 2); n |= (n >> 4); n |= (n >> 8); n |= (n >> 16); n |= (n >> 32); return n - (n >> 1); } ll hbiti(ll n) { assert(n); return log2(hbit(n)); } // ll hbitk(ll n) { ll k = 0; rer(i, 5) { ll a = k + (1ll << i); ll // b = 1ll << a; if (b <= n)k += 1ll << i; } return k;} // 初期化は0を渡す ll nextComb(ll &mask, ll n, ll r) { if (!mask) return mask = (1LL << r) - 1; ll x = mask & -mask; /*最下位の1*/ ll y = mask + x; /*連続した下の1を繰り上がらせる*/ ll res = ((mask & ~y) / x >> 1) | y; if (bget(res, n)) return mask = 0; else return mask = res; } // n桁以下でビットがr個立っているもののvectorを返す vi bitCombList(ll n, ll r) { vi res; ll m = 0; while (nextComb(m, n, r)) { res.push_back(m); } return res; } /*over*/ #define forbit1_2(i, mas) \ for (int forbitj = !mas ? 0 : lbit(mas), forbitm = mas, \ i = !mas ? 0 : log2(forbitj); \ forbitm; forbitm = forbitm ^ forbitj, \ forbitj = !forbitm ? 1 : lbit(forbitm), i = log2(forbitj)) /*over*/ #define forbit1_3(i, N, mas) \ for (int forbitj = !mas ? 0 : lbit(mas), forbitm = mas, \ i = !mas ? 0 : log2(forbitj); \ forbitm && i < N; forbitm = forbitm ^ forbitj, \ forbitj = !forbitm ? 1 : lbit(forbitm), i = log2(forbitj)) // masの立ってるindexを見る // i, [N], mas #define forbit1(...) over3(__VA_ARGS__, forbit1_3, forbit1_2)(__VA_ARGS__) // masが立っていないindexを見る // i, N, mas #define forbit0(i, N, mas) forbit1(i, (mask(N) & (~(mas)))) // forsubをスニペットして使う // Mの部分集合(0,M含む)を見る 3^sz(S)個ある #define forsub_all(m, M) for (int m = M; m != -1; m = m == 0 ? -1 : (m - 1) & M) // BASE進数 template <size_t BASE> class base_num { int v; public: base_num(int v = 0) : v(v){}; int operator[](int i) { return bget(v, i, BASE); } void operator++() { v++; } void operator++(signed) { v++; } operator int() { return v; } }; #define base3(mas, lim, BASE) for (base_num<BASE> mas; mas < lim; mas++) #define base2(mas, lim) base3(mas, lim, 2) #define base(...) over3(__VA_ARGS__, base3, base2, base1)(__VA_ARGS__) // aにある物をtrueとする vb bool_(vi a, int n) { vb ret(max(max(a) + 1, n)); rep(i, sz(a)) ret[a[i]] = true; return ret; } char itoal(ll i) { return 'a' + i; } char itoaL(ll i) { return 'A' + i; } ll altoi(char c) { if ('A' <= c && c <= 'Z') return c - 'A'; return c - 'a'; } ll ctoi(char c) { return c - '0'; } char itoc(ll i) { return i + '0'; } ll vtoi(vi &v) { ll res = 0; if (sz(v) > 18) { debugline("vtoi"); deb(sz(v)); ole(); } rep(i, sz(v)) { res *= 10; res += v[i]; } return res; } vi itov(ll i) { vi res; while (i) { res.push_back(i % 10); i /= 10; } res = rev(res); return res; } vi stov(string &a) { ll n = sz(a); vi ret(n); rep(i, n) { ret[i] = a[i] - '0'; } return ret; } // 基準を満たさないものは0になる vi stov(string &a, char one) { ll n = sz(a); vi ret(n); rep(i, n) ret[i] = a[i] == one; return ret; } vector<vector<ll>> ctoi(vector<vector<char>> s, char c) { ll n = sz(s), m = sz(s[0]); vector<vector<ll>> res(n, vector<ll>(m)); rep(i, n) rep(j, m) res[i][j] = s[i][j] == c; return res; } // #define use_compress //[i] := vを返す // aは0~n-1で置き換えられる vi compress(vi &a) { vi b; ll len = a.size(); for (ll i = 0; i < len; ++i) { b.push_back(a[i]); } sort(b); unique(b); for (ll i = 0; i < len; ++i) { a[i] = lower_bound(ALL(b), a[i]) - b.begin(); } ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } #ifdef use_compress // ind[i] := i番目に小さい数 // map[v] := vは何番目に小さいか vi compress(vi &a, umapi &map) { vi b; ll len = a.size(); for (ll i = 0; i < len; ++i) { b.push_back(a[i]); } sort(b); unique(b); for (ll i = 0; i < len; ++i) { ll v = a[i]; a[i] = lower_bound(ALL(b), a[i]) - b.begin(); map[v] = a[i]; } ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } vi compress(vi &a, vi &r) { vi b; ll len = a.size(); fora(v, a) { b.push_back(v); } fora(v, r) { b.push_back(v); } sort(b); unique(b); for (ll i = 0; i < len; ++i) a[i] = lower_bound(ALL(b), a[i]) - b.begin(); for (ll i = 0; i < sz(r); ++i) r[i] = lower_bound(ALL(b), r[i]) - b.begin(); ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } vi compress(vi &a, vi &r, vi &s) { vi b; ll len = a.size(); fora(v, a) { b.push_back(v); } fora(v, r) { b.push_back(v); } fora(v, s) { b.push_back(v); } sort(b); unique(b); for (ll i = 0; i < len; ++i) a[i] = lower_bound(ALL(b), a[i]) - b.begin(); for (ll i = 0; i < sz(r); ++i) r[i] = lower_bound(ALL(b), r[i]) - b.begin(); for (ll i = 0; i < sz(s); ++i) r[i] = lower_bound(ALL(b), s[i]) - b.begin(); ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } vi compress(vector<vi> &a) { vi b; fora(vv, a) { fora(v, vv) { b.push_back(v); } } sort(b); unique(b); fora(vv, a) { fora(v, vv) { v = lower_bound(ALL(b), v) - b.begin(); } } ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } vi compress(vector<vector<vi>> &a) { vi b; fora(vvv, a) { fora(vv, vvv) { fora(v, vv) { b.push_back(v); } } } sort(b); unique(b); fora(vvv, a) { fora(vv, vvv) { fora(v, vv) { v = lower_bound(ALL(b), v) - b.begin(); } } } ll blen = sz(b); vi ret(blen); rep(i, blen) { ret[i] = b[i]; } return ret; } void compress(ll a[], ll len) { vi b; for (ll i = 0; i < len; ++i) { b.push_back(a[i]); } sort(b); unique(b); for (ll i = 0; i < len; ++i) { a[i] = lower_bound(ALL(b), a[i]) - b.begin(); } } #endif // 要素が見つからなかったときに困る #define binarySearch(a, v) (binary_search(ALL(a), v)) #define lowerIndex(a, v) (lower_bound(ALL(a), v) - a.begin()) #define upperIndex(a, v) (upper_bound(ALL(a), v) - a.begin()) #define rlowerIndex(a, v) (upper_bound(ALL(a), v) - a.begin() - 1) #define rupperIndex(a, v) (lower_bound(ALL(a), v) - a.begin() - 1) template <class T, class U, class W> T lowerBound(vector<T> &a, U v, W banpei) { auto it = lower_bound(a.begin(), a.end(), v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T upperBound(vector<T> &a, U v, W banpei) { auto it = upper_bound(a.begin(), a.end(), v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T rlowerBound(vector<T> &a, U v, W banpei) { auto it = upper_bound(a.begin(), a.end(), v); if (it == a.begin()) return banpei; else { return *(--it); } } template <class T, class U, class W> T rupperBound(vector<T> &a, U v, W banpei) { auto it = lower_bound(a.begin(), a.end(), v); if (it == a.begin()) return banpei; else { return *(--it); } } // todo 消せないか template <class T, class U, class W> T lowerBound(set<T> &a, U v, W banpei) { auto it = a.lower_bound(v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T upperBound(set<T> &a, U v, W banpei) { auto it = a.upper_bound(v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T rlowerBound(set<T> &a, U v, W banpei) { auto it = a.upper_bound(v); if (it == a.begin()) return banpei; else { return *(--it); } } template <class T, class U, class W> T rupperBound(set<T> &a, U v, W banpei) { auto it = a.lower_bound(v); if (it == a.begin()) return banpei; else { return *(--it); } } template <class T, class U, class W> T lowerBound(mset<T> &a, U v, W banpei) { auto it = a.lower_bound(v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T upperBound(mset<T> &a, U v, W banpei) { auto it = a.upper_bound(v); if (it == a.end()) return banpei; else return *it; } template <class T, class U, class W> T rlowerBound(mset<T> &a, U v, W banpei) { auto it = a.upper_bound(v); if (it == a.begin()) return banpei; else { return *(--it); } } template <class T, class U, class W> T rupperBound(mset<T> &a, U v, W banpei) { auto it = a.lower_bound(v); if (it == a.begin()) return banpei; else { return *(--it); } } #define next2(a) next(next(a)) #define prev2(a) prev(prev(a)) // 狭義の単調増加列 長さを返す template <class T> int lis(vector<T> &a) { int n = sz(a); vi tail(n + 1, MAX<T>()); rep(i, n) { int id = lowerIndex(tail, a[i]); /**/ tail[id] = a[i]; } return lowerIndex(tail, MAX<T>()); } template <class T> int lis_eq(vector<T> &a) { int n = sz(a); vi tail(n + 1, MAX<T>()); rep(i, n) { int id = upperIndex(tail, a[i]); /**/ tail[id] = a[i]; } return lowerIndex(tail, MAX<T>()); } // iteratorを返す // valueが1以上の物を返す 0は見つけ次第削除 // vを減らす場合 (*it).se--でいい template <class T, class U, class V> auto lower_map(map<T, U> &m, V k) { auto ret = m.lower_bound(k); while (ret != m.end() && (*ret).second == 0) { ret = m.erase(ret); } return ret; } template <class T, class U, class V> auto upper_map(map<T, U> &m, V k) { auto ret = m.upper_bound(k); while (ret != m.end() && (*ret).second == 0) { ret = m.erase(ret); } return ret; } // 存在しなければエラー template <class T, class U, class V> auto rlower_map(map<T, U> &m, V k) { auto ret = upper_map(m, k); assert(ret != m.begin()); ret--; while (1) { if ((*ret).second != 0) break; assert(ret != m.begin()); auto next = ret; --next; m.erase(ret); ret = next; } return ret; } template <class T, class U, class V> auto rupper_map(map<T, U> &m, V k) { auto ret = lower_map(m, k); assert(ret != m.begin()); ret--; while (1) { if ((*ret).second != 0) break; assert(ret != m.begin()); auto next = ret; --next; m.erase(ret); ret = next; } return ret; } template <class... T> void fin(T... s) { out(s...); exit(0); } // 便利 数学 math // sub ⊂ top bool subset(int sub, int top) { return (sub & top) == sub; } //-180 ~ 180 degree double atand(double h, double w) { return atan2(h, w) / PI * 180; } //% -mの場合、最小の正の数を返す ll mod(ll a, ll m) { if (m < 0) m *= -1; return (a % m + m) % m; } // ll pow(ll a) { return a * a; }; template <class T> T fact(int v) { static vector<T> fact(2, 1); if (sz(fact) <= v) { rep(i, sz(fact), v + 1) { fact.emplace_back(fact.back() * i); } } return fact[v]; } ll comi(ll n, ll r) { assert(n < 100); static vvi(pas, 100, 100); if (pas[0][0]) return pas[n][r]; pas[0][0] = 1; rep(i, 1, 100) { pas[i][0] = 1; rep(j, 1, i + 1) pas[i][j] = pas[i - 1][j - 1] + pas[i - 1][j]; } return pas[n][r]; } // 二項係数の偶奇を返す int com_mod2(int n, int r) { return n == (r | (n - r)); } double comd2(ll n, ll r) { static vvd(comb, 2020, 2020); if (comb[0][0] == 0) { comb[0][0] = 1; rep(i, 2000) { comb[i + 1][0] = 1; rep(j, 1, i + 2) { comb[i + 1][j] = comb[i][j] + comb[i][j - 1]; } } } return comb[n][r]; } double comd(int n, int r) { if (r < 0 || r > n) return 0; if (n < 2020) return comd2(n, r); static vd fact(2, 1); if (sz(fact) <= n) { rep(i, sz(fact), n + 1) { fact.push_back(fact.back() * i); } } return fact[n] / fact[n - r] / fact[r]; } #define gcd my_gcd template <class T, class U, class V = typename max_type<T, U>::type> V gcd(T a_, U b_) { V a = a_; V b = b_; while (b) a %= b, swap(a, b); return abs(a); } template <class T> T gcd(const vector<T> &b) { T res = b[0]; rep(i, 1, sz(b)) res = gcd(b[i], res); return res; } #define lcm my_lcm ll lcm(ll a, ll b) { return a / gcd(a, b) * b; } ll lcm(vi a) { ll res = a[0]; rep(i, 1, sz(a)) res = lcm(a[i], res); return res; } ll ceil(ll a, ll b) { if (b == 0) { debugline("ceil"); deb(a, b); ole(); return -1; } else if (a < 0) { return 0; } else { return (a + b - 1) / b; } } #define hypot my_hypot double hypot(double dx, double dy) { return std::sqrt(dx * dx + dy * dy); } ll sig0(int t) { return t <= 0 ? 0 : ((1 + t) * t) >> 1; } bint sig0(bint t) { return t <= 0 ? 0 : ((1 + t) * t) >> 1; } // ll sig(ll s, ll t) { return ((s + t) * (t - s + 1)) >> 1; } ll sig(ll s, ll t) { if (s > t) swap(s, t); return sig0(t - s) + s * (t - s + 1); } #define tousa_i tosa_i #define lower_tousa_i lower_tosa_i #define upper_tousa upper_tosa #define upper_tousa_i upper_tosa_i ll tosa_i(ll st, ll ad, ll v) { assert(((v - st) % ad) == 0); return (v - st) / ad; } ll tosa_s(ll st, ll ad, ll len) { return st * len + sig0(len - 1) * ad; } // ax + r (x は非負整数) で表せる整数のうち、v 以上となる最小の整数 ll lower_tosa(ll st, ll ad, ll v) { if (st >= v) return st; return (v - st + ad - 1) / ad * ad + st; } // 第何項か ll lower_tosa_i(ll st, ll ad, ll v) { if (st >= v) return 0; return (v - st + ad - 1) / ad; } ll upper_tosa(ll st, ll ad, ll v) { return lower_tosa(st, ad, v + 1); } ll upper_tosa_i(ll st, ll ad, ll v) { return lower_tosa_i(st, ad, v + 1); } // b * res <= aを満たす [l, r)を返す div P drange_ika(int a, int b) { P null_p = mp(linf, linf); if (b == 0) { if (a >= 0) { return mp(-linf, linf + 1) /*全て*/; } else { return null_p /*無い*/; } } else { if (a >= 0) { if (b > 0) { return mp(-linf, a / b + 1); } else { return mp(-(a / -b), linf + 1); } } else { if (b > 0) { return mp(-linf, -ceil(-a, b) + 1); } else { return mp(ceil(-a, -b), linf + 1); } } } } // v * v >= aとなる最小のvを返す ll sqrt(ll a) { if (a < 0) { debugline("sqrt"); deb(a); ole(); } ll res = (ll)std::sqrt(a); while (res * res < a) ++res; return res; } double log(double e, double x) { return log(x) / log(e); } /*@formatter:off*/ // 機能拡張 #define dtie(a, b) \ int a, b; \ tie(a, b) template <class T, class U> string to_string(T a, U b) { string res = ""; res += a; res += b; return res; } template <class T, class U, class V> string to_string(T a, U b, V c) { string res = ""; res += a; res += b; res += c; return res; } template <class T, class U, class V, class W> string to_string(T a, U b, V c, W d) { string res = ""; res += a; res += b; res += c; res += d; return res; } template <class T, class U, class V, class W, class X> string to_string(T a, U b, V c, W d, X e) { string res = ""; res += a; res += b; res += c; res += d; res += e; return res; } // todo stringもセットで // find_ifはsubrを使う string sub(string &A, int l = -1, int r = -1) { set_lr12(l, r, sz(A)); assert(0 <= l && l <= r && r <= sz(A)); return A.substr(l, r - l); } template <class T> vector<T> sub(const vector<T> &A, int l, int r) { assert(0 <= l && l <= r && r <= sz(A)); vector<T> ret(r - l); std::copy(A.begin() + l, A.begin() + r, ret.begin()); return ret; } template <class T> vector<T> sub(const vector<T> &A, int r) { return sub(A, 0, r); } #if __cplusplus >= 201703L template <class I, require_t(has_value_type<I>::value)> I subn(const I &A, int l, int len) { return sub(A, l, l + len); } #endif template <class T, class F> // sub2で呼ぶ vector<T> sub(const vector<vector<T>> &A, int h, int w, int ah, int aw, F f) { vector<T> res; while (0 <= h && h < sz(A) && 0 <= w && w < sz(A[h]) && f(A[h][w])) { res.emplace_back(A[h][w]); h += ah; w += aw; } return res; } template <class T> vector<T> sub(const vector<vector<T>> &A, int h, int w, int ah, int aw) { return sub(A, h, w, ah, aw, [&](T v) { return true; }); } // range_nowを返す(find_ifでしか使われない) #if __cplusplus >= 201703L template <class T> auto subr(const vector<T> &A, int l) { return range_now(vector<T>(A.begin() + l, A.end()), l); } #endif #define sub25(A, h, w, ah, aw) sub(A, h, w, ah, aw) #define sub26(A, h, w, ah, aw, siki_r) \ sub(A, h, w, ah, aw, [&](auto v) { return v siki_r; }) #define sub27(A, h, w, ah, aw, v, siki) \ sub(A, h, w, ah, aw, [&](auto v) { return siki; }) #define sub2(...) over7(__VA_ARGS__, sub27, sub26, sub25)(__VA_ARGS__) constexpr int bsetlen = 50001; // constexpr int bsetlen = 5050; #define bset bitset<bsetlen> bool operator<(bitset<bsetlen> &a, bitset<bsetlen> &b) { rer(i, bsetlen - 1) { if (a[i] < b[i]) return true; if (a[i] > b[i]) return false; } return false; } bool operator>(bitset<bsetlen> &a, bitset<bsetlen> &b) { rer(i, bsetlen - 1) { if (a[i] > b[i]) return true; if (a[i] < b[i]) return false; } return false; } bool operator<=(bitset<bsetlen> &a, bitset<bsetlen> &b) { rer(i, bsetlen - 1) { if (a[i] < b[i]) return true; if (a[i] > b[i]) return false; } return true; } bool operator>=(bitset<bsetlen> &a, bitset<bsetlen> &b) { rer(i, bsetlen - 1) { if (a[i] > b[i]) return true; if (a[i] < b[i]) return false; } return true; } string operator~(string &a) { string res = a; for (auto &&c : res) { if (c == '0') c = '1'; else if (c == '1') c = '0'; else { cerr << "cant ~" << a << "must bit" << endl; exit(0); } } return res; } ostream &operator<<(ostream &os, bset &a) { bitset<10> b; vi list; rep(i, bsetlen) { if (a[i]) list.push_back(i), b[i] = 1; } os << b << ", " << list; return os; } int hbiti(bset &a) { rer(i, bsetlen) { if (a[i]) return i; } return -1; } #define hk(a, b, c) (a <= b && b < c) // O(N/64) bset nap(bset &a, int v) { bset r = a | a << v; return r; } bset nap(bset &a, bset &v) { bset r = a; rep(i, bsetlen) { if (v[i]) r |= a << i; } return r; } template <class T> int count(set<T> &S, T l, T r) { assert(l < r); auto it = S.lower_bound(l); return it != S.end() && (*it) < r; } // template<class T> void seth(vector<vector<T>> &S, int w, vector<T> &v) // {assert(sz(S) == sz(v));assert(w < sz(S[0]));rep(h, sz(S)) { S[h][w] = v[h]; // }} template <class T> vector<T> geth(vector<vector<T>> &S, int w) { assert(w < sz(S[0])); vector<T> ret(sz(S)); rep(h, sz(S)) { ret[h] = S[h][w]; } return ret; } // vector<bool>[i]は参照を返さないため、こうしないとvb[i] |= // trueがコンパイルエラー vb::reference operator|=(vb::reference a, bool b) { return a = a | b; } vb::reference operator&=(vb::reference a, bool b) { return a = a & b; } template <class T, class U> void operator+=(pair<T, U> &a, pair<T, U> &b) { a.fi += b.fi; a.se += b.se; } template <class T, class U> pair<T, U> operator+(const pair<T, U> &a, const pair<T, U> &b) { return pair<T, U>(a.fi + b.fi, a.se + b.se); } template <class T, class U> pair<T, U> operator-(const pair<T, U> &a, const pair<T, U> &b) { return pair<T, U>(a.fi - b.fi, a.se - b.se); } template <class T, class U> pair<T, U> operator-(const pair<T, U> &a) { return pair<T, U>(-a.first, -a.second); } template <typename CharT, typename Traits, typename Alloc> basic_string<CharT, Traits, Alloc> operator+(const basic_string<CharT, Traits, Alloc> &lhs, const int rhs) { #ifdef _DEBUG static bool was = false; if (!was) message += "str += 65 is 'A' not \"65\" "; was = true; #endif return lhs + (char)rhs; } template <typename CharT, typename Traits, typename Alloc> basic_string<CharT, Traits, Alloc> operator+(const int lhs, const basic_string<CharT, Traits, Alloc> &rhs) { #ifdef _DEBUG static bool was = false; if (!was) message += "str += 65 is 'A' not \"65\" "; was = true; #endif return (char)lhs + rhs; } template <typename CharT, typename Traits, typename Alloc> void operator+=(basic_string<CharT, Traits, Alloc> &lhs, const int rv) { lhs = lhs + rv; } template <typename CharT, typename Traits, typename Alloc> basic_string<CharT, Traits, Alloc> operator+(const basic_string<CharT, Traits, Alloc> &lhs, const signed rv) { const int rv2 = rv; return lhs + rv2; } template <typename CharT, typename Traits, typename Alloc> void operator+=(basic_string<CharT, Traits, Alloc> &lhs, const signed rv) { const int v = rv; lhs += v; } template <typename CharT, typename Traits, typename Alloc> void operator*=(basic_string<CharT, Traits, Alloc> &s, int num) { auto bek = s; s = ""; for (; num; num >>= 1) { if (num & 1) { s += bek; } bek += bek; } } template <class T, class U> void operator+=(queue<T> &a, U v) { a.push(v); } template <class T, class U> void operator+=(deque<T> &a, U v) { a.push_back(v); } template <class T> priority_queue<T, vector<T>, greater<T>> & operator+=(priority_queue<T, vector<T>, greater<T>> &a, vector<T> &v) { fora(d, v) { a.push(d); } return a; } template <class T, class U> priority_queue<T, vector<T>, greater<T>> & operator+=(priority_queue<T, vector<T>, greater<T>> &a, U v) { a.push(v); return a; } template <class T, class U> priority_queue<T> &operator+=(priority_queue<T> &a, U v) { a.push(v); return a; } template <class T> set<T> &operator+=(set<T> &a, vector<T> v) { fora(d, v) { a.insert(d); } return a; } template <class T, class U> auto operator+=(set<T> &a, U v) { return a.insert(v); } template <class T, class U> auto operator-=(set<T> &a, U v) { return a.erase(v); } template <class T, class U> auto operator+=(mset<T> &a, U v) { return a.insert(v); } template <class T, class U> set<T, greater<T>> &operator+=(set<T, greater<T>> &a, U v) { a.insert(v); return a; } template <class T, class U> vector<T> &operator+=(vector<T> &a, U v) { a.push_back(v); return a; } template <class T, class U> vector<T> operator+(U v, const vector<T> &a) { vector<T> ret = a; ret.insert(ret.begin(), v); return ret; } template <class T> vector<T> operator+(const vector<T> &a, const vector<T> &b) { vector<T> ret; ret = a; fora(v, b) { ret += v; } return ret; } template <class T> vector<T> &operator+=(vector<T> &a, const vector<T> &b) { rep(i, sz(b)) { /*こうしないとa+=aで両辺が増え続けてバグる*/ a.push_back(b[i]); } return a; } template <class T, class U> map<T, U> &operator+=(map<T, U> &a, map<T, U> &b) { for (auto &&bv : b) { a[bv.first] += bv.second; } return a; } template <class T, class U> vector<T> operator+(const vector<T> &a, const U &v) { vector<T> ret = a; ret += v; return ret; } template <class T, class U> auto operator+=(uset<T> &a, U v) { return a.insert(v); } template <class T> vector<T> operator%(vector<T> &a, int v) { vi ret(sz(a)); rep(i, sz(a)) { ret[i] = a[i] % v; } return ret; } template <class T> vector<T> operator%=(vector<T> &a, int v) { rep(i, sz(a)) { a[i] %= v; } return a; } vi operator&(vi &a, vi &b) { assert(sz(a) == sz(b)); vi ret(sz(a)); rep(i, sz(a)) { ret[i] = min(a[i], b[i]); } return ret; } template <class T> void operator+=(mset<T> &a, vector<T> &v) { for (auto &&u : v) a.insert(u); } template <class T> void operator+=(set<T> &a, vector<T> &v) { for (auto &&u : v) a.insert(u); } template <class T> void operator+=(vector<T> &a, set<T> &v) { for (auto &&u : v) a.emplace_back(u); } template <class T> void operator+=(vector<T> &a, mset<T> &v) { for (auto &&u : v) a.emplace_back(u); } template <class T> vector<T> &operator-=(vector<T> &a, vector<T> &b) { if (sz(a) != sz(b)) { debugline("vector<T> operator-="); deb(a); deb(b); exit(0); } rep(i, sz(a)) a[i] -= b[i]; return a; } template <class T> vector<T> operator-(vector<T> &a, vector<T> &b) { if (sz(a) != sz(b)) { debugline("vector<T> operator-"); deb(a); deb(b); ole(); } vector<T> res(sz(a)); rep(i, sz(a)) res[i] = a[i] - b[i]; return res; } // template<class T, class U> void operator*=(vector<T> &a, U b) { vector<T> // ta = a; rep(b-1){ a+=ta; }} template <typename T> void erase(T &v, unsigned ll i) { v.erase(v.begin() + i); } template <typename T> void erase(T &v, unsigned ll s, unsigned ll e) { v.erase(v.begin() + s, v.begin() + e); } template <class T, class... I> auto erased(T &v, I... arg) { auto ret = v; erase(ret, arg...); return ret; } template <typename T> void pop_front(vector<T> &v) { erase(v, 0); } template <typename T> void entry(vector<T> &v, unsigned ll s, unsigned ll e) { erase(v, e, sz(v)); erase(v, 0, s); } template <class T, class U> void erase(map<T, U> &m, ll okl, ll ngr) { m.erase(m.lower_bound(okl), m.lower_bound(ngr)); } template <class T> void erase(set<T> &m, ll okl, ll ngr) { m.erase(m.lower_bound(okl), m.lower_bound(ngr)); } template <typename T> void erasen(vector<T> &v, unsigned ll s, unsigned ll n) { v.erase(v.begin() + s, v.begin() + s + n); } template <typename T, typename U> void insert(vector<T> &v, unsigned ll i, U t) { v.insert(v.begin() + i, t); } template <typename T, typename U> void push_front(vector<T> &v, U t) { v.insert(v.begin(), t); } template <typename T, typename U> void insert(vector<T> &v, unsigned ll i, vector<T> list) { for (auto &&va : list) v.insert(v.begin() + i++, va); } vector<string> split(const string &a, const char deli) { string b = a + deli; ll l = 0, r = 0, n = b.size(); vector<string> res; rep(i, n) { if (b[i] == deli) { r = i; if (l < r) res.push_back(b.substr(l, r - l)); l = i + 1; } } return res; } vector<string> split(const string &a, const string deli) { vector<string> res; ll kn = sz(deli); std::string::size_type Pos(a.find(deli)); ll l = 0; while (Pos != std::string::npos) { if (Pos - l) res.push_back(a.substr(l, Pos - l)); l = Pos + kn; Pos = a.find(deli, Pos + kn); } if (sz(a) - l) res.push_back(a.substr(l, sz(a) - l)); return res; } ll stoi(string &s) { return stol(s); } #define assert_yn(yn_v, v) \ ; \ assert(yn_v == 0 || yn_v == v); \ yn_v = v; // 不完全な対策、現状はautohotkeyで対応 int yn_v = 0; void yn(bool a) { assert_yn(yn_v, 1); if (a) cout << "yes" << endl; else cout << "no" << endl; } void fyn(bool a) { assert_yn(yn_v, 1); yn(a); exit(0); } void Yn(bool a) { assert_yn(yn_v, 2); if (a) cout << "Yes" << endl; else cout << "No" << endl; } void fYn(bool a) { assert_yn(yn_v, 2); Yn(a); exit(0); } void YN(bool a) { assert_yn(yn_v, 3); if (a) cout << "YES" << endl; else cout << "NO" << endl; } void fYN(bool a) { assert_yn(yn_v, 3); YN(a); exit(0); } int ab_v = 0; void fAb(bool a) { assert_yn(ab_v, 1); if (a) cout << "Alice" << endl; else cout << "Bob"; } void fAB(bool a) { assert_yn(yn_v, 2); if (a) cout << "ALICE" << endl; else cout << "BOB"; } int pos_v = 0; void Possible(bool a) { assert_yn(pos_v, 1); if (a) cout << "Possible" << endl; else cout << "Impossible" << endl; exit(0); } void POSSIBLE(bool a) { assert_yn(pos_v, 2); if (a) cout << "POSSIBLE" << endl; else cout << "IMPOSSIBLE" << endl; exit(0); } void fPossible(bool a) { assert_yn(pos_v, 1) Possible(a); exit(0); } void fPOSSIBLE(bool a) { assert_yn(pos_v, 2) POSSIBLE(a); exit(0); } template <typename T> class fixed_point : T { public: explicit constexpr fixed_point(T &&t) noexcept : T(std::forward<T>(t)) {} template <typename... Args> constexpr decltype(auto) operator()(Args &&...args) const { return T::operator()(*this, std::forward<Args>(args)...); } }; template <typename T> static inline constexpr decltype(auto) fix(T &&t) noexcept { return fixed_point<T>{std::forward<T>(t)}; } // 未分類 // 0,2,1 1番目と2番目の次元を入れ替える template <class T> auto irekae(vector<vector<vector<T>>> &A, int x, int y, int z) { #define irekae_resize_loop(a, b, c) \ resize(res, a, b, c); \ rep(i, a) rep(j, b) rep(k, c) vector<vector<vector<T>>> res; if (x == 0 && y == 1 && z == 2) { res = A; } else if (x == 0 && y == 2 && z == 1) { irekae_resize_loop(sz(A), sz(A[0][0]), sz(A[0])) { res[i][j][k] = A[i][k][j]; } } else if (x == 1 && y == 0 && z == 2) { irekae_resize_loop(sz(A[0]), sz(A), sz(A[0][0])) { res[i][j][k] = A[j][i][k]; } } else if (x == 1 && y == 2 && z == 0) { irekae_resize_loop(sz(A[0]), sz(A[0][0]), sz(A)) { res[i][j][k] = A[k][i][j]; } } else if (x == 2 && y == 0 && z == 1) { irekae_resize_loop(sz(A[0][0]), sz(A), sz(A[0])) { res[i][j][k] = A[j][k][i]; } } else if (x == 2 && y == 1 && z == 0) { irekae_resize_loop(sz(A[0][0]), sz(A[0]), sz(A)) { res[i][j][k] = A[k][j][i]; } } return res; #undef irekae_resize_loop } template <class T> auto irekae(vector<vector<T>> &A, int i = 1, int j = 0) { vvt(res, sz(A[0]), sz(A)); rep(i, sz(A)) { rep(j, sz(A[0])) { res[j][i] = A[i][j]; } } return res; } // tou分割する template <typename Iterable> vector<Iterable> table(const Iterable &a, int tou = 2) { int N = sz(a); vector<Iterable> res(tou); int hab = N / tou; vi lens(tou, hab); rep(i, N % tou) { lens[tou - 1 - i]++; } int l = 0; rep(i, tou) { int len = lens[i]; int r = l + len; res[i].resize(len); std::copy(a.begin() + l, a.begin() + r, res[i].begin()); l = r; } return res; } // 長さn毎に分割する template <typename Iterable> vector<Iterable> table_n(const Iterable &a, int len) { int N = sz(a); vector<Iterable> res(ceil(N, len)); vi lens(N / len, len); if (N % len) lens.push_back(N % len); int l = 0; rep(i, sz(lens)) { int len = lens[i]; int r = l + len; res[i].resize(len); std::copy(a.begin() + l, a.begin() + r, res[i].begin()); l = r; } return res; } // 縦を返す vi &geth(vvi() & a, int w) { static vi ret; ret.resize(sz(a)); rep(i, sz(a)) { ret[i] = a[i][w]; } return ret; } //@起動時 struct initon { initon() { cin.tie(0); ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(16); srand((unsigned)clock() + (unsigned)time(NULL)); }; } initonv; // #define pre prev // #define nex next // gra mll pr // 上下左右 const string udlr = "udlr"; string UDLR = "UDLR"; // x4と連動 UDLR.find('U') := x4[0] vc atoz = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; vc AtoZ = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; // 右、上が正 constexpr ll h4[] = {1, -1, 0, 0}; constexpr ll w4[] = {0, 0, -1, 1}; constexpr ll h8[] = {0, 1, 0, -1, -1, 1, 1, -1}; constexpr ll w8[] = {1, 0, -1, 0, 1, -1, 1, -1}; int mei_inc(int h, int w, int H, int W, int i) { while (++i < 4) { if (inside(h + h4[i], w + w4[i], H, W)) return i; } return i; } #define mei(nh, nw, h, w) \ for (int i = mei_inc(h, w, H, W, -1), nh = i < 4 ? h + h4[i] : 0, \ nw = i < 4 ? w + w4[i] : 0; \ i < 4; i = mei_inc(h, w, H, W, i), nh = h + h4[i], nw = w + w4[i]) int mei_inc8(int h, int w, int H, int W, int i) { while (++i < 8) { if (inside(h + h8[i], w + w8[i], H, W)) return i; } return i; } #define mei8(nh, nw, h, w) \ for (int i = mei_inc8(h, w, H, W, -1), nh = i < 8 ? h + h8[i] : 0, \ nw = i < 8 ? w + w8[i] : 0; \ i < 8; i = mei_inc8(h, w, H, W, i), nh = h + h8[i], nw = w + w8[i]) int mei_incv(int h, int w, int H, int W, int i, vp &p) { while (++i < sz(p)) { if (inside(h + p[i].fi, w + p[i].se, H, W)) return i; } return i; } #define meiv(nh, nw, h, w, p) \ for (int i = mei_incv(h, w, H, W, -1, p), nh = i < sz(p) ? h + p[i].fi : 0, \ nw = i < sz(p) ? w + p[i].se : 0; \ i < sz(p); \ i = mei_incv(h, w, H, W, i, p), nh = h + p[i].fi, nw = w + p[i].se) // H*Wのグリッドを斜めに分割する // 右上 vector<vp> naname_list_ne(int H, int W) { vector<vp> res(H + W - 1); rep(sh, H) { int sw = 0; res[sh] += mp(sh, sw); int nh = sh; int nw = sw; while (1) { nh--; nw++; if (0 <= nh && nw < W) { res[sh] += mp(nh, nw); } else { break; } } } rep(sw, 1, W) { int sh = H - 1; res[H + sw - 1] += mp(sh, sw); int nh = sh; int nw = sw; while (1) { nh--; nw++; if (0 <= nh && nw < W) { res[H + sw - 1] += mp(nh, nw); } else { break; } } } return res; } // 右下 vector<vp> naname_list_se(int H, int W) { vector<vp> res(H + W - 1); rep(sh, H) { int sw = 0; res[sh] += mp(sh, sw); int nh = sh; int nw = sw; while (1) { nh++; nw++; if (0 <= nh && nh < H && nw < W) { res[sh] += mp(nh, nw); } else { break; } } } rep(sw, 1, W) { int sh = 0; res[H + sw - 1] += mp(sh, sw); int nh = sh; int nw = sw; while (1) { nh++; nw++; if (0 <= nh && nh < H && nw < W) { res[H + sw - 1] += mp(nh, nw); } else { break; } } } return res; } // グラフ内で #undef getid // #define getidとしているため、ここを書き直したらgraphも書き直す #define getid_2(h, w) ((h) * (W) + (w)) #define getid_1(p) ((p).first * W + (p).second) #define getid(...) over2(__VA_ARGS__, getid_2, getid_1)(__VA_ARGS__) #define getp(id) mp((id) / W, (id) % W) #define set_shuffle() \ std::random_device seed_gen; \ std::mt19937 engine(seed_gen()) #define shuffle(a) std::shuffle((a).begin(), (a).end(), engine); // 1980 開始からtime ms経っていたらtrue vb bit_bool(int v, int len) { assert(bit(len) > v); vb ret(len); rep(i, len) { ret[i] = bget(v, i); } return ret; } vi tov(vb &a) { vi ret; rep(i, sz(a)) { if (a[i]) ret.push_back(i); } return ret; } bool kaibun(const str &S) { return S == rev(S); } template <class T> vector<T> repeat(const vector<T> &A, int kaisu) { vector<T> ret; while (kaisu--) { ret += A; } return ret; } #define rge range #define upd update // S[{s, t, d}] #define strs slice_str struct slice_str { string S; slice_str() {} slice_str(const string &S) : S(S) {} slice_str(int len, char c) : S(len, c) {} auto size() { return S.size(); } char &operator[](int p) { return S[p]; } string operator[](initializer_list<int> p) { if (sz(p) == 1) { return S.substr(0, *(p.begin())); } else if (sz(p) == 2) { int l = *(p.begin()); int r = *(next(p.begin())); return S.substr(l, r - l); } else { auto it = p.begin(); int s = *(it++); int t = *(it++); int d = *(it); if (d == -1) { int s_ = sz(S) - s - 1; int t_ = sz(S) - t - 1; return rev(S).substr(s_, t_ - s_); } else if (d < 0) { t = max(-1ll, t); string ret; while (s > t) { ret += S[s]; s += d; } return ret; } else { t = min(sz(S), t); string ret; while (s < t) { ret += S[s]; s += d; } return ret; } } } operator string &() { return S; } template <class T> void operator+=(const T &a) { S += a; } bool operator==(const slice_str &rhs) { return S == rhs.S; } auto pop_back() { return S.pop_back(); } }; ostream &operator<<(ostream &os, const slice_str &a) { os << a.S; return os; } istream &operator>>(istream &iss, slice_str &a) { iss >> a.S; return iss; } template <class T> bool can(const T &v, int i) { return 0 <= i && i < sz(v); } #if __cplusplus >= 201703L // template<class T> auto sum(int a, T v...) {return (v + ... + 0);} #endif #define VEC vector // string.substr()は長さを指定するため、間違えやすい #define substr my_substr #endif /*UNTITLED15_TEMPLATE_H*/ #endif // † ←template終了 /*@formatter:on*/ // vectorで取れる要素数 // bool=> 1e9 * 8.32 // int => 1e8 * 2.6 // ll => 1e8 * 1.3 // 3次元以上取るとメモリがヤバい // static配列を使う vvc(ba); ll N, M, H, W; vi A, B, C; // 14:43 void solve() { in(N); dnao2(Vs, Ws, N); din(Q); int mid_lim = min(bit(11), N + 1); auto get_path = [&](int v) { vi D; D += v; while (v > 1) { v /= 2; D += v; } return D; }; // 1-indexed static signed dp_u[bit(11) + 1][k5]; rep(cur, 1, mid_lim) { auto D = get_path(cur); int dn = sz(D); rep(mas, bit(dn)) { int v = 0, w = 0; forbit1(di, mas) { v += Vs[D[di]]; w += Ws[D[di]]; } if (w < k5) chma(dp_u[cur][w], v); } rep(w, k5 - 1) { chma(dp_u[cur][w + 1], dp_u[cur][w]); } } // deb(dp_u); rep(q, Q) { din(v, L); if (v < mid_lim) { out(dp_u[v][L]); continue; } int u_last = 0; vi D; { vi D2 = get_path(v); fora(d, D2) { if (d >= mid_lim) D += d; else { chma(u_last, d); } } } deb(q, D, u_last); int N = sz(D); int max_v = 0; rep(mas, bit(N)) { int v = 0, w = 0; forbit1(di, mas) { v += Vs[D[di]]; w += Ws[D[di]]; } if (w <= L) { chma(max_v, v + dp_u[u_last][L - w]); } } out(max_v); } } auto my(ll n, vi &a) { return 0; } auto sister(ll n, vi &a) { ll ret = 0; return ret; } signed main() { solve(); #define arg n, a #ifdef _DEBUG bool bad = 0; for (ll i = 0, ok = 1; i < k5 && ok; ++i) { ll n = rand(1, 8); vi a = ranv(n, 1, 10); auto myres = my(arg); auto res = sister(arg); ok = myres == res; if (!ok) { out(arg); cerr << "AC : " << res << endl; cerr << "MY : " << myres << endl; bad = 1; break; } } if (!bad) { // solveを書き直す // solveを呼び出す } exit(0); #endif return 0; };
replace
7,125
7,126
7,125
7,126
MLE
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef int I; #define REP(i, n) for (I i = 0; i < (I)(n); i++) I n; I vw[26214][2], dp[1024][100001]; I c1, c2; void dfs(I i) { I j = i / 2; if (i > 1) { for (I k = c2; k + 1; k--) { if (dp[j - 1][k] or !k) { I ne = k + vw[i - 1][1]; if (ne <= c2) dp[i - 1][ne] = max(dp[j - 1][k] + vw[i - 1][0], dp[i - 1][ne]); } dp[i - 1][k] = dp[j - 1][k]; } } if (i * 2 <= min(c1, n)) dfs(i * 2); if (i * 2 + 1 <= min(c1, n)) dfs(i * 2 + 1); } signed main() { cin >> n; // vw.resize(n); REP(i, n) { I x, y; cin >> vw[i][0] >> vw[i][1]; } c1 = 1024; c2 = 100000; // dp.resize(c1);REP(i,c1)dp[i].resize(c2+1); dp[0][vw[0][1]] = vw[0][0]; dfs(1); REP(i, c1) REP(j, c2) dp[i][j + 1] = max(dp[i][j], dp[i][j + 1]); I q; cin >> q; REP(i, q) { I v, l; cin >> v >> l; vector<I> cand; while (v > c1) { cand.push_back(v); v = v / 2; } I r = cand.size(); I ans = 0; REP(j, 1 << r) { I v_sub = 0; I w_sub = 0; REP(k, r) { if (j >> k & 1) { v_sub += vw[cand[k] - 1][0]; w_sub += vw[cand[k] - 1][1]; } } if (w_sub <= l) ans = max(ans, dp[v - 1][l - w_sub] + v_sub); } cout << ans << endl; } }
#include <bits/stdc++.h> using namespace std; typedef int I; #define REP(i, n) for (I i = 0; i < (I)(n); i++) I n; I vw[323456][2], dp[1024][100001]; I c1, c2; void dfs(I i) { I j = i / 2; if (i > 1) { for (I k = c2; k + 1; k--) { if (dp[j - 1][k] or !k) { I ne = k + vw[i - 1][1]; if (ne <= c2) dp[i - 1][ne] = max(dp[j - 1][k] + vw[i - 1][0], dp[i - 1][ne]); } dp[i - 1][k] = dp[j - 1][k]; } } if (i * 2 <= min(c1, n)) dfs(i * 2); if (i * 2 + 1 <= min(c1, n)) dfs(i * 2 + 1); } signed main() { cin >> n; // vw.resize(n); REP(i, n) { I x, y; cin >> vw[i][0] >> vw[i][1]; } c1 = 1024; c2 = 100000; // dp.resize(c1);REP(i,c1)dp[i].resize(c2+1); dp[0][vw[0][1]] = vw[0][0]; dfs(1); REP(i, c1) REP(j, c2) dp[i][j + 1] = max(dp[i][j], dp[i][j + 1]); I q; cin >> q; REP(i, q) { I v, l; cin >> v >> l; vector<I> cand; while (v > c1) { cand.push_back(v); v = v / 2; } I r = cand.size(); I ans = 0; REP(j, 1 << r) { I v_sub = 0; I w_sub = 0; REP(k, r) { if (j >> k & 1) { v_sub += vw[cand[k] - 1][0]; w_sub += vw[cand[k] - 1][1]; } } if (w_sub <= l) ans = max(ans, dp[v - 1][l - w_sub] + v_sub); } cout << ans << endl; } }
replace
6
7
6
7
-11
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; int p[1024][1 << 17], v[1 << 19], w[1 << 19], q, a, l, i; int f(int a, int l) { if (l < 0) return -1e9; if (!a) return 0; if (a > 1023) return max(f(a / 2, l), f(a / 2, l - w[a]) + v[a]); if (~p[a][l]) return p[a][l]; return p[a][l] = max({f(a / 2, l), f(a, l - 1), f(a / 2, l - w[a]) + v[a]}); }; int main() { memset(p, -1, 1 << 31); cin >> l; for (; i++ < l;) cin >> v[i] >> w[i]; cin >> q; while (q--) { cin >> a >> l; cout << f(a, l) << " "; } }
#include <bits/stdc++.h> using namespace std; int p[1024][1 << 17], v[1 << 19], w[1 << 19], q, a, l, i; int f(int a, int l) { if (l < 0) return -1e9; if (!a) return 0; if (a > 1023) return max(f(a / 2, l), f(a / 2, l - w[a]) + v[a]); if (~p[a][l]) return p[a][l]; return p[a][l] = max({f(a / 2, l), f(a, l - 1), f(a / 2, l - w[a]) + v[a]}); }; int main() { memset(p, -1, 1 << 29); cin >> l; for (; i++ < l;) cin >> v[i] >> w[i]; cin >> q; while (q--) { cin >> a >> l; cout << f(a, l) << " "; } }
replace
15
16
15
16
-11
p02648
C++
Time Limit Exceeded
// raja1999 // #pragma comment(linker, "/stack:200000000") // #pragma GCC optimize("Ofast") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,avx,avx2") #include <algorithm> #include <bits/stdc++.h> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <iomanip> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <utility> #include <vector> // setbase - cout << setbase (16)a; cout << 100 << endl; Prints 64 // setfill - cout << setfill ('x') << setw (5); cout << 77 <<endl;prints xxx77 // setprecision - cout << setprecision (14) << f << endl; Prints x.xxxx // cout.precision(x) cout<<fixed<<val; // prints x digits after decimal in val using namespace std; using namespace __gnu_pbds; #define f(i, a, b) for (i = a; i < b; i++) #define rep(i, n) f(i, 0, n) #define fd(i, a, b) for (i = a; i >= b; i--) #define pb push_back #define mp make_pair #define vi vector<int> #define vl vector<ll> #define ss second #define ff first #define ll long long #define pii pair<int, int> #define pll pair<ll, ll> #define sz(a) a.size() #define inf (1000 * 1000 * 1000 + 5) #define all(a) a.begin(), a.end() #define tri pair<int, pii> #define vii vector<pii> #define vll vector<pll> #define viii vector<tri> #define mod (1000 * 1000 * 1000 + 7) #define pqueue priority_queue<int> #define pdqueue priority_queue<int, vi, greater<int>> // #define int ll typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // std::ios::sync_with_stdio(false); ll v[(1 << 18) + 5], w[(1 << 18) + 5]; ll brute(int n, int l) { ll val = 0, lol, haha, j, k, res = 0; vii vec; while (n >= 1) { vec.pb(mp(v[n], w[n])); n /= 2; val++; } rep(j, (1 << val)) { lol = 0; haha = 0; rep(k, vec.size()) { if (j & (1 << k)) { lol += vec[k].ff; haha += vec[k].ss; } } if (haha <= l) { res = max(res, lol); } } // cout<<res<<" "<<val<<endl; return res; } int u[100005], l[100005]; vector<pair<ll, ll>>::iterator it; vector<vll> GG((1 << 10) + 5); vector<vl> MM((1 << 10) + 5); int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); ll n, q, i, val, c, lol, haha, res, j, k, maxi, req, pos, rem, iinf, node; iinf = inf; iinf *= inf; vii vec; cin >> n; rep(i, n) { cin >> v[i + 1] >> w[i + 1]; } cin >> q; rep(i, q) { cin >> u[i] >> l[i]; } if (n < 128) { rep(i, q) { cout << brute(u[i], l[i]) << endl; } } else { int lev = 0; int n1 = n; while (n1 >= 1) { n1 /= 2; lev++; } val = (lev + 1) / 2; f(i, 1, n + 1) { n1 = i; c = 0; vec.clear(); while (n1 >= 1) { c++; vec.pb(mp(v[n1], w[n1])); n1 /= 2; } if (c == val) { rep(j, (1 << val)) { lol = 0; haha = 0; rep(k, vec.size()) { if (j & (1 << k)) { lol += vec[k].ff; haha += vec[k].ss; } } if (haha <= 100000) { GG[i].pb(mp(haha, lol)); } } sort(all(GG[i])); maxi = 0; MM[i].resize(GG[i].size() + 2); f(j, 0, GG[i].size()) { maxi = max(maxi, GG[i][j].ss); MM[i][j] = maxi; } } } rep(i, q) { n1 = u[i]; c = 0; while (n1 >= 1) { c++; n1 /= 2; } if (c < val) { cout << brute(u[i], l[i]) << endl; } else { n1 = u[i]; req = c - val; vec.clear(); while (req--) { vec.pb(mp(v[n1], w[n1])); n1 /= 2; } node = n1; req = c - val; res = 0; rep(j, (1 << req)) { lol = 0; haha = 0; rep(k, vec.size()) { if (j & (1 << k)) { lol += vec[k].ff; haha += vec[k].ss; } } if (haha <= l[i]) { rem = l[i] - haha; it = upper_bound(GG[node].begin(), GG[node].end(), mp(rem, iinf)); it--; pos = (it - GG[node].begin()); res = max(res, lol + MM[node][pos]); } } cout << res << endl; } } } return 0; }
// raja1999 // #pragma comment(linker, "/stack:200000000") // #pragma GCC optimize("Ofast") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,avx,avx2") #include <algorithm> #include <bits/stdc++.h> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <iomanip> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <utility> #include <vector> // setbase - cout << setbase (16)a; cout << 100 << endl; Prints 64 // setfill - cout << setfill ('x') << setw (5); cout << 77 <<endl;prints xxx77 // setprecision - cout << setprecision (14) << f << endl; Prints x.xxxx // cout.precision(x) cout<<fixed<<val; // prints x digits after decimal in val using namespace std; using namespace __gnu_pbds; #define f(i, a, b) for (i = a; i < b; i++) #define rep(i, n) f(i, 0, n) #define fd(i, a, b) for (i = a; i >= b; i--) #define pb push_back #define mp make_pair #define vi vector<int> #define vl vector<ll> #define ss second #define ff first #define ll long long #define pii pair<int, int> #define pll pair<ll, ll> #define sz(a) a.size() #define inf (1000 * 1000 * 1000 + 5) #define all(a) a.begin(), a.end() #define tri pair<int, pii> #define vii vector<pii> #define vll vector<pll> #define viii vector<tri> #define mod (1000 * 1000 * 1000 + 7) #define pqueue priority_queue<int> #define pdqueue priority_queue<int, vi, greater<int>> // #define int ll typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // std::ios::sync_with_stdio(false); ll v[(1 << 18) + 5], w[(1 << 18) + 5]; ll brute(int n, int l) { ll val = 0, lol, haha, j, k, res = 0; vii vec; while (n >= 1) { vec.pb(mp(v[n], w[n])); n /= 2; val++; } rep(j, (1 << val)) { lol = 0; haha = 0; rep(k, vec.size()) { if (j & (1 << k)) { lol += vec[k].ff; haha += vec[k].ss; } } if (haha <= l) { res = max(res, lol); } } // cout<<res<<" "<<val<<endl; return res; } int u[100005], l[100005]; vector<pair<ll, ll>>::iterator it; vector<vll> GG((1 << 10) + 5); vector<vl> MM((1 << 10) + 5); int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); ll n, q, i, val, c, lol, haha, res, j, k, maxi, req, pos, rem, iinf, node; iinf = inf; iinf *= inf; vii vec; cin >> n; rep(i, n) { cin >> v[i + 1] >> w[i + 1]; } cin >> q; rep(i, q) { cin >> u[i] >> l[i]; } if (n < 128) { rep(i, q) { cout << brute(u[i], l[i]) << endl; } } else { int lev = 0; int n1 = n; while (n1 >= 1) { n1 /= 2; lev++; } val = (lev + 1) / 2; val++; f(i, 1, n + 1) { n1 = i; c = 0; vec.clear(); while (n1 >= 1) { c++; vec.pb(mp(v[n1], w[n1])); n1 /= 2; } if (c == val) { rep(j, (1 << val)) { lol = 0; haha = 0; rep(k, vec.size()) { if (j & (1 << k)) { lol += vec[k].ff; haha += vec[k].ss; } } if (haha <= 100000) { GG[i].pb(mp(haha, lol)); } } sort(all(GG[i])); maxi = 0; MM[i].resize(GG[i].size() + 2); f(j, 0, GG[i].size()) { maxi = max(maxi, GG[i][j].ss); MM[i][j] = maxi; } } } rep(i, q) { n1 = u[i]; c = 0; while (n1 >= 1) { c++; n1 /= 2; } if (c < val) { cout << brute(u[i], l[i]) << endl; } else { n1 = u[i]; req = c - val; vec.clear(); while (req--) { vec.pb(mp(v[n1], w[n1])); n1 /= 2; } node = n1; req = c - val; res = 0; rep(j, (1 << req)) { lol = 0; haha = 0; rep(k, vec.size()) { if (j & (1 << k)) { lol += vec[k].ff; haha += vec[k].ss; } } if (haha <= l[i]) { rem = l[i] - haha; it = upper_bound(GG[node].begin(), GG[node].end(), mp(rem, iinf)); it--; pos = (it - GG[node].begin()); res = max(res, lol + MM[node][pos]); } } cout << res << endl; } } } return 0; }
insert
108
108
108
109
TLE
p02648
Python
Time Limit Exceeded
import sys n, *inp = map(int, sys.stdin.buffer.read().split()) vvv = [0] + inp[0 : n * 2 : 2] www = [0] + inp[1 : n * 2 : 2] weight_limit = 10**5 precalc_limit = min(1 << 9, n + 1) precalc = [[0] * (weight_limit + 1)] for u in range(1, precalc_limit): v = vvv[u] w = www[u] dp = precalc[u >> 1][:] for x in range(weight_limit, w - 1, -1): nv = dp[x - w] + v if dp[x] < nv: dp[x] = nv precalc.append(dp) buf = [] mp = iter(inp[n * 2 + 1 :]) for u, l in zip(mp, mp): if u < precalc_limit: buf.append(precalc[u][l]) continue dp_w = [0] dp_v = [0] while u >= precalc_limit: v = vvv[u] w = www[u] for i in range(len(dp_w)): nw = dp_w[i] + w if nw > l: continue nv = dp_v[i] + v dp_w.append(nw) dp_v.append(nv) u >>= 1 ans = 0 for w, v in zip(dp_w, dp_v): nv = v + precalc[u][l - w] if ans < nv: ans = nv buf.append(ans) print("\n".join(map(str, buf)))
import sys n, *inp = map(int, sys.stdin.buffer.read().split()) vvv = [0] + inp[0 : n * 2 : 2] www = [0] + inp[1 : n * 2 : 2] weight_limit = 10**5 precalc_limit = min(1 << 10, n + 1) precalc = [[0] * (weight_limit + 1)] for u in range(1, precalc_limit): v = vvv[u] w = www[u] dp = precalc[u >> 1][:] for x in range(weight_limit, w - 1, -1): nv = dp[x - w] + v if dp[x] < nv: dp[x] = nv precalc.append(dp) buf = [] mp = iter(inp[n * 2 + 1 :]) for u, l in zip(mp, mp): if u < precalc_limit: buf.append(precalc[u][l]) continue dp_w = [0] dp_v = [0] while u >= precalc_limit: v = vvv[u] w = www[u] for i in range(len(dp_w)): nw = dp_w[i] + w if nw > l: continue nv = dp_v[i] + v dp_w.append(nw) dp_v.append(nv) u >>= 1 ans = 0 for w, v in zip(dp_w, dp_v): nv = v + precalc[u][l - w] if ans < nv: ans = nv buf.append(ans) print("\n".join(map(str, buf)))
replace
7
8
7
8
TLE
p02648
C++
Time Limit Exceeded
#pragma GCC optimize("O3") #pragma GCC target("sse4") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef complex<ld> cd; typedef pair<int, int> pi; typedef pair<ll, ll> pl; typedef pair<ld, ld> pd; typedef vector<int> vi; typedef vector<ld> vd; typedef vector<ll> vl; typedef vector<pi> vpi; typedef vector<pl> vpl; typedef vector<cd> vcd; #define FOR(i, a, b) for (int i = a; i < (b); i++) #define F0R(i, a) for (int i = 0; i < (a); i++) #define FORd(i, a, b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i, a) for (int i = (a)-1; i >= 0; i--) #define sz(x) (int)(x).size() #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound #define all(x) x.begin(), x.end() #define ins insert mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int MOD = 1000000007; const char nl = '\n'; const int MX = 100001; // check the limits, dummy const int K = 10; set<pi> ops[1 << (K + 1)]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int N; cin >> N; int V[N + 1], W[N + 1]; F0R(i, N) cin >> V[i + 1] >> W[i + 1]; FOR(r, 1, min(N + 1, (1 << (K + 1)))) { vpi vals; int cur = r; while (cur > 0) { pi X = {W[cur], V[cur]}; vals.pb(X); cur /= 2; } F0R(m, (1 << sz(vals))) { int v = 0, w = 0; F0R(i, sz(vals)) { if (m & (1 << i)) { w += vals[i].f; v += vals[i].s; } } // cout << r << " " << m << " " << v << " " << w << nl; auto it = ops[r].ub({w, -1}); if (it != ops[r].begin()) { it--; if (it->s >= v) { continue; } } it = ops[r].ub({w, -1}); while (it != ops[r].end() && it->s <= v) { ops[r].erase(it); it = ops[r].ub({w, -1}); } ops[r].ins({w, v}); } } int Q; cin >> Q; F0R(q, Q) { int ve, L; cin >> ve >> L; vpi vals; int cur = ve; while (cur >= (1 << (K + 1))) { pi X = {W[cur], V[cur]}; vals.pb(X); cur /= 2; } int ans = 0; F0R(m, 1 << sz(vals)) { int v = 0, w = 0; F0R(i, sz(vals)) { if (m & (1 << i)) { w += vals[i].f; v += vals[i].s; } } auto it = ops[cur].ub({L - w + 1, -1}); if (it == ops[cur].begin()) continue; it--; ans = max(ans, v + it->s); } cout << ans << nl; } return 0; } // read the question correctly (ll vs int) // template by bqi343
#pragma GCC optimize("O3") #pragma GCC target("sse4") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef complex<ld> cd; typedef pair<int, int> pi; typedef pair<ll, ll> pl; typedef pair<ld, ld> pd; typedef vector<int> vi; typedef vector<ld> vd; typedef vector<ll> vl; typedef vector<pi> vpi; typedef vector<pl> vpl; typedef vector<cd> vcd; #define FOR(i, a, b) for (int i = a; i < (b); i++) #define F0R(i, a) for (int i = 0; i < (a); i++) #define FORd(i, a, b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i, a) for (int i = (a)-1; i >= 0; i--) #define sz(x) (int)(x).size() #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound #define all(x) x.begin(), x.end() #define ins insert mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int MOD = 1000000007; const char nl = '\n'; const int MX = 100001; // check the limits, dummy const int K = 9; set<pi> ops[1 << (K + 1)]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int N; cin >> N; int V[N + 1], W[N + 1]; F0R(i, N) cin >> V[i + 1] >> W[i + 1]; FOR(r, 1, min(N + 1, (1 << (K + 1)))) { vpi vals; int cur = r; while (cur > 0) { pi X = {W[cur], V[cur]}; vals.pb(X); cur /= 2; } F0R(m, (1 << sz(vals))) { int v = 0, w = 0; F0R(i, sz(vals)) { if (m & (1 << i)) { w += vals[i].f; v += vals[i].s; } } // cout << r << " " << m << " " << v << " " << w << nl; auto it = ops[r].ub({w, -1}); if (it != ops[r].begin()) { it--; if (it->s >= v) { continue; } } it = ops[r].ub({w, -1}); while (it != ops[r].end() && it->s <= v) { ops[r].erase(it); it = ops[r].ub({w, -1}); } ops[r].ins({w, v}); } } int Q; cin >> Q; F0R(q, Q) { int ve, L; cin >> ve >> L; vpi vals; int cur = ve; while (cur >= (1 << (K + 1))) { pi X = {W[cur], V[cur]}; vals.pb(X); cur /= 2; } int ans = 0; F0R(m, 1 << sz(vals)) { int v = 0, w = 0; F0R(i, sz(vals)) { if (m & (1 << i)) { w += vals[i].f; v += vals[i].s; } } auto it = ops[cur].ub({L - w + 1, -1}); if (it == ops[cur].begin()) continue; it--; ans = max(ans, v + it->s); } cout << ans << nl; } return 0; } // read the question correctly (ll vs int) // template by bqi343
replace
42
43
42
43
TLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using ll = long long; using uint = unsigned int; using ull = unsigned long long; using ld = long double; template <typename T, int n> using arr = T (&)[n]; template <typename T, int n> using c_arr = const T (&)[n]; template <typename T> using max_heap = std::priority_queue<T>; template <typename T> using min_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>; constexpr int popcount(const ull v) { return v ? __builtin_popcountll(v) : 0; } constexpr int log2p1(const ull v) { return v ? 64 - __builtin_clzll(v) : 0; } constexpr int lsbp1(const ull v) { return __builtin_ffsll(v); } constexpr int clog(const ull v) { return v ? log2p1(v - 1) : 0; } constexpr ull ceil2(const ull v) { return 1ULL << clog(v); } constexpr ull floor2(const ull v) { return v ? (1ULL << (log2p1(v) - 1)) : 0ULL; } constexpr bool btest(const ull mask, const int ind) { return (mask >> ind) & 1ULL; } template <typename T> void bset(T &mask, const int ind) { mask |= ((T)1 << ind); } template <typename T> void breset(T &mask, const int ind) { mask &= ~((T)1 << ind); } template <typename T> void bflip(T &mask, const int ind) { mask ^= ((T)1 << ind); } template <typename T> void bset(T &mask, const int ind, const bool b) { (b ? bset(mask, ind) : breset(mask, ind)); } template <typename T> bool chmin(T &a, const T &b) { return (a > b ? a = b, true : false); } template <typename T> bool chmax(T &a, const T &b) { return (a < b ? a = b, true : false); } template <typename T> constexpr T inf_v = std::numeric_limits<T>::max() / 4; template <typename Real> constexpr Real pi_v = Real{3.141592653589793238462643383279502884}; constexpr ull TEN(const int n) { return n == 0 ? 1ULL : TEN(n - 1) * 10ULL; } template <typename F> struct fix : F { fix(F &&f) : F{std::forward<F>(f)} {} template <typename... Args> auto operator()(Args &&...args) const { return F::operator()(*this, std::forward<Args>(args)...); } }; class printer { public: printer(std::ostream &os_ = std::cout) : os{os_} {} template <typename T> int operator()(const T &v) { return os << v, 0; } template <typename T> int operator()(const std::vector<T> &vs) { for (int i = 0; i < (int)vs.size(); i++) { os << (i ? " " : ""), this->operator()(vs[i]); } return 0; } template <typename T> int operator()(const std::vector<std::vector<T>> &vss) { for (int i = 0; i < (int)vss.size(); i++) { os << (0 <= i or i + 1 < (int)vss.size() ? "\n" : ""), this->operator()(vss[i]); } return 0; } template <typename T, typename... Args> int operator()(const T &v, const Args &...args) { return this->operator()(v), os << ' ', this->operator()(args...), 0; } template <typename... Args> int ln(const Args &...args) { return this->operator()(args...), os << '\n', 0; } template <typename... Args> int el(const Args &...args) { return this->operator()(args...), os << std::endl, 0; } template <typename... Args> int fmt(const std::string &s, const Args &...args) { return rec(s, 0, args...); } private: int rec(const std::string &s, int index) { return os << s.substr(index, s.size()), 0; } template <typename T, typename... Args> int rec(const std::string &s, int index, const T &v, const Args &...args) { return index == s.size() ? 0 : s[index] == '%' ? (this->operator()(v), rec(s, index + 1, args...)) : (os << s[index], rec(s, index + 1, v, args...)); } std::ostream &os; }; printer out; template <typename T, typename F> std::vector<T> generated(const int n, F f) { std::vector<T> ans(n); return std::generate(ans.begin(), ans.end(), f), ans; } std::vector<int> ioted(const int n, const int offset = 0) { std::vector<int> ans(n); return std::iota(ans.begin(), ans.end(), offset), ans; } template <typename Vs> Vs reversed(const Vs &vs) { auto ans = vs; return std::reverse(ans.begin(), ans.end()), ans; } template <typename T, typename F = std::less<T>> std::vector<T> sorted(const std::vector<T> &vs, F comp = F{}) { auto ans = vs; return std::sort(ans.begin(), ans.end(), comp), ans; } template <typename F> std::vector<int> sorted_iota(const int n, F comp = F{}, const int offset = 0) { return sorted(ioted(n, offset), comp); } class scanner { public: scanner(std::istream &is_ = std::cin) : is{is_} { is.tie(nullptr), std::ios::sync_with_stdio(false); } template <typename T> T val() { static T v; return is >> v, v; } template <typename T> T val(const T offset) { return val<T>() - offset; } template <typename T> std::vector<T> vec(const int n) { return generated<T>(n, [&] { return val<T>(); }); } template <typename T> std::vector<T> vec(const int n, const T offset) { return generated<T>(n, [&] { return val<T>(offset); }); } template <typename T> std::vector<std::vector<T>> vvec(const int n0, const int n1) { return generated<std::vector<T>>(n0, [&] { return vec<T>(n1); }); } template <typename T> std::vector<std::vector<T>> vvec(const int n0, const int n1, const T offset) { return generated<std::vector<T>>(n0, [&] { return vec<T>(n1, offset); }); } template <typename... Args> auto tup() { return std::tuple<std::decay_t<Args>...>{val<Args>()...}; } template <typename... Args> auto tup(const Args &...offsets) { return std::tuple<std::decay_t<Args>...>{val<Args>(offsets)...}; } private: std::istream &is; }; scanner in; #define SHOW(...) static_cast<void>(0) template <typename T, typename Int, int n, int i> auto make_v(typename std::enable_if<(i == n), c_arr<Int, n>>::type, const T &v = T{}) { return v; } template <typename T, typename Int, int n, int i> auto make_v(typename std::enable_if<(i < n), c_arr<Int, n>>::type szs, const T &v = T{}) { return std::vector<decltype(make_v<T, Int, n, i + 1>(szs, v))>( szs[i], make_v<T, Int, n, i + 1>(szs, v)); } template <typename T, typename Int, int n> auto make_v(c_arr<Int, n> szs, const T &t = T{}) { return make_v<T, Int, n, 0>(szs, t); } int main() { constexpr int L = 100000; const auto N = in.val<int>(); const int H = 8; std::vector<int> vs(std::max(N + 1, 1 << H), 0), ws(std::max(N + 1, 1 << H), 0); for (int i = 1; i <= N; i++) { vs[i] = in.val<int>(), ws[i] = in.val<int>(); } using pii = std::pair<int, int>; std::vector<std::vector<pii>> ucandss(1 << H); std::vector<std::vector<int>> dps(1 << H, std::vector<int>(L + 1, 0)); ucandss[0] = {{0, 0}}; for (int i = 1; i < (1 << H); i++) { const int pi = i / 2; std::vector<pii> add; for (const auto &[w, v] : ucandss[pi]) { const int nw = w + ws[i], nv = v + vs[i]; if (nw > L) { break; } add.push_back({nw, nv}); } std::merge(ucandss[pi].begin(), ucandss[pi].end(), add.begin(), add.end(), std::back_inserter(ucandss[i])); for (const auto &p : ucandss[i]) { dps[i][p.first] = p.second; } for (int j = 1; j <= L; j++) { chmax(dps[i][j], dps[i][j - 1]); } } const auto Q = in.val<int>(); for (int q = 0; q < Q; q++) { const auto [u, l] = in.tup<int, int>(); std::vector<pii> lcands{{0, 0}}; int i = u; for (; i >= (1 << H); i /= 2) { std::vector<pii> add; for (const auto &[w, v] : lcands) { const int nw = w + ws[i], nv = v + vs[i]; if (nw > L) { break; } add.push_back({nw, nv}); } const int len = lcands.size(); for (const auto &p : add) { lcands.push_back(p); } std::inplace_merge(lcands.begin(), lcands.begin() + len, lcands.end()); } int v = 0; for (auto &p : lcands) { chmax(v, p.second), chmax(p.second, v); } int max = 0; for (const auto &[lw, lv] : lcands) { if (lw > l) { break; } const int rw = l - lw; chmax(max, lv + dps[i][rw]); } out.ln(max); } return 0; }
#include <bits/stdc++.h> using ll = long long; using uint = unsigned int; using ull = unsigned long long; using ld = long double; template <typename T, int n> using arr = T (&)[n]; template <typename T, int n> using c_arr = const T (&)[n]; template <typename T> using max_heap = std::priority_queue<T>; template <typename T> using min_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>; constexpr int popcount(const ull v) { return v ? __builtin_popcountll(v) : 0; } constexpr int log2p1(const ull v) { return v ? 64 - __builtin_clzll(v) : 0; } constexpr int lsbp1(const ull v) { return __builtin_ffsll(v); } constexpr int clog(const ull v) { return v ? log2p1(v - 1) : 0; } constexpr ull ceil2(const ull v) { return 1ULL << clog(v); } constexpr ull floor2(const ull v) { return v ? (1ULL << (log2p1(v) - 1)) : 0ULL; } constexpr bool btest(const ull mask, const int ind) { return (mask >> ind) & 1ULL; } template <typename T> void bset(T &mask, const int ind) { mask |= ((T)1 << ind); } template <typename T> void breset(T &mask, const int ind) { mask &= ~((T)1 << ind); } template <typename T> void bflip(T &mask, const int ind) { mask ^= ((T)1 << ind); } template <typename T> void bset(T &mask, const int ind, const bool b) { (b ? bset(mask, ind) : breset(mask, ind)); } template <typename T> bool chmin(T &a, const T &b) { return (a > b ? a = b, true : false); } template <typename T> bool chmax(T &a, const T &b) { return (a < b ? a = b, true : false); } template <typename T> constexpr T inf_v = std::numeric_limits<T>::max() / 4; template <typename Real> constexpr Real pi_v = Real{3.141592653589793238462643383279502884}; constexpr ull TEN(const int n) { return n == 0 ? 1ULL : TEN(n - 1) * 10ULL; } template <typename F> struct fix : F { fix(F &&f) : F{std::forward<F>(f)} {} template <typename... Args> auto operator()(Args &&...args) const { return F::operator()(*this, std::forward<Args>(args)...); } }; class printer { public: printer(std::ostream &os_ = std::cout) : os{os_} {} template <typename T> int operator()(const T &v) { return os << v, 0; } template <typename T> int operator()(const std::vector<T> &vs) { for (int i = 0; i < (int)vs.size(); i++) { os << (i ? " " : ""), this->operator()(vs[i]); } return 0; } template <typename T> int operator()(const std::vector<std::vector<T>> &vss) { for (int i = 0; i < (int)vss.size(); i++) { os << (0 <= i or i + 1 < (int)vss.size() ? "\n" : ""), this->operator()(vss[i]); } return 0; } template <typename T, typename... Args> int operator()(const T &v, const Args &...args) { return this->operator()(v), os << ' ', this->operator()(args...), 0; } template <typename... Args> int ln(const Args &...args) { return this->operator()(args...), os << '\n', 0; } template <typename... Args> int el(const Args &...args) { return this->operator()(args...), os << std::endl, 0; } template <typename... Args> int fmt(const std::string &s, const Args &...args) { return rec(s, 0, args...); } private: int rec(const std::string &s, int index) { return os << s.substr(index, s.size()), 0; } template <typename T, typename... Args> int rec(const std::string &s, int index, const T &v, const Args &...args) { return index == s.size() ? 0 : s[index] == '%' ? (this->operator()(v), rec(s, index + 1, args...)) : (os << s[index], rec(s, index + 1, v, args...)); } std::ostream &os; }; printer out; template <typename T, typename F> std::vector<T> generated(const int n, F f) { std::vector<T> ans(n); return std::generate(ans.begin(), ans.end(), f), ans; } std::vector<int> ioted(const int n, const int offset = 0) { std::vector<int> ans(n); return std::iota(ans.begin(), ans.end(), offset), ans; } template <typename Vs> Vs reversed(const Vs &vs) { auto ans = vs; return std::reverse(ans.begin(), ans.end()), ans; } template <typename T, typename F = std::less<T>> std::vector<T> sorted(const std::vector<T> &vs, F comp = F{}) { auto ans = vs; return std::sort(ans.begin(), ans.end(), comp), ans; } template <typename F> std::vector<int> sorted_iota(const int n, F comp = F{}, const int offset = 0) { return sorted(ioted(n, offset), comp); } class scanner { public: scanner(std::istream &is_ = std::cin) : is{is_} { is.tie(nullptr), std::ios::sync_with_stdio(false); } template <typename T> T val() { static T v; return is >> v, v; } template <typename T> T val(const T offset) { return val<T>() - offset; } template <typename T> std::vector<T> vec(const int n) { return generated<T>(n, [&] { return val<T>(); }); } template <typename T> std::vector<T> vec(const int n, const T offset) { return generated<T>(n, [&] { return val<T>(offset); }); } template <typename T> std::vector<std::vector<T>> vvec(const int n0, const int n1) { return generated<std::vector<T>>(n0, [&] { return vec<T>(n1); }); } template <typename T> std::vector<std::vector<T>> vvec(const int n0, const int n1, const T offset) { return generated<std::vector<T>>(n0, [&] { return vec<T>(n1, offset); }); } template <typename... Args> auto tup() { return std::tuple<std::decay_t<Args>...>{val<Args>()...}; } template <typename... Args> auto tup(const Args &...offsets) { return std::tuple<std::decay_t<Args>...>{val<Args>(offsets)...}; } private: std::istream &is; }; scanner in; #define SHOW(...) static_cast<void>(0) template <typename T, typename Int, int n, int i> auto make_v(typename std::enable_if<(i == n), c_arr<Int, n>>::type, const T &v = T{}) { return v; } template <typename T, typename Int, int n, int i> auto make_v(typename std::enable_if<(i < n), c_arr<Int, n>>::type szs, const T &v = T{}) { return std::vector<decltype(make_v<T, Int, n, i + 1>(szs, v))>( szs[i], make_v<T, Int, n, i + 1>(szs, v)); } template <typename T, typename Int, int n> auto make_v(c_arr<Int, n> szs, const T &t = T{}) { return make_v<T, Int, n, 0>(szs, t); } int main() { constexpr int L = 100000; const auto N = in.val<int>(); const int H = 10; std::vector<int> vs(std::max(N + 1, 1 << H), 0), ws(std::max(N + 1, 1 << H), 0); for (int i = 1; i <= N; i++) { vs[i] = in.val<int>(), ws[i] = in.val<int>(); } using pii = std::pair<int, int>; std::vector<std::vector<pii>> ucandss(1 << H); std::vector<std::vector<int>> dps(1 << H, std::vector<int>(L + 1, 0)); ucandss[0] = {{0, 0}}; for (int i = 1; i < (1 << H); i++) { const int pi = i / 2; std::vector<pii> add; for (const auto &[w, v] : ucandss[pi]) { const int nw = w + ws[i], nv = v + vs[i]; if (nw > L) { break; } add.push_back({nw, nv}); } std::merge(ucandss[pi].begin(), ucandss[pi].end(), add.begin(), add.end(), std::back_inserter(ucandss[i])); for (const auto &p : ucandss[i]) { dps[i][p.first] = p.second; } for (int j = 1; j <= L; j++) { chmax(dps[i][j], dps[i][j - 1]); } } const auto Q = in.val<int>(); for (int q = 0; q < Q; q++) { const auto [u, l] = in.tup<int, int>(); std::vector<pii> lcands{{0, 0}}; int i = u; for (; i >= (1 << H); i /= 2) { std::vector<pii> add; for (const auto &[w, v] : lcands) { const int nw = w + ws[i], nv = v + vs[i]; if (nw > L) { break; } add.push_back({nw, nv}); } const int len = lcands.size(); for (const auto &p : add) { lcands.push_back(p); } std::inplace_merge(lcands.begin(), lcands.begin() + len, lcands.end()); } int v = 0; for (auto &p : lcands) { chmax(v, p.second), chmax(p.second, v); } int max = 0; for (const auto &[lw, lv] : lcands) { if (lw > l) { break; } const int rw = l - lw; chmax(max, lv + dps[i][rw]); } out.ln(max); } return 0; }
replace
173
174
173
174
TLE
p02648
C++
Runtime Error
#include <algorithm> #include <bitset> #include <cmath> #include <cstdio> #include <cstring> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <tuple> #include <vector> using namespace std; #define DEBUG_ //!!$BDs=P;~$K%3%a%s%H%"%&%H(B!! #ifdef DEBUG_ #define dump(x) cerr << #x << " = " << (x) << endl; #else #define dump(x) ; #endif #define equals(a, b) (fabs((a) - (b)) < EPS) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define SZ(x) ((int)(x).size()) #define pb push_back #define eb emplace_back // #define int long long typedef long long LL; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<VI> VVI; typedef vector<VL> VVL; typedef vector<string> VS; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template <class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return 1; } return 0; } template <typename T> std::string printVector(const std::vector<T> &data) { std::stringstream ss; std::ostream_iterator<T> out_it(ss, ", "); ss << "["; std::copy(data.begin(), data.end() - 1, out_it); ss << data.back() << "]"; return ss.str(); } template <typename T> void print_array(const T &ary, int size) { REP(i, size) { cout << ary[i] << " "; } cout << endl; } const int mod = 1e9 + 7; const LL LINF = 1001002003004005006ll; const int INF = 1001001001; const double EPS = (1e-10); const long double PI = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899; int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; signed main(int argc, char const *argv[]) { cin.tie(0); ios::sync_with_stdio(false); cout << setprecision(12); int N; cin >> N; VL V(N + 10), W(N + 10); REP(i, N) cin >> V[i + 1] >> W[i + 1]; VVL dp((1 << 9), VL(100010)); FOR(j, W[1], 100010) dp[1][j] = V[1]; FOR(i, 1, (1 << 8) + 1) { if (i > N) break; REP(j, 100010) { if (i * 2 <= N) { if (j - W[i * 2] >= 0) dp[i * 2][j] = max(dp[i][j], dp[i][j - W[i * 2]] + V[i * 2]); else dp[i * 2][j] = dp[i][j]; } if (i * 2 + 1 <= N) { if (j - W[i * 2 + 1] >= 0) dp[i * 2 + 1][j] = max(dp[i][j], dp[i][j - W[i * 2 + 1]] + V[i * 2 + 1]); else dp[i * 2 + 1][j] = dp[i][j]; } } } // cout << "dp[2]" << endl; // REP(i,300){ // // dp[2][*] // cout << i << " " << dp[2][i] << endl; // } // cout << "dp[4]" << endl; // REP(i,300){ // // dp[4][*] // cout << i << " " << dp[4][i] << endl; // } // cout << "dp[9]" << endl; // REP(i,300){ // // dp[9][*] // cout << i << " " << dp[9][i] << endl; // } int Q; cin >> Q; REP(_, Q) { LL v, L; cin >> v >> L; if (v < (1 << 9)) { cout << dp[v][L] << "\n"; } else { VL tv, tw; while (v >= (1 << 9)) { tv.eb(V[v]); tw.eb(W[v]); v /= 2; } int sz = SZ(tv); LL ans = 0; for (int mask = 0; mask < (1 << sz); mask++) { LL nv = 0, nw = 0; REP(i, sz) { if ((mask >> i) & 1) { nv += tv[i]; nw += tw[i]; } } if (nw > L) continue; chmax(ans, nv + dp[v][L - nw]); } cout << ans << endl; } } }
#include <algorithm> #include <bitset> #include <cmath> #include <cstdio> #include <cstring> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <tuple> #include <vector> using namespace std; #define DEBUG_ //!!$BDs=P;~$K%3%a%s%H%"%&%H(B!! #ifdef DEBUG_ #define dump(x) cerr << #x << " = " << (x) << endl; #else #define dump(x) ; #endif #define equals(a, b) (fabs((a) - (b)) < EPS) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define SZ(x) ((int)(x).size()) #define pb push_back #define eb emplace_back // #define int long long typedef long long LL; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<VI> VVI; typedef vector<VL> VVL; typedef vector<string> VS; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template <class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return 1; } return 0; } template <typename T> std::string printVector(const std::vector<T> &data) { std::stringstream ss; std::ostream_iterator<T> out_it(ss, ", "); ss << "["; std::copy(data.begin(), data.end() - 1, out_it); ss << data.back() << "]"; return ss.str(); } template <typename T> void print_array(const T &ary, int size) { REP(i, size) { cout << ary[i] << " "; } cout << endl; } const int mod = 1e9 + 7; const LL LINF = 1001002003004005006ll; const int INF = 1001001001; const double EPS = (1e-10); const long double PI = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899; int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; signed main(int argc, char const *argv[]) { cin.tie(0); ios::sync_with_stdio(false); cout << setprecision(12); int N; cin >> N; VL V(N + 10), W(N + 10); REP(i, N) cin >> V[i + 1] >> W[i + 1]; VVL dp((1 << 9), VL(100010)); FOR(j, W[1], 100010) dp[1][j] = V[1]; FOR(i, 1, (1 << 8)) { if (i > N) break; REP(j, 100010) { if (i * 2 <= N) { if (j - W[i * 2] >= 0) dp[i * 2][j] = max(dp[i][j], dp[i][j - W[i * 2]] + V[i * 2]); else dp[i * 2][j] = dp[i][j]; } if (i * 2 + 1 <= N) { if (j - W[i * 2 + 1] >= 0) dp[i * 2 + 1][j] = max(dp[i][j], dp[i][j - W[i * 2 + 1]] + V[i * 2 + 1]); else dp[i * 2 + 1][j] = dp[i][j]; } } } // cout << "dp[2]" << endl; // REP(i,300){ // // dp[2][*] // cout << i << " " << dp[2][i] << endl; // } // cout << "dp[4]" << endl; // REP(i,300){ // // dp[4][*] // cout << i << " " << dp[4][i] << endl; // } // cout << "dp[9]" << endl; // REP(i,300){ // // dp[9][*] // cout << i << " " << dp[9][i] << endl; // } int Q; cin >> Q; REP(_, Q) { LL v, L; cin >> v >> L; if (v < (1 << 9)) { cout << dp[v][L] << "\n"; } else { VL tv, tw; while (v >= (1 << 9)) { tv.eb(V[v]); tw.eb(W[v]); v /= 2; } int sz = SZ(tv); LL ans = 0; for (int mask = 0; mask < (1 << sz); mask++) { LL nv = 0, nw = 0; REP(i, sz) { if ((mask >> i) & 1) { nv += tv[i]; nw += tw[i]; } } if (nw > L) continue; chmax(ans, nv + dp[v][L - nw]); } cout << ans << endl; } } }
replace
96
97
96
97
-6
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; #define DEBUG(x) cerr << #x << ": " << x << endl; #define DEBUG_VEC(v) \ cerr << #v << ":"; \ for (int i = 0; i < v.size(); i++) \ cerr << " " << v[i]; \ cerr << endl; #define DEBUG_MAT(v) \ cerr << #v << endl; \ for (int i = 0; i < v.size(); i++) { \ for (int j = 0; j < v[i].size(); j++) { \ cerr << v[i][j] << " "; \ } \ cerr << endl; \ } typedef long long ll; // #define int ll #define vi vector<int> #define vl vector<ll> #define vii vector<vector<int>> #define vll vector<vector<ll>> #define vs vector<string> #define pii pair<int, int> #define pis pair<int, string> #define psi pair<string, int> #define pll pair<ll, ll> template <class S, class T> pair<S, T> operator+(const pair<S, T> &s, const pair<S, T> &t) { return pair<S, T>(s.first + t.first, s.second + t.second); } template <class S, class T> pair<S, T> operator-(const pair<S, T> &s, const pair<S, T> &t) { return pair<S, T>(s.first - t.first, s.second - t.second); } template <class S, class T> ostream &operator<<(ostream &os, pair<S, T> p) { os << "(" << p.first << ", " << p.second << ")"; return os; } #define X first #define Y second #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define rep1(i, n) for (int i = 1; i <= (int)(n); i++) #define rrep(i, n) for (int i = (int)(n)-1; i >= 0; i--) #define rrep1(i, n) for (int i = (int)(n); i > 0; i--) #define REP(i, a, b) for (int i = a; i < b; i++) #define in(x, a, b) (a <= x && x < b) #define all(c) c.begin(), c.end() template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template <class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return 1; } return 0; } #define UNIQUE(v) v.erase(std::unique(v.begin(), v.end()), v.end()); const ll inf = 1000000001; const ll INF = (ll)1e18 + 1; const long double pi = 3.1415926535897932384626433832795028841971L; #define Sp(p) cout << setprecision(25) << fixed << p << endl; // int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; // int dx2[8] = { 1,1,0,-1,-1,-1,0,1 }, dy2[8] = { 0,1,1,1,0,-1,-1,-1 }; vi dx = {1, 0, -1, 0}, dy = {0, 1, 0, -1}; vi dx2 = {1, 1, 0, -1, -1, -1, 0, 1}, dy2 = {0, 1, 1, 1, 0, -1, -1, -1}; #define fio() \ cin.tie(0); \ ios::sync_with_stdio(false); // const ll MOD = 1000000007; const ll MOD = 998244353; // #define mp make_pair // #define endl '\n' signed main() { // fio(); int n; scanf("%d", &n); int depth = 21; int mask = 1 << 20; while ((mask & n) == 0) { depth--; mask >>= 1; } // DEBUG(depth); vi v(n), w(n); rep(i, n) { scanf("%d %d", &v[i], &w[i]); // cin >> v[i] >> w[i]; } int half = depth / 2; vector<vector<pii>> dp((1 << half) - 1); int n1 = dp.size(); rep(i, n1) { if (i == 0) { dp[i].push_back(pii(0, 0)); dp[i].push_back(pii(w[i], v[i])); continue; } int par = (i - 1) / 2; for (int j = 0; j < dp[par].size(); j++) { pii wv = dp[par][j]; dp[i].push_back(wv); wv.first += w[i]; wv.second += v[i]; dp[i].push_back(wv); } sort(all(dp[i])); UNIQUE(dp[i]); vector<pii> dp2; int ma = -inf; rep(j, dp[i].size()) { pii wv = dp[i][j]; if (wv.first >= 100001) break; if (wv.second <= ma) continue; while (dp2.size() > 0 and dp2.back().first == wv.first) dp2.pop_back(); dp2.push_back(wv); chmax(ma, wv.second); } swap(dp[i], dp2); } // vector<vector<pii>> dp2(n - n1); // for (int u = n1; u < n; u++) { // int i = u - n1; // int par = (u - 1) / 2; // if (par < n1) { // dp2[i].push_back(pii(0, 0)); // dp2[i].push_back(pii(w[u], v[u])); // continue; // } // for (int j = 0; j < dp2[par - n1].size(); j++) { // pii wv = dp2[par - n1][j]; // dp2[i].push_back(wv); // wv.first += w[u]; // wv.second += v[u]; // dp2[i].push_back(wv); // } // sort(all(dp2[i])); // UNIQUE(dp2[i]); // vector<pii> dp3; // int ma = -inf; // rep (j, dp2[i].size()) { // pii wv = dp2[i][j]; // if (wv.first >= 100001) break; // if (wv.second <= ma) continue; // while (dp3.size() > 0 and dp3.back().first == wv.first) // dp3.pop_back(); dp3.push_back(wv); chmax(ma, wv.second); // } // swap(dp2[i], dp3); // } // DEBUG_MAT(dp); // DEBUG_MAT(dp2); int q; scanf("%d", &q); // cin >> q; while (q--) { int u, l; scanf("%d %d", &u, &l); // cin >> u >> l; u--; if (n == 1) { if (w[u] <= l) { cout << v[u] << endl; } else { cout << 0 << endl; } continue; } if (u < dp.size()) { auto itr = lower_bound(all(dp[u]), pii(l + 1, -inf)); itr--; cout << itr->second << '\n'; continue; } int par = u; vector<pii> his; while (par >= dp.size()) { his.push_back(pii(w[par], v[par])); par = (par - 1) / 2; } // vector<pii> t1 = dp[par], t2 = dp2[u - n1]; int ans = 0; int m = his.size(); rep(i, 1 << m) { pii wv(0, 0); rep(j, m) { if (i & (1 << j)) { wv.first += his[j].first; wv.second += his[j].second; } } int giri = l - wv.first; if (giri < 0) continue; auto itr = lower_bound(all(dp[par]), pii(giri + 1, -inf)); itr--; chmax(ans, wv.second + itr->second); } cout << ans << '\n'; } }
#include <bits/stdc++.h> using namespace std; #define DEBUG(x) cerr << #x << ": " << x << endl; #define DEBUG_VEC(v) \ cerr << #v << ":"; \ for (int i = 0; i < v.size(); i++) \ cerr << " " << v[i]; \ cerr << endl; #define DEBUG_MAT(v) \ cerr << #v << endl; \ for (int i = 0; i < v.size(); i++) { \ for (int j = 0; j < v[i].size(); j++) { \ cerr << v[i][j] << " "; \ } \ cerr << endl; \ } typedef long long ll; // #define int ll #define vi vector<int> #define vl vector<ll> #define vii vector<vector<int>> #define vll vector<vector<ll>> #define vs vector<string> #define pii pair<int, int> #define pis pair<int, string> #define psi pair<string, int> #define pll pair<ll, ll> template <class S, class T> pair<S, T> operator+(const pair<S, T> &s, const pair<S, T> &t) { return pair<S, T>(s.first + t.first, s.second + t.second); } template <class S, class T> pair<S, T> operator-(const pair<S, T> &s, const pair<S, T> &t) { return pair<S, T>(s.first - t.first, s.second - t.second); } template <class S, class T> ostream &operator<<(ostream &os, pair<S, T> p) { os << "(" << p.first << ", " << p.second << ")"; return os; } #define X first #define Y second #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define rep1(i, n) for (int i = 1; i <= (int)(n); i++) #define rrep(i, n) for (int i = (int)(n)-1; i >= 0; i--) #define rrep1(i, n) for (int i = (int)(n); i > 0; i--) #define REP(i, a, b) for (int i = a; i < b; i++) #define in(x, a, b) (a <= x && x < b) #define all(c) c.begin(), c.end() template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template <class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return 1; } return 0; } #define UNIQUE(v) v.erase(std::unique(v.begin(), v.end()), v.end()); const ll inf = 1000000001; const ll INF = (ll)1e18 + 1; const long double pi = 3.1415926535897932384626433832795028841971L; #define Sp(p) cout << setprecision(25) << fixed << p << endl; // int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; // int dx2[8] = { 1,1,0,-1,-1,-1,0,1 }, dy2[8] = { 0,1,1,1,0,-1,-1,-1 }; vi dx = {1, 0, -1, 0}, dy = {0, 1, 0, -1}; vi dx2 = {1, 1, 0, -1, -1, -1, 0, 1}, dy2 = {0, 1, 1, 1, 0, -1, -1, -1}; #define fio() \ cin.tie(0); \ ios::sync_with_stdio(false); // const ll MOD = 1000000007; const ll MOD = 998244353; // #define mp make_pair // #define endl '\n' signed main() { // fio(); int n; scanf("%d", &n); int depth = 21; int mask = 1 << 20; while ((mask & n) == 0) { depth--; mask >>= 1; } // DEBUG(depth); vi v(n), w(n); rep(i, n) { scanf("%d %d", &v[i], &w[i]); // cin >> v[i] >> w[i]; } int half = depth / 2; if (half == 8 or half == 9) { half = 11; } vector<vector<pii>> dp((1 << half) - 1); int n1 = dp.size(); rep(i, n1) { if (i == 0) { dp[i].push_back(pii(0, 0)); dp[i].push_back(pii(w[i], v[i])); continue; } int par = (i - 1) / 2; for (int j = 0; j < dp[par].size(); j++) { pii wv = dp[par][j]; dp[i].push_back(wv); wv.first += w[i]; wv.second += v[i]; dp[i].push_back(wv); } sort(all(dp[i])); UNIQUE(dp[i]); vector<pii> dp2; int ma = -inf; rep(j, dp[i].size()) { pii wv = dp[i][j]; if (wv.first >= 100001) break; if (wv.second <= ma) continue; while (dp2.size() > 0 and dp2.back().first == wv.first) dp2.pop_back(); dp2.push_back(wv); chmax(ma, wv.second); } swap(dp[i], dp2); } // vector<vector<pii>> dp2(n - n1); // for (int u = n1; u < n; u++) { // int i = u - n1; // int par = (u - 1) / 2; // if (par < n1) { // dp2[i].push_back(pii(0, 0)); // dp2[i].push_back(pii(w[u], v[u])); // continue; // } // for (int j = 0; j < dp2[par - n1].size(); j++) { // pii wv = dp2[par - n1][j]; // dp2[i].push_back(wv); // wv.first += w[u]; // wv.second += v[u]; // dp2[i].push_back(wv); // } // sort(all(dp2[i])); // UNIQUE(dp2[i]); // vector<pii> dp3; // int ma = -inf; // rep (j, dp2[i].size()) { // pii wv = dp2[i][j]; // if (wv.first >= 100001) break; // if (wv.second <= ma) continue; // while (dp3.size() > 0 and dp3.back().first == wv.first) // dp3.pop_back(); dp3.push_back(wv); chmax(ma, wv.second); // } // swap(dp2[i], dp3); // } // DEBUG_MAT(dp); // DEBUG_MAT(dp2); int q; scanf("%d", &q); // cin >> q; while (q--) { int u, l; scanf("%d %d", &u, &l); // cin >> u >> l; u--; if (n == 1) { if (w[u] <= l) { cout << v[u] << endl; } else { cout << 0 << endl; } continue; } if (u < dp.size()) { auto itr = lower_bound(all(dp[u]), pii(l + 1, -inf)); itr--; cout << itr->second << '\n'; continue; } int par = u; vector<pii> his; while (par >= dp.size()) { his.push_back(pii(w[par], v[par])); par = (par - 1) / 2; } // vector<pii> t1 = dp[par], t2 = dp2[u - n1]; int ans = 0; int m = his.size(); rep(i, 1 << m) { pii wv(0, 0); rep(j, m) { if (i & (1 << j)) { wv.first += his[j].first; wv.second += his[j].second; } } int giri = l - wv.first; if (giri < 0) continue; auto itr = lower_bound(all(dp[par]), pii(giri + 1, -inf)); itr--; chmax(ans, wv.second + itr->second); } cout << ans << '\n'; } }
insert
103
103
103
106
TLE
p02648
C++
Time Limit Exceeded
#include <algorithm> #include <array> #include <cassert> #include <climits> #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <memory> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> struct Node { long long int value; int weight; }; int bit_length(const int value) { return value == 0 ? 0 : 1 + bit_length(value >> 1); } int main() { constexpr int l_max = 100000; std::cin.tie(nullptr); std::cin.sync_with_stdio(false); int n; std::cin >> n; std::vector<Node> nodes(n); for (auto &node : nodes) std::cin >> node.value >> node.weight; std::vector<std::vector<Node>> cache(1 << (bit_length(n) - 1)); cache[0].push_back(Node{0, 0}); cache[0].push_back(nodes[0]); for (auto i = 1; i < cache.size(); ++i) { const auto prev = ((i + 1) >> 1) - 1; cache[i] = cache[prev]; const auto current = nodes[i]; for (const auto &p : cache[prev]) { if (p.weight + current.weight > l_max) continue; cache[i].push_back( Node{current.value + p.value, current.weight + p.weight}); } } const auto comparator = [](const Node &a, const Node &b) { return a.weight == b.weight ? a.value > b.value : a.weight < b.weight; }; for (auto &s : cache) { std::sort(s.begin(), s.end(), comparator); for (auto i = 1; i < s.size(); ++i) { s[i].value = std::max(s[i].value, s[i - 1].value); } } const auto find = [](const int weight, const Node &a) { return a.weight > weight; }; int q; std::vector<Node> until; until.reserve(n - cache.size()); for (std::cin >> q; q > 0; --q) { int u, l; std::cin >> u >> l; if (u <= cache.size()) { const auto pos = std::distance( cache[u - 1].begin(), std::upper_bound(cache[u - 1].begin(), cache[u - 1].end(), l, find)); if (pos > 0) { std::cout << cache[u - 1][pos - 1].value << '\n'; } else { std::cout << 0 << '\n'; } } else { until.clear(); until.push_back(Node{0, 0}); while (u > cache.size()) { const auto node = nodes[u - 1]; for (int i = until.size() - 1; i >= 0; --i) { if (until[i].weight + node.weight > l) continue; until.push_back( Node{until[i].value + node.value, until[i].weight + node.weight}); } u >>= 1; } long long int result{0}; for (const auto &n : until) { const auto pos = std::distance(cache[u - 1].begin(), std::upper_bound(cache[u - 1].begin(), cache[u - 1].end(), l - n.weight, find)); if (pos > 0) { result = std::max(result, cache[u - 1][pos - 1].value + n.value); } } std::cout << result << '\n'; } } }
#include <algorithm> #include <array> #include <cassert> #include <climits> #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <memory> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> struct Node { long long int value; int weight; }; int bit_length(const int value) { return value == 0 ? 0 : 1 + bit_length(value >> 1); } int main() { constexpr int l_max = 100000; std::cin.tie(nullptr); std::cin.sync_with_stdio(false); int n; std::cin >> n; std::vector<Node> nodes(n); for (auto &node : nodes) std::cin >> node.value >> node.weight; std::vector<std::vector<Node>> cache(1 << (bit_length(n) >> 1)); cache[0].push_back(Node{0, 0}); cache[0].push_back(nodes[0]); for (auto i = 1; i < cache.size(); ++i) { const auto prev = ((i + 1) >> 1) - 1; cache[i] = cache[prev]; const auto current = nodes[i]; for (const auto &p : cache[prev]) { if (p.weight + current.weight > l_max) continue; cache[i].push_back( Node{current.value + p.value, current.weight + p.weight}); } } const auto comparator = [](const Node &a, const Node &b) { return a.weight == b.weight ? a.value > b.value : a.weight < b.weight; }; for (auto &s : cache) { std::sort(s.begin(), s.end(), comparator); for (auto i = 1; i < s.size(); ++i) { s[i].value = std::max(s[i].value, s[i - 1].value); } } const auto find = [](const int weight, const Node &a) { return a.weight > weight; }; int q; std::vector<Node> until; until.reserve(n - cache.size()); for (std::cin >> q; q > 0; --q) { int u, l; std::cin >> u >> l; if (u <= cache.size()) { const auto pos = std::distance( cache[u - 1].begin(), std::upper_bound(cache[u - 1].begin(), cache[u - 1].end(), l, find)); if (pos > 0) { std::cout << cache[u - 1][pos - 1].value << '\n'; } else { std::cout << 0 << '\n'; } } else { until.clear(); until.push_back(Node{0, 0}); while (u > cache.size()) { const auto node = nodes[u - 1]; for (int i = until.size() - 1; i >= 0; --i) { if (until[i].weight + node.weight > l) continue; until.push_back( Node{until[i].value + node.value, until[i].weight + node.weight}); } u >>= 1; } long long int result{0}; for (const auto &n : until) { const auto pos = std::distance(cache[u - 1].begin(), std::upper_bound(cache[u - 1].begin(), cache[u - 1].end(), l - n.weight, find)); if (pos > 0) { result = std::max(result, cache[u - 1][pos - 1].value + n.value); } } std::cout << result << '\n'; } } }
replace
37
38
37
38
TLE
p02648
C++
Runtime Error
#pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma GCC optimize("unroll-loops") #include <algorithm> #include <bitset> //UWAGA - w czasie kompilacji musi byc znany rozmiar wektora - nie mozna go zmienic #include <cassert> #include <chrono> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iomanip> //do setprecision #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <vector> using namespace std; #define FOR(i, b, e) for (int i = (b); i < (e); ++i) #define FORQ(i, b, e) for (int i = (b); i <= (e); ++i) #define FORD(i, b, e) for (int i = (b)-1; i >= (e); --i) #define REP(x, n) for (int x = 0; x < (n); ++x) #define ALL(u) (u).begin(), (u).end() #define ST first #define ND second #define PB push_back #define MP make_pair #define LL long long #define ULL unsigned LL #define LD long double typedef pair<int, int> PII; const double pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342; const int MR = 1e5 + 10; const int MS = 1 << 18; const int LH = 10; LL dp[512][MR]; PII t[MS]; int h[MS]; int main() { int N; scanf("%d", &N); FORQ(i, 1, N) scanf("%d%d", &t[i].first, &t[i].second); // wylicz dp dla roota, h[root] == 0 FOR(i, t[1].second, MR) dp[1][i] = t[1].first; FORQ(v, 2, N) { // wylicz h int par = v / 2; h[v] = h[par] + 1; if (h[v] < LH) { // wylicz dp do meet in the middle FOR(i, 1, t[v].second) dp[v][i] = dp[par][i]; FOR(i, t[v].second, MR) dp[v][i] = max(dp[par][i], dp[par][i - t[v].second] + t[v].first); } } // jedz query int Q; scanf("%d", &Q); REP(xxx, Q) { int v, L; scanf("%d%d", &v, &L); // zobacz, czy od razu mamy wynik if (h[v] < LH) { printf("%lld\n", dp[v][L]); continue; } // wez kazdy podzbior rodzicow o glebokosci >= LH vector<int> par; while (h[v] >= LH) { par.push_back(v); v >>= 1; } // teraz w v mamy rodzica o h[v] < LH i tam mamy wyliczone dp LL res = 0; REP(mask, 1 << par.size()) { int W = 0; LL V = 0; REP(i, par.size()) if (mask & (1 << i)) { V += t[par[i]].first; W += t[par[i]].second; if (W > L) break; } if (W <= L) res = max(res, V + dp[v][L - W]); } printf("%lld\n", res); } return 0; } // FOR GNU C++ use the following pattern: // Uncomment the code below and change your main into main2 // It does not build in MS C++ // But it does increase the stack size from 256 MB on CF and uses GNU C++ // #include <Processthreadsapi.h> // #include <iostream> // #include <Synchapi.h> // #include <windows.h> // #include <process.h> // // DWORD WINAPI MyThreadFunction(LPVOID lpParam) { // main2(nullptr); // return 0; // } // int main() { // auto h = CreateThread(nullptr, 1024 << 20, MyThreadFunction, nullptr, // STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr); WaitForSingleObject(h, // INFINITE); // }
#pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma GCC optimize("unroll-loops") #include <algorithm> #include <bitset> //UWAGA - w czasie kompilacji musi byc znany rozmiar wektora - nie mozna go zmienic #include <cassert> #include <chrono> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iomanip> //do setprecision #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <vector> using namespace std; #define FOR(i, b, e) for (int i = (b); i < (e); ++i) #define FORQ(i, b, e) for (int i = (b); i <= (e); ++i) #define FORD(i, b, e) for (int i = (b)-1; i >= (e); --i) #define REP(x, n) for (int x = 0; x < (n); ++x) #define ALL(u) (u).begin(), (u).end() #define ST first #define ND second #define PB push_back #define MP make_pair #define LL long long #define ULL unsigned LL #define LD long double typedef pair<int, int> PII; const double pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342; const int MR = 1e5 + 10; const int MS = 1 << 18; const int LH = 10; LL dp[1024][MR]; PII t[MS]; int h[MS]; int main() { int N; scanf("%d", &N); FORQ(i, 1, N) scanf("%d%d", &t[i].first, &t[i].second); // wylicz dp dla roota, h[root] == 0 FOR(i, t[1].second, MR) dp[1][i] = t[1].first; FORQ(v, 2, N) { // wylicz h int par = v / 2; h[v] = h[par] + 1; if (h[v] < LH) { // wylicz dp do meet in the middle FOR(i, 1, t[v].second) dp[v][i] = dp[par][i]; FOR(i, t[v].second, MR) dp[v][i] = max(dp[par][i], dp[par][i - t[v].second] + t[v].first); } } // jedz query int Q; scanf("%d", &Q); REP(xxx, Q) { int v, L; scanf("%d%d", &v, &L); // zobacz, czy od razu mamy wynik if (h[v] < LH) { printf("%lld\n", dp[v][L]); continue; } // wez kazdy podzbior rodzicow o glebokosci >= LH vector<int> par; while (h[v] >= LH) { par.push_back(v); v >>= 1; } // teraz w v mamy rodzica o h[v] < LH i tam mamy wyliczone dp LL res = 0; REP(mask, 1 << par.size()) { int W = 0; LL V = 0; REP(i, par.size()) if (mask & (1 << i)) { V += t[par[i]].first; W += t[par[i]].second; if (W > L) break; } if (W <= L) res = max(res, V + dp[v][L - W]); } printf("%lld\n", res); } return 0; } // FOR GNU C++ use the following pattern: // Uncomment the code below and change your main into main2 // It does not build in MS C++ // But it does increase the stack size from 256 MB on CF and uses GNU C++ // #include <Processthreadsapi.h> // #include <iostream> // #include <Synchapi.h> // #include <windows.h> // #include <process.h> // // DWORD WINAPI MyThreadFunction(LPVOID lpParam) { // main2(nullptr); // return 0; // } // int main() { // auto h = CreateThread(nullptr, 1024 << 20, MyThreadFunction, nullptr, // STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr); WaitForSingleObject(h, // INFINITE); // }
replace
51
52
51
52
-11
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x, to) for (x = 0; x < (to); x++) #define FORR(x, arr) for (auto &x : arr) #define ITR(x, c) for (__typeof(c.begin()) x = c.begin(); x != c.end(); x++) #define ALL(a) (a.begin()), (a.end()) #define ZERO(a) memset(a, 0, sizeof(a)) #define MINUS(a) memset(a, 0xff, sizeof(a)) //------------------------------------------------------- int N; int P[(1 << 18) + 1]; int D[1 << 19]; int V[1 << 19], W[1 << 19]; int Q; int T[1 << 19], L[1 << 19]; ll ret[1 << 19]; vector<int> tar[1 << 19]; vector<int> VV[1 << 19]; vector<pair<int, ll>> cand[1 << 19]; const int DI = 12; void solve() { int i, j, k, l, r, x, y; string s; cin >> N; for (i = 1; i <= N; i++) { if (i > 1) { P[i] = i / 2; D[i] = D[i / 2] + 1; VV[i] = VV[i / 2]; } VV[i].push_back(i); cin >> V[i] >> W[i]; } cin >> Q; FOR(i, Q) { cin >> T[i] >> L[i]; tar[T[i]].push_back(i); } for (i = 1; i < 1 << DI; i++) if (i <= N) { vector<pair<ll, ll>> A; int len = VV[i].size(); int mask; FOR(mask, 1 << len) { int v = 0, w = 0; FOR(j, len) if (mask & (1 << j)) v += V[VV[i][j]], w += W[VV[i][j]]; if (w <= 100000) A.push_back({w, v}); } sort(ALL(A)); cand[i].push_back({0, 0}); FORR(a, A) { while (cand[i].size() && cand[i].back().first == a.first) cand[i].pop_back(); if (cand[i].empty() || cand[i].back().second < a.second) { cand[i].push_back(a); } } FORR(t, tar[i]) { x = lower_bound(ALL(cand[i]), make_pair(L[t] + 1, 0LL)) - cand[i].begin(); x--; ret[t] = cand[i][x].second; } } for (i = 1 << DI; i < 1 << 18; i++) if (i <= N) { vector<int> C; int p = 0; FORR(c, VV[i]) { if (D[c] >= DI) C.push_back(c); else p = max(p, c); } FORR(t, tar[i]) { int len = VV[i].size(); int mask; FOR(mask, 1 << len) { int v = 0, w = 0; FOR(j, len) if (mask & (1 << j)) v += V[C[j]], w += W[C[j]]; if (w <= L[t]) { x = lower_bound(ALL(cand[p]), make_pair(L[t] - w + 1, 0LL)) - cand[p].begin(); x--; ret[t] = max(ret[t], cand[p][x].second + v); } } } } FOR(i, Q) cout << ret[i] << endl; } int main(int argc, char **argv) { string s; int i; if (argc == 1) ios::sync_with_stdio(false), cin.tie(0); FOR(i, argc - 1) s += argv[i + 1], s += '\n'; FOR(i, s.size()) ungetc(s[s.size() - 1 - i], stdin); cout.tie(0); solve(); return 0; }
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x, to) for (x = 0; x < (to); x++) #define FORR(x, arr) for (auto &x : arr) #define ITR(x, c) for (__typeof(c.begin()) x = c.begin(); x != c.end(); x++) #define ALL(a) (a.begin()), (a.end()) #define ZERO(a) memset(a, 0, sizeof(a)) #define MINUS(a) memset(a, 0xff, sizeof(a)) //------------------------------------------------------- int N; int P[(1 << 18) + 1]; int D[1 << 19]; int V[1 << 19], W[1 << 19]; int Q; int T[1 << 19], L[1 << 19]; ll ret[1 << 19]; vector<int> tar[1 << 19]; vector<int> VV[1 << 19]; vector<pair<int, ll>> cand[1 << 19]; const int DI = 12; void solve() { int i, j, k, l, r, x, y; string s; cin >> N; for (i = 1; i <= N; i++) { if (i > 1) { P[i] = i / 2; D[i] = D[i / 2] + 1; VV[i] = VV[i / 2]; } VV[i].push_back(i); cin >> V[i] >> W[i]; } cin >> Q; FOR(i, Q) { cin >> T[i] >> L[i]; tar[T[i]].push_back(i); } for (i = 1; i < 1 << DI; i++) if (i <= N) { vector<pair<ll, ll>> A; int len = VV[i].size(); int mask; FOR(mask, 1 << len) { int v = 0, w = 0; FOR(j, len) if (mask & (1 << j)) v += V[VV[i][j]], w += W[VV[i][j]]; if (w <= 100000) A.push_back({w, v}); } sort(ALL(A)); cand[i].push_back({0, 0}); FORR(a, A) { while (cand[i].size() && cand[i].back().first == a.first) cand[i].pop_back(); if (cand[i].empty() || cand[i].back().second < a.second) { cand[i].push_back(a); } } FORR(t, tar[i]) { x = lower_bound(ALL(cand[i]), make_pair(L[t] + 1, 0LL)) - cand[i].begin(); x--; ret[t] = cand[i][x].second; } } for (i = 1 << DI; i < 1 << 18; i++) if (i <= N) { vector<int> C; int p = 0; FORR(c, VV[i]) { if (D[c] >= DI) C.push_back(c); else p = max(p, c); } FORR(t, tar[i]) { int len = C.size(); int mask; FOR(mask, 1 << len) { int v = 0, w = 0; FOR(j, len) if (mask & (1 << j)) v += V[C[j]], w += W[C[j]]; if (w <= L[t]) { x = lower_bound(ALL(cand[p]), make_pair(L[t] - w + 1, 0LL)) - cand[p].begin(); x--; ret[t] = max(ret[t], cand[p][x].second + v); } } } } FOR(i, Q) cout << ret[i] << endl; } int main(int argc, char **argv) { string s; int i; if (argc == 1) ios::sync_with_stdio(false), cin.tie(0); FOR(i, argc - 1) s += argv[i + 1], s += '\n'; FOR(i, s.size()) ungetc(s[s.size() - 1 - i], stdin); cout.tie(0); solve(); return 0; }
replace
90
91
90
91
0
p02648
C++
Time Limit Exceeded
#include <algorithm> #include <bits/stdc++.h> #include <cctype> #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <vector> using namespace std; typedef long double ld; typedef long long ll; typedef pair<ll, ll> pii; typedef pair<ll, bool> pib; typedef vector<bool> vb; typedef vector<ll> vi; typedef vector<vi> vvi; typedef vector<vvi> vvvi; typedef vector<pii> vpii; typedef vector<vpii> vvpii; typedef vector<double> vf; typedef queue<ll> qi; typedef long double ld; #define mp make_pair #define mt make_tuple #define pb push_back #define rep(i, N) for (ll i = 0; i < N; i++) #define repa(i, a, N) for (ll i = a; i < N; i++) #define repr(i, N) for (ll i = N - 1; i >= 0; i--) #define drep(i, N, j, M) rep(i, N) rep(j, M) #define trep(i, N, j, M, k, L) rep(i, N) rep(j, M) rep(k, L) #define all(A) A.begin(), A.end() #define uni(A) A.erase(unique(all(A)), A.end()) template <class t, class u> ostream &operator<<(ostream &os, const pair<t, u> &p) { return os << "{" << p.first << "," << p.second << "}"; } template <class t> ostream &operator<<(ostream &os, const vector<t> &v) { os << "{"; for (auto e : v) os << e << ","; return os << "}" << endl; } template <class t, class u> ostream &operator<<(ostream &os, const unordered_map<t, u> &m) { os << "{"; for (auto itr = m.begin(); itr != m.end(); ++itr) { os << "(" << itr->first << ", " << itr->second << "), "; } return os << "}"; } template <class t> ostream &operator<<(ostream &os, const set<t> &m) { os << "{"; for (auto itr = m.begin(); itr != m.end(); ++itr) { os << *itr << ", "; } return os << "}"; } template <class t> ostream &operator<<(ostream &os, const multiset<t> &m) { os << "{"; for (auto itr = m.begin(); itr != m.end(); ++itr) { os << *itr << ", "; } return os << "}"; } const ll LLMAX = numeric_limits<long long>::max() / 3; const double DMAX = numeric_limits<double>::max() / 3; const double PI = 3.141592653589793; // const ll MOD = 1e9 + 7; const ll MOD = 998244353; template <std::int_fast64_t Modulus> class modint { using i64 = std::int_fast64_t; public: i64 a; constexpr modint(const i64 x = 0) noexcept : a(x % Modulus) {} constexpr i64 &value() noexcept { return a; } constexpr const i64 &value() const noexcept { return a; } constexpr modint operator+(const modint rhs) const noexcept { return modint(*this) += rhs; } constexpr modint operator-(const modint rhs) const noexcept { return modint(*this) -= rhs; } constexpr modint operator*(const modint rhs) const noexcept { return modint(*this) *= rhs; } constexpr modint operator/(const modint rhs) const noexcept { return modint(*this) /= rhs; } constexpr modint &operator+=(const modint rhs) noexcept { a += rhs.a; if (a >= Modulus) { a -= Modulus; } return *this; } constexpr modint &operator-=(const modint rhs) noexcept { if (a < rhs.a) { a += Modulus; } a -= rhs.a; return *this; } constexpr modint &operator*=(const modint rhs) noexcept { a = a * rhs.a % Modulus; return *this; } constexpr modint &operator/=(modint rhs) noexcept { i64 exp = Modulus - 2; while (exp) { if (exp % 2) { *this *= rhs; } rhs *= rhs; exp /= 2; } return *this; } }; template <std::int_fast64_t Modulus> ostream &operator<<(ostream &os, const modint<Modulus> &m) { return os << (m.a + Modulus) % Modulus; } typedef modint<MOD> mod; typedef vector<mod> vm; typedef vector<vm> vvm; typedef vector<vvm> vvvm; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } void No() { cout << "No" << endl; } void Yes() { cout << "Yes" << endl; } void NO() { cout << "NO" << endl; } void YES() { cout << "YES" << endl; } vector<ll> fac(1e6 + 1); // n!(mod M) vector<ll> ifac(1e6 + 1); // k!^{M-2} (mod ll mpow(ll x, ll n) { // x^n(mod M) ←普通にpow(x,n)では溢れてしまうため,随時mod計算 ll ans = 1; while (n != 0) { if (n & 1) ans = ans * x % MOD; x = x * x % MOD; n = n >> 1; } return ans; } ll comb(ll a, ll b) { // aCbをmod計算 if (a == 0 && b == 0) return 1; if (a < b || a < 0) return 0; ll tmp = ifac[a - b] * ifac[b] % MOD; return tmp * fac[a] % MOD; } void pre_calc_comb() { fac[0] = 1; ifac[0] = 1; for (ll i = 0; i < 1e6; i++) { fac[i + 1] = fac[i] * (i + 1) % MOD; // n!(mod M) ifac[i + 1] = ifac[i] * mpow(i + 1, MOD - 2) % MOD; // k!^{M-2} (mod M) ←累乗にmpowを採用 } } template <class T> class SegTree { int n; vector<T> data; T def; function<T(T, T)> operation; function<T(T, T)> update; T _query(int a, int b, int k, int l, int r) { if (r <= a || b <= l) return def; if (a <= l && r <= b) return data[k]; else { T c1 = _query(a, b, 2 * k + 1, l, (l + r) / 2); T c2 = _query(a, b, 2 * k + 2, (l + r) / 2, r); return operation(c1, c2); } } public: SegTree(size_t _n, T _def, function<T(T, T)> _operation, function<T(T, T)> _update) : def(_def), operation(_operation), update(_update) { n = 1; while (n < _n) { n *= 2; } data = vector<T>(2 * n - 1, def); } void change(int i, T x) { i += n - 1; data[i] = update(data[i], x); while (i > 0) { i = (i - 1) / 2; data[i] = operation(data[i * 2 + 1], data[i * 2 + 2]); } } T query(int a, int b) { return _query(a, b, 0, 0, n); } T operator[](int i) { return data[i + n - 1]; } }; vector<ll> divisor(ll n) { vector<ll> ret; for (ll i = 1; i * i <= n; i++) { if (n % i == 0) { ret.push_back(i); if (i * i != n) ret.push_back(n / i); } } sort(begin(ret), end(ret)); return (ret); } /* SegTree<ll> st(N, LLMAX, // a: left child, b: right child [](ll a, ll b) {return min(a, b); }, // d: old, x: query [](ll d, ll x) {return x; }); // */ ll gcd(ll a, ll b) { if (a == 0) return b; if (b == 0) return a; if (a % b == 0) { return (b); } else { return (gcd(b, a % b)); } } ll N, M, K, Q; ll ans = 0; ll H, W; void solveD() { cin >> N; vpii VW(N); rep(i, N) { ll v, w; cin >> v >> w; VW[i] = mp(v, w); } cin >> Q; vpii VL(Q); ll ml = 0; ll M = (1 << 9) - 1; rep(i, Q) { ll v, l; cin >> v >> l; chmax(ml, l); VL[i] = mp(v, l); } vvi dp(M + 1, vi(ml + 1, 0)); repa(i, 1, M + 1) { pii vw = VW[i - 1]; ll value = vw.first; ll weight = vw.second; rep(w, ml + 1) { if (w >= weight) { dp[i][w] = max(dp[i / 2][w - weight] + value, dp[i / 2][w]); } else { dp[i][w] = dp[i / 2][w]; } } } rep(q, Q) { pii vl = VL[q]; ll v = vl.first; ll l = vl.second; vi x(0); while (v > M) { x.pb(v); v /= 2; } ll maxValue = 0; ll xs = x.size(); rep(bit, 1 << xs) { ll value = 0; ll weight = 0; rep(i, xs) { if (bit & (1 << i)) { value += VW[x[i] - 1].first; weight += VW[x[i] - 1].second; } } if (l >= weight) { chmax(maxValue, dp[v][l - weight] + value); } } cout << maxValue << '\n'; } } int main() { ios::sync_with_stdio(false); cin.tie(0); solveD(); return 0; }
#include <algorithm> #include <bits/stdc++.h> #include <cctype> #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <vector> using namespace std; typedef long double ld; typedef long long ll; typedef pair<ll, ll> pii; typedef pair<ll, bool> pib; typedef vector<bool> vb; typedef vector<ll> vi; typedef vector<vi> vvi; typedef vector<vvi> vvvi; typedef vector<pii> vpii; typedef vector<vpii> vvpii; typedef vector<double> vf; typedef queue<ll> qi; typedef long double ld; #define mp make_pair #define mt make_tuple #define pb push_back #define rep(i, N) for (ll i = 0; i < N; i++) #define repa(i, a, N) for (ll i = a; i < N; i++) #define repr(i, N) for (ll i = N - 1; i >= 0; i--) #define drep(i, N, j, M) rep(i, N) rep(j, M) #define trep(i, N, j, M, k, L) rep(i, N) rep(j, M) rep(k, L) #define all(A) A.begin(), A.end() #define uni(A) A.erase(unique(all(A)), A.end()) template <class t, class u> ostream &operator<<(ostream &os, const pair<t, u> &p) { return os << "{" << p.first << "," << p.second << "}"; } template <class t> ostream &operator<<(ostream &os, const vector<t> &v) { os << "{"; for (auto e : v) os << e << ","; return os << "}" << endl; } template <class t, class u> ostream &operator<<(ostream &os, const unordered_map<t, u> &m) { os << "{"; for (auto itr = m.begin(); itr != m.end(); ++itr) { os << "(" << itr->first << ", " << itr->second << "), "; } return os << "}"; } template <class t> ostream &operator<<(ostream &os, const set<t> &m) { os << "{"; for (auto itr = m.begin(); itr != m.end(); ++itr) { os << *itr << ", "; } return os << "}"; } template <class t> ostream &operator<<(ostream &os, const multiset<t> &m) { os << "{"; for (auto itr = m.begin(); itr != m.end(); ++itr) { os << *itr << ", "; } return os << "}"; } const ll LLMAX = numeric_limits<long long>::max() / 3; const double DMAX = numeric_limits<double>::max() / 3; const double PI = 3.141592653589793; // const ll MOD = 1e9 + 7; const ll MOD = 998244353; template <std::int_fast64_t Modulus> class modint { using i64 = std::int_fast64_t; public: i64 a; constexpr modint(const i64 x = 0) noexcept : a(x % Modulus) {} constexpr i64 &value() noexcept { return a; } constexpr const i64 &value() const noexcept { return a; } constexpr modint operator+(const modint rhs) const noexcept { return modint(*this) += rhs; } constexpr modint operator-(const modint rhs) const noexcept { return modint(*this) -= rhs; } constexpr modint operator*(const modint rhs) const noexcept { return modint(*this) *= rhs; } constexpr modint operator/(const modint rhs) const noexcept { return modint(*this) /= rhs; } constexpr modint &operator+=(const modint rhs) noexcept { a += rhs.a; if (a >= Modulus) { a -= Modulus; } return *this; } constexpr modint &operator-=(const modint rhs) noexcept { if (a < rhs.a) { a += Modulus; } a -= rhs.a; return *this; } constexpr modint &operator*=(const modint rhs) noexcept { a = a * rhs.a % Modulus; return *this; } constexpr modint &operator/=(modint rhs) noexcept { i64 exp = Modulus - 2; while (exp) { if (exp % 2) { *this *= rhs; } rhs *= rhs; exp /= 2; } return *this; } }; template <std::int_fast64_t Modulus> ostream &operator<<(ostream &os, const modint<Modulus> &m) { return os << (m.a + Modulus) % Modulus; } typedef modint<MOD> mod; typedef vector<mod> vm; typedef vector<vm> vvm; typedef vector<vvm> vvvm; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } void No() { cout << "No" << endl; } void Yes() { cout << "Yes" << endl; } void NO() { cout << "NO" << endl; } void YES() { cout << "YES" << endl; } vector<ll> fac(1e6 + 1); // n!(mod M) vector<ll> ifac(1e6 + 1); // k!^{M-2} (mod ll mpow(ll x, ll n) { // x^n(mod M) ←普通にpow(x,n)では溢れてしまうため,随時mod計算 ll ans = 1; while (n != 0) { if (n & 1) ans = ans * x % MOD; x = x * x % MOD; n = n >> 1; } return ans; } ll comb(ll a, ll b) { // aCbをmod計算 if (a == 0 && b == 0) return 1; if (a < b || a < 0) return 0; ll tmp = ifac[a - b] * ifac[b] % MOD; return tmp * fac[a] % MOD; } void pre_calc_comb() { fac[0] = 1; ifac[0] = 1; for (ll i = 0; i < 1e6; i++) { fac[i + 1] = fac[i] * (i + 1) % MOD; // n!(mod M) ifac[i + 1] = ifac[i] * mpow(i + 1, MOD - 2) % MOD; // k!^{M-2} (mod M) ←累乗にmpowを採用 } } template <class T> class SegTree { int n; vector<T> data; T def; function<T(T, T)> operation; function<T(T, T)> update; T _query(int a, int b, int k, int l, int r) { if (r <= a || b <= l) return def; if (a <= l && r <= b) return data[k]; else { T c1 = _query(a, b, 2 * k + 1, l, (l + r) / 2); T c2 = _query(a, b, 2 * k + 2, (l + r) / 2, r); return operation(c1, c2); } } public: SegTree(size_t _n, T _def, function<T(T, T)> _operation, function<T(T, T)> _update) : def(_def), operation(_operation), update(_update) { n = 1; while (n < _n) { n *= 2; } data = vector<T>(2 * n - 1, def); } void change(int i, T x) { i += n - 1; data[i] = update(data[i], x); while (i > 0) { i = (i - 1) / 2; data[i] = operation(data[i * 2 + 1], data[i * 2 + 2]); } } T query(int a, int b) { return _query(a, b, 0, 0, n); } T operator[](int i) { return data[i + n - 1]; } }; vector<ll> divisor(ll n) { vector<ll> ret; for (ll i = 1; i * i <= n; i++) { if (n % i == 0) { ret.push_back(i); if (i * i != n) ret.push_back(n / i); } } sort(begin(ret), end(ret)); return (ret); } /* SegTree<ll> st(N, LLMAX, // a: left child, b: right child [](ll a, ll b) {return min(a, b); }, // d: old, x: query [](ll d, ll x) {return x; }); // */ ll gcd(ll a, ll b) { if (a == 0) return b; if (b == 0) return a; if (a % b == 0) { return (b); } else { return (gcd(b, a % b)); } } ll N, M, K, Q; ll ans = 0; ll H, W; void solveD() { cin >> N; vpii VW(N); rep(i, N) { ll v, w; cin >> v >> w; VW[i] = mp(v, w); } cin >> Q; vpii VL(Q); ll ml = 0; ll M = (1 << 10) - 1; rep(i, Q) { ll v, l; cin >> v >> l; chmax(ml, l); VL[i] = mp(v, l); } vvi dp(M + 1, vi(ml + 1, 0)); repa(i, 1, M + 1) { pii vw = VW[i - 1]; ll value = vw.first; ll weight = vw.second; rep(w, ml + 1) { if (w >= weight) { dp[i][w] = max(dp[i / 2][w - weight] + value, dp[i / 2][w]); } else { dp[i][w] = dp[i / 2][w]; } } } rep(q, Q) { pii vl = VL[q]; ll v = vl.first; ll l = vl.second; vi x(0); while (v > M) { x.pb(v); v /= 2; } ll maxValue = 0; ll xs = x.size(); rep(bit, 1 << xs) { ll value = 0; ll weight = 0; rep(i, xs) { if (bit & (1 << i)) { value += VW[x[i] - 1].first; weight += VW[x[i] - 1].second; } } if (l >= weight) { chmax(maxValue, dp[v][l - weight] + value); } } cout << maxValue << '\n'; } } int main() { ios::sync_with_stdio(false); cin.tie(0); solveD(); return 0; }
replace
303
304
303
304
TLE
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<ll, ll> pll; typedef pair<ll, int> pli; typedef pair<int, int> pii; typedef pair<ll, ld> pld; typedef pair<pii, int> ppiii; typedef pair<pii, ll> ppiil; typedef pair<pll, ll> pplll; typedef pair<pli, int> pplii; typedef vector<vector<ll>> vvl; typedef vector<vector<int>> vvi; typedef vector<vector<pll>> vvpll; #define rep(i, a, b) for (ll i = (a); i < (b); i++) #define rrep(i, a, b) for (ll i = (a); i > (b); i--) #define pb push_back #define tostr to_string #define mkp make_pair const ll INF = 1e18; const ll MOD = 1e9 + 7; void print(ld out) { cout << fixed << setprecision(12) << out << '\n'; } template <typename T> void print(T out) { cout << out << '\n'; } template <typename T1, typename T2> void print(pair<T1, T2> out) { cout << out.first << ' ' << out.second << '\n'; } template <typename T> void print(vector<T> A) { rep(i, 0, A.size()) { cout << A[i]; cout << (i == A.size() - 1 ? '\n' : ' '); } } template <typename T> void print(set<T> S) { vector<T> A(S.begin(), S.end()); print(A); } template <typename T> inline bool chmax(T &x, T y) { return (y > x) ? x = y, true : false; } template <typename T> inline bool chmin(T &x, T y) { return (y < x) ? x = y, true : false; } ll sum(vector<ll> A) { ll res = 0; for (ll a : A) res += a; return res; } ll max(vector<ll> A) { ll res = -INF; for (ll a : A) chmax(res, a); return res; } ll min(vector<ll> A) { ll res = INF; for (ll a : A) chmin(res, a); return res; } ll toint(string s) { ll res = 0; for (char c : s) { res *= 10; res += (c - '0'); } return res; } int toint(char c) { return c - '0'; } char tochar(int i) { return '0' + i; } inline ll pow(int x, ll n) { ll res = 1; rep(_, 0, n) res *= x; return res; } inline ll pow(ll x, ll n, int mod) { ll res = 1; while (n > 0) { if (n & 1) { res = (res * x) % mod; } x = (x * x) % mod; n >>= 1; } return res; } inline ll floor(ll a, ll b) { if (a < 0) { return (a - b + 1) / b; } else { return a / b; } } inline ll ceil(ll a, ll b) { if (a >= 0) { return (a + b - 1) / b; } else { return a / b; } } int popcount(ll S) { return __builtin_popcountll(S); } ll gcd(ll a, ll b) { return __gcd(a, b); } ll N, Q; const ll M = 1 << 9; const ll MAXW = 100000; vector<int> V, W, par; vvl nodes; int dp[M + 1][MAXW + 1]; void dfs(ll u, ll prev, ll depth) { if (depth == M) return; rep(w, 0, MAXW + 1) { chmax(dp[u + 1][w], dp[prev + 1][w]); if (w + W[u] <= MAXW) { chmax(dp[u + 1][w + W[u]], dp[prev + 1][w] + V[u]); } } for (ll v : nodes[u]) { if (prev == v) continue; dfs(v, u, depth + 1); } return; } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> N; V.resize(N); W.resize(N); par.resize(N); nodes.resize(N); rep(i, 0, N) cin >> V[i] >> W[i]; ll v; par[0] = -1; rep(u, 2, N + 1) { v = u / 2; nodes[u - 1].pb(v - 1); nodes[v - 1].pb(u - 1); par[u - 1] = v - 1; } dfs(0, -1, 0); cin >> Q; ll x, L, cur, ans, bitln, w; vector<int> li; rep(_, 0, Q) { cin >> x >> L; x--; li.clear(); cur = x; while (cur != -1) { li.pb(cur); cur = par[cur]; } if (li.size() <= 9) { ans = dp[x + 1][L]; print(ans); } else { ans = 0; bitln = li.size() - 9; rep(bit, 0, 1 << bitln) { v = w = 0; rep(i, 0, bitln) { if (bit >> i & 1) { v += V[li[i]]; w += W[li[i]]; } } if (w > L) continue; chmax(ans, v + dp[li[bitln] + 1][L - w]); } print(ans); } } return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<ll, ll> pll; typedef pair<ll, int> pli; typedef pair<int, int> pii; typedef pair<ll, ld> pld; typedef pair<pii, int> ppiii; typedef pair<pii, ll> ppiil; typedef pair<pll, ll> pplll; typedef pair<pli, int> pplii; typedef vector<vector<ll>> vvl; typedef vector<vector<int>> vvi; typedef vector<vector<pll>> vvpll; #define rep(i, a, b) for (ll i = (a); i < (b); i++) #define rrep(i, a, b) for (ll i = (a); i > (b); i--) #define pb push_back #define tostr to_string #define mkp make_pair const ll INF = 1e18; const ll MOD = 1e9 + 7; void print(ld out) { cout << fixed << setprecision(12) << out << '\n'; } template <typename T> void print(T out) { cout << out << '\n'; } template <typename T1, typename T2> void print(pair<T1, T2> out) { cout << out.first << ' ' << out.second << '\n'; } template <typename T> void print(vector<T> A) { rep(i, 0, A.size()) { cout << A[i]; cout << (i == A.size() - 1 ? '\n' : ' '); } } template <typename T> void print(set<T> S) { vector<T> A(S.begin(), S.end()); print(A); } template <typename T> inline bool chmax(T &x, T y) { return (y > x) ? x = y, true : false; } template <typename T> inline bool chmin(T &x, T y) { return (y < x) ? x = y, true : false; } ll sum(vector<ll> A) { ll res = 0; for (ll a : A) res += a; return res; } ll max(vector<ll> A) { ll res = -INF; for (ll a : A) chmax(res, a); return res; } ll min(vector<ll> A) { ll res = INF; for (ll a : A) chmin(res, a); return res; } ll toint(string s) { ll res = 0; for (char c : s) { res *= 10; res += (c - '0'); } return res; } int toint(char c) { return c - '0'; } char tochar(int i) { return '0' + i; } inline ll pow(int x, ll n) { ll res = 1; rep(_, 0, n) res *= x; return res; } inline ll pow(ll x, ll n, int mod) { ll res = 1; while (n > 0) { if (n & 1) { res = (res * x) % mod; } x = (x * x) % mod; n >>= 1; } return res; } inline ll floor(ll a, ll b) { if (a < 0) { return (a - b + 1) / b; } else { return a / b; } } inline ll ceil(ll a, ll b) { if (a >= 0) { return (a + b - 1) / b; } else { return a / b; } } int popcount(ll S) { return __builtin_popcountll(S); } ll gcd(ll a, ll b) { return __gcd(a, b); } ll N, Q; const ll M = 1 << 9; const ll MAXW = 100000; vector<int> V, W, par; vvl nodes; int dp[M + 1][MAXW + 1]; void dfs(ll u, ll prev, ll depth) { if (depth == 9) return; rep(w, 0, MAXW + 1) { chmax(dp[u + 1][w], dp[prev + 1][w]); if (w + W[u] <= MAXW) { chmax(dp[u + 1][w + W[u]], dp[prev + 1][w] + V[u]); } } for (ll v : nodes[u]) { if (prev == v) continue; dfs(v, u, depth + 1); } return; } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> N; V.resize(N); W.resize(N); par.resize(N); nodes.resize(N); rep(i, 0, N) cin >> V[i] >> W[i]; ll v; par[0] = -1; rep(u, 2, N + 1) { v = u / 2; nodes[u - 1].pb(v - 1); nodes[v - 1].pb(u - 1); par[u - 1] = v - 1; } dfs(0, -1, 0); cin >> Q; ll x, L, cur, ans, bitln, w; vector<int> li; rep(_, 0, Q) { cin >> x >> L; x--; li.clear(); cur = x; while (cur != -1) { li.pb(cur); cur = par[cur]; } if (li.size() <= 9) { ans = dp[x + 1][L]; print(ans); } else { ans = 0; bitln = li.size() - 9; rep(bit, 0, 1 << bitln) { v = w = 0; rep(i, 0, bitln) { if (bit >> i & 1) { v += V[li[i]]; w += W[li[i]]; } } if (w > L) continue; chmax(ans, v + dp[li[bitln] + 1][L - w]); } print(ans); } } return 0; }
replace
120
121
120
121
-11
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; // type alias typedef long long LL; typedef pair<int, int> II; typedef tuple<int, int, int> III; typedef vector<int> VI; typedef vector<string> VS; typedef unordered_map<int, int> MAPII; typedef unordered_set<int> SETI; template <class T> using VV = vector<vector<T>>; // minmax template <class T> inline T SMIN(T &a, const T b) { return a = (a > b) ? b : a; } template <class T> inline T SMAX(T &a, const T b) { return a = (a < b) ? b : a; } // repetition #define FORE(i, a, b) for (int i = (a); i <= (b); ++i) #define REPE(i, n) for (int i = 0; i <= (n); ++i) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) for (int i = 0; i < (n); ++i) #define FORR(x, arr) for (auto &x : arr) #define SZ(a) int((a).size()) // collection #define ALL(c) (c).begin(), (c).end() // DP #define MINUS(dp) memset(dp, -1, sizeof(dp)) #define ZERO(dp) memset(dp, 0, sizeof(dp)) // stdout #define println(args...) fprintf(stdout, ##args), putchar('\n'); // debug cerr template <class Iter> void __kumaerrc(Iter begin, Iter end) { for (; begin != end; ++begin) { cerr << *begin << ','; } cerr << endl; } void __kumaerr(istream_iterator<string> it) { (void)it; cerr << endl; } template <typename T, typename... Args> void __kumaerr(istream_iterator<string> it, T a, Args... args) { cerr << *it << "=" << a << ", ", __kumaerr(++it, args...); } template <typename S, typename T> std::ostream &operator<<(std::ostream &_os, const std::pair<S, T> &_p) { return _os << "{" << _p.first << ',' << _p.second << "}"; } #define __KUMATRACE__ true #ifdef __KUMATRACE__ #define dump(args...) \ { \ string _s = #args; \ replace(_s.begin(), _s.end(), ',', ' '); \ stringstream _ss(_s); \ istream_iterator<string> _it(_ss); \ __kumaerr(_it, args); \ } #define dumpc(ar) \ { \ cerr << #ar << ": "; \ FORR(x, (ar)) { cerr << x << ','; } \ cerr << endl; \ } #define dumpC(beg, end) \ { \ cerr << "~" << #end << ": "; \ __kumaerrc(beg, end); \ } #else #define dump(args...) #define dumpc(ar) #define dumpC(beg, end) #endif // $ cp-batch KnapsackQueriesOnATree | diff KnapsackQueriesOnATree.out - // $ g++ -std=c++14 -Wall -O2 -D_GLIBCXX_DEBUG -fsanitize=address // KnapsackQueriesOnATree.cpp && ./a.out /* 6/13/2020 5:57-6:10 give up 6/14/2020 14:10-14:24, 15:15-18:15 WA https://img.atcoder.jp/tokiomarine2020/editorial.pdf https://youtu.be/Kjk26wgMSQ8?t=2286 https://docs.google.com/document/d/1Yq384PEooRVsmlzB103YMLWwE_JhPN8AbxZagNrF_vY/edit#bookmark=id.tb0msy32svc9 https://twitter.com/satanic0258/status/1271807919785295872 https://twitter.com/kyort0n/status/1271851466064400384 https://twitter.com/chokudai/status/1271808513593929729 https://twitter.com/kyopro_friends/status/1271807533762531328 https://twitter.com/ei1333/status/1271806944735490052 https://twitter.com/semiexp/status/1271805208650149888 https://twitter.com/maspy_stars/status/1271805358801997825 https://twitter.com/yosupot/status/1271805134150881282 https://twitter.com/HIR180/status/1271804701663625216 https://ngtkana.growi.cloud/solutions/contests/tokiomarine2020 https://hir180.hateblo.jp/entry/2020/06/14/132815 */ const int MAX_N = (1 << 18) + 1, MAX_W = 1e5 + 1; LL V[MAX_N]; int W[MAX_N]; int N, Q; const int midd = 9; LL dp[1 << 10][MAX_W]; void dfs1(int i, int d) { if (d > midd || i > N) return; // dump(i,d); REP(w, MAX_W) { LL pval = i == 0 ? 0 : dp[i / 2][w]; if (w + W[i] < MAX_W) SMAX(dp[i][w + W[i]], pval + V[i]); SMAX(dp[i][w], pval); } FORE(c, 2 * i, 2 * i + 1) dfs1(c, d + 1); } int midroot(int i) { while (i >= (1 << midd)) i >>= 1; return i; } const LL Inf = 1e17; LL dfs2(int i, LL cur, int w, int L, int T, int pos) { if (w > L) return -Inf; if (i > T) { LL res = dp[midroot(i)][L - w] + cur; if (res == 0) { dump(i, cur, w, L, midroot(i), dp[midroot(i)][L - w]); } return dp[midroot(i)][L - w] + cur; } LL res = -Inf; int c = 2 * i + ((T >> pos) & 1); // dump(i,2*i,(T>>pos)&1,c,T); LL a = dfs2(c, cur, w, L, T, pos - 1), b = dfs2(c, cur + V[i], w + W[i], L, T, pos - 1); SMAX(res, max(a, b)); return res; } void solve() { dfs1(1, 1); while (Q--) { int u, L; cin >> u >> L; LL res = 0; if (u < (1 << midd)) { // dump(u,L,dp[u][L]); res = dp[u][L]; } else { int maxd = 0; int uu = u; while (uu > 0) maxd++, uu >>= 1; int pos = maxd - midd - 1; int c = 2 * midroot(u) + ((u >> pos) & 1); // dump(u,c); res = dfs2(c, 0, 0, L, u, pos - 1); } cout << res << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout << setprecision(12) << fixed; cin >> N; REP(i, N) cin >> V[i + 1] >> W[i + 1]; cin >> Q; solve(); return 0; }
#include <bits/stdc++.h> using namespace std; // type alias typedef long long LL; typedef pair<int, int> II; typedef tuple<int, int, int> III; typedef vector<int> VI; typedef vector<string> VS; typedef unordered_map<int, int> MAPII; typedef unordered_set<int> SETI; template <class T> using VV = vector<vector<T>>; // minmax template <class T> inline T SMIN(T &a, const T b) { return a = (a > b) ? b : a; } template <class T> inline T SMAX(T &a, const T b) { return a = (a < b) ? b : a; } // repetition #define FORE(i, a, b) for (int i = (a); i <= (b); ++i) #define REPE(i, n) for (int i = 0; i <= (n); ++i) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) for (int i = 0; i < (n); ++i) #define FORR(x, arr) for (auto &x : arr) #define SZ(a) int((a).size()) // collection #define ALL(c) (c).begin(), (c).end() // DP #define MINUS(dp) memset(dp, -1, sizeof(dp)) #define ZERO(dp) memset(dp, 0, sizeof(dp)) // stdout #define println(args...) fprintf(stdout, ##args), putchar('\n'); // debug cerr template <class Iter> void __kumaerrc(Iter begin, Iter end) { for (; begin != end; ++begin) { cerr << *begin << ','; } cerr << endl; } void __kumaerr(istream_iterator<string> it) { (void)it; cerr << endl; } template <typename T, typename... Args> void __kumaerr(istream_iterator<string> it, T a, Args... args) { cerr << *it << "=" << a << ", ", __kumaerr(++it, args...); } template <typename S, typename T> std::ostream &operator<<(std::ostream &_os, const std::pair<S, T> &_p) { return _os << "{" << _p.first << ',' << _p.second << "}"; } #define __KUMATRACE__ true #ifdef __KUMATRACE__ #define dump(args...) \ { \ string _s = #args; \ replace(_s.begin(), _s.end(), ',', ' '); \ stringstream _ss(_s); \ istream_iterator<string> _it(_ss); \ __kumaerr(_it, args); \ } #define dumpc(ar) \ { \ cerr << #ar << ": "; \ FORR(x, (ar)) { cerr << x << ','; } \ cerr << endl; \ } #define dumpC(beg, end) \ { \ cerr << "~" << #end << ": "; \ __kumaerrc(beg, end); \ } #else #define dump(args...) #define dumpc(ar) #define dumpC(beg, end) #endif // $ cp-batch KnapsackQueriesOnATree | diff KnapsackQueriesOnATree.out - // $ g++ -std=c++14 -Wall -O2 -D_GLIBCXX_DEBUG -fsanitize=address // KnapsackQueriesOnATree.cpp && ./a.out /* 6/13/2020 5:57-6:10 give up 6/14/2020 14:10-14:24, 15:15-18:15 WA https://img.atcoder.jp/tokiomarine2020/editorial.pdf https://youtu.be/Kjk26wgMSQ8?t=2286 https://docs.google.com/document/d/1Yq384PEooRVsmlzB103YMLWwE_JhPN8AbxZagNrF_vY/edit#bookmark=id.tb0msy32svc9 https://twitter.com/satanic0258/status/1271807919785295872 https://twitter.com/kyort0n/status/1271851466064400384 https://twitter.com/chokudai/status/1271808513593929729 https://twitter.com/kyopro_friends/status/1271807533762531328 https://twitter.com/ei1333/status/1271806944735490052 https://twitter.com/semiexp/status/1271805208650149888 https://twitter.com/maspy_stars/status/1271805358801997825 https://twitter.com/yosupot/status/1271805134150881282 https://twitter.com/HIR180/status/1271804701663625216 https://ngtkana.growi.cloud/solutions/contests/tokiomarine2020 https://hir180.hateblo.jp/entry/2020/06/14/132815 */ const int MAX_N = (1 << 18) + 1, MAX_W = 1e5 + 1; LL V[MAX_N]; int W[MAX_N]; int N, Q; const int midd = 10; LL dp[1 << (midd + 1)][MAX_W]; void dfs1(int i, int d) { if (d > midd || i > N) return; // dump(i,d); REP(w, MAX_W) { LL pval = i == 0 ? 0 : dp[i / 2][w]; if (w + W[i] < MAX_W) SMAX(dp[i][w + W[i]], pval + V[i]); SMAX(dp[i][w], pval); } FORE(c, 2 * i, 2 * i + 1) dfs1(c, d + 1); } int midroot(int i) { while (i >= (1 << midd)) i >>= 1; return i; } const LL Inf = 1e17; LL dfs2(int i, LL cur, int w, int L, int T, int pos) { if (w > L) return -Inf; if (i > T) { LL res = dp[midroot(i)][L - w] + cur; if (res == 0) { dump(i, cur, w, L, midroot(i), dp[midroot(i)][L - w]); } return dp[midroot(i)][L - w] + cur; } LL res = -Inf; int c = 2 * i + ((T >> pos) & 1); // dump(i,2*i,(T>>pos)&1,c,T); LL a = dfs2(c, cur, w, L, T, pos - 1), b = dfs2(c, cur + V[i], w + W[i], L, T, pos - 1); SMAX(res, max(a, b)); return res; } void solve() { dfs1(1, 1); while (Q--) { int u, L; cin >> u >> L; LL res = 0; if (u < (1 << midd)) { // dump(u,L,dp[u][L]); res = dp[u][L]; } else { int maxd = 0; int uu = u; while (uu > 0) maxd++, uu >>= 1; int pos = maxd - midd - 1; int c = 2 * midroot(u) + ((u >> pos) & 1); // dump(u,c); res = dfs2(c, 0, 0, L, u, pos - 1); } cout << res << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout << setprecision(12) << fixed; cin >> N; REP(i, N) cin >> V[i + 1] >> W[i + 1]; cin >> Q; solve(); return 0; }
replace
118
120
118
120
TLE
p02648
C++
Time Limit Exceeded
#include <algorithm> #include <iostream> #include <map> #include <math.h> #include <queue> #include <string> #include <vector> using namespace std; int n, q; int v[(1 << 18) + 1], w[(1 << 18) + 1]; int dp[550][100001]; int inf = -1; int vq, wq; int dfs(int i, int weight) { // cout << i << " " << weight << " " << dp[i][weight] << endl; int res = 0; if (i < 550 && weight <= 100000) { if (dp[i][weight] != inf) return dp[i][weight]; } if (i == 0) { res = 0; } else if (weight < w[i]) { res = dfs(i / 2, weight); } else { res = max(dfs(i / 2, weight), dfs(i / 2, weight - w[i]) + v[i]); } if (i < 550 && weight <= 100000) dp[i][weight] = res; return res; } int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> v[i] >> w[i]; } for (int i = 0; i < 550; i++) { for (int j = 0; j <= 100000; j++) { dp[i][j] = inf; } } cin >> q; for (int j = 0; j < q; j++) { cin >> vq >> wq; cout << dfs(vq, wq) << endl; } return 0; }
#include <algorithm> #include <iostream> #include <map> #include <math.h> #include <queue> #include <string> #include <vector> using namespace std; int n, q; int v[(1 << 18) + 1], w[(1 << 18) + 1]; int dp[550][100001]; int inf = -1; int vq, wq; int dfs(int i, int weight) { // cout << i << " " << weight << " " << dp[i][weight] << endl; int res = 0; if (i < 550 && weight <= 100000) { if (dp[i][weight] != inf) return dp[i][weight]; } if (i == 0) { res = 0; } else if (weight < w[i]) { res = dfs(i / 2, weight); } else { res = max(dfs(i / 2, weight), dfs(i / 2, weight - w[i]) + v[i]); } if (i < 550 && weight <= 100000) dp[i][weight] = res; return res; } int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> v[i] >> w[i]; } for (int i = 0; i < 550; i++) { for (int j = 0; j <= 100000; j++) { dp[i][j] = inf; } } for (int j = 0; j < 512; j++) { for (int k = 0; k <= 100000; k++) { dfs(j, k); } } cin >> q; for (int j = 0; j < q; j++) { cin >> vq >> wq; cout << dfs(vq, wq) << endl; } return 0; }
insert
46
46
46
52
TLE
p02648
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; vector<pair<int, int>> Prepare(const vector<pair<int, int>> &a, int bound) { const int n = static_cast<int>(a.size()); vector<pair<int, int>> result; for (int i = 0; i < (1 << n); ++i) { int x = 0, y = 0; for (int j = 0; j < n; ++j) { if (~i & (1 << j)) continue; x += a[j].first; y += a[j].second; } if (x > bound) continue; result.emplace_back(x, y); } sort(result.begin(), result.end()); int size = 1; for (int i = 1; i < (int)result.size(); ++i) { if (result[i].second <= result[size - 1].second) continue; result[size] = result[i]; ++size; } result.resize(size); return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<pair<int, int>> a(n); for (auto &e : a) cin >> e.second >> e.first; int s = min(512, n); vector<vector<pair<int, int>>> memo(s + 5); for (int i = 1; i < s; ++i) { int v = i; vector<pair<int, int>> b; while (v > 0) { b.push_back(a[v - 1]); v /= 2; } memo[i] = Prepare(b, 100000); } int q; cin >> q; for (int i = 0; i < q; ++i) { int v, bound; cin >> v >> bound; vector<pair<int, int>> b, x, y; while (v > 0) { if (v < s) { y = memo[v]; break; } b.push_back(a[v - 1]); v /= 2; } x = Prepare(b, bound); while (y.back().first > bound) y.pop_back(); const int n = static_cast<int>(x.size()); const int m = static_cast<int>(y.size()); int result = max(x.back().second, y.back().second); for (int i = 0, j = m - 1; i < n; ++i) { while (j >= 0 && x[i].first + y[j].first > bound) --j; if (j >= 0) result = max(result, x[i].second + y[j].second); } cout << result << '\n'; } }
#include <bits/stdc++.h> using namespace std; vector<pair<int, int>> Prepare(const vector<pair<int, int>> &a, int bound) { const int n = static_cast<int>(a.size()); vector<pair<int, int>> result; for (int i = 0; i < (1 << n); ++i) { int x = 0, y = 0; for (int j = 0; j < n; ++j) { if (~i & (1 << j)) continue; x += a[j].first; y += a[j].second; } if (x > bound) continue; result.emplace_back(x, y); } sort(result.begin(), result.end()); int size = 1; for (int i = 1; i < (int)result.size(); ++i) { if (result[i].second <= result[size - 1].second) continue; result[size] = result[i]; ++size; } result.resize(size); return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<pair<int, int>> a(n); for (auto &e : a) cin >> e.second >> e.first; int s = min(1024, n + 1); vector<vector<pair<int, int>>> memo(s + 5); for (int i = 1; i < s; ++i) { int v = i; vector<pair<int, int>> b; while (v > 0) { b.push_back(a[v - 1]); v /= 2; } memo[i] = Prepare(b, 100000); } int q; cin >> q; for (int i = 0; i < q; ++i) { int v, bound; cin >> v >> bound; vector<pair<int, int>> b, x, y; while (v > 0) { if (v < s) { y = memo[v]; break; } b.push_back(a[v - 1]); v /= 2; } x = Prepare(b, bound); while (y.back().first > bound) y.pop_back(); const int n = static_cast<int>(x.size()); const int m = static_cast<int>(y.size()); int result = max(x.back().second, y.back().second); for (int i = 0, j = m - 1; i < n; ++i) { while (j >= 0 && x[i].first + y[j].first > bound) --j; if (j >= 0) result = max(result, x[i].second + y[j].second); } cout << result << '\n'; } }
replace
45
46
45
46
0
p02648
C++
Runtime Error
// #pragma GCC optimize("Ofast") // #pragma GCC optimize ("unroll-loops") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma warning(disable : 4786) #pragma warning(disable : 4996) #include <algorithm> #include <array> #include <assert.h> #include <bitset> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <functional> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> using namespace std; #define sim template <class c #define ris return *this #define dor > debug &operator<< #define eni(x) \ sim > typename enable_if<sizeof dud<c>(0) x 1, debug &>::type operator<<( \ c i) { sim > struct rge { c b, e; }; sim > rge<c> range(c i, c j) { return rge<c>{i, j}; } sim > auto dud(c *x) -> decltype(cerr << *x, 0); sim > char dud(...); struct debug { #ifdef LOCAL ~debug() { cerr << endl; } template <class c> typename enable_if<sizeof dud<c>(0) != 1, debug &>::type operator<<(c i) { cerr << boolalpha << i; return *this; } template <class c, int = 0> typename enable_if<sizeof dud<c>(0) == 1, debug &>::type operator<<(c i) { return *this << range(begin(i), end(i)); } sim, class b dor(pair<b, c> d) { ris << "(" << d.first << ", " << d.second << ")"; } sim dor(rge<c> d) { *this << "["; for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; ris << "]"; } #else sim dor(const c &) { ris; } #endif }; #define watch(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " #define MEM(a, b) memset(a, (b), sizeof(a)) #define CLR(a) memset(a, 0, sizeof(a)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define ABS(X) ((X) > 0 ? (X) : (-(X))) #define S(X) ((X) * (X)) #define SZ(V) (int)V.size() #define FORN(i, n) for (int i = 0; i < n; i++) #define FORAB(i, a, b) for (int i = a; i <= b; i++) #define ALL(V) V.begin(), V.end() #define IN(A, B, C) ((B) <= (A) && (A) <= (C)) #define AIN(A, B, C) assert(IN(A, B, C)) typedef long long int LL; // typedef __int128 LLL; typedef long long LLL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; typedef pair<double, double> PDD; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<PLL> VPL; typedef vector<PII> VP; typedef vector<double> VD; typedef vector<vector<int>> VVI; typedef vector<string> VS; typedef long double ld; #define MAXN 1000006 // #define MAXN 1006 const LL MOD = 1000000007; // const LL MOD = 998244353; const LL INF = 2000000000000000001LL; // 2e18 + 1 VP V[1 << 10]; int v[(1 << 18) + 5], w[(1 << 18) + 5]; int n, q; void dfs(int at, int dep) { if (v[at] == 0) return; if (at == 1) { V[at].push_back({0, 0}); V[at].push_back({w[at], v[at]}); } else { for (auto &p : V[at / 2]) { V[at].push_back(p); V[at].push_back({p.first + w[at], p.second + v[at]}); } } sort(ALL(V[at])); int mx = 0; for (int i = 0; i < SZ(V[at]); i++) { mx = MAX(mx, V[at][i].second); V[at][i].second = mx; } dfs(at * 2, dep + 1); dfs(at * 2 + 1, dep + 1); } int Query(int v, int L) { if (L == 0) return 0; if (v < (1 << 10)) { auto iV = upper_bound(ALL(V[v]), PII({L + 1, -1})); iV--; return iV->second; } int x = Query(v / 2, L); int y = (L < w[v] ? 0 : Query(v / 2, L - w[v]) + ::v[v]); return MAX(x, y); } void solve(int ks) { scanf("%d", &n); FORAB(i, 1, n) scanf("%d %d", &v[i], &w[i]); dfs(1, 1); scanf("%d", &q); while (q--) { int v, L; scanf("%d %d", &v, &L); int ans = Query(v, L); printf("%d\n", ans); } } void gen() {} int main() { double start_time = clock(); #ifdef LOCAL freopen("C:\\Home\\ContestCodes\\sample.in", "r", stdin); // freopen("C:\\Home\\ContestCodes\\sample.in", "r", stdin); // freopen("out.out", "w", stdout); #endif gen(); if (0) { int T; scanf("%d", &T); // AIN(T, 1, 5000); for (int ks = 1; ks <= T; ks++) { solve(ks); if (ks % 1 == 0) fprintf(stderr, "%d done\n", ks); } } else { solve(0); } double end_time = clock(); fprintf(stderr, "Time = %lf\n", (end_time - start_time) / CLOCKS_PER_SEC); return 0; }
// #pragma GCC optimize("Ofast") // #pragma GCC optimize ("unroll-loops") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma warning(disable : 4786) #pragma warning(disable : 4996) #include <algorithm> #include <array> #include <assert.h> #include <bitset> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <functional> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> using namespace std; #define sim template <class c #define ris return *this #define dor > debug &operator<< #define eni(x) \ sim > typename enable_if<sizeof dud<c>(0) x 1, debug &>::type operator<<( \ c i) { sim > struct rge { c b, e; }; sim > rge<c> range(c i, c j) { return rge<c>{i, j}; } sim > auto dud(c *x) -> decltype(cerr << *x, 0); sim > char dud(...); struct debug { #ifdef LOCAL ~debug() { cerr << endl; } template <class c> typename enable_if<sizeof dud<c>(0) != 1, debug &>::type operator<<(c i) { cerr << boolalpha << i; return *this; } template <class c, int = 0> typename enable_if<sizeof dud<c>(0) == 1, debug &>::type operator<<(c i) { return *this << range(begin(i), end(i)); } sim, class b dor(pair<b, c> d) { ris << "(" << d.first << ", " << d.second << ")"; } sim dor(rge<c> d) { *this << "["; for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; ris << "]"; } #else sim dor(const c &) { ris; } #endif }; #define watch(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " #define MEM(a, b) memset(a, (b), sizeof(a)) #define CLR(a) memset(a, 0, sizeof(a)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define ABS(X) ((X) > 0 ? (X) : (-(X))) #define S(X) ((X) * (X)) #define SZ(V) (int)V.size() #define FORN(i, n) for (int i = 0; i < n; i++) #define FORAB(i, a, b) for (int i = a; i <= b; i++) #define ALL(V) V.begin(), V.end() #define IN(A, B, C) ((B) <= (A) && (A) <= (C)) #define AIN(A, B, C) assert(IN(A, B, C)) typedef long long int LL; // typedef __int128 LLL; typedef long long LLL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; typedef pair<double, double> PDD; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<PLL> VPL; typedef vector<PII> VP; typedef vector<double> VD; typedef vector<vector<int>> VVI; typedef vector<string> VS; typedef long double ld; #define MAXN 1000006 // #define MAXN 1006 const LL MOD = 1000000007; // const LL MOD = 998244353; const LL INF = 2000000000000000001LL; // 2e18 + 1 VP V[1 << 10]; int v[(1 << 18) + 5], w[(1 << 18) + 5]; int n, q; void dfs(int at, int dep) { if (v[at] == 0) return; if (dep == 11) return; if (at == 1) { V[at].push_back({0, 0}); V[at].push_back({w[at], v[at]}); } else { for (auto &p : V[at / 2]) { V[at].push_back(p); V[at].push_back({p.first + w[at], p.second + v[at]}); } } sort(ALL(V[at])); int mx = 0; for (int i = 0; i < SZ(V[at]); i++) { mx = MAX(mx, V[at][i].second); V[at][i].second = mx; } dfs(at * 2, dep + 1); dfs(at * 2 + 1, dep + 1); } int Query(int v, int L) { if (L == 0) return 0; if (v < (1 << 10)) { auto iV = upper_bound(ALL(V[v]), PII({L + 1, -1})); iV--; return iV->second; } int x = Query(v / 2, L); int y = (L < w[v] ? 0 : Query(v / 2, L - w[v]) + ::v[v]); return MAX(x, y); } void solve(int ks) { scanf("%d", &n); FORAB(i, 1, n) scanf("%d %d", &v[i], &w[i]); dfs(1, 1); scanf("%d", &q); while (q--) { int v, L; scanf("%d %d", &v, &L); int ans = Query(v, L); printf("%d\n", ans); } } void gen() {} int main() { double start_time = clock(); #ifdef LOCAL freopen("C:\\Home\\ContestCodes\\sample.in", "r", stdin); // freopen("C:\\Home\\ContestCodes\\sample.in", "r", stdin); // freopen("out.out", "w", stdout); #endif gen(); if (0) { int T; scanf("%d", &T); // AIN(T, 1, 5000); for (int ks = 1; ks <= T; ks++) { solve(ks); if (ks % 1 == 0) fprintf(stderr, "%d done\n", ks); } } else { solve(0); } double end_time = clock(); fprintf(stderr, "Time = %lf\n", (end_time - start_time) / CLOCKS_PER_SEC); return 0; }
insert
116
116
116
118
0
Time = 0.000112
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> #define ADD(a, b) a = (a + ll(b)) % mod #define MUL(a, b) a = (a * ll(b)) % mod #define MAX(a, b) a = max(a, b) #define MIN(a, b) a = min(a, b) #define rep(i, a, b) for (int i = int(a); i < int(b); i++) #define rer(i, a, b) for (int i = int(a) - 1; i >= int(b); i--) #define all(a) (a).begin(), (a).end() #define sz(v) (int)(v).size() #define pb push_back #define sec second #define fst first #define debug(fmt, ...) Debug(__LINE__, ":", fmt, ##__VA_ARGS__) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pi; typedef pair<ll, ll> pl; typedef pair<int, pi> ppi; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vl> mat; typedef complex<double> comp; void Debug() { cerr << '\n'; } template <class FIRST, class... REST> void Debug(FIRST arg, REST... rest) { cerr << arg << " "; Debug(rest...); } template <class T> ostream &operator<<(ostream &out, const vector<T> &v) { out << "["; if (!v.empty()) { rep(i, 0, sz(v) - 1) out << v[i] << ", "; out << v.back(); } out << "]"; return out; } template <class S, class T> ostream &operator<<(ostream &out, const pair<S, T> &v) { out << "(" << v.first << ", " << v.second << ")"; return out; } const int MAX_N = 500010; const int MAX_V = 100010; const double eps = 1e-6; const ll mod = 1000000007; const int inf = (1 << 30) - 1; const ll linf = 1LL << 60; const double PI = 3.14159265358979323846; mt19937 rng; // use it by rng() % mod, shuffle(all(vec), rng) /////////////////////////////////////////////////////////////////////////////////////////////////// const int B = (1 << 9) - 1; int V[MAX_N], W[MAX_N]; int N, Q; vector<pi> query[MAX_N]; // L, query num int dp[MAX_N]; int ans[MAX_N]; vector<pi> vw[20]; int dep(int v) { int res = 1; while (v != 0) { res++; v = (v - 1) / 2; } return res; } void loop(int v, int d) { if (v >= N) return; if (v < 9) { rep(i, 0, 100000 + 1) dp[i] = -inf; rep(bit, 0, (1 << (d + 1))) { int at = v; int val = 0, weight = 0; rep(i, 0, (d + 1)) { if ((bit & (1 << i))) { val += V[at]; weight += W[at]; } at = (at - 1) / 2; } if (weight <= 100000) MAX(dp[weight], val); } rep(i, 0, 100000) { MAX(dp[i + 1], dp[i]); } // debug(vi(dp, dp + 10)); } else { vw[d] = vw[d - 1]; rep(i, 0, sz(vw[d - 1])) { vw[d].pb(pi(vw[d - 1][i].fst + V[v], vw[d - 1][i].sec + W[v])); } } rep(i, 0, sz(query[v])) { int idx = query[v][i].sec; int l = query[v][i].fst; int res = 0; rep(j, 0, sz(vw[d])) { // debug(vw[d], query[v][i]); if (l - vw[d][j].sec >= 0) { MAX(res, vw[d][j].fst + dp[l - vw[d][j].sec]); } } ans[idx] = res; } loop(v * 2 + 1, d + 1); loop(v * 2 + 2, d + 1); } void solve() { cin >> N; rep(i, 0, N) { cin >> V[i] >> W[i]; } cin >> Q; rep(i, 0, Q) { int v, l; cin >> v >> l; v--; query[v].pb(pi(l, i)); } rep(i, 0, 20) { vw[i].pb(pi(0, 0)); } loop(0, 0); rep(i, 0, Q) { cout << ans[i] << "\n"; } } uint32_t rd() { uint32_t res; #ifdef __MINGW32__ asm volatile("rdrand %0" : "=a"(res)::"cc"); #else res = std::random_device()(); #endif return res; } int main() { #ifndef LOCAL ios::sync_with_stdio(false); cin.tie(0); #endif cout << fixed; cout.precision(20); cerr << fixed; cerr.precision(6); rng.seed(rd()); #ifdef LOCAL // freopen("in.txt", "wt", stdout); //for tester if (!freopen("in.txt", "rt", stdin)) return 1; #endif solve(); cerr << "Time: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; return 0; }
#include <bits/stdc++.h> #define ADD(a, b) a = (a + ll(b)) % mod #define MUL(a, b) a = (a * ll(b)) % mod #define MAX(a, b) a = max(a, b) #define MIN(a, b) a = min(a, b) #define rep(i, a, b) for (int i = int(a); i < int(b); i++) #define rer(i, a, b) for (int i = int(a) - 1; i >= int(b); i--) #define all(a) (a).begin(), (a).end() #define sz(v) (int)(v).size() #define pb push_back #define sec second #define fst first #define debug(fmt, ...) Debug(__LINE__, ":", fmt, ##__VA_ARGS__) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pi; typedef pair<ll, ll> pl; typedef pair<int, pi> ppi; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vl> mat; typedef complex<double> comp; void Debug() { cerr << '\n'; } template <class FIRST, class... REST> void Debug(FIRST arg, REST... rest) { cerr << arg << " "; Debug(rest...); } template <class T> ostream &operator<<(ostream &out, const vector<T> &v) { out << "["; if (!v.empty()) { rep(i, 0, sz(v) - 1) out << v[i] << ", "; out << v.back(); } out << "]"; return out; } template <class S, class T> ostream &operator<<(ostream &out, const pair<S, T> &v) { out << "(" << v.first << ", " << v.second << ")"; return out; } const int MAX_N = 500010; const int MAX_V = 100010; const double eps = 1e-6; const ll mod = 1000000007; const int inf = (1 << 30) - 1; const ll linf = 1LL << 60; const double PI = 3.14159265358979323846; mt19937 rng; // use it by rng() % mod, shuffle(all(vec), rng) /////////////////////////////////////////////////////////////////////////////////////////////////// const int B = (1 << 9) - 1; int V[MAX_N], W[MAX_N]; int N, Q; vector<pi> query[MAX_N]; // L, query num int dp[MAX_N]; int ans[MAX_N]; vector<pi> vw[20]; int dep(int v) { int res = 1; while (v != 0) { res++; v = (v - 1) / 2; } return res; } void loop(int v, int d) { if (v >= N) return; if (d < 9) { rep(i, 0, 100000 + 1) dp[i] = -inf; rep(bit, 0, (1 << (d + 1))) { int at = v; int val = 0, weight = 0; rep(i, 0, (d + 1)) { if ((bit & (1 << i))) { val += V[at]; weight += W[at]; } at = (at - 1) / 2; } if (weight <= 100000) MAX(dp[weight], val); } rep(i, 0, 100000) { MAX(dp[i + 1], dp[i]); } // debug(vi(dp, dp + 10)); } else { vw[d] = vw[d - 1]; rep(i, 0, sz(vw[d - 1])) { vw[d].pb(pi(vw[d - 1][i].fst + V[v], vw[d - 1][i].sec + W[v])); } } rep(i, 0, sz(query[v])) { int idx = query[v][i].sec; int l = query[v][i].fst; int res = 0; rep(j, 0, sz(vw[d])) { // debug(vw[d], query[v][i]); if (l - vw[d][j].sec >= 0) { MAX(res, vw[d][j].fst + dp[l - vw[d][j].sec]); } } ans[idx] = res; } loop(v * 2 + 1, d + 1); loop(v * 2 + 2, d + 1); } void solve() { cin >> N; rep(i, 0, N) { cin >> V[i] >> W[i]; } cin >> Q; rep(i, 0, Q) { int v, l; cin >> v >> l; v--; query[v].pb(pi(l, i)); } rep(i, 0, 20) { vw[i].pb(pi(0, 0)); } loop(0, 0); rep(i, 0, Q) { cout << ans[i] << "\n"; } } uint32_t rd() { uint32_t res; #ifdef __MINGW32__ asm volatile("rdrand %0" : "=a"(res)::"cc"); #else res = std::random_device()(); #endif return res; } int main() { #ifndef LOCAL ios::sync_with_stdio(false); cin.tie(0); #endif cout << fixed; cout.precision(20); cerr << fixed; cerr.precision(6); rng.seed(rd()); #ifdef LOCAL // freopen("in.txt", "wt", stdout); //for tester if (!freopen("in.txt", "rt", stdin)) return 1; #endif solve(); cerr << "Time: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; return 0; }
replace
73
74
73
74
TLE
p02648
C++
Time Limit Exceeded
// ----------------------------------- // author : MatsuTaku // country : Japan // created : 06/13/20 21:03:09 // ----------------------------------- #include <bits/stdc++.h> using namespace std; using ll = long long; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; struct Data { int v = 0, w = 0; }; vector<Data> ds(n + 1); for (int i = 0; i < n; i++) { int v, w; cin >> v >> w; ds[i + 1] = {v, w}; } int m = min(1 << 9, n); vector<vector<int>> dp(m + 1, vector<int>(1e5 + 1, -1)); dp[0][0] = 0; for (int t = 1; t <= m; t++) { dp[t] = dp[t / 2]; for (int s = 1e5; s >= ds[t].w; s--) { if (dp[t / 2][s - ds[t].w] == -1) continue; dp[t][s] = max(dp[t][s], dp[t / 2][s - ds[t].w] + ds[t].v); } } for (int t = 1; t <= m; t++) { for (int s = 1; s <= 1e5; s++) { dp[t][s] = max(dp[t][s], dp[t][s - 1]); } } int q; cin >> q; for (int i = 0; i < q; i++) { int v, l; cin >> v >> l; int f = 0; while (v >> f > m) { f++; } int ans = dp[v >> f][l]; if (v > m) { for (int mask = 1; mask < 1 << f; mask++) { int cv = 0, cw = 0; for (int j = 0; j < f; j++) { if ((mask & (1 << j)) == 0) continue; cv += ds[v >> (f - j - 1)].v; cw += ds[v >> (f - j - 1)].w; if (cw > l) break; } if (cw > l) continue; ans = max(ans, dp[v >> f][l - cw] + cv); } } cout << ans << endl; } return 0; }
// ----------------------------------- // author : MatsuTaku // country : Japan // created : 06/13/20 21:03:09 // ----------------------------------- #include <bits/stdc++.h> using namespace std; using ll = long long; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; struct Data { int v = 0, w = 0; }; vector<Data> ds(n + 1); for (int i = 0; i < n; i++) { int v, w; cin >> v >> w; ds[i + 1] = {v, w}; } int m = min(2 << 9, n); vector<vector<int>> dp(m + 1, vector<int>(1e5 + 1, -1)); dp[0][0] = 0; for (int t = 1; t <= m; t++) { dp[t] = dp[t / 2]; for (int s = 1e5; s >= ds[t].w; s--) { if (dp[t / 2][s - ds[t].w] == -1) continue; dp[t][s] = max(dp[t][s], dp[t / 2][s - ds[t].w] + ds[t].v); } } for (int t = 1; t <= m; t++) { for (int s = 1; s <= 1e5; s++) { dp[t][s] = max(dp[t][s], dp[t][s - 1]); } } int q; cin >> q; for (int i = 0; i < q; i++) { int v, l; cin >> v >> l; int f = 0; while (v >> f > m) { f++; } int ans = dp[v >> f][l]; if (v > m) { for (int mask = 1; mask < 1 << f; mask++) { int cv = 0, cw = 0; for (int j = 0; j < f; j++) { if ((mask & (1 << j)) == 0) continue; cv += ds[v >> (f - j - 1)].v; cw += ds[v >> (f - j - 1)].w; if (cw > l) break; } if (cw > l) continue; ans = max(ans, dp[v >> f][l - cw] + cv); } } cout << ans << endl; } return 0; }
replace
26
27
26
27
TLE
p02648
C++
Time Limit Exceeded
#pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; const int P = 1 << 2; const int INF = 1 << 22; int main() { int N; cin >> N; vector<int> V(N), W(N); for (int i = 0; i < N; i++) { cin >> V[i] >> W[i]; } int Q; cin >> Q; vector<int> query_v(Q); vector<int> query_L(Q); set<int> qv; for (int i = 0; i < Q; i++) { cin >> query_v[i] >> query_L[i]; qv.insert(query_v[i]); } vector<vector<pair<int, int>>> t2(N); for (int i = 0; i < N; i++) { vector<int> V2, W2; int v = i + 1; V2.push_back(V[i]); W2.push_back(W[i]); if (v < P) { while (v > 1) { v /= 2; V2.push_back(V[v - 1]); W2.push_back(W[v - 1]); } } else { if (!qv.count(v)) { continue; } while (v >= P * 2) { v /= 2; V2.push_back(V[v - 1]); W2.push_back(W[v - 1]); } } int cnt = V2.size(); vector<pair<int, int>> t; for (int j = 0; j < (1 << cnt); j++) { int v_t = 0; int w_t = 0; for (int k = 0; k < cnt; k++) { if ((j >> k) & 1) { v_t += V2[k]; w_t += W2[k]; } } t.emplace_back(w_t, v_t); } sort(t.begin(), t.end()); t2[i].push_back(t[0]); int cnt2 = t.size(); for (int j = 1; j < cnt2; j++) { if (t2[i].back().first == t[j].first) { t2[i].back().second = t[j].second; } else { if (t2[i].back().second < t[j].second) { t2[i].push_back(t[j]); } } } } /* for (int i = 0; i < N; i++){ cout << "i = " << i << endl; for (auto p : t2[i]){ cout << "(" << p.first << "," << p.second << ") "; } cout << endl; } */ for (int i = 0; i < Q; i++) { int v = query_v[i]; int L = query_L[i]; if (v < P) { auto itr = upper_bound(t2[v - 1].begin(), t2[v - 1].end(), make_pair(L, INF)) - 1; cout << (*itr).second << endl; } else { int w = v; while (w >= P) { w /= 2; } int ans = 0; for (auto p : t2[v - 1]) { if (L - p.first >= 0) { auto itr = upper_bound(t2[w - 1].begin(), t2[w - 1].end(), make_pair(L - p.first, INF)) - 1; ans = max(ans, p.second + (*itr).second); } } cout << ans << endl; } } }
#pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; const int P = 1 << 11; const int INF = 1 << 22; int main() { int N; cin >> N; vector<int> V(N), W(N); for (int i = 0; i < N; i++) { cin >> V[i] >> W[i]; } int Q; cin >> Q; vector<int> query_v(Q); vector<int> query_L(Q); set<int> qv; for (int i = 0; i < Q; i++) { cin >> query_v[i] >> query_L[i]; qv.insert(query_v[i]); } vector<vector<pair<int, int>>> t2(N); for (int i = 0; i < N; i++) { vector<int> V2, W2; int v = i + 1; V2.push_back(V[i]); W2.push_back(W[i]); if (v < P) { while (v > 1) { v /= 2; V2.push_back(V[v - 1]); W2.push_back(W[v - 1]); } } else { if (!qv.count(v)) { continue; } while (v >= P * 2) { v /= 2; V2.push_back(V[v - 1]); W2.push_back(W[v - 1]); } } int cnt = V2.size(); vector<pair<int, int>> t; for (int j = 0; j < (1 << cnt); j++) { int v_t = 0; int w_t = 0; for (int k = 0; k < cnt; k++) { if ((j >> k) & 1) { v_t += V2[k]; w_t += W2[k]; } } t.emplace_back(w_t, v_t); } sort(t.begin(), t.end()); t2[i].push_back(t[0]); int cnt2 = t.size(); for (int j = 1; j < cnt2; j++) { if (t2[i].back().first == t[j].first) { t2[i].back().second = t[j].second; } else { if (t2[i].back().second < t[j].second) { t2[i].push_back(t[j]); } } } } /* for (int i = 0; i < N; i++){ cout << "i = " << i << endl; for (auto p : t2[i]){ cout << "(" << p.first << "," << p.second << ") "; } cout << endl; } */ for (int i = 0; i < Q; i++) { int v = query_v[i]; int L = query_L[i]; if (v < P) { auto itr = upper_bound(t2[v - 1].begin(), t2[v - 1].end(), make_pair(L, INF)) - 1; cout << (*itr).second << endl; } else { int w = v; while (w >= P) { w /= 2; } int ans = 0; for (auto p : t2[v - 1]) { if (L - p.first >= 0) { auto itr = upper_bound(t2[w - 1].begin(), t2[w - 1].end(), make_pair(L - p.first, INF)) - 1; ans = max(ans, p.second + (*itr).second); } } cout << ans << endl; } } }
replace
5
6
5
6
TLE
p02648
C++
Time Limit Exceeded
#include "bits/stdc++.h" using namespace std; #define mod 1000000007 #define dom 998244353 #define all(c) begin(c), end(c) #define rep(i, n) repi(i, 0, n) #define repi(i, a, b) for (int i = (a); i < (b); i++) #define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--) template <typename T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <typename T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } #define long long long #define List vector #define var auto #define Count size() #define Length size() #define in : #define foreach for using pi = pair<int, int>; int dd[] = {0, 1, 0, -1, 0}; // →↓←↑ const int P = 1 << 8; const int Q = 1 << 9; int N; vector<int> V; vector<int> W; vector<vector<pi>> D; void mode4(int v, int L, vector<pi> Z) { int ans = 0; int K = Z.size(); for (int i = 0; i < 1 << K; i++) { int sw = 0, sv = 0; for (int j = 0; j < K; j++) { if (i >> j & 1) { sw += Z[j].first; sv += Z[j].second; } } if (sw <= L) { var q = pi(L - sw, INT_MAX / 3); // cout << D[0].size() << " " << v - P << endl; // var B = lower_bound(all(D[v - P]), make_pair(L - sw, INT_MAX)); // int pos = distance(D[v - P].begin(), B); // cout << pos << endl; int tv = (lower_bound(all(D[v - P]), make_pair(L - sw, INT_MAX)) - 1)->second; chmax(ans, sv + tv); } } cout << ans << "\n"; } void mode1(int v, int L) { vector<pi> Z; int j = v; while (j > 0) { Z.push_back(pi(W[j], V[j])); j >>= 1; } int K = Z.size(); int ans = 0; for (int i = 0; i < 1 << K; i++) { int sw = 0, sv = 0; for (int j = 0; j < K; j++) { if (i >> j & 1) { sw += Z[j].first; sv += Z[j].second; } } if (sw <= L) { chmax(ans, sv); } } cout << ans << "\n"; } void mode2(int v, int L) { vector<pi> Z; mode4(v, L, Z); } void mode3(int v, int L) { vector<pi> Z; int j = v; while (j >= Q) { Z.push_back(pi(W[j], V[j])); j >>= 1; } mode4(j, L, Z); } void solve() { int N; cin >> N; V = vector<int>(N + 1); W = vector<int>(N + 1); for (int i = 1; i <= N; i++) { cin >> V[i] >> W[i]; // V[i] = i;W[i] = i; } D = vector<vector<pi>>(P); for (int ww = P; ww <= min(N, Q - 1); ww++) { vector<pi> Z; int j = ww; while (j > 0) { Z.push_back(pi(W[j], V[j])); j >>= 1; } vector<pi> ps; int K = Z.size(); for (int i = 0; i < 1 << K; i++) { int sw = 0, sv = 0; for (int j = 0; j < K; j++) { if (i >> j & 1) { sw += Z[j].first; sv += Z[j].second; } } ps.push_back(pi(sw, sv)); } sort(all(ps)); int m = 1; for (int i = 1; i < ps.size(); i++) { if (ps[m - 1].second < ps[i].second) { ps[m++] = ps[i]; } } ps.resize(m); D[ww - P] = ps; } int T; cin >> T; for (int t = 0; t < T; t++) { int v, L; cin >> v >> L; // v = t; L = t; // cout << "id" << t << endl; if (v < P) { mode1(v, L); } else if (v < Q) { mode2(v, L); } else { mode3(v, L); } } } int main() { cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(11); solve(); return 0; }
#include "bits/stdc++.h" using namespace std; #define mod 1000000007 #define dom 998244353 #define all(c) begin(c), end(c) #define rep(i, n) repi(i, 0, n) #define repi(i, a, b) for (int i = (a); i < (b); i++) #define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--) template <typename T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <typename T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } #define long long long #define List vector #define var auto #define Count size() #define Length size() #define in : #define foreach for using pi = pair<int, int>; int dd[] = {0, 1, 0, -1, 0}; // →↓←↑ const int P = 1 << 9; const int Q = 1 << 10; int N; vector<int> V; vector<int> W; vector<vector<pi>> D; void mode4(int v, int L, vector<pi> Z) { int ans = 0; int K = Z.size(); for (int i = 0; i < 1 << K; i++) { int sw = 0, sv = 0; for (int j = 0; j < K; j++) { if (i >> j & 1) { sw += Z[j].first; sv += Z[j].second; } } if (sw <= L) { var q = pi(L - sw, INT_MAX / 3); // cout << D[0].size() << " " << v - P << endl; // var B = lower_bound(all(D[v - P]), make_pair(L - sw, INT_MAX)); // int pos = distance(D[v - P].begin(), B); // cout << pos << endl; int tv = (lower_bound(all(D[v - P]), make_pair(L - sw, INT_MAX)) - 1)->second; chmax(ans, sv + tv); } } cout << ans << "\n"; } void mode1(int v, int L) { vector<pi> Z; int j = v; while (j > 0) { Z.push_back(pi(W[j], V[j])); j >>= 1; } int K = Z.size(); int ans = 0; for (int i = 0; i < 1 << K; i++) { int sw = 0, sv = 0; for (int j = 0; j < K; j++) { if (i >> j & 1) { sw += Z[j].first; sv += Z[j].second; } } if (sw <= L) { chmax(ans, sv); } } cout << ans << "\n"; } void mode2(int v, int L) { vector<pi> Z; mode4(v, L, Z); } void mode3(int v, int L) { vector<pi> Z; int j = v; while (j >= Q) { Z.push_back(pi(W[j], V[j])); j >>= 1; } mode4(j, L, Z); } void solve() { int N; cin >> N; V = vector<int>(N + 1); W = vector<int>(N + 1); for (int i = 1; i <= N; i++) { cin >> V[i] >> W[i]; // V[i] = i;W[i] = i; } D = vector<vector<pi>>(P); for (int ww = P; ww <= min(N, Q - 1); ww++) { vector<pi> Z; int j = ww; while (j > 0) { Z.push_back(pi(W[j], V[j])); j >>= 1; } vector<pi> ps; int K = Z.size(); for (int i = 0; i < 1 << K; i++) { int sw = 0, sv = 0; for (int j = 0; j < K; j++) { if (i >> j & 1) { sw += Z[j].first; sv += Z[j].second; } } ps.push_back(pi(sw, sv)); } sort(all(ps)); int m = 1; for (int i = 1; i < ps.size(); i++) { if (ps[m - 1].second < ps[i].second) { ps[m++] = ps[i]; } } ps.resize(m); D[ww - P] = ps; } int T; cin >> T; for (int t = 0; t < T; t++) { int v, L; cin >> v >> L; // v = t; L = t; // cout << "id" << t << endl; if (v < P) { mode1(v, L); } else if (v < Q) { mode2(v, L); } else { mode3(v, L); } } } int main() { cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(11); solve(); return 0; }
replace
32
34
32
34
TLE
p02648
C++
Runtime Error
#include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <map> #include <queue> #include <set> #include <stack> #include <vector> using namespace std; #define MOD 1000000007 #define f(i, n) for (int i = 0; i < (int)(n); i++) #define N 200010 vector<pair<int, int>> a[N]; vector<pair<int, int>> aa; vector<pair<int, int>> b; int val[N]; int wgt[N]; int n, k, nn, kk, mx, sz, q, lim, vec, xx, yy, zz; int x, y, z; int ans; int main() { scanf("%d", &n); x = n + 1; y = 0; while (x > 1) { x /= 2; y++; } y = min(11, y); k = 1; f(i, y) k *= 2; f(i, n) { scanf("%d %d", &val[i + 1], &wgt[i + 1]); } a[1].push_back(make_pair(0, 0)); a[1].push_back(make_pair(wgt[1], val[1])); for (int i = 2; i < k; i++) { x = i / 2; sz = a[x].size(); aa = a[x]; f(j, sz) { y = a[x][j].first + wgt[i]; z = a[x][j].second + val[i]; aa.push_back(make_pair(y, z)); } sort(aa.begin(), aa.end()); sz *= 2; mx = -1; f(j, sz) { if (mx < aa[j].second) { a[i].push_back(aa[j]); mx = aa[j].second; } } } scanf("%d", &q); f(qq, q) { scanf("%d %d", &vec, &lim); b.clear(); b.push_back(make_pair(0, 0)); while (vec >= k) { aa = b; sz = b.size(); f(j, sz) { y = b[j].first + wgt[vec]; z = b[j].second + val[vec]; aa.push_back(make_pair(y, z)); } sort(aa.begin(), aa.end()); b.clear(); sz *= 2; mx = -1; f(j, sz) { if (mx < aa[j].second) { b.push_back(aa[j]); mx = aa[j].second; } } vec /= 2; } sz = a[vec].size(); x = 0; y = b.size(); y--; ans = 0; while ((x < sz) && (y >= 0)) { xx = (a[vec][x].first) + (b[y].first); yy = (a[vec][x].second) + (b[y].second); if (xx <= lim) { ans = max(ans, yy); x++; } else { y--; } } printf("%d\n", ans); } return 0; }
#include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <map> #include <queue> #include <set> #include <stack> #include <vector> using namespace std; #define MOD 1000000007 #define f(i, n) for (int i = 0; i < (int)(n); i++) #define N 800010 vector<pair<int, int>> a[N]; vector<pair<int, int>> aa; vector<pair<int, int>> b; int val[N]; int wgt[N]; int n, k, nn, kk, mx, sz, q, lim, vec, xx, yy, zz; int x, y, z; int ans; int main() { scanf("%d", &n); x = n + 1; y = 0; while (x > 1) { x /= 2; y++; } y = min(11, y); k = 1; f(i, y) k *= 2; f(i, n) { scanf("%d %d", &val[i + 1], &wgt[i + 1]); } a[1].push_back(make_pair(0, 0)); a[1].push_back(make_pair(wgt[1], val[1])); for (int i = 2; i < k; i++) { x = i / 2; sz = a[x].size(); aa = a[x]; f(j, sz) { y = a[x][j].first + wgt[i]; z = a[x][j].second + val[i]; aa.push_back(make_pair(y, z)); } sort(aa.begin(), aa.end()); sz *= 2; mx = -1; f(j, sz) { if (mx < aa[j].second) { a[i].push_back(aa[j]); mx = aa[j].second; } } } scanf("%d", &q); f(qq, q) { scanf("%d %d", &vec, &lim); b.clear(); b.push_back(make_pair(0, 0)); while (vec >= k) { aa = b; sz = b.size(); f(j, sz) { y = b[j].first + wgt[vec]; z = b[j].second + val[vec]; aa.push_back(make_pair(y, z)); } sort(aa.begin(), aa.end()); b.clear(); sz *= 2; mx = -1; f(j, sz) { if (mx < aa[j].second) { b.push_back(aa[j]); mx = aa[j].second; } } vec /= 2; } sz = a[vec].size(); x = 0; y = b.size(); y--; ans = 0; while ((x < sz) && (y >= 0)) { xx = (a[vec][x].first) + (b[y].first); yy = (a[vec][x].second) + (b[y].second); if (xx <= lim) { ans = max(ans, yy); x++; } else { y--; } } printf("%d\n", ans); } return 0; }
replace
14
15
14
15
0
p02648
C++
Runtime Error
#include <bits/stdc++.h> #define ll long long int #define ld long double #define f first #define s second #define pb push_back #define eb emplace_back #define mk make_pair #define mt make_tuple #define MOD 1000000007 #define fo(i, a, b) for (i = a; i < b; i++) #define foe(i, a, b) for (i = a; i <= b; i++) #define all(x) x.begin(), x.end() #define vi vector<int> #define vl vector<long long int> #define pii pair<int, int> #define pll pair<long long int, long long int> #define vpii vector<pair<int, int>> #define vpll vector<pair<long long int, long long int>> #define boost \ ios::sync_with_stdio(false); \ cin.tie(0) using namespace std; const int inf = 1e9 + 5; const ll inf64 = 1e18 + 5; const int MAX = 1 << 18; const int N = 550; const int L = 10; int lvl[MAX]; vector<pii> pre[N]; vector<pii> a; void rec(int x, int l, vector<pii> v) { if (x >= a.size()) return; v.pb({a[x].f, a[x].s}); if (l == L) { for (int i = 0; i < (1 << L); i++) { int ww = 0, vv = 0; for (int j = 0; j < L; j++) { if ((1 << j) & i) { ww += v[j].s; vv += v[j].f; } } pre[x].pb({ww, vv}); } sort(all(pre[x]), [&](const pii p1, const pii p2) { if (p1.f == p2.f) return p1.s < p2.s; return p1.f < p2.f; }); for (int i = 1; i < pre[x].size(); i++) pre[x][i].s = max(pre[x][i].s, pre[x][i - 1].s); return; } rec(2 * x, l + 1, v); rec(2 * x + 1, l + 1, v); } int main() { boost; int n, q, x, y, i; cin >> n; a.pb({0, 0}); lvl[1] = 1; foe(i, 2, n) lvl[i] = lvl[i / 2] + 1; foe(i, 1, n) { cin >> x >> y; a.pb({x, y}); } rec(1, 1, {}); cin >> q; while (q--) { int val, W; cin >> val >> W; vector<int> v; int ans = 0; if (lvl[val] < L) { do { v.pb(val); val /= 2; } while (val); int x = v.size(); for (int i = 0; i < (1 << x); i++) { int ww = 0, vv = 0; for (int j = 0; j < x; j++) { if ((1 << j) & i) { ww += a[v[j]].s; vv += a[v[j]].f; } } if (ww <= W) ans = max(ans, vv); } } else { while (lvl[val] > L) { v.pb(val); val /= 2; } int node = val; int x = v.size(); for (int i = 0; i < (1 << x); i++) { int ww = 0, vv = 0; for (int j = 0; j < x; j++) { if ((1 << j) & i) { ww += a[v[j]].s; vv += a[v[j]].f; } } if (ww <= W) { pii p = {W - ww, inf}; ans = max(ans, vv); int ind = upper_bound(all(pre[node]), p) - pre[node].begin(); --ind; if (ind >= 0) ans = max(ans, vv + pre[node][ind].s); } } } cout << ans << '\n'; } }
#include <bits/stdc++.h> #define ll long long int #define ld long double #define f first #define s second #define pb push_back #define eb emplace_back #define mk make_pair #define mt make_tuple #define MOD 1000000007 #define fo(i, a, b) for (i = a; i < b; i++) #define foe(i, a, b) for (i = a; i <= b; i++) #define all(x) x.begin(), x.end() #define vi vector<int> #define vl vector<long long int> #define pii pair<int, int> #define pll pair<long long int, long long int> #define vpii vector<pair<int, int>> #define vpll vector<pair<long long int, long long int>> #define boost \ ios::sync_with_stdio(false); \ cin.tie(0) using namespace std; const int inf = 1e9 + 5; const ll inf64 = 1e18 + 5; const int MAX = 1 << 18; const int N = 1100; const int L = 10; int lvl[MAX]; vector<pii> pre[N]; vector<pii> a; void rec(int x, int l, vector<pii> v) { if (x >= a.size()) return; v.pb({a[x].f, a[x].s}); if (l == L) { for (int i = 0; i < (1 << L); i++) { int ww = 0, vv = 0; for (int j = 0; j < L; j++) { if ((1 << j) & i) { ww += v[j].s; vv += v[j].f; } } pre[x].pb({ww, vv}); } sort(all(pre[x]), [&](const pii p1, const pii p2) { if (p1.f == p2.f) return p1.s < p2.s; return p1.f < p2.f; }); for (int i = 1; i < pre[x].size(); i++) pre[x][i].s = max(pre[x][i].s, pre[x][i - 1].s); return; } rec(2 * x, l + 1, v); rec(2 * x + 1, l + 1, v); } int main() { boost; int n, q, x, y, i; cin >> n; a.pb({0, 0}); lvl[1] = 1; foe(i, 2, n) lvl[i] = lvl[i / 2] + 1; foe(i, 1, n) { cin >> x >> y; a.pb({x, y}); } rec(1, 1, {}); cin >> q; while (q--) { int val, W; cin >> val >> W; vector<int> v; int ans = 0; if (lvl[val] < L) { do { v.pb(val); val /= 2; } while (val); int x = v.size(); for (int i = 0; i < (1 << x); i++) { int ww = 0, vv = 0; for (int j = 0; j < x; j++) { if ((1 << j) & i) { ww += a[v[j]].s; vv += a[v[j]].f; } } if (ww <= W) ans = max(ans, vv); } } else { while (lvl[val] > L) { v.pb(val); val /= 2; } int node = val; int x = v.size(); for (int i = 0; i < (1 << x); i++) { int ww = 0, vv = 0; for (int j = 0; j < x; j++) { if ((1 << j) & i) { ww += a[v[j]].s; vv += a[v[j]].f; } } if (ww <= W) { pii p = {W - ww, inf}; ans = max(ans, vv); int ind = upper_bound(all(pre[node]), p) - pre[node].begin(); --ind; if (ind >= 0) ans = max(ans, vv + pre[node][ind].s); } } } cout << ans << '\n'; } }
replace
27
28
27
28
0
p02648
C++
Runtime Error
#pragma region template 2.4 #include <bits/stdc++.h> using namespace std; template <typename T> using pq_asc = priority_queue<T, vector<T>, greater<T>>; typedef long long ll; typedef vector<ll> vi; typedef vector<vi> vvi; typedef pair<ll, ll> ii; typedef vector<ii> vii; typedef vector<string> vs; #define REP(i, n) for (ll i = 0; i < (n); ++i) #define REP1(i, n) for (ll i = 1; i <= (n); ++i) #define FOR(i, a) for (auto &i : a) #define CH(f, x, y) x = f(x, y) #define IN(T, x) \ T x; \ cin >> x; #define AIN(T, a, n) \ vector<T> a(n); \ FOR(i, a) \ cin >> i; #define A2IN(T1, a, T2, b, n) \ vector<T1> a(n); \ vector<T2> b(n); \ REP(i, n) \ cin >> a[i] >> b[i]; #define OUT(x) cout << (x) << endl; #define FOUT(x) cout << fixed << setprecision(15) << (x) << endl; #define ALL(a) (a).begin(), (a).end() #define SORT(a) sort(ALL(a)) #define RSORT(a) \ SORT(a); \ reverse(ALL(a)) #define DUMP(x) cout << #x << " = " << (x) << endl; #define DUMPA(a) \ cout << #a << " = {"; \ JOUT(ALL(a), ", ", cout) << "}" << endl; template <typename T> ostream &JOUT(T s, T e, string sep = " ", ostream &os = cout) { if (s != e) { os << *s; ++s; } while (s != e) { os << sep << *s; ++s; } return os; } ostream &YES(bool cond, string yes = "Yes", string no = "No", ostream &os = cout) { if (cond) { os << yes << endl; } else { os << no << endl; } return os; } template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { os << '(' << p.first << ", " << p.second << ')'; return os; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << '['; JOUT(ALL(v), ", ", os) << ']'; return os; } const ll INF = 1e18; const ll MOD = 1e9 + 7; #pragma endregion template const ll C = 1e5; ll N, M; vi V, W; vvi dp; void f(ll i) { if (i > N) { return; } REP1(j, C) { dp[i][j] = dp[i / 2][j]; if (j >= W[i]) { CH(max, dp[i][j], dp[i / 2][j - W[i]] + V[i]); } } f(2 * i); f(2 * i + 1); } ll g(ll i, ll L) { if (i <= M) { return dp[i][L]; } ll res = g(i / 2, L); if (L >= W[i]) { CH(max, res, g(i / 2, L - W[i]) + V[i]); } return res; } int main() { cin >> N; V.resize(N + 1); W.resize(N + 1); REP1(i, N) { cin >> V[i] >> W[i]; } M = min(512LL, N); dp.assign(M + 1, vi(C + 1)); f(1); IN(ll, Q); REP(q, Q) { IN(ll, v); IN(ll, L); OUT(g(v, L)); } }
#pragma region template 2.4 #include <bits/stdc++.h> using namespace std; template <typename T> using pq_asc = priority_queue<T, vector<T>, greater<T>>; typedef long long ll; typedef vector<ll> vi; typedef vector<vi> vvi; typedef pair<ll, ll> ii; typedef vector<ii> vii; typedef vector<string> vs; #define REP(i, n) for (ll i = 0; i < (n); ++i) #define REP1(i, n) for (ll i = 1; i <= (n); ++i) #define FOR(i, a) for (auto &i : a) #define CH(f, x, y) x = f(x, y) #define IN(T, x) \ T x; \ cin >> x; #define AIN(T, a, n) \ vector<T> a(n); \ FOR(i, a) \ cin >> i; #define A2IN(T1, a, T2, b, n) \ vector<T1> a(n); \ vector<T2> b(n); \ REP(i, n) \ cin >> a[i] >> b[i]; #define OUT(x) cout << (x) << endl; #define FOUT(x) cout << fixed << setprecision(15) << (x) << endl; #define ALL(a) (a).begin(), (a).end() #define SORT(a) sort(ALL(a)) #define RSORT(a) \ SORT(a); \ reverse(ALL(a)) #define DUMP(x) cout << #x << " = " << (x) << endl; #define DUMPA(a) \ cout << #a << " = {"; \ JOUT(ALL(a), ", ", cout) << "}" << endl; template <typename T> ostream &JOUT(T s, T e, string sep = " ", ostream &os = cout) { if (s != e) { os << *s; ++s; } while (s != e) { os << sep << *s; ++s; } return os; } ostream &YES(bool cond, string yes = "Yes", string no = "No", ostream &os = cout) { if (cond) { os << yes << endl; } else { os << no << endl; } return os; } template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { os << '(' << p.first << ", " << p.second << ')'; return os; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << '['; JOUT(ALL(v), ", ", os) << ']'; return os; } const ll INF = 1e18; const ll MOD = 1e9 + 7; #pragma endregion template const ll C = 1e5; ll N, M; vi V, W; vvi dp; void f(ll i) { if (i > M) { return; } REP1(j, C) { dp[i][j] = dp[i / 2][j]; if (j >= W[i]) { CH(max, dp[i][j], dp[i / 2][j - W[i]] + V[i]); } } f(2 * i); f(2 * i + 1); } ll g(ll i, ll L) { if (i <= M) { return dp[i][L]; } ll res = g(i / 2, L); if (L >= W[i]) { CH(max, res, g(i / 2, L - W[i]) + V[i]); } return res; } int main() { cin >> N; V.resize(N + 1); W.resize(N + 1); REP1(i, N) { cin >> V[i] >> W[i]; } M = min(512LL, N); dp.assign(M + 1, vi(C + 1)); f(1); IN(ll, Q); REP(q, Q) { IN(ll, v); IN(ll, L); OUT(g(v, L)); } }
replace
83
84
83
84
0
p02648
C++
Runtime Error
#pragma GCC optimize("Ofast") #include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound #include <bitset> // bitset #include <cctype> // isupper, islower, isdigit, toupper, tolower #include <complex> // complex #include <cstdint> // int64_t, int*_t #include <cstdio> // printf #include <deque> // deque #include <functional> #include <iomanip> // setprecision #include <iostream> // cout, endl, cin #include <map> // map #include <math.h> #include <queue> // queue, priority_queue #include <set> // set #include <stack> // stack #include <string> // string, to_string, stoi #include <tuple> // tuple, make_tuple #include <unordered_map> // unordered_map #include <unordered_set> // unordered_set #include <utility> // pair, make_pair #include <vector> // vector using namespace std; using ll = long long; using P = pair<int, int>; constexpr ll INF = 1e18; constexpr int inf = 1e9; constexpr ll mod2 = 1000000007; constexpr ll mod = 998244353; const int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; const int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } // -------------------------------------------------------------------------- int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; int K = 9; vector<int> V(N + 1), W(N + 1); for (int i = 1; i <= N; i++) { cin >> V[i] >> W[i]; } vector<int> depth(N + 1, 0); for (int i = 2; i <= N; i++) { depth[i] = depth[i / 2] + 1; } vector<vector<int>> dp((1LL << K), vector<int>(100005, 0)); for (int i = 1; i <= min((1 << K), N); i++) { for (int j = 0; j <= 100000; j++) { chmax(dp[i][j], dp[i / 2][j]); chmax(dp[i][j + 1], dp[i / 2][j]); if (j + W[i] <= 100000) { chmax(dp[i][j + W[i]], dp[i / 2][j] + V[i]); } } } int Q; cin >> Q; for (int i = 0; i < Q; i++) { int v, L; cin >> v >> L; if (depth[v] < K) { cout << dp[v][L] << "\n"; } else { vector<int> now; while (depth[v] >= K) { now.emplace_back(v); v /= 2; } int ans = 0; for (int bit = 0; bit < (1LL << (now.size())); bit++) { int sum_V = 0, sum_W = 0; for (int k = 0; k < now.size(); k++) { if (bit & (1LL << k)) { sum_V += V[now[k]]; sum_W += W[now[k]]; } } if (sum_W <= L) { chmax(ans, sum_V + dp[v][L - sum_W]); } } cout << ans << "\n"; } } return 0; }
#pragma GCC optimize("Ofast") #include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound #include <bitset> // bitset #include <cctype> // isupper, islower, isdigit, toupper, tolower #include <complex> // complex #include <cstdint> // int64_t, int*_t #include <cstdio> // printf #include <deque> // deque #include <functional> #include <iomanip> // setprecision #include <iostream> // cout, endl, cin #include <map> // map #include <math.h> #include <queue> // queue, priority_queue #include <set> // set #include <stack> // stack #include <string> // string, to_string, stoi #include <tuple> // tuple, make_tuple #include <unordered_map> // unordered_map #include <unordered_set> // unordered_set #include <utility> // pair, make_pair #include <vector> // vector using namespace std; using ll = long long; using P = pair<int, int>; constexpr ll INF = 1e18; constexpr int inf = 1e9; constexpr ll mod2 = 1000000007; constexpr ll mod = 998244353; const int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; const int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } // -------------------------------------------------------------------------- int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; int K = 9; vector<int> V(N + 1), W(N + 1); for (int i = 1; i <= N; i++) { cin >> V[i] >> W[i]; } vector<int> depth(N + 1, 0); for (int i = 2; i <= N; i++) { depth[i] = depth[i / 2] + 1; } vector<vector<int>> dp((1LL << K), vector<int>(100005, 0)); for (int i = 1; i < min((1 << K), N + 1); i++) { for (int j = 0; j <= 100000; j++) { chmax(dp[i][j], dp[i / 2][j]); chmax(dp[i][j + 1], dp[i / 2][j]); if (j + W[i] <= 100000) { chmax(dp[i][j + W[i]], dp[i / 2][j] + V[i]); } } } int Q; cin >> Q; for (int i = 0; i < Q; i++) { int v, L; cin >> v >> L; if (depth[v] < K) { cout << dp[v][L] << "\n"; } else { vector<int> now; while (depth[v] >= K) { now.emplace_back(v); v /= 2; } int ans = 0; for (int bit = 0; bit < (1LL << (now.size())); bit++) { int sum_V = 0, sum_W = 0; for (int k = 0; k < now.size(); k++) { if (bit & (1LL << k)) { sum_V += V[now[k]]; sum_W += W[now[k]]; } } if (sum_W <= L) { chmax(ans, sum_V + dp[v][L - sum_W]); } } cout << ans << "\n"; } } return 0; }
replace
62
63
62
63
-6
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
p02648
C++
Runtime Error
#include <stdio.h> int n, q; long long p = 10000000; long long v[1024 * 256 + 1]; long long w[1024 * 256 + 1]; long long u[100000]; long long l[100000]; int s[1024]; int ss, uu; long long e[256]; long long ee[128 + 1]; long long ef[128 + 1]; long long d[1024][1024]; long long te, ans; int ar, br; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%lld%lld", v + i, w + i); } scanf("%d", &q); for (int i = 0; i < q; i++) { scanf("%lld%lld", u + i, l + i); } d[0][0] = 0; s[0] = 1; for (int i = 1; i < 1024; i++) { te = w[i] * p + v[i]; ss = s[i / 2]; for (int j = 0; j < s[i / 2]; j++) { e[j] = d[i / 2][j] + te; } ar = 0, br = 0; d[i / 2][ss] = p * p; e[ss] = p * p; s[i] = 2 * ss; while (ar + br < s[i]) { if (d[i / 2][ar] < e[br]) { d[i][ar + br] = d[i / 2][ar]; ar++; } else { d[i][ar + br] = e[br]; br++; } } for (int j = 1; j < s[i]; j++) { if (d[i][j - 1] % p > d[i][j] % p) { d[i][j] = d[i][j - 1]; } } } for (int i = 0; i < q; i++) { uu = u[i]; ans = 0; if (uu >= 1024) { ss = 1; e[0] = 0; while (uu >= 1024) { te = w[uu] * p + v[uu]; for (int k = 0; k < ss; k++) { ee[k] = e[k]; ef[k] = e[k] + te; } ar = 0, br = 0; ee[ss] = p * p; ef[ss] = p * p; while (ar < ss || br < ss) { if (ee[ar] < ef[br]) { e[ar + br] = ee[ar]; ar++; } else { e[ar + br] = ef[br]; br++; } } uu /= 2; ss *= 2; } for (int j = 1; j < ss; j++) { if (e[j - 1] % p > e[j] % p) { e[j] = e[j - 1]; } } ar = ss - 1; for (int j = 0; j < s[uu]; j++) { while (ar + 1 && (d[uu][j] + e[ar]) / p > l[i]) ar--; if (!(ar + 1)) break; if ((d[uu][j] + e[ar]) % p > ans) { ans = (d[uu][j] + e[ar]) % p; } } } else { for (int j = 0; j < s[uu]; j++) { if (d[uu][j] / p <= l[i]) { if (d[uu][j] % p > ans) { ans = d[uu][j] % p; } } } } printf("%lld\n", ans); } }
#include <stdio.h> int n, q; long long p = 10000000; long long v[1024 * 256 + 1]; long long w[1024 * 256 + 1]; long long u[100000]; long long l[100000]; int s[1024]; int ss, uu; long long e[512 + 1]; long long ee[128 + 1]; long long ef[128 + 1]; long long d[1024][1024]; long long te, ans; int ar, br; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%lld%lld", v + i, w + i); } scanf("%d", &q); for (int i = 0; i < q; i++) { scanf("%lld%lld", u + i, l + i); } d[0][0] = 0; s[0] = 1; for (int i = 1; i < 1024; i++) { te = w[i] * p + v[i]; ss = s[i / 2]; for (int j = 0; j < s[i / 2]; j++) { e[j] = d[i / 2][j] + te; } ar = 0, br = 0; d[i / 2][ss] = p * p; e[ss] = p * p; s[i] = 2 * ss; while (ar + br < s[i]) { if (d[i / 2][ar] < e[br]) { d[i][ar + br] = d[i / 2][ar]; ar++; } else { d[i][ar + br] = e[br]; br++; } } for (int j = 1; j < s[i]; j++) { if (d[i][j - 1] % p > d[i][j] % p) { d[i][j] = d[i][j - 1]; } } } for (int i = 0; i < q; i++) { uu = u[i]; ans = 0; if (uu >= 1024) { ss = 1; e[0] = 0; while (uu >= 1024) { te = w[uu] * p + v[uu]; for (int k = 0; k < ss; k++) { ee[k] = e[k]; ef[k] = e[k] + te; } ar = 0, br = 0; ee[ss] = p * p; ef[ss] = p * p; while (ar < ss || br < ss) { if (ee[ar] < ef[br]) { e[ar + br] = ee[ar]; ar++; } else { e[ar + br] = ef[br]; br++; } } uu /= 2; ss *= 2; } for (int j = 1; j < ss; j++) { if (e[j - 1] % p > e[j] % p) { e[j] = e[j - 1]; } } ar = ss - 1; for (int j = 0; j < s[uu]; j++) { while (ar + 1 && (d[uu][j] + e[ar]) / p > l[i]) ar--; if (!(ar + 1)) break; if ((d[uu][j] + e[ar]) % p > ans) { ans = (d[uu][j] + e[ar]) % p; } } } else { for (int j = 0; j < s[uu]; j++) { if (d[uu][j] / p <= l[i]) { if (d[uu][j] % p > ans) { ans = d[uu][j] % p; } } } } printf("%lld\n", ans); } }
replace
9
10
9
10
0
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> #include <stdio.h> using namespace std; typedef long long int ll; typedef long double ld; typedef unsigned long long int lu; typedef vector<int> vi; typedef vector<ll> vl; typedef set<ll> sl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef pair<int, int> ii; typedef pair<ll, ll> il; #define sz(a) ll((a).size()) #define test(t) \ ll t; \ cin >> t; \ while (t--) #define pb push_back #define all(c) (c).begin(), (c).end() #define tr(c, i) \ for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) #define present(c, x) ((c).find(x) != (c).end()) #define cpresent(c, x) (find(all(c), x) != (c).end()) #define fastio \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) #define Vi vector #define pr pair #define mpr make_pair #define fi first #define se second #define isnum(a) (a >= 48 && a <= 57) #define isS(a) (a >= 'a' && a <= 'z') #define isU(a) (a >= 'A' && a <= 'Z') #define toS(a) (isU(a) ? a + 32 : a) #define toU(a) (isS(a) ? a - 32 : a) #define toC(a) a & 15 vector<ll> sprime; ll d[100005]; vector<char> prime(1000000 + 5, true); void sieve(ll n) { // O(nloglogn) time prime[0] = prime[1] = false; for (ll i = 2; i <= n; ++i) { if (prime[i]) { sprime.pb(i); for (ll j = 2 * i; j <= n; j += i) { prime[j] = false; } } } } #define forn(i, e) for (int i = 0; i < e; i++) #define rep(i, a, b) for (i = a; i < b; i++) #define REP(i, a, b) for (i = a; i <= b; i++) #define reprev(i, a, b) for (i = a; i >= b; i--) // Convex Hull Trick typedef ll LT; typedef pair<LT, LT> LP; struct CHT { deque<LP> d; LT get(LT x) { while (sz(d) >= 2) { LT a = d[0].fi * x + d[0].se; LT b = d[1].fi * x + d[1].se; if (a <= b) break; // get min d.pop_front(); } return d[0].fi * x + d[0].se; } void add(LP x) { // decreasing order of x.fi while (sz(d) >= 2) { LP y = d[sz(d) - 1]; LP z = d[sz(d) - 2]; if ((x.se - y.se) * (z.fi - y.fi) >= (y.fi - x.fi) * (y.se - z.se)) break; // both d.pop_back(); } d.pb(x); } }; // #define leadzero(a) __builtin_clz(a) // count leading zeros #define trailzero(a) __builtin_ctz(a) // count trailing zeros #define bitcount(a) __builtin_popcount(a) // count set bits (add ll) #define ln cout << endl #define sp cout << " " #define maxe(a) *max_element(a.begin(), a.end()) #define maxi(a) max_element(a.begin(), a.end()) - a.begin() #define mine(a) *min_element(a.begin(), a.end()) #define mini(a) min_element(a.begin(), a.end()) - a.begin() ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); } ll fastpowMOD(ll a, ll p, ll MOD) { if (p == 0) return 1; ll z = fastpowMOD(a, p / 2, MOD); z = (z * z) % MOD; if (p % 2) z = (z * a) % MOD; return z; } ll fastpow(ll a, ll p) { if (p == 0) return 1; ll z = fastpow(a, p / 2); z = (z * z); if (p % 2) z = (z * a); return z; } // CHT stands for convex hull trick ll search1(ll a[], ll f, ll n) { ll left = 1; ll right = n + 1; while (right - left > 1) { ll mid = left + (right - left) / 2; if (a[mid] < f) { left = mid; } else right = mid; } return a[left]; } const ll INF = 1e18; vector<ll> lazy; vector<ll> tree; void updateRange(ll node, ll start, ll end, ll l, ll r, ll val) { if (lazy[node] != 0) { // This node needs to be updated tree[node] += (/*end - start*/ +1) * lazy[node]; // Update it if (start != end) { lazy[node * 2] += lazy[node]; // Mark child as lazy lazy[node * 2 + 1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if (start > end or start > r or end < l) // Current segment is not within range [l, r] return; if (start >= l and end <= r) { // Segment is fully within range lazy[node] += (/*end - start*/ +1) * val; if (start != end) { // Not leaf node lazy[node * 2] += lazy[node]; lazy[node * 2 + 1] += lazy[node]; } tree[node] += lazy[node]; lazy[node] = 0; return; } ll mid = (start + end) / 2; updateRange(node * 2, start, mid, l, r, val); // Updating left child updateRange(node * 2 + 1, mid + 1, end, l, r, val); // Updating right child tree[node] = max(tree[node * 2], tree[node * 2 + 1]); // Updating root with max value } ll queryRange(ll node, ll start, ll end, ll l, ll r) { if (lazy[node] != 0) { // This node needs to be updated tree[node] += (/*end - start +*/ 1) * lazy[node]; // Update it if (start != end) { lazy[node * 2] += lazy[node]; // Mark child as lazy lazy[node * 2 + 1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if (start > end or start > r or end < l) return -INF; // Out of range if (start >= l and end <= r) // Current segment is totally within range [l, r] return tree[node]; ll mid = (start + end) / 2; if (r <= mid) return queryRange(node * 2, start, mid, l, r); else if (l >= mid + 1) return queryRange(node * 2 + 1, mid + 1, end, l, r); ll p1 = queryRange(node * 2, start, mid, l, r); // Query left child ll p2 = queryRange(node * 2 + 1, mid + 1, end, l, r); // Query right child // tree[node] = max(tree[node*2],tree[node*2+1]); return max(p1, p2); } void convert_reduce(ll arr[], ll n) { vector<pair<ll, ll>> v; for (ll i = 0; i < n; i++) v.push_back(make_pair(arr[i], i)); sort(v.begin(), v.end()); ll cnt = 0; for (ll i = 0; i < n; i++) { arr[v[i].second] = cnt; ll j = i; while (j < n && v[j].fi == v[i].fi) arr[v[j++].second] = cnt; i = j - 1; cnt++; } } // for bfs ll dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; bool valid(ll i, ll j, ll n, ll m) { return i >= 1 && i <= n && j >= 1 && j <= m; } ll MOD = 998244353; /* D - Knapsack Queries on a tree https://atcoder.jp/contests/tokiomarine2020/tasks/tokiomarine2020_d https://img.atcoder.jp/tokiomarine2020/editorial.pdf For simplicity, let N = 2^(2K) −1. Also, let M := max Li. We will introduce an algorithm that works in O(N +2^K(M +Q)) time. In this problem, K = 9 and M = 105, so 2^K(M +Q) ≈ 10^8, and thus it will run in time. First, for each vertex v at depth K −1 or shallower and each non-negative integer k at most M, we compute Dv,k: the maximum possible total value of items when we choose items from v and its ancestors so that the total weight is at most k. By computing them in the order from distance from the root, we can find all Dv,k in O(2KM) time. Then, we will process the query. Let v be the specified vertex. Among the vertices that are v or its ancestors, at most K have depths of K or deeper. Thus, we can try all subsets of the items in the vertices at depth K or deeper in O(2K) time. After deciding the subset to choose from the vertices at depth K or deeper, we can use D∗,∗ to know the optimal subset to choose from the vertices at depth K − 1 or shallower in O(1) time. Thus, we can process each query in O(2^K) time. Therefore, we can solve the problem in a total of O(N + 2^K(M + Q)) time. */ const ll N = (ll)3e5 + 5; ll v[N], w[N]; ll dp[(1 << 9) + 5][(ll)1e5 + 4]; int main() { // fastio; ll n, i, j, k, q; // cin>>n; scanf("%lld", &n); REP(i, 1, n) scanf("%lld %lld", &v[i], &w[i]); ll lim = (1 << 9); // ll dp[lim+5][(ll)1e5]; memset(dp, 0, sizeof(dp)); rep(i, 1, min(lim, n + 1)) { ll par = i / 2; rep(j, 0, (ll)1e5 + 1) { dp[i][j] = dp[par][j]; if (j >= w[i]) { dp[i][j] = max(dp[i][j], dp[par][j - w[i]] + v[i]); } if (j > 0) dp[i][j] = max(dp[i][j], dp[i][j - 1]); } } scanf("%lld", &q); ll val[11]; REP(i, 0, 10) val[i] = (1 << i); while (q--) { ll u, L; scanf("%lld %lld", &u, &L); if (u < lim) { printf("%lld\n", dp[u][L]); continue; } vl path; ll tm = u; while (tm > 0) { path.pb(tm); tm /= 2; } ll len = sz(path) - 9; ll ans = 0; rep(i, 0, val[len]) { ll sumv = 0, sumw = 0; rep(j, 0, len) { if (i & (1 << j)) { sumv += v[path[j]]; sumw += w[path[j]]; } } if (sumw <= L) { ans = max(ans, sumv + dp[path[len]][L - sumw]); } } printf("%lld\n", ans); } return 0; }
#include <bits/stdc++.h> #include <stdio.h> using namespace std; typedef long long int ll; typedef long double ld; typedef unsigned long long int lu; typedef vector<int> vi; typedef vector<ll> vl; typedef set<ll> sl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef pair<int, int> ii; typedef pair<ll, ll> il; #define sz(a) ll((a).size()) #define test(t) \ ll t; \ cin >> t; \ while (t--) #define pb push_back #define all(c) (c).begin(), (c).end() #define tr(c, i) \ for (__typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) #define present(c, x) ((c).find(x) != (c).end()) #define cpresent(c, x) (find(all(c), x) != (c).end()) #define fastio \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) #define Vi vector #define pr pair #define mpr make_pair #define fi first #define se second #define isnum(a) (a >= 48 && a <= 57) #define isS(a) (a >= 'a' && a <= 'z') #define isU(a) (a >= 'A' && a <= 'Z') #define toS(a) (isU(a) ? a + 32 : a) #define toU(a) (isS(a) ? a - 32 : a) #define toC(a) a & 15 vector<ll> sprime; ll d[100005]; vector<char> prime(1000000 + 5, true); void sieve(ll n) { // O(nloglogn) time prime[0] = prime[1] = false; for (ll i = 2; i <= n; ++i) { if (prime[i]) { sprime.pb(i); for (ll j = 2 * i; j <= n; j += i) { prime[j] = false; } } } } #define forn(i, e) for (int i = 0; i < e; i++) #define rep(i, a, b) for (i = a; i < b; i++) #define REP(i, a, b) for (i = a; i <= b; i++) #define reprev(i, a, b) for (i = a; i >= b; i--) // Convex Hull Trick typedef ll LT; typedef pair<LT, LT> LP; struct CHT { deque<LP> d; LT get(LT x) { while (sz(d) >= 2) { LT a = d[0].fi * x + d[0].se; LT b = d[1].fi * x + d[1].se; if (a <= b) break; // get min d.pop_front(); } return d[0].fi * x + d[0].se; } void add(LP x) { // decreasing order of x.fi while (sz(d) >= 2) { LP y = d[sz(d) - 1]; LP z = d[sz(d) - 2]; if ((x.se - y.se) * (z.fi - y.fi) >= (y.fi - x.fi) * (y.se - z.se)) break; // both d.pop_back(); } d.pb(x); } }; // #define leadzero(a) __builtin_clz(a) // count leading zeros #define trailzero(a) __builtin_ctz(a) // count trailing zeros #define bitcount(a) __builtin_popcount(a) // count set bits (add ll) #define ln cout << endl #define sp cout << " " #define maxe(a) *max_element(a.begin(), a.end()) #define maxi(a) max_element(a.begin(), a.end()) - a.begin() #define mine(a) *min_element(a.begin(), a.end()) #define mini(a) min_element(a.begin(), a.end()) - a.begin() ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); } ll fastpowMOD(ll a, ll p, ll MOD) { if (p == 0) return 1; ll z = fastpowMOD(a, p / 2, MOD); z = (z * z) % MOD; if (p % 2) z = (z * a) % MOD; return z; } ll fastpow(ll a, ll p) { if (p == 0) return 1; ll z = fastpow(a, p / 2); z = (z * z); if (p % 2) z = (z * a); return z; } // CHT stands for convex hull trick ll search1(ll a[], ll f, ll n) { ll left = 1; ll right = n + 1; while (right - left > 1) { ll mid = left + (right - left) / 2; if (a[mid] < f) { left = mid; } else right = mid; } return a[left]; } const ll INF = 1e18; vector<ll> lazy; vector<ll> tree; void updateRange(ll node, ll start, ll end, ll l, ll r, ll val) { if (lazy[node] != 0) { // This node needs to be updated tree[node] += (/*end - start*/ +1) * lazy[node]; // Update it if (start != end) { lazy[node * 2] += lazy[node]; // Mark child as lazy lazy[node * 2 + 1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if (start > end or start > r or end < l) // Current segment is not within range [l, r] return; if (start >= l and end <= r) { // Segment is fully within range lazy[node] += (/*end - start*/ +1) * val; if (start != end) { // Not leaf node lazy[node * 2] += lazy[node]; lazy[node * 2 + 1] += lazy[node]; } tree[node] += lazy[node]; lazy[node] = 0; return; } ll mid = (start + end) / 2; updateRange(node * 2, start, mid, l, r, val); // Updating left child updateRange(node * 2 + 1, mid + 1, end, l, r, val); // Updating right child tree[node] = max(tree[node * 2], tree[node * 2 + 1]); // Updating root with max value } ll queryRange(ll node, ll start, ll end, ll l, ll r) { if (lazy[node] != 0) { // This node needs to be updated tree[node] += (/*end - start +*/ 1) * lazy[node]; // Update it if (start != end) { lazy[node * 2] += lazy[node]; // Mark child as lazy lazy[node * 2 + 1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if (start > end or start > r or end < l) return -INF; // Out of range if (start >= l and end <= r) // Current segment is totally within range [l, r] return tree[node]; ll mid = (start + end) / 2; if (r <= mid) return queryRange(node * 2, start, mid, l, r); else if (l >= mid + 1) return queryRange(node * 2 + 1, mid + 1, end, l, r); ll p1 = queryRange(node * 2, start, mid, l, r); // Query left child ll p2 = queryRange(node * 2 + 1, mid + 1, end, l, r); // Query right child // tree[node] = max(tree[node*2],tree[node*2+1]); return max(p1, p2); } void convert_reduce(ll arr[], ll n) { vector<pair<ll, ll>> v; for (ll i = 0; i < n; i++) v.push_back(make_pair(arr[i], i)); sort(v.begin(), v.end()); ll cnt = 0; for (ll i = 0; i < n; i++) { arr[v[i].second] = cnt; ll j = i; while (j < n && v[j].fi == v[i].fi) arr[v[j++].second] = cnt; i = j - 1; cnt++; } } // for bfs ll dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; bool valid(ll i, ll j, ll n, ll m) { return i >= 1 && i <= n && j >= 1 && j <= m; } ll MOD = 998244353; /* D - Knapsack Queries on a tree https://atcoder.jp/contests/tokiomarine2020/tasks/tokiomarine2020_d https://img.atcoder.jp/tokiomarine2020/editorial.pdf For simplicity, let N = 2^(2K) −1. Also, let M := max Li. We will introduce an algorithm that works in O(N +2^K(M +Q)) time. In this problem, K = 9 and M = 105, so 2^K(M +Q) ≈ 10^8, and thus it will run in time. First, for each vertex v at depth K −1 or shallower and each non-negative integer k at most M, we compute Dv,k: the maximum possible total value of items when we choose items from v and its ancestors so that the total weight is at most k. By computing them in the order from distance from the root, we can find all Dv,k in O(2KM) time. Then, we will process the query. Let v be the specified vertex. Among the vertices that are v or its ancestors, at most K have depths of K or deeper. Thus, we can try all subsets of the items in the vertices at depth K or deeper in O(2K) time. After deciding the subset to choose from the vertices at depth K or deeper, we can use D∗,∗ to know the optimal subset to choose from the vertices at depth K − 1 or shallower in O(1) time. Thus, we can process each query in O(2^K) time. Therefore, we can solve the problem in a total of O(N + 2^K(M + Q)) time. */ const ll N = (ll)3e5 + 5; ll v[N], w[N]; ll dp[(1 << 9) + 5][(ll)1e5 + 4]; int main() { // fastio; ll n, i, j, k, q; // cin>>n; scanf("%lld", &n); REP(i, 1, n) scanf("%lld %lld", &v[i], &w[i]); ll lim = (1 << 9); // ll dp[lim+5][(ll)1e5]; memset(dp, 0, sizeof(dp)); rep(i, 1, min(lim, n + 1)) { ll par = i / 2; rep(j, 0, (ll)1e5 + 1) { dp[i][j] = dp[par][j]; if (j >= w[i]) { dp[i][j] = max(dp[i][j], dp[par][j - w[i]] + v[i]); } if (j > 0) dp[i][j] = max(dp[i][j], dp[i][j - 1]); } } scanf("%lld", &q); ll val[11]; REP(i, 0, 10) val[i] = (1 << i); while (q--) { ll u, L; scanf("%lld %lld", &u, &L); if (u < lim) { printf("%lld\n", dp[u][L]); continue; } vl path; ll tm = u; while (tm > 0) { path.pb(tm); tm /= 2; } ll len = sz(path) - 9; ll ans = 0; rep(i, 0, val[len]) { ll sumv = 0, sumw = 0; rep(j, 0, len) { if (i >> j & 1) { sumv += v[path[j]]; sumw += w[path[j]]; } } if (sumw <= L) { ans = max(ans, sumv + dp[path[len]][L - sumw]); } } printf("%lld\n", ans); } return 0; }
replace
292
293
292
293
TLE
p02648
C++
Time Limit Exceeded
#include <algorithm> #include <bitset> #include <climits> #include <cmath> #include <cstdio> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <unordered_map> #include <vector> #define MOD 1000000007 #define MOD2 998244353 #define int long long #define double long double #define EPS 1e-9 // #define PI 3.14159265358979 #define rep(i, n) for (int i = 0; i < (int)(n); i++) using namespace std; template <typename T> ostream &operator<<(ostream &os, const vector<T> &A) { for (int i = 0; i < A.size(); i++) os << A[i] << " "; os << endl; return os; } template <> ostream &operator<<(ostream &os, const vector<vector<int>> &A) { int N = A.size(); for (int i = 0; i < N; i++) { for (int j = 0; j < A[i].size(); j++) os << A[i][j] << " "; os << endl; } return os; } typedef pair<int, int> pii; typedef long long ll; struct edge { int from, to, d, c; edge(int _from = 0, int _to = 0, int _d = 0, int _c = 0) { from = _from; to = _to; d = _d; c = _c; } bool operator<(const edge &rhs) const { return (d == rhs.d) ? (c < rhs.c) : (d < rhs.d); } }; struct aabb { int x1, y1, x2, y2; aabb(int x1, int y1, int x2, int y2) : x1(x1), y1(y1), x2(x2), y2(y2) {} }; typedef vector<edge> edges; typedef vector<edges> graph; struct flow { int to, cap, rev, cost; flow(int to = 0, int cap = 0, int rev = 0, int cost = 0) : to(to), cap(cap), rev(rev), cost(cost) {} }; typedef vector<vector<flow>> flows; const int di[4] = {0, -1, 0, 1}; const int dj[4] = {-1, 0, 1, 0}; const int ci[5] = {0, 0, -1, 0, 1}; const int cj[5] = {0, -1, 0, 1, 0}; const ll LINF = LLONG_MAX / 2; const int INF = INT_MAX / 2; const double PI = acos(-1); int pow2(int n) { return 1LL << n; } template <typename T, typename U> bool chmin(T &x, const U &y) { if (x > y) { x = y; return true; } return false; } template <typename T, typename U> bool chmax(T &x, const U &y) { if (x < y) { x = y; return true; } return false; } struct initializer { initializer() { cout << fixed << setprecision(20); } }; initializer _____; int N, M, K, T, Q, H, W; signed main() { cin >> N; vector<int> V(N + 1), W(N + 1); rep(i, N) cin >> V[i + 1] >> W[i + 1]; cin >> Q; int MAXLEVEL = 9; M = min(N, (1LL << MAXLEVEL) - 1); int LMAX = 1e5 + 1; // int LMAX = 10; vector<vector<int>> dp(M + 1, vector<int>(LMAX, -1)); dp[0][0] = 0; rep(i2, M) { int i = i2 + 1; rep(j, LMAX) { chmax(dp[i][j], dp[i / 2][j]); int k = j - W[i]; if (k >= 0 && dp[i / 2][k] != -1) { chmax(dp[i][j], dp[i / 2][k] + V[i]); } } } rep(i2, M) { int i = i2 + 1; rep(j, LMAX - 1) { chmax(dp[i][j + 1], dp[i][j]); } } // cout << dp; while (Q--) { int v, L; cin >> v >> L; if (v <= (1LL << MAXLEVEL) - 1) { cout << dp[v][L] << endl; } else { vector<pii> A; while (v >= (1LL << MAXLEVEL)) { A.emplace_back(W[v], V[v]); v /= 2; } int ans = 0; int X = A.size(); for (int b = 0; b < (1 << X); b++) { int Wtmp = 0, Vtmp = 0; rep(i, X) { if ((b >> i) & 1) { Wtmp += A[i].first; Vtmp += A[i].second; } } if (Wtmp <= L) { chmax(ans, dp[v][L - Wtmp] + Vtmp); } } cout << ans << endl; } } return 0; }
#include <algorithm> #include <bitset> #include <climits> #include <cmath> #include <cstdio> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <unordered_map> #include <vector> #define MOD 1000000007 #define MOD2 998244353 #define int long long #define double long double #define EPS 1e-9 // #define PI 3.14159265358979 #define rep(i, n) for (int i = 0; i < (int)(n); i++) using namespace std; template <typename T> ostream &operator<<(ostream &os, const vector<T> &A) { for (int i = 0; i < A.size(); i++) os << A[i] << " "; os << endl; return os; } template <> ostream &operator<<(ostream &os, const vector<vector<int>> &A) { int N = A.size(); for (int i = 0; i < N; i++) { for (int j = 0; j < A[i].size(); j++) os << A[i][j] << " "; os << endl; } return os; } typedef pair<int, int> pii; typedef long long ll; struct edge { int from, to, d, c; edge(int _from = 0, int _to = 0, int _d = 0, int _c = 0) { from = _from; to = _to; d = _d; c = _c; } bool operator<(const edge &rhs) const { return (d == rhs.d) ? (c < rhs.c) : (d < rhs.d); } }; struct aabb { int x1, y1, x2, y2; aabb(int x1, int y1, int x2, int y2) : x1(x1), y1(y1), x2(x2), y2(y2) {} }; typedef vector<edge> edges; typedef vector<edges> graph; struct flow { int to, cap, rev, cost; flow(int to = 0, int cap = 0, int rev = 0, int cost = 0) : to(to), cap(cap), rev(rev), cost(cost) {} }; typedef vector<vector<flow>> flows; const int di[4] = {0, -1, 0, 1}; const int dj[4] = {-1, 0, 1, 0}; const int ci[5] = {0, 0, -1, 0, 1}; const int cj[5] = {0, -1, 0, 1, 0}; const ll LINF = LLONG_MAX / 2; const int INF = INT_MAX / 2; const double PI = acos(-1); int pow2(int n) { return 1LL << n; } template <typename T, typename U> bool chmin(T &x, const U &y) { if (x > y) { x = y; return true; } return false; } template <typename T, typename U> bool chmax(T &x, const U &y) { if (x < y) { x = y; return true; } return false; } struct initializer { initializer() { cout << fixed << setprecision(20); } }; initializer _____; int N, M, K, T, Q, H, W; signed main() { cin >> N; vector<int> V(N + 1), W(N + 1); rep(i, N) cin >> V[i + 1] >> W[i + 1]; cin >> Q; int MAXLEVEL = 10; M = min(N, (1LL << MAXLEVEL) - 1); int LMAX = 1e5 + 1; // int LMAX = 10; vector<vector<int>> dp(M + 1, vector<int>(LMAX, -1)); dp[0][0] = 0; rep(i2, M) { int i = i2 + 1; rep(j, LMAX) { chmax(dp[i][j], dp[i / 2][j]); int k = j - W[i]; if (k >= 0 && dp[i / 2][k] != -1) { chmax(dp[i][j], dp[i / 2][k] + V[i]); } } } rep(i2, M) { int i = i2 + 1; rep(j, LMAX - 1) { chmax(dp[i][j + 1], dp[i][j]); } } // cout << dp; while (Q--) { int v, L; cin >> v >> L; if (v <= (1LL << MAXLEVEL) - 1) { cout << dp[v][L] << endl; } else { vector<pii> A; while (v >= (1LL << MAXLEVEL)) { A.emplace_back(W[v], V[v]); v /= 2; } int ans = 0; int X = A.size(); for (int b = 0; b < (1 << X); b++) { int Wtmp = 0, Vtmp = 0; rep(i, X) { if ((b >> i) & 1) { Wtmp += A[i].first; Vtmp += A[i].second; } } if (Wtmp <= L) { chmax(ans, dp[v][L - Wtmp] + Vtmp); } } cout << ans << endl; } } return 0; }
replace
108
109
108
109
TLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; #define rep(i, x, y) for (ll i = (x); i < (y); i++) #define rrep(i, x, y) for (ll i = (ll)(y)-1; i >= (x); i--) #define all(x) (x).begin(), (x).end() #ifdef LOCAL #define debug(x) \ cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \ << " " << __FILE__ << endl #define itrdebug(x) \ cerr << #x << " "; \ for (auto &el : (x)) { \ cerr << (el) << " "; \ } \ cerr << endl #define dassert(...) assert(__VA_ARGS__) #else #define debug(x) #define itrdebug(x) #define dassert(...) #endif // #define int long long typedef long long ll; const ll MOD = 1e9 + 7; const long double EPS = 1e-8; void solve(long long N, std::vector<long long> V, std::vector<long long> W, long long Q, std::vector<long long> v, std::vector<long long> L) { vector<vector<int>> dp(min<int>(pow(2, 9) + 1, N + 1), vector<int>(1e5 + 1, 0)); rep(i, 1, dp.size()) { int parent = i / 2; rep(j, 0, dp.front().size()) { dp[i][j] = dp[parent][j]; if (j - W[i] >= 0) dp[i][j] = max<int>(dp[i][j], dp[parent][j - W[i]] + V[i]); if (j > 0) dp[i][j] = max(dp[i][j], dp[i][j - 1]); } } rep(ti, 0, Q) { if (v[ti] < dp.size()) { cout << dp[v[ti]][L[ti]] << endl; continue; } vector<pair<int, int>> items; int current = v[ti]; while (current >= dp.size()) { items.emplace_back(W[current], V[current]); current /= 2; } int answer = 0; rep(i, 0, 1 << items.size()) { int weightSum = 0, valueSum = 0; rep(j, 0, items.size()) { if (i & (1 << j)) { weightSum += items[j].first; valueSum += items[j].second; } if (weightSum > L[ti]) break; } if (weightSum <= L[ti]) { answer = max(answer, valueSum + dp[current][L[ti] - weightSum]); } } cout << answer << endl; } } signed main() { // ios_base::sync_with_stdio(false); // cin.tie(NULL); long long N; scanf("%lld", &N); std::vector<long long> V(N + 1); std::vector<long long> W(N + 1); for (int i = 1; i <= N; i++) { scanf("%lld", &V[i]); scanf("%lld", &W[i]); } long long Q; scanf("%lld", &Q); std::vector<long long> v(Q); std::vector<long long> L(Q); for (int i = 0; i < Q; i++) { scanf("%lld", &v[i]); scanf("%lld", &L[i]); } solve(N, std::move(V), std::move(W), Q, std::move(v), std::move(L)); return 0; }
#include <bits/stdc++.h> using namespace std; #define rep(i, x, y) for (ll i = (x); i < (y); i++) #define rrep(i, x, y) for (ll i = (ll)(y)-1; i >= (x); i--) #define all(x) (x).begin(), (x).end() #ifdef LOCAL #define debug(x) \ cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \ << " " << __FILE__ << endl #define itrdebug(x) \ cerr << #x << " "; \ for (auto &el : (x)) { \ cerr << (el) << " "; \ } \ cerr << endl #define dassert(...) assert(__VA_ARGS__) #else #define debug(x) #define itrdebug(x) #define dassert(...) #endif // #define int long long typedef long long ll; const ll MOD = 1e9 + 7; const long double EPS = 1e-8; void solve(long long N, std::vector<long long> V, std::vector<long long> W, long long Q, std::vector<long long> v, std::vector<long long> L) { vector<vector<int>> dp(min<int>(pow(2, 10) + 1, N + 1), vector<int>(1e5 + 1, 0)); rep(i, 1, dp.size()) { int parent = i / 2; rep(j, 0, dp.front().size()) { dp[i][j] = dp[parent][j]; if (j - W[i] >= 0) dp[i][j] = max<int>(dp[i][j], dp[parent][j - W[i]] + V[i]); if (j > 0) dp[i][j] = max(dp[i][j], dp[i][j - 1]); } } rep(ti, 0, Q) { if (v[ti] < dp.size()) { cout << dp[v[ti]][L[ti]] << endl; continue; } vector<pair<int, int>> items; int current = v[ti]; while (current >= dp.size()) { items.emplace_back(W[current], V[current]); current /= 2; } int answer = 0; rep(i, 0, 1 << items.size()) { int weightSum = 0, valueSum = 0; rep(j, 0, items.size()) { if (i & (1 << j)) { weightSum += items[j].first; valueSum += items[j].second; } if (weightSum > L[ti]) break; } if (weightSum <= L[ti]) { answer = max(answer, valueSum + dp[current][L[ti] - weightSum]); } } cout << answer << endl; } } signed main() { // ios_base::sync_with_stdio(false); // cin.tie(NULL); long long N; scanf("%lld", &N); std::vector<long long> V(N + 1); std::vector<long long> W(N + 1); for (int i = 1; i <= N; i++) { scanf("%lld", &V[i]); scanf("%lld", &W[i]); } long long Q; scanf("%lld", &Q); std::vector<long long> v(Q); std::vector<long long> L(Q); for (int i = 0; i < Q; i++) { scanf("%lld", &v[i]); scanf("%lld", &L[i]); } solve(N, std::move(V), std::move(W), Q, std::move(v), std::move(L)); return 0; }
replace
30
31
30
31
TLE
p02648
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i) #define FOR(i, a, b) for (int i = (a), i##_len = (b); i < i##_len; i++) #define FORD(i, a, b) for (int i = (a), i##_len = (b); i > i##_len; i--) #define ALL(x) (x).begin(), (x).end() // sortなどの引数を省略したい #define MAX(x) *max_element(ALL(x)) #define MIN(x) *min_element(ALL(x)) int main() { int n, q; cin >> n; vector<tuple<int, int>> vw(n); REP(i, n) { int a, b; cin >> a >> b; vw[i] = make_tuple(a, b); } cin >> q; vector<tuple<int, int>> vl(q); REP(i, q) { int a, b; cin >> a >> b; vl[i] = make_tuple(a, b); } int former = min(4, n); vector<vector<int>> former_dp(former, vector<int>(100001, -1)); vector<set<int>> former_set(former); former_dp[0][0] = 0; former_dp[0][get<1>(vw[0])] = get<0>(vw[0]); former_set[0].insert(0); former_set[0].insert(get<1>(vw[0])); FOR(i, 1, former) { int v, w; tie(v, w) = vw[i]; auto &anc_dp = former_dp[(i - 1) / 2]; auto &now_dp = former_dp[i]; auto &anc_set = former_set[(i - 1) / 2]; auto &now_set = former_set[i]; for (auto j : anc_set) { now_dp[j] = anc_dp[j]; now_set.insert(j); } for (auto j : anc_set) { if (w + j <= 100000) { now_dp[w + j] = max(now_dp[w + j], anc_dp[j] + v); now_set.insert(w + j); } } } REP(i, former) { int m = 0; auto &now_dp = former_dp[i]; FOR(j, 1, 100001) { m = max(m, now_dp[j]); now_dp[j] = m; } } for (auto temp : vl) { int v, l; tie(v, l) = temp; if (v <= former) { cout << former_dp[v - 1][l] << endl; continue; } vector<tuple<int, int>> later; int vv = v; while (vv > former) { later.push_back(vw[vv - 1]); vv >>= 1; } auto &anc_dp = former_dp[vv - 1]; int m = later.size(); int ans = 0; REP(i, pow(2, m)) { int v_sum = 0; int w_sum = 0; int ii = i; for (auto temp : later) { int j, k; tie(j, k) = temp; if (ii & 1) { v_sum += j; w_sum += k; } ii >>= 1; } if (w_sum > l) { continue; } ans = max(ans, v_sum + anc_dp[l - w_sum]); } cout << ans << endl; } }
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i) #define FOR(i, a, b) for (int i = (a), i##_len = (b); i < i##_len; i++) #define FORD(i, a, b) for (int i = (a), i##_len = (b); i > i##_len; i--) #define ALL(x) (x).begin(), (x).end() // sortなどの引数を省略したい #define MAX(x) *max_element(ALL(x)) #define MIN(x) *min_element(ALL(x)) int main() { int n, q; cin >> n; vector<tuple<int, int>> vw(n); REP(i, n) { int a, b; cin >> a >> b; vw[i] = make_tuple(a, b); } cin >> q; vector<tuple<int, int>> vl(q); REP(i, q) { int a, b; cin >> a >> b; vl[i] = make_tuple(a, b); } int former = min(512, n); vector<vector<int>> former_dp(former, vector<int>(100001, -1)); vector<set<int>> former_set(former); former_dp[0][0] = 0; former_dp[0][get<1>(vw[0])] = get<0>(vw[0]); former_set[0].insert(0); former_set[0].insert(get<1>(vw[0])); FOR(i, 1, former) { int v, w; tie(v, w) = vw[i]; auto &anc_dp = former_dp[(i - 1) / 2]; auto &now_dp = former_dp[i]; auto &anc_set = former_set[(i - 1) / 2]; auto &now_set = former_set[i]; for (auto j : anc_set) { now_dp[j] = anc_dp[j]; now_set.insert(j); } for (auto j : anc_set) { if (w + j <= 100000) { now_dp[w + j] = max(now_dp[w + j], anc_dp[j] + v); now_set.insert(w + j); } } } REP(i, former) { int m = 0; auto &now_dp = former_dp[i]; FOR(j, 1, 100001) { m = max(m, now_dp[j]); now_dp[j] = m; } } for (auto temp : vl) { int v, l; tie(v, l) = temp; if (v <= former) { cout << former_dp[v - 1][l] << endl; continue; } vector<tuple<int, int>> later; int vv = v; while (vv > former) { later.push_back(vw[vv - 1]); vv >>= 1; } auto &anc_dp = former_dp[vv - 1]; int m = later.size(); int ans = 0; REP(i, pow(2, m)) { int v_sum = 0; int w_sum = 0; int ii = i; for (auto temp : later) { int j, k; tie(j, k) = temp; if (ii & 1) { v_sum += j; w_sum += k; } ii >>= 1; } if (w_sum > l) { continue; } ans = max(ans, v_sum + anc_dp[l - w_sum]); } cout << ans << endl; } }
replace
27
28
27
28
TLE
p02649
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; template <typename T> void out(T x) { cout << x << endl; exit(0); } #define watch(x) cout << (#x) << " is " << (x) << endl using ll = long long; const ll mod = 1e9 + 7; const int maxn = 1e6 + 5; int n, k, S, T; // S: AND // T: OR bool compat(int x) { if ((x | T) != T) return false; if ((x & S) != S) return false; return true; } bool ok(ll mask) { // check S for (int i = 0; i < 18; i++) { if (!(S >> i & 1)) { if (mask >> i & 1) { if (!((mask >> (i + 18)) & 1)) { return false; } } } } // check T for (int i = 0; i < 18; i++) { if (T >> i & 1) { if (!(mask >> i & 1)) { return false; } } else { if (mask >> i & 1) { return false; } } } return true; } ll make(int x, ll mask) { for (int j = 0; j < 18; j++) { if (x >> j & 1) { mask |= (1ll << j); } else { mask |= (1ll << (18 + j)); } } return mask; } unordered_map<ll, ll> dp[55]; // dp[size][have] int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> k >> S >> T; if ((S & T) != S) out(0); vector<int> a; while (n--) { int x; cin >> x; if (compat(x)) { a.push_back(x); } } dp[0][0] = 1; for (int x : a) { for (int sz = k - 1; sz >= 0; sz--) { for (auto p : dp[sz]) { ll nmask = make(x, p.first); dp[sz + 1][nmask] += p.second; } } } ll res = 0; for (int i = 1; i <= k; i++) { for (auto p : dp[i]) { if (ok(p.first)) { res += p.second; } } } cout << res << endl; return 0; }
#include <bits/stdc++.h> using namespace std; template <typename T> void out(T x) { cout << x << endl; exit(0); } #define watch(x) cout << (#x) << " is " << (x) << endl using ll = long long; const ll mod = 1e9 + 7; const int maxn = 1e6 + 5; int n, k, S, T; // S: AND // T: OR bool compat(int x) { if ((x | T) != T) return false; if ((x & S) != S) return false; return true; } bool ok(ll mask) { // check S for (int i = 0; i < 18; i++) { if (!(S >> i & 1)) { if (mask >> i & 1) { if (!((mask >> (i + 18)) & 1)) { return false; } } } } // check T for (int i = 0; i < 18; i++) { if (T >> i & 1) { if (!(mask >> i & 1)) { return false; } } else { if (mask >> i & 1) { return false; } } } return true; } ll make(ll x, ll mask) { mask |= x; x = (~x) & ((1 << 18) - 1); mask |= (x << 18); return mask; } unordered_map<ll, ll> dp[55]; // dp[size][have] int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> k >> S >> T; if ((S & T) != S) out(0); vector<int> a; while (n--) { int x; cin >> x; if (compat(x)) { a.push_back(x); } } dp[0][0] = 1; for (int x : a) { for (int sz = k - 1; sz >= 0; sz--) { for (auto p : dp[sz]) { ll nmask = make(x, p.first); dp[sz + 1][nmask] += p.second; } } } ll res = 0; for (int i = 1; i <= k; i++) { for (auto p : dp[i]) { if (ok(p.first)) { res += p.second; } } } cout << res << endl; return 0; }
replace
55
63
55
59
TLE
p02649
C++
Runtime Error
#include <bits/stdc++.h> #include <math.h> #define rep(i, n) for (int i = 0; i < (n); ++i) #define PI 3.14159265359 using namespace std; using ll = long long; using P = pair<int, int>; int cnt[1000000], cntid[50]; ll c[50][50], cc[50][50]; int main() { int n, k, s, t; cin >> n >> k >> s >> t; rep(i, 1000000) { cnt[i] = 0; } vector<int> atmp(n); rep(i, n) cin >> atmp[i]; rep(i, n + 1) rep(j, n + 1) c[i][j] = 0; rep(i, n + 1) { c[i][0] = 1; for (int j = 1; j <= i; j++) { c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; } } rep(i, n + 1) { cc[i][0] = 0; for (int j = 1; j <= n; j++) { cc[i][j] = cc[i][j - 1] + c[i][j]; } } // if si = 1 and ti = 0, no set meets the condition; // if si = 0 and ti = 1, the i-th bit is to be considered; vector<int> bit; int maxb = -1; rep(i, 20) { int si = (s >> i) & 1, ti = (t >> i) & 1; if (si == 1 && ti == 0) { cout << 0 << endl; return 0; } else if (si == 0 && ti == 1) { bit.push_back(i); maxb++; } } // if aij = 0 and sj = 1 or aij = 1 and tj = 0, ai is not included in any set; // only bits included in bit are added to a; vector<int> a; rep(i, n) { int ai = atmp[i]; bool flug = true; rep(j, 20) { int aij = (ai >> j) & 1, sj = (s >> j) & 1, tj = (t >> j) & 1; if ((aij == 0 && sj == 1) || (aij == 1 && tj == 0)) { flug = false; } } if (flug) { a.push_back(0); rep(j, bit.size()) { int aij = ai & (1 << bit[j]); if (aij) { maxb = max(maxb, j); a[a.size() - 1] += 1 << j; } } } } if (a.size() == 0) { cout << 0 << endl; return 0; } /* cout << "bit"; rep(i, bit.size()) cout << " " << bit[i]; cout << endl; cout << "a "; rep(i, a.size()) cout << a[i] << " "; cout << endl; cout << "maxb " << maxb << endl; */ ll ans = 0; rep(i, 1 << (maxb + 1)) { int one = 0; rep(l, maxb + 1) one += (i >> l) & 1; // cout << "one " << one << endl; rep(l, a.size()) { int ani = a[l] & i; cnt[ani]++; cntid[l] = ani; } // cout << "i:" << i << ":"; rep(l, 1<<(maxb + 1)) cout << " " << cnt[l]; // cout << endl; ll co = (one % 2 == 0) ? 1 : -1; rep(l, a.size()) { // choose at most k element from a set of size cnt[cntid[l]]; ans += co * cc[cnt[cntid[l]]][k]; cnt[cntid[l]] = 0; } } cout << ans << endl; return 0; } /* */
#include <bits/stdc++.h> #include <math.h> #define rep(i, n) for (int i = 0; i < (n); ++i) #define PI 3.14159265359 using namespace std; using ll = long long; using P = pair<int, int>; int cnt[1000000], cntid[50]; ll c[51][51], cc[51][51]; int main() { int n, k, s, t; cin >> n >> k >> s >> t; rep(i, 1000000) { cnt[i] = 0; } vector<int> atmp(n); rep(i, n) cin >> atmp[i]; rep(i, n + 1) rep(j, n + 1) c[i][j] = 0; rep(i, n + 1) { c[i][0] = 1; for (int j = 1; j <= i; j++) { c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; } } rep(i, n + 1) { cc[i][0] = 0; for (int j = 1; j <= n; j++) { cc[i][j] = cc[i][j - 1] + c[i][j]; } } // if si = 1 and ti = 0, no set meets the condition; // if si = 0 and ti = 1, the i-th bit is to be considered; vector<int> bit; int maxb = -1; rep(i, 20) { int si = (s >> i) & 1, ti = (t >> i) & 1; if (si == 1 && ti == 0) { cout << 0 << endl; return 0; } else if (si == 0 && ti == 1) { bit.push_back(i); maxb++; } } // if aij = 0 and sj = 1 or aij = 1 and tj = 0, ai is not included in any set; // only bits included in bit are added to a; vector<int> a; rep(i, n) { int ai = atmp[i]; bool flug = true; rep(j, 20) { int aij = (ai >> j) & 1, sj = (s >> j) & 1, tj = (t >> j) & 1; if ((aij == 0 && sj == 1) || (aij == 1 && tj == 0)) { flug = false; } } if (flug) { a.push_back(0); rep(j, bit.size()) { int aij = ai & (1 << bit[j]); if (aij) { maxb = max(maxb, j); a[a.size() - 1] += 1 << j; } } } } if (a.size() == 0) { cout << 0 << endl; return 0; } /* cout << "bit"; rep(i, bit.size()) cout << " " << bit[i]; cout << endl; cout << "a "; rep(i, a.size()) cout << a[i] << " "; cout << endl; cout << "maxb " << maxb << endl; */ ll ans = 0; rep(i, 1 << (maxb + 1)) { int one = 0; rep(l, maxb + 1) one += (i >> l) & 1; // cout << "one " << one << endl; rep(l, a.size()) { int ani = a[l] & i; cnt[ani]++; cntid[l] = ani; } // cout << "i:" << i << ":"; rep(l, 1<<(maxb + 1)) cout << " " << cnt[l]; // cout << endl; ll co = (one % 2 == 0) ? 1 : -1; rep(l, a.size()) { // choose at most k element from a set of size cnt[cntid[l]]; ans += co * cc[cnt[cntid[l]]][k]; cnt[cntid[l]] = 0; } } cout << ans << endl; return 0; } /* */
replace
9
10
9
10
0
p02649
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; using P = pair<int, int>; const int M = 1000000007; int main() { cin.tie(0); ios::sync_with_stdio(0); int n, k, s, t; cin >> n >> k >> s >> t; if ((s | t) != t) { cout << 0 << '\n'; return 0; } vector<int> a; for (int i = 0; i < n; ++i) { int aa; cin >> aa; if ((aa & s) == s && (aa | t) == t) { a.push_back(aa); } } n = a.size(); k = min(n, k); vector<P> cond; for (int i = 0; i < 18; ++i) { if (((s >> i) & 1) == 0) { cond.push_back({i, 0}); } if (((t >> i) & 1) == 1) { cond.push_back({i, 1}); } } vector<unordered_map<long long, long long>> dp(k + 1); dp[0][0] = 1; for (int i = 0; i < n; ++i) { long long mask = 0; for (int j = 0; j < (int)cond.size(); ++j) { if (((a[i] >> cond[j].first) & 1) == cond[j].second) { mask ^= 1LL << j; } } for (int j = k - 1; j >= 0; --j) { for (auto &l : dp[j]) { dp[j + 1][l.first | mask] += l.second; } } } long long ans = 0; for (auto &i : dp) { ans += i[(1LL << (int)cond.size()) - 1]; } cout << ans << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; using P = pair<int, int>; const int M = 1000000007; int main() { cin.tie(0); ios::sync_with_stdio(0); int n, k, s, t; cin >> n >> k >> s >> t; if ((s | t) != t) { cout << 0 << '\n'; return 0; } vector<int> a; for (int i = 0; i < n; ++i) { int aa; cin >> aa; if ((aa & s) == s && (aa | t) == t) { a.push_back(aa); } } n = a.size(); k = min(n, k); vector<P> cond; for (int i = 0; i < 18; ++i) { if (((s >> i) & 1) == 0) { cond.push_back({i, 0}); } if (((t >> i) & 1) == 1) { cond.push_back({i, 1}); } } vector<unordered_map<long long, long long>> dp(k + 1); for (int i = 0; i <= k; ++i) { dp[i].reserve(1 << 18); } dp[0][0] = 1; for (int i = 0; i < n; ++i) { long long mask = 0; for (int j = 0; j < (int)cond.size(); ++j) { if (((a[i] >> cond[j].first) & 1) == cond[j].second) { mask ^= 1LL << j; } } for (int j = k - 1; j >= 0; --j) { for (auto &l : dp[j]) { dp[j + 1][l.first | mask] += l.second; } } } long long ans = 0; for (auto &i : dp) { ans += i[(1LL << (int)cond.size()) - 1]; } cout << ans << '\n'; return 0; }
insert
34
34
34
37
TLE
p02649
C++
Time Limit Exceeded
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; // not a multiset // find_by_order(k) -> itr of k-th(0-based) element // order_of_key(k) -> index of lower_bound(k) using ordered_set = tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>; // https://codeforces.com/blog/entry/62393 struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; template <class t, class u> using hash_table = gp_hash_table<t, u, custom_hash>; // count が使えない // find を,しようね! // move コンストラクタがないのでマージテクで壊れる バカ using ll = long long; #define int ll #define rng(i, a, b) for (int i = int(a); i < int(b); i++) #define rep(i, b) rng(i, 0, b) #define gnr(i, a, b) for (int i = int(b) - 1; i >= int(a); i--) #define per(i, b) gnr(i, 0, b) #define pb push_back #define eb emplace_back #define a first #define b second #define bg begin() #define ed end() #define all(x) x.bg, x.ed #define si(x) int(x.size()) #ifdef LOCAL #define dmp(x) cerr << __LINE__ << " " << #x << " " << x << endl #else #define dmp(x) void(0) #endif template <class t, class u> void chmax(t &a, u b) { if (a < b) a = b; } template <class t, class u> void chmin(t &a, u b) { if (b < a) a = b; } template <class t> using vc = vector<t>; template <class t> using vvc = vc<vc<t>>; using pi = pair<int, int>; using vi = vc<int>; template <class t, class u> ostream &operator<<(ostream &os, const pair<t, u> &p) { return os << "{" << p.a << "," << p.b << "}"; } template <class t> ostream &operator<<(ostream &os, const vc<t> &v) { os << "{"; for (auto e : v) os << e << ","; return os << "}"; } #define mp make_pair #define mt make_tuple #define one(x) memset(x, -1, sizeof(x)) #define zero(x) memset(x, 0, sizeof(x)) #ifdef LOCAL void dmpr(ostream &os) { os << endl; } template <class T, class... Args> void dmpr(ostream &os, const T &t, const Args &...args) { os << t << " "; dmpr(os, args...); } #define dmp2(...) dmpr(cerr, __LINE__, ##__VA_ARGS__) #else #define dmp2(...) void(0) #endif using uint = unsigned; using ull = unsigned long long; template <class t, size_t n> ostream &operator<<(ostream &os, const array<t, n> &a) { return os << vc<t>(all(a)); } template <int i, class T> void print_tuple(ostream &, const T &) {} template <int i, class T, class H, class... Args> void print_tuple(ostream &os, const T &t) { if (i) os << ","; os << get<i>(t); print_tuple<i + 1, T, Args...>(os, t); } template <class... Args> ostream &operator<<(ostream &os, const tuple<Args...> &t) { os << "{"; print_tuple<0, tuple<Args...>, Args...>(os, t); return os << "}"; } template <class t> void print(t x, int suc = 1) { cout << x; if (suc == 1) cout << "\n"; if (suc == 2) cout << " "; } ll read() { ll i; cin >> i; return i; } vi readvi(int n, int off = 0) { vi v(n); rep(i, n) v[i] = read() + off; return v; } template <class T> void print(const vector<T> &v, int suc = 1) { rep(i, v.size()) print(v[i], i == int(v.size()) - 1 ? suc : 2); } string readString() { string s; cin >> s; return s; } template <class T> T sq(const T &t) { return t * t; } // #define CAPITAL void yes(bool ex = true) { #ifdef CAPITAL cout << "YES" << "\n"; #else cout << "Yes" << "\n"; #endif if (ex) exit(0); } void no(bool ex = true) { #ifdef CAPITAL cout << "NO" << "\n"; #else cout << "No" << "\n"; #endif if (ex) exit(0); } void possible(bool ex = true) { #ifdef CAPITAL cout << "POSSIBLE" << "\n"; #else cout << "Possible" << "\n"; #endif if (ex) exit(0); } void impossible(bool ex = true) { #ifdef CAPITAL cout << "IMPOSSIBLE" << "\n"; #else cout << "Impossible" << "\n"; #endif if (ex) exit(0); } constexpr ll ten(int n) { return n == 0 ? 1 : ten(n - 1) * 10; } const ll infLL = LLONG_MAX / 3; #ifdef int const int inf = infLL; #else const int inf = INT_MAX / 2 - 100; #endif int topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); } int topbit(ll t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); } int botbit(signed a) { return a == 0 ? 32 : __builtin_ctz(a); } int botbit(ll a) { return a == 0 ? 64 : __builtin_ctzll(a); } int popcount(signed t) { return __builtin_popcount(t); } int popcount(ll t) { return __builtin_popcountll(t); } bool ispow2(int i) { return i && (i & -i) == i; } ll mask(int i) { return (ll(1) << i) - 1; } bool inc(int a, int b, int c) { return a <= b && b <= c; } template <class t> void mkuni(vc<t> &v) { sort(all(v)); v.erase(unique(all(v)), v.ed); } ll rand_int(ll l, ll r) { //[l, r] #ifdef LOCAL static mt19937_64 gen; #else static mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count()); #endif return uniform_int_distribution<ll>(l, r)(gen); } template <class t> void myshuffle(vc<t> &a) { rep(i, si(a)) swap(a[i], a[rand_int(0, i)]); } template <class t> int lwb(const vc<t> &v, const t &a) { return lower_bound(all(v), a) - v.bg; } void sub(vi a, int len, int k) { // dmp2(a,len,k); int n = si(a); chmin(k, n); /*int ans=0; rep(bit,1<<n){ int x=mask(len),y=0; rep(i,n)if(bit&1<<i){ x&=a[i]; y|=a[i]; } if(popcount(bit)<=k&&x==0&&y==mask(len)) ans++; } print(ans);*/ const int m = mask(len); sort(all(a), [&](int i, int j) { return popcount(i) > popcount(j); }); using ht = hash_table<int, int>; vvc<ht> memo(n, vc<ht>(k)); auto rec = [&](auto self, int i, int j, int x, int y) -> int { if (i == n || j == k) return x == 0 && y == m; int idx = (x << len) + y; auto itr = memo[i][j].find(idx); if (itr != memo[i][j].ed) return itr->b; int res = self(self, i + 1, j, x, y); res += self(self, i + 1, j + 1, x & a[i], y | a[i]); return memo[i][j][idx] = res; }; print(rec(rec, 0, 0, m, 0)); } signed main() { cin.tie(0); ios::sync_with_stdio(0); cout << fixed << setprecision(20); int n, k, s, t; cin >> n >> k >> s >> t; if ((s & t) != s) { dmp(0); print(0); return 0; } int dif = t ^ s; vi pos; rep(i, 18) if (dif & 1 << i) pos.pb(i); // dmp(pos); vi a; rep(_, n) { int x; cin >> x; if ((x & s) != s) continue; if ((x & ~t)) continue; int y = 0; rep(i, si(pos)) y += ((x >> pos[i]) & 1) << i; a.pb(y); } sub(a, si(pos), k); }
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; // not a multiset // find_by_order(k) -> itr of k-th(0-based) element // order_of_key(k) -> index of lower_bound(k) using ordered_set = tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>; // https://codeforces.com/blog/entry/62393 struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; template <class t, class u> using hash_table = gp_hash_table<t, u, custom_hash>; // count が使えない // find を,しようね! // move コンストラクタがないのでマージテクで壊れる バカ using ll = long long; #define int ll #define rng(i, a, b) for (int i = int(a); i < int(b); i++) #define rep(i, b) rng(i, 0, b) #define gnr(i, a, b) for (int i = int(b) - 1; i >= int(a); i--) #define per(i, b) gnr(i, 0, b) #define pb push_back #define eb emplace_back #define a first #define b second #define bg begin() #define ed end() #define all(x) x.bg, x.ed #define si(x) int(x.size()) #ifdef LOCAL #define dmp(x) cerr << __LINE__ << " " << #x << " " << x << endl #else #define dmp(x) void(0) #endif template <class t, class u> void chmax(t &a, u b) { if (a < b) a = b; } template <class t, class u> void chmin(t &a, u b) { if (b < a) a = b; } template <class t> using vc = vector<t>; template <class t> using vvc = vc<vc<t>>; using pi = pair<int, int>; using vi = vc<int>; template <class t, class u> ostream &operator<<(ostream &os, const pair<t, u> &p) { return os << "{" << p.a << "," << p.b << "}"; } template <class t> ostream &operator<<(ostream &os, const vc<t> &v) { os << "{"; for (auto e : v) os << e << ","; return os << "}"; } #define mp make_pair #define mt make_tuple #define one(x) memset(x, -1, sizeof(x)) #define zero(x) memset(x, 0, sizeof(x)) #ifdef LOCAL void dmpr(ostream &os) { os << endl; } template <class T, class... Args> void dmpr(ostream &os, const T &t, const Args &...args) { os << t << " "; dmpr(os, args...); } #define dmp2(...) dmpr(cerr, __LINE__, ##__VA_ARGS__) #else #define dmp2(...) void(0) #endif using uint = unsigned; using ull = unsigned long long; template <class t, size_t n> ostream &operator<<(ostream &os, const array<t, n> &a) { return os << vc<t>(all(a)); } template <int i, class T> void print_tuple(ostream &, const T &) {} template <int i, class T, class H, class... Args> void print_tuple(ostream &os, const T &t) { if (i) os << ","; os << get<i>(t); print_tuple<i + 1, T, Args...>(os, t); } template <class... Args> ostream &operator<<(ostream &os, const tuple<Args...> &t) { os << "{"; print_tuple<0, tuple<Args...>, Args...>(os, t); return os << "}"; } template <class t> void print(t x, int suc = 1) { cout << x; if (suc == 1) cout << "\n"; if (suc == 2) cout << " "; } ll read() { ll i; cin >> i; return i; } vi readvi(int n, int off = 0) { vi v(n); rep(i, n) v[i] = read() + off; return v; } template <class T> void print(const vector<T> &v, int suc = 1) { rep(i, v.size()) print(v[i], i == int(v.size()) - 1 ? suc : 2); } string readString() { string s; cin >> s; return s; } template <class T> T sq(const T &t) { return t * t; } // #define CAPITAL void yes(bool ex = true) { #ifdef CAPITAL cout << "YES" << "\n"; #else cout << "Yes" << "\n"; #endif if (ex) exit(0); } void no(bool ex = true) { #ifdef CAPITAL cout << "NO" << "\n"; #else cout << "No" << "\n"; #endif if (ex) exit(0); } void possible(bool ex = true) { #ifdef CAPITAL cout << "POSSIBLE" << "\n"; #else cout << "Possible" << "\n"; #endif if (ex) exit(0); } void impossible(bool ex = true) { #ifdef CAPITAL cout << "IMPOSSIBLE" << "\n"; #else cout << "Impossible" << "\n"; #endif if (ex) exit(0); } constexpr ll ten(int n) { return n == 0 ? 1 : ten(n - 1) * 10; } const ll infLL = LLONG_MAX / 3; #ifdef int const int inf = infLL; #else const int inf = INT_MAX / 2 - 100; #endif int topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); } int topbit(ll t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); } int botbit(signed a) { return a == 0 ? 32 : __builtin_ctz(a); } int botbit(ll a) { return a == 0 ? 64 : __builtin_ctzll(a); } int popcount(signed t) { return __builtin_popcount(t); } int popcount(ll t) { return __builtin_popcountll(t); } bool ispow2(int i) { return i && (i & -i) == i; } ll mask(int i) { return (ll(1) << i) - 1; } bool inc(int a, int b, int c) { return a <= b && b <= c; } template <class t> void mkuni(vc<t> &v) { sort(all(v)); v.erase(unique(all(v)), v.ed); } ll rand_int(ll l, ll r) { //[l, r] #ifdef LOCAL static mt19937_64 gen; #else static mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count()); #endif return uniform_int_distribution<ll>(l, r)(gen); } template <class t> void myshuffle(vc<t> &a) { rep(i, si(a)) swap(a[i], a[rand_int(0, i)]); } template <class t> int lwb(const vc<t> &v, const t &a) { return lower_bound(all(v), a) - v.bg; } void sub(vi a, int len, int k) { // dmp2(a,len,k); int n = si(a); chmin(k, n); vvc<int> w(n, vi(n)); w[0][0] = 1; rng(i, 1, n) { rep(j, i) { w[i][j] += w[i - 1][j]; w[i][j + 1] += w[i - 1][j]; } } rep(i, n) rep(j, n - 1) w[i][j + 1] += w[i][j]; int ans = 0; rep(i, n) { vi buf(1 << len); rep(j, i) buf[a[i] ^ a[j]]++; rep(lv, len) rep(bit, 1 << len) if (bit & 1 << lv) buf[bit] += buf[bit ^ 1 << lv]; rep(bit, 1 << len) { ans += w[buf[bit]][k - 1] * ((len - popcount(bit)) % 2 == 0 ? 1 : -1); } } print(ans); } signed main() { cin.tie(0); ios::sync_with_stdio(0); cout << fixed << setprecision(20); int n, k, s, t; cin >> n >> k >> s >> t; if ((s & t) != s) { dmp(0); print(0); return 0; } int dif = t ^ s; vi pos; rep(i, 18) if (dif & 1 << i) pos.pb(i); // dmp(pos); vi a; rep(_, n) { int x; cin >> x; if ((x & s) != s) continue; if ((x & ~t)) continue; int y = 0; rep(i, si(pos)) y += ((x >> pos[i]) & 1) << i; a.pb(y); } sub(a, si(pos), k); }
replace
249
276
249
269
TLE
p02649
C++
Runtime Error
#include <bits/stdc++.h> #define ADD(a, b) a = (a + ll(b)) % mod #define MUL(a, b) a = (a * ll(b)) % mod #define MAX(a, b) a = max(a, b) #define MIN(a, b) a = min(a, b) #define rep(i, a, b) for (int i = int(a); i < int(b); i++) #define rer(i, a, b) for (int i = int(a) - 1; i >= int(b); i--) #define all(a) (a).begin(), (a).end() #define sz(v) (int)(v).size() #define pb push_back #define sec second #define fst first #define debug(fmt, ...) Debug(__LINE__, ":", fmt, ##__VA_ARGS__) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pi; typedef pair<ll, ll> pl; typedef pair<int, pi> ppi; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vl> mat; typedef complex<double> comp; void Debug() { cerr << '\n'; } template <class FIRST, class... REST> void Debug(FIRST arg, REST... rest) { cerr << arg << " "; Debug(rest...); } template <class T> ostream &operator<<(ostream &out, const vector<T> &v) { out << "["; if (!v.empty()) { rep(i, 0, sz(v) - 1) out << v[i] << ", "; out << v.back(); } out << "]"; return out; } template <class S, class T> ostream &operator<<(ostream &out, const pair<S, T> &v) { out << "(" << v.first << ", " << v.second << ")"; return out; } const int MAX_N = 500010; const int MAX_V = 100010; const double eps = 1e-6; const ll mod = 1000000007; const int inf = (1 << 30) - 1; const ll linf = 1LL << 60; const double PI = 3.14159265358979323846; mt19937 rng; // use it by rng() % mod, shuffle(all(vec), rng) /////////////////////////////////////////////////////////////////////////////////////////////////// ll C[2010][2010]; void C_init(int n) { n++; rep(i, 0, n) C[i][0] = 1; rep(i, 1, n) { rep(j, 1, i + 1) { C[i][j] = C[i - 1][j] + C[i - 1][j - 1]; } } } vector<ll> moebius(vector<ll> f) { // inverse of the first zeta int n = sz(f); for (int i = 0; (1 << i) < n; i++) { rep(j, 0, n) if (!(j & (1 << i))) f[j] -= f[j | (1 << i)]; } return f; } int N, K, S, T; int A[110]; const int L = 5; ll dp[(1 << L)]; void solve() { C_init(51); cin >> N >> K >> T >> S; // S-> or, T-> and if ((S & T) != T) { cout << 0 << "\n"; return; } int M = 0; rep(i, 0, N) { int a; cin >> a; if (((T & a) == T) && (S & a) == a) A[M++] = a; } N = M; rep(bit, 0, (1 << L)) { //(1が立っているところが0) rep(i, 0, N) { int cnt = 0; rep(j, i + 1, N) { if ((A[i] & bit) == (A[j] & bit)) cnt++; } rep(j, 0, min(cnt, K - 1) + 1) { dp[bit] += C[cnt][j]; } } } // int rans = 0; // rep(i, 1, (1 << N)) { // int s = 0, t = (1 << L) - 1; // if(__builtin_popcount(i) > K) continue; // rep(j, 0, N) { // if(!(i & (1 << j))) continue; // s |= A[j]; // t &= A[j]; // } // if(s == S && t == T) rans++; // } auto ans = moebius(vl(dp, dp + (1 << L))); // debug(ans); cout << ans[((1 << L) - 1 - S) | T] << "\n"; } uint32_t rd() { uint32_t res; #ifdef __MINGW32__ asm volatile("rdrand %0" : "=a"(res)::"cc"); #else res = std::random_device()(); #endif return res; } int main() { #ifndef LOCAL ios::sync_with_stdio(false); cin.tie(0); #endif cout << fixed; cout.precision(20); cerr << fixed; cerr.precision(6); rng.seed(rd()); #ifdef LOCAL // freopen("in.txt", "wt", stdout); //for tester if (!freopen("in.txt", "rt", stdin)) return 1; #endif solve(); cerr << "Time: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; return 0; }
#include <bits/stdc++.h> #define ADD(a, b) a = (a + ll(b)) % mod #define MUL(a, b) a = (a * ll(b)) % mod #define MAX(a, b) a = max(a, b) #define MIN(a, b) a = min(a, b) #define rep(i, a, b) for (int i = int(a); i < int(b); i++) #define rer(i, a, b) for (int i = int(a) - 1; i >= int(b); i--) #define all(a) (a).begin(), (a).end() #define sz(v) (int)(v).size() #define pb push_back #define sec second #define fst first #define debug(fmt, ...) Debug(__LINE__, ":", fmt, ##__VA_ARGS__) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pi; typedef pair<ll, ll> pl; typedef pair<int, pi> ppi; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vl> mat; typedef complex<double> comp; void Debug() { cerr << '\n'; } template <class FIRST, class... REST> void Debug(FIRST arg, REST... rest) { cerr << arg << " "; Debug(rest...); } template <class T> ostream &operator<<(ostream &out, const vector<T> &v) { out << "["; if (!v.empty()) { rep(i, 0, sz(v) - 1) out << v[i] << ", "; out << v.back(); } out << "]"; return out; } template <class S, class T> ostream &operator<<(ostream &out, const pair<S, T> &v) { out << "(" << v.first << ", " << v.second << ")"; return out; } const int MAX_N = 500010; const int MAX_V = 100010; const double eps = 1e-6; const ll mod = 1000000007; const int inf = (1 << 30) - 1; const ll linf = 1LL << 60; const double PI = 3.14159265358979323846; mt19937 rng; // use it by rng() % mod, shuffle(all(vec), rng) /////////////////////////////////////////////////////////////////////////////////////////////////// ll C[2010][2010]; void C_init(int n) { n++; rep(i, 0, n) C[i][0] = 1; rep(i, 1, n) { rep(j, 1, i + 1) { C[i][j] = C[i - 1][j] + C[i - 1][j - 1]; } } } vector<ll> moebius(vector<ll> f) { // inverse of the first zeta int n = sz(f); for (int i = 0; (1 << i) < n; i++) { rep(j, 0, n) if (!(j & (1 << i))) f[j] -= f[j | (1 << i)]; } return f; } int N, K, S, T; int A[110]; const int L = 18; ll dp[(1 << L)]; void solve() { C_init(51); cin >> N >> K >> T >> S; // S-> or, T-> and if ((S & T) != T) { cout << 0 << "\n"; return; } int M = 0; rep(i, 0, N) { int a; cin >> a; if (((T & a) == T) && (S & a) == a) A[M++] = a; } N = M; rep(bit, 0, (1 << L)) { //(1が立っているところが0) rep(i, 0, N) { int cnt = 0; rep(j, i + 1, N) { if ((A[i] & bit) == (A[j] & bit)) cnt++; } rep(j, 0, min(cnt, K - 1) + 1) { dp[bit] += C[cnt][j]; } } } // int rans = 0; // rep(i, 1, (1 << N)) { // int s = 0, t = (1 << L) - 1; // if(__builtin_popcount(i) > K) continue; // rep(j, 0, N) { // if(!(i & (1 << j))) continue; // s |= A[j]; // t &= A[j]; // } // if(s == S && t == T) rans++; // } auto ans = moebius(vl(dp, dp + (1 << L))); // debug(ans); cout << ans[((1 << L) - 1 - S) | T] << "\n"; } uint32_t rd() { uint32_t res; #ifdef __MINGW32__ asm volatile("rdrand %0" : "=a"(res)::"cc"); #else res = std::random_device()(); #endif return res; } int main() { #ifndef LOCAL ios::sync_with_stdio(false); cin.tie(0); #endif cout << fixed; cout.precision(20); cerr << fixed; cerr.precision(6); rng.seed(rd()); #ifdef LOCAL // freopen("in.txt", "wt", stdout); //for tester if (!freopen("in.txt", "rt", stdin)) return 1; #endif solve(); cerr << "Time: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; return 0; }
replace
73
74
73
74
0
Time: 0.024163 s.
p02649
C++
Time Limit Exceeded
#include <bits/stdc++.h> #define REP(i, n) for (ll i = 0; i < n; i++) #define MP make_pair #define F first #define S second typedef long long ll; using namespace std; int main() { ll n, k, s, t, a[50]; cin >> n >> k >> s >> t; REP(i, n) cin >> a[i]; vector<map<pair<ll, ll>, ll>> dp(k); REP(i, n) { for (ll j = k - 2; j + 1; j--) { for (auto l = dp[j].begin(); l != dp[j].end(); l++) { dp[j + 1][MP((l->F.F) & a[i], (l->F.S) | a[i])] += (l->S); } } dp[0][MP(a[i], a[i])] = 1; } n = 0; REP(i, k) n += (dp[i][MP(s, t)]); cout << n; }
#include <bits/stdc++.h> #define REP(i, n) for (ll i = 0; i < n; i++) #define MP make_pair #define F first #define S second typedef long long ll; using namespace std; int main() { ll n, k, s, t, a[50]; cin >> n >> k >> s >> t; REP(i, n) cin >> a[i]; map<pair<ll, ll>, ll> dp[50]; REP(i, n) { for (ll j = k - 2; j + 1; j--) { for (auto l = dp[j].begin(); l != dp[j].end(); l++) { dp[j + 1][MP((l->F.F) & a[i], (l->F.S) | a[i])] += (l->S); } } dp[0][MP(a[i], a[i])] = 1; } n = 0; REP(i, k) n += (dp[i][MP(s, t)]); cout << n; }
replace
11
12
11
12
TLE
p02649
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 55; int a[N], n; ll c[N][N], sc[N][N]; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, k, s, t; cin >> n >> k >> s >> t; for (int i = 0; i < 18; i++) if ((s & (1 << i)) == 1 && (t & (1 << i)) == 0) { cout << "0\n"; return 0; } c[0][0] = 1; for (int i = 1; i <= n; ++i) { c[i][0] = 1; for (int j = 1; j <= i; ++j) c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; } for (int i = 0; i <= n; ++i) { sc[i][0] = 0; for (int j = 1; j <= k; ++j) sc[i][j] = sc[i][j - 1] + c[i][j]; } for (int i = 1; i <= n; ++i) cin >> a[i]; { static int b[N]; for (int i = 1; i <= n; ++i) b[i] = a[i]; int tot = 0; for (int i = 1; i <= n; ++i) { bool flg = 1; for (int j = 0; j < 18; ++j) { if ((s & (1 << j)) == (t & (1 << j)) && (a[i] & (1 << j)) != (s & (1 << j))) { flg = false; break; } } if (flg) b[++tot] = a[i]; } n = tot; for (int i = 1; i <= n; ++i) a[i] = b[i]; } ll ans = 0; for (int mask = s ^ t;; mask = (mask - 1) & (s ^ t)) { static int cnt[N]; for (int i = 1; i <= n; ++i) { ++cnt[a[i] & mask]; } ll tmp = 0; for (int i = 1; i <= n; ++i) { tmp += sc[cnt[a[i] & mask]][k]; cnt[a[i] & mask] = 0; } if (__builtin_popcount(mask) & 1) ans -= tmp; else ans += tmp; if (!mask) break; } cout << ans << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 55; int a[N], n; ll c[N][N], sc[N][N]; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, k, s, t; cin >> n >> k >> s >> t; for (int i = 0; i < 18; i++) if ((s & (1 << i)) == 1 && (t & (1 << i)) == 0) { cout << "0\n"; return 0; } c[0][0] = 1; for (int i = 1; i <= n; ++i) { c[i][0] = 1; for (int j = 1; j <= i; ++j) c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; } for (int i = 0; i <= n; ++i) { sc[i][0] = 0; for (int j = 1; j <= k; ++j) sc[i][j] = sc[i][j - 1] + c[i][j]; } for (int i = 1; i <= n; ++i) cin >> a[i]; { static int b[N]; for (int i = 1; i <= n; ++i) b[i] = a[i]; int tot = 0; for (int i = 1; i <= n; ++i) { bool flg = 1; for (int j = 0; j < 18; ++j) { if ((s & (1 << j)) == (t & (1 << j)) && (a[i] & (1 << j)) != (s & (1 << j))) { flg = false; break; } } if (flg) b[++tot] = a[i]; } n = tot; for (int i = 1; i <= n; ++i) a[i] = b[i]; } ll ans = 0; for (int mask = s ^ t;; mask = (mask - 1) & (s ^ t)) { static int cnt[1 << 19]; for (int i = 1; i <= n; ++i) { ++cnt[a[i] & mask]; } ll tmp = 0; for (int i = 1; i <= n; ++i) { tmp += sc[cnt[a[i] & mask]][k]; cnt[a[i] & mask] = 0; } if (__builtin_popcount(mask) & 1) ans -= tmp; else ans += tmp; if (!mask) break; } cout << ans << '\n'; return 0; }
replace
54
55
54
55
0
p02649
C++
Time Limit Exceeded
#include <bits/stdc++.h> using i64 = int64_t; template <class T> using Vec = std::vector<T>; template <class K, class V> using UM = std::unordered_map<K, V>; using namespace std; namespace std { template <> struct hash<pair<int, int>> { size_t operator()(pair<int, int> p) const noexcept { return (size_t(p.first) << 18) | (size_t(p.second)); } }; } // namespace std int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int n, k, s, t; cin >> n >> k >> s >> t; Vec<int> as(n); for (auto &a : as) cin >> a; if ((s & t) != s || (s | t) != t) { cout << 0; return 0; } auto invalid = [&](int a) { return s != (s & a) || t != (t | a); }; as.erase(remove_if(as.begin(), as.end(), invalid), as.end()); n = as.size(); Vec<UM<pair<int, int>, i64>> by_andor(k + 19); by_andor[0][{t, s}] = 1; for (auto &lvl : by_andor) lvl.reserve(1 << 14); int aand, oor; for (int i = 0; i < as.size(); ++i) { int a = as[i]; for (int j = min(i, k - 1); j >= 0; --j) { auto &next = by_andor[j + 1]; for (auto &[key, value] : by_andor[j]) { tie(aand, oor) = key; next[{aand & a, oor | a}] += value; } } } i64 ans = 0; for (int i = 0; i <= k; ++i) ans += by_andor[i][{s, t}]; cout << ans << '\n'; return 0; }
#include <bits/stdc++.h> using i64 = int64_t; template <class T> using Vec = std::vector<T>; template <class K, class V> using UM = std::unordered_map<K, V>; using namespace std; namespace std { template <> struct hash<pair<int, int>> { size_t operator()(pair<int, int> p) const noexcept { return (size_t(p.first) << 18) | (size_t(p.second)); } }; } // namespace std int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int n, k, s, t; cin >> n >> k >> s >> t; Vec<int> as(n); for (auto &a : as) cin >> a; if ((s & t) != s || (s | t) != t) { cout << 0; return 0; } auto invalid = [&](int a) { return s != (s & a) || t != (t | a); }; as.erase(remove_if(as.begin(), as.end(), invalid), as.end()); n = as.size(); Vec<UM<pair<int, int>, i64>> by_andor(k + 19); by_andor[0][{t, s}] = 1; for (auto &lvl : by_andor) lvl.reserve(1 << 18); int aand, oor; for (int i = 0; i < as.size(); ++i) { int a = as[i]; for (int j = min(i, k - 1); j >= 0; --j) { auto &next = by_andor[j + 1]; for (auto &[key, value] : by_andor[j]) { tie(aand, oor) = key; next[{aand & a, oor | a}] += value; } } } i64 ans = 0; for (int i = 0; i <= k; ++i) ans += by_andor[i][{s, t}]; cout << ans << '\n'; return 0; }
replace
41
42
41
42
TLE
p02649
C++
Time Limit Exceeded
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #define fi first #define se second #define pb push_back #define E "\n" using namespace std; const long long MOD = (long long)1e9 + 7; int n, k, s, t, a[55], sz, al; long long ans, candi[2][18], combi[60][60], F[60][60]; vector<int> vec; int cnt_bit(int x) { int cnt = 0; while (x) { if (x & 1) cnt++; x = x >> 1; } return cnt; } void fun(int cur, int sign, long long res, int v) { if (cur == 18) { int tmp = cnt_bit(res); // cout << sign * F[tmp][k - 1] << E; ans += sign * F[tmp][k - 1]; } else { if (((t >> cur) & 1) ^ ((s >> cur) & 1)) { if ((v >> cur) & 1) { fun(cur + 1, sign, res, v); fun(cur + 1, -sign, res & candi[1][cur], v); } else { fun(cur + 1, sign, res, v); fun(cur + 1, -sign, res & candi[0][cur], v); } } else fun(cur + 1, sign, res, v); } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); for (int i = 1; i <= 50; i++) combi[i][0] = 1; combi[1][1] = 1; for (int i = 2; i <= 50; i++) { for (int j = 1; j <= i; j++) { combi[i][j] = combi[i - 1][j] + combi[i - 1][j - 1]; } } for (int i = 1; i <= 50; i++) { F[i][0] = 0; for (int j = 1; j <= 50; j++) { F[i][j] = combi[i][j] + F[i][j - 1]; } } cin >> n >> k; cin >> s >> t; for (int i = 0; i < n; i++) cin >> a[i]; if (((s & t) != s) || ((s | t) != t)) { cout << 0 << E; } else { for (int i = 0; i < n; i++) { if ((a[i] & s) != s) continue; if ((a[i] | t) != t) continue; vec.pb(a[i]); } sz = vec.size(); for (int i = 0; i < sz; i++) { if (s == t && vec[i] == t) { ans++; } al = i; memset(candi, 0, sizeof(candi)); for (int j = 0; j < i; j++) { for (int u = 0; u < 18; u++) { candi[(vec[j] >> u) & 1][u] += 1LL << j; } } fun(0, 1, (1LL << al) - 1, vec[i]); } cout << ans << E; } // system("pause"); return 0; }
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #define fi first #define se second #define pb push_back #define E "\n" using namespace std; const long long MOD = (long long)1e9 + 7; int n, k, s, t, a[55], sz, al; long long ans, candi[2][18], combi[60][60], F[60][60]; vector<int> vec; int cnt_bit(long long x) { int cnt = 0; while (x) { if (x & 1) cnt++; x = x >> 1; } return cnt; } void fun(int cur, int sign, long long res, int v) { if (cur == 18) { int tmp = cnt_bit(res); // cout << sign * F[tmp][k - 1] << E; ans += sign * F[tmp][k - 1]; } else { if (((t >> cur) & 1) ^ ((s >> cur) & 1)) { if ((v >> cur) & 1) { fun(cur + 1, sign, res, v); fun(cur + 1, -sign, res & candi[1][cur], v); } else { fun(cur + 1, sign, res, v); fun(cur + 1, -sign, res & candi[0][cur], v); } } else fun(cur + 1, sign, res, v); } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); for (int i = 1; i <= 50; i++) combi[i][0] = 1; combi[1][1] = 1; for (int i = 2; i <= 50; i++) { for (int j = 1; j <= i; j++) { combi[i][j] = combi[i - 1][j] + combi[i - 1][j - 1]; } } for (int i = 1; i <= 50; i++) { F[i][0] = 0; for (int j = 1; j <= 50; j++) { F[i][j] = combi[i][j] + F[i][j - 1]; } } cin >> n >> k; cin >> s >> t; for (int i = 0; i < n; i++) cin >> a[i]; if (((s & t) != s) || ((s | t) != t)) { cout << 0 << E; } else { for (int i = 0; i < n; i++) { if ((a[i] & s) != s) continue; if ((a[i] | t) != t) continue; vec.pb(a[i]); } sz = vec.size(); for (int i = 0; i < sz; i++) { if (s == t && vec[i] == t) { ans++; } al = i; memset(candi, 0, sizeof(candi)); for (int j = 0; j < i; j++) { for (int u = 0; u < 18; u++) { candi[(vec[j] >> u) & 1][u] += 1LL << j; } } fun(0, 1, (1LL << al) - 1, vec[i]); } cout << ans << E; } // system("pause"); return 0; }
replace
14
15
14
15
TLE
p02649
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; int main() { int N, K, S, T; cin >> N >> K >> S >> T; vector<map<pair<int, int>, long long>> dp(K + 1); dp[0][{(1 << 18) - 1, 0}] = 1; for (int i = 0; i < N; ++i) { int a; cin >> a; for (int k = K - 1; k >= 0; --k) { for (auto &p : dp[k]) { int prod, sum; tie(prod, sum) = p.first; dp[k + 1][{prod & a, sum | a}] += p.second; } } } long long ans = 0; for (int k = 1; k <= K; ++k) { ans += dp[k][{S, T}]; } cout << ans << endl; return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int N, K, S, T; cin >> N >> K >> S >> T; vector<map<pair<int, int>, long long>> dp(K + 1); dp[0][{(1 << 18) - 1, 0}] = 1; for (int i = 0; i < N; ++i) { int a; cin >> a; if ((a & S) != S) continue; if ((a | T) != T) continue; for (int k = K - 1; k >= 0; --k) { for (auto &p : dp[k]) { int prod, sum; tie(prod, sum) = p.first; dp[k + 1][{prod & a, sum | a}] += p.second; } } } long long ans = 0; for (int k = 1; k <= K; ++k) { ans += dp[k][{S, T}]; } cout << ans << endl; return 0; }
insert
14
14
14
18
TLE
p02650
C++
Time Limit Exceeded
#pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") #define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define SZ(x) ((int)((x).size())) template <typename T1, typename T2> string print_iterable(T1 begin_iter, T2 end_iter, int counter) { bool done_something = false; stringstream res; res << "["; for (; begin_iter != end_iter and counter; ++begin_iter) { done_something = true; counter--; res << *begin_iter << ", "; } string str = res.str(); if (done_something) { str.pop_back(); str.pop_back(); } str += "]"; return str; } vector<int> SortIndex(int size, std::function<bool(int, int)> compare) { vector<int> ord(size); for (int i = 0; i < size; i++) ord[i] = i; sort(ord.begin(), ord.end(), compare); return ord; } template <typename T> bool MinPlace(T &a, const T &b) { if (a > b) { a = b; return true; } return false; } template <typename T> bool MaxPlace(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <typename S, typename T> ostream &operator<<(ostream &out, const pair<S, T> &p) { out << "{" << p.first << ", " << p.second << "}"; return out; } template <typename T> ostream &operator<<(ostream &out, const vector<T> &v) { out << "["; for (int i = 0; i < (int)v.size(); i++) { out << v[i]; if (i != (int)v.size() - 1) out << ", "; } out << "]"; return out; } template <class TH> void _dbg(const char *name, TH val) { clog << name << ": " << val << endl; } template <class TH, class... TA> void _dbg(const char *names, TH curr_val, TA... vals) { while (*names != ',') clog << *names++; clog << ": " << curr_val << ", "; _dbg(names + 1, vals...); } #if DEBUG && !ONLINE_JUDGE ifstream input_from_file("input.txt"); #define cin input_from_file #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__) #define dbg_arr(x, len) \ clog << #x << ": " << print_iterable(x, x + len, -1) << endl; #else #define dbg(...) #define dbg_arr(x, len) #endif /////////////////////////////////////////////////////////////////////////// //////////////////// DO NOT TOUCH BEFORE THIS LINE //////////////////////// /////////////////////////////////////////////////////////////////////////// LL solve(int W, int H, int K) { vector<int> preg(W); for (int i = 0; i < W; i++) preg[i] = __gcd(i, H); LL res = 0; for (int y = 1; y < H; y++) { for (int x1 = 1; x1 < W; x1++) { if ((H - y) * x1 > 2 * K + 2 * H) break; LL U = 2 * K - (H - y) * x1; if (((LL)y) * x1 <= U) { res += 2 * (x1 - 1) + 1; continue; } int low = 1; if (y <= U) { low = U / y; res += 2 * (low - 1); } int g = __gcd(x1, y); for (int x2 = low; x2 <= x1; x2++) { if (x1 != x2 and y * x2 > 2 * K + g + min(x2, H - y) + min(x1 - x2, H)) x2 = x1; if ((LL)y * x2 > 1e6) break; LL c = (H - y) * x1 + y * x2 - (g + __gcd(x2, H - y) + preg[x1 - x2]) + 2; if (c <= 2 * K) res += (x1 != x2) ? 2 : 1; } } } return res; } int main() { ios::sync_with_stdio(false); cin.tie(0); // Remove in problems with online queries! int W, H, K; cin >> W >> H >> K; LL ris1 = solve(W, H, K); LL ris2 = solve(H, W, K); cout << 2 * (ris1 + ris2) << endl; }
#pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") #define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define SZ(x) ((int)((x).size())) template <typename T1, typename T2> string print_iterable(T1 begin_iter, T2 end_iter, int counter) { bool done_something = false; stringstream res; res << "["; for (; begin_iter != end_iter and counter; ++begin_iter) { done_something = true; counter--; res << *begin_iter << ", "; } string str = res.str(); if (done_something) { str.pop_back(); str.pop_back(); } str += "]"; return str; } vector<int> SortIndex(int size, std::function<bool(int, int)> compare) { vector<int> ord(size); for (int i = 0; i < size; i++) ord[i] = i; sort(ord.begin(), ord.end(), compare); return ord; } template <typename T> bool MinPlace(T &a, const T &b) { if (a > b) { a = b; return true; } return false; } template <typename T> bool MaxPlace(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <typename S, typename T> ostream &operator<<(ostream &out, const pair<S, T> &p) { out << "{" << p.first << ", " << p.second << "}"; return out; } template <typename T> ostream &operator<<(ostream &out, const vector<T> &v) { out << "["; for (int i = 0; i < (int)v.size(); i++) { out << v[i]; if (i != (int)v.size() - 1) out << ", "; } out << "]"; return out; } template <class TH> void _dbg(const char *name, TH val) { clog << name << ": " << val << endl; } template <class TH, class... TA> void _dbg(const char *names, TH curr_val, TA... vals) { while (*names != ',') clog << *names++; clog << ": " << curr_val << ", "; _dbg(names + 1, vals...); } #if DEBUG && !ONLINE_JUDGE ifstream input_from_file("input.txt"); #define cin input_from_file #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__) #define dbg_arr(x, len) \ clog << #x << ": " << print_iterable(x, x + len, -1) << endl; #else #define dbg(...) #define dbg_arr(x, len) #endif /////////////////////////////////////////////////////////////////////////// //////////////////// DO NOT TOUCH BEFORE THIS LINE //////////////////////// /////////////////////////////////////////////////////////////////////////// LL solve(int W, int H, int K) { vector<int> preg(W); for (int i = 0; i < W; i++) preg[i] = __gcd(i, H); LL res = 0; for (int y = 1; y < H; y++) { for (int x1 = 1; x1 < W; x1++) { if ((H - y) * x1 > 2 * K + 2 * H) break; LL U = 2 * K - (H - y) * x1; if (((LL)y) * x1 <= U) { res += 2 * (x1 - 1) + 1; continue; } int low = 1; if (y <= U) { low = U / y; res += 2 * (low - 1); } int g = __gcd(x1, y); for (int x2 = low; x2 <= x1; x2++) { if (x1 != x2 and (H - y) * x1 + y * x2 > 2 * K + g + min(x2, H - y) + min(x1 - x2, H)) x2 = x1; if ((LL)y * x2 > 1e6) break; LL c = (H - y) * x1 + y * x2 - (g + __gcd(x2, H - y) + preg[x1 - x2]) + 2; if (c <= 2 * K) res += (x1 != x2) ? 2 : 1; } } } return res; } int main() { ios::sync_with_stdio(false); cin.tie(0); // Remove in problems with online queries! int W, H, K; cin >> W >> H >> K; LL ris1 = solve(W, H, K); LL ris2 = solve(H, W, K); cout << 2 * (ris1 + ris2) << endl; }
replace
120
121
120
122
TLE
p02650
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x, to) for (x = 0; x < (to); x++) #define FORR(x, arr) for (auto &x : arr) #define ITR(x, c) for (__typeof(c.begin()) x = c.begin(); x != c.end(); x++) #define ALL(a) (a.begin()), (a.end()) #define ZERO(a) memset(a, 0, sizeof(a)) #define MINUS(a) memset(a, 0xff, sizeof(a)) //------------------------------------------------------- int H, W, K; void solve() { int i, j, k, l, r, x, y; string s; cin >> H >> W >> K; ll ret = 0; FOR(i, 2) { for (int s = 0; s <= H - 2; s++) { int R = 2 * K + __gcd(s, W) - 2; ll pat = 0; for (x = 1; x < W; x++) { int R2 = R - s * x; if (R2 < 0) break; int Ymi = R2 / W; // if(Ymi) pat+=Ymi-1; // for(y=max(1,Ymi);y<=Ymi+2 && y+s<H;y++) { for (y = 1; y <= Ymi + 2 && y + s < H; y++) { ll v = 1LL * W * y - __gcd(x, y) - __gcd(W - x, y + s); if (v <= R2) pat++; } } ret += ((s == 0) ? 1 : 2) * pat; } swap(H, W); } cout << 2 * ret << endl; } int main(int argc, char **argv) { string s; int i; if (argc == 1) ios::sync_with_stdio(false), cin.tie(0); FOR(i, argc - 1) s += argv[i + 1], s += '\n'; FOR(i, s.size()) ungetc(s[s.size() - 1 - i], stdin); cout.tie(0); solve(); return 0; }
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x, to) for (x = 0; x < (to); x++) #define FORR(x, arr) for (auto &x : arr) #define ITR(x, c) for (__typeof(c.begin()) x = c.begin(); x != c.end(); x++) #define ALL(a) (a.begin()), (a.end()) #define ZERO(a) memset(a, 0, sizeof(a)) #define MINUS(a) memset(a, 0xff, sizeof(a)) //------------------------------------------------------- int H, W, K; void solve() { int i, j, k, l, r, x, y; string s; cin >> H >> W >> K; ll ret = 0; FOR(i, 2) { for (int s = 0; s <= H - 2; s++) { int R = 2 * K + __gcd(s, W) - 2; ll pat = 0; for (x = 1; x < W; x++) { int R2 = R - s * x; if (R2 < 0) break; int Ymi = min(H - s - 2, R2 / W - 1); if (Ymi > 0) pat += Ymi; for (y = max(1, Ymi + 1); y <= Ymi + 2 && y + s < H; y++) { ll v = 1LL * W * y - __gcd(x, y) - __gcd(W - x, y + s); if (v <= R2) pat++; } } ret += ((s == 0) ? 1 : 2) * pat; } swap(H, W); } cout << 2 * ret << endl; } int main(int argc, char **argv) { string s; int i; if (argc == 1) ios::sync_with_stdio(false), cin.tie(0); FOR(i, argc - 1) s += argv[i + 1], s += '\n'; FOR(i, s.size()) ungetc(s[s.size() - 1 - i], stdin); cout.tie(0); solve(); return 0; }
replace
31
35
31
35
TLE
p02650
C++
Time Limit Exceeded
#include <algorithm> #include <cmath> #include <complex> #include <cstdio> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; #define MOD 1000000007 #define MOD2 998244353 #define PRIM 3 #define INF (1 << 29) #define LINF (1LL << 60) #define EPS (1e-10) #define PI 3.1415926535897932384626433832795028 typedef long long Int; typedef pair<Int, Int> P; typedef long double Real; typedef complex<Real> CP; Int gcd(Int x, Int y) { if (x == 0) return y; return gcd(y % x, x); } Int inside(Int x1, Int y1, Int x2, Int y2) { Int s = abs(x1 * y2 - x2 * y1); s += 2; s -= gcd(abs(x1), abs(y1)); s -= gcd(abs(x2), abs(y2)); s -= gcd(abs(x2 - x1), abs(y2 - y1)); return s / 2; } Int cnt(Int w, Int h, Int k) { Int ans = 0; for (Int x = 1; x < w; x++) { for (Int s = 0; s < h - 1; s++) { if (inside(1, x, -s, w) > 2 * k) break; if (inside(1, x, -s, w) > k) continue; Int bottom = 1, top = h - s; while (top - bottom > 1) { Int mid = (top + bottom) / 2; if (inside(mid, x, -s, w) <= k) bottom = mid; else top = mid; } if (s == 0) ans += bottom; else ans += bottom * 2; } } return ans; } int main() { Int w, h, k; cin >> w >> h >> k; cout << 2 * cnt(w, h, k) + 2 * cnt(h, w, k) << endl; return 0; }
#include <algorithm> #include <cmath> #include <complex> #include <cstdio> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; #define MOD 1000000007 #define MOD2 998244353 #define PRIM 3 #define INF (1 << 29) #define LINF (1LL << 60) #define EPS (1e-10) #define PI 3.1415926535897932384626433832795028 typedef long long Int; typedef pair<Int, Int> P; typedef long double Real; typedef complex<Real> CP; Int gcd(Int x, Int y) { if (x == 0) return y; return gcd(y % x, x); } Int inside(Int x1, Int y1, Int x2, Int y2) { Int s = abs(x1 * y2 - x2 * y1); s += 2; s -= gcd(abs(x1), abs(y1)); s -= gcd(abs(x2), abs(y2)); s -= gcd(abs(x2 - x1), abs(y2 - y1)); return s / 2; } Int cnt(Int w, Int h, Int k) { Int ans = 0; for (Int x = 1; x < w; x++) { for (Int s = 0; s < h - 1; s++) { if (inside(1, x, -s, w) > 2 * k) break; if (inside(1, x, -s, w) > k) continue; Int R = 2 * k - x * s - 2 + gcd(w, s); Int bottom = max(1LL, R / w), top = min(h - s, R / w + 2); bottom = min(bottom, top - 1); while (top - bottom > 1) { Int mid = (top + bottom) / 2; if (inside(mid, x, -s, w) <= k) bottom = mid; else top = mid; } if (s == 0) ans += bottom; else ans += bottom * 2; } } return ans; } int main() { Int w, h, k; cin >> w >> h >> k; cout << 2 * cnt(w, h, k) + 2 * cnt(h, w, k) << endl; return 0; }
replace
48
49
48
51
TLE
p02650
C++
Time Limit Exceeded
#include <bits/stdc++.h> #define long long long int using namespace std; // @author: pashka int gcd(int a, int b) { while (b > 0) { int c = a % b; a = b; b = c; } return a; } map<pair<int, int>, int> mem; int get(int x, int y) { x = abs(x); y = abs(y); return gcd(x, y); // typedef typename map<pair<int, int>, int>::mapped_type V; // auto r = mem.insert({{x, y}, V()}); // V &v=r.first->second; // if (r.second) // v = gcd(x, y); // return v; } long calc(long w, long h, long k) { long res = 0; vector<int> mem(h + 1); vector<int> t2(h + 1); vector<int> mem2(h + 1); for (long b = 1; b < w; b++) { for (long c = 1; c < h && c * w <= 2 * (k + w); c++) { int mm = get(c, b); if (c * w > 2 * k + w + (w - b) + mm) continue; for (long a = c; a < h && c * w + (a - c) * b <= 2 * (k + w); a++) { long s = c * w + (a - c) * b; if (s / 2 <= k) { res++; if (a != c) res++; continue; } long g = mm; if ((s - g + 2) / 2 <= k) { res++; if (a != c) res++; continue; } if (t2[a] != b) { t2[a] = b; mem2[a] = get(a, w - b); } g += mem2[a]; if ((s - g + 2) / 2 <= k) { res++; if (a != c) res++; continue; } if (mem[a - c] == 0) { mem[a - c] = get(a - c, w); } g += mem[a - c]; if ((s - g + 2) / 2 <= k) { res++; if (a != c) res++; continue; } } } } return res; } int main() { ios::sync_with_stdio(false); int w, h, k; cin >> w >> h >> k; auto start = std::chrono::high_resolution_clock::now(); cout << (calc(w, h, k) + calc(h, w, k)) * 2; auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = finish - start; cerr << elapsed.count() << "\n"; return 0; }
#include <bits/stdc++.h> #define long long long int using namespace std; // @author: pashka int gcd(int a, int b) { while (b > 0) { int c = a % b; a = b; b = c; } return a; } map<pair<int, int>, int> mem; int get(int x, int y) { x = abs(x); y = abs(y); return gcd(x, y); // typedef typename map<pair<int, int>, int>::mapped_type V; // auto r = mem.insert({{x, y}, V()}); // V &v=r.first->second; // if (r.second) // v = gcd(x, y); // return v; } long calc(long w, long h, long k) { long res = 0; vector<int> mem(h + 1); vector<int> t2(h + 1); vector<int> mem2(h + 1); for (long b = 1; b < w; b++) { for (long c = 1; c < h && c * w <= 2 * (k + w); c++) { int mm = get(c, b); // c * w + (a - c) * b <= 2k; long mina = max((2 * k - c * w) / b + c, c); mina = min(mina, h); if (mina > c) { res += (mina - c) * 2 - 1; } for (long a = mina; a < h && c * w + (a - c) * b <= 2 * (k + w); a++) { long s = c * w + (a - c) * b; if (s / 2 <= k) { res++; if (a != c) res++; continue; } long g = mm; if ((s - g + 2) / 2 <= k) { res++; if (a != c) res++; continue; } if (t2[a] != b) { t2[a] = b; mem2[a] = get(a, w - b); } g += mem2[a]; if ((s - g + 2) / 2 <= k) { res++; if (a != c) res++; continue; } if (mem[a - c] == 0) { mem[a - c] = get(a - c, w); } g += mem[a - c]; if ((s - g + 2) / 2 <= k) { res++; if (a != c) res++; continue; } } } } return res; } int main() { ios::sync_with_stdio(false); int w, h, k; cin >> w >> h >> k; auto start = std::chrono::high_resolution_clock::now(); cout << (calc(w, h, k) + calc(h, w, k)) * 2; auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = finish - start; cerr << elapsed.count() << "\n"; return 0; }
replace
37
40
37
44
TLE
p02651
Python
Runtime Error
def solve(n, a_list, s): for i in range(n - 1, -1, -1): if s[i] == "0": r = 2 ** (a_list[i].bit_length() - 1) for j in range(i): if a_list[j] & r > 0: a_list[j] = a_list[i] ^ a_list[j] else: if a_list[i] > 0: return 1 return 0 def main(): t = int(input()) res_list = [] for _ in range(t): n = int(input()) a_list = list(map(int, input().split())) s = input() res = solve(n, a_list, s) res_list.append(res) for res in res_list: print(res) def test(): assert solve(2, [1, 2], "10") == 1 assert solve(2, [1, 1], "10") == 0 assert solve(6, [2, 3, 4, 5, 6, 7], "111000") == 0 if __name__ == "__main__": test() main()
def solve(n, a_list, s): for i in range(n - 1, -1, -1): if s[i] == "0": if a_list[i] == 0: continue r = 2 ** (a_list[i].bit_length() - 1) for j in range(i): if a_list[j] & r > 0: a_list[j] = a_list[i] ^ a_list[j] else: if a_list[i] > 0: return 1 return 0 def main(): t = int(input()) res_list = [] for _ in range(t): n = int(input()) a_list = list(map(int, input().split())) s = input() res = solve(n, a_list, s) res_list.append(res) for res in res_list: print(res) def test(): assert solve(2, [1, 2], "10") == 1 assert solve(2, [1, 1], "10") == 0 assert solve(6, [2, 3, 4, 5, 6, 7], "111000") == 0 if __name__ == "__main__": test() main()
insert
3
3
3
5
0
p02651
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef long long LL; #define N 120 const LL k = 60; LL n, a[N], f[80]; char s[N]; void ins(LL x) { for (LL i = k; ~i; --i) { if (x >> i & 1) { if (!f[i]) { f[i] = x; return; } else x ^= f[i]; } } } bool pd(LL x) { for (LL i = k; ~i; --i) { if (x >> i & 1) { if (!f[i]) return 0; x ^= f[i]; } } return 1; } void solve() { scanf("%lld", &n); for (LL i = 1; i <= n; ++i) scanf("%lld", a + i); scanf("%s", s + 1); memset(f, 0, sizeof f); LL flag = 0; for (LL i = n; i; --i) { if (s[i] == '0') ins(a[i]); else if (!pd(a[i])) { flag = 1; break; } } printf("%lld\n", flag); } int main() { LL T; scanf("%lld", &T); while (T--) solve(); return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long LL; #define N 300 const LL k = 60; LL n, a[N], f[80]; char s[N]; void ins(LL x) { for (LL i = k; ~i; --i) { if (x >> i & 1) { if (!f[i]) { f[i] = x; return; } else x ^= f[i]; } } } bool pd(LL x) { for (LL i = k; ~i; --i) { if (x >> i & 1) { if (!f[i]) return 0; x ^= f[i]; } } return 1; } void solve() { scanf("%lld", &n); for (LL i = 1; i <= n; ++i) scanf("%lld", a + i); scanf("%s", s + 1); memset(f, 0, sizeof f); LL flag = 0; for (LL i = n; i; --i) { if (s[i] == '0') ins(a[i]); else if (!pd(a[i])) { flag = 1; break; } } printf("%lld\n", flag); } int main() { LL T; scanf("%lld", &T); while (T--) solve(); return 0; }
replace
5
6
5
6
0
p02651
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; template <typename T> inline T read() { T x = 0, f = 0; char c = getchar(); while (!isdigit(c)) f = c == '-', c = getchar(); while (isdigit(c)) x = x * 10 + c - 48, c = getchar(); return f ? -x : x; } #define int long long namespace run { const int N = 109; namespace linebasis { int a[69]; inline void insert(int x) { for (int i = 63; ~i; i--) if ((x >> i) & 1) { if (!a[i]) return a[i] = x, void(); else x ^= a[i]; } } inline bool check(int x) { for (int i = 63; ~i; i--) if ((x >> i) & 1) x ^= a[i]; return !x; } } // namespace linebasis using namespace linebasis; int n, A[N]; char s[N]; int main() { int T = read<int>(); while (T--) { n = read<int>(); for (int i = 1; i <= n; i++) A[i] = read<int>(); cin >> s + 1; memset(a, 0, sizeof a); int peg = 0; for (int i = n; i >= 1; i--) if (s[i] == '1' && !check(A[i])) peg = 1; else insert(A[i]); if (!peg) puts("0"); else puts("1"); } return 0; } } // namespace run #undef int int main() { #ifdef my freopen(".in", "r", stdin); freopen(".out", "w", stdout); #endif return run::main(); }
#include <bits/stdc++.h> using namespace std; template <typename T> inline T read() { T x = 0, f = 0; char c = getchar(); while (!isdigit(c)) f = c == '-', c = getchar(); while (isdigit(c)) x = x * 10 + c - 48, c = getchar(); return f ? -x : x; } #define int long long namespace run { const int N = 209; namespace linebasis { int a[69]; inline void insert(int x) { for (int i = 63; ~i; i--) if ((x >> i) & 1) { if (!a[i]) return a[i] = x, void(); else x ^= a[i]; } } inline bool check(int x) { for (int i = 63; ~i; i--) if ((x >> i) & 1) x ^= a[i]; return !x; } } // namespace linebasis using namespace linebasis; int n, A[N]; char s[N]; int main() { int T = read<int>(); while (T--) { n = read<int>(); for (int i = 1; i <= n; i++) A[i] = read<int>(); cin >> s + 1; memset(a, 0, sizeof a); int peg = 0; for (int i = n; i >= 1; i--) if (s[i] == '1' && !check(A[i])) peg = 1; else insert(A[i]); if (!peg) puts("0"); else puts("1"); } return 0; } } // namespace run #undef int int main() { #ifdef my freopen(".in", "r", stdin); freopen(".out", "w", stdout); #endif return run::main(); }
replace
13
14
13
14
0
p02651
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 110, M = 64; ll a[N]; int n; char s[N]; ll b[N]; ll insert(ll x) { for (int i = 60; ~i; i--) if (1 & (x >> i)) { if (!b[i]) { b[i] = x; break; } else x ^= b[i]; } return x; } void Main() { for (int i = 0; i < M; i++) b[i] = 0; cin >> n; for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); scanf("%s", s + 1); bool Ans = 0; for (int i = n; i; i--) { if (s[i] == '0') { insert(a[i]); } else { ll d = insert(a[i]); // cerr << d << "??" << endl; Ans |= d != 0; } } printf("%d\n", (int)Ans); } int main() { int T; cin >> T; while (T--) Main(); }
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 1010, M = 64; ll a[N]; int n; char s[N]; ll b[N]; ll insert(ll x) { for (int i = 60; ~i; i--) if (1 & (x >> i)) { if (!b[i]) { b[i] = x; break; } else x ^= b[i]; } return x; } void Main() { for (int i = 0; i < M; i++) b[i] = 0; cin >> n; for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); scanf("%s", s + 1); bool Ans = 0; for (int i = n; i; i--) { if (s[i] == '0') { insert(a[i]); } else { ll d = insert(a[i]); // cerr << d << "??" << endl; Ans |= d != 0; } } printf("%d\n", (int)Ans); } int main() { int T; cin >> T; while (T--) Main(); }
replace
3
4
3
4
0
p02651
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define rep1(i, n) for (int i = 1; i <= (int)(n); i++) // Bit Matrix const int MAX_ROW = 110; // to be set appropriately const int MAX_COL = 210; // to be set appropriately struct BitMatrix { int H, W; bitset<MAX_COL> val[MAX_ROW]; BitMatrix(int m = 1, int n = 1) : H(m), W(n) {} inline bitset<MAX_COL> &operator[](int i) { return val[i]; } }; int GaussJordan(BitMatrix &A, bool is_extended = false) { int rank = 0; for (int col = 0; col < A.W; ++col) { if (is_extended && col == A.W - 1) break; int pivot = -1; for (int row = rank; row < A.H; ++row) { if (A[row][col]) { pivot = row; break; } } if (pivot == -1) continue; swap(A[pivot], A[rank]); for (int row = 0; row < A.H; ++row) { if (row != rank && A[row][col]) A[row] ^= A[rank]; } ++rank; } return rank; } const int MD = 65; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; rep(ti, t) { int n; cin >> n; vector<ll> a(n); rep(i, n) cin >> a[i]; string s; cin >> s; BitMatrix A(n + 1, MD + 1); // 1 BitMatrix B(n + 1, MD + 1); // 0 rep(i, s.size()) { rep(j, MD) { A[i][j] = 0; B[i][j] = 0; } } int ans = 0; for (int i = s.size() - 1; i >= 0; i--) { if (s[i] == '1') { ll cv = 0; rep(j, 63) { if ((1LL << j) & a[i]) { if (((1LL << j) & cv) == 0) { rep(l, n) { // bs 可能? if (B[l][j]) { rep(k, 63) { if (B[l][k]) { cv ^= (1LL << k); } } break; } else if (l == n - 1) { ans = 1; } } } cv ^= (1LL << j); } } if (cv != 0) ans = 1; } else { rep(j, 63) { if (a[i] & (1LL << j)) B[n][j] = 1; } GaussJordan(B, true); } } cout << ans << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define rep1(i, n) for (int i = 1; i <= (int)(n); i++) // Bit Matrix const int MAX_ROW = 210; // to be set appropriately const int MAX_COL = 110; // to be set appropriately struct BitMatrix { int H, W; bitset<MAX_COL> val[MAX_ROW]; BitMatrix(int m = 1, int n = 1) : H(m), W(n) {} inline bitset<MAX_COL> &operator[](int i) { return val[i]; } }; int GaussJordan(BitMatrix &A, bool is_extended = false) { int rank = 0; for (int col = 0; col < A.W; ++col) { if (is_extended && col == A.W - 1) break; int pivot = -1; for (int row = rank; row < A.H; ++row) { if (A[row][col]) { pivot = row; break; } } if (pivot == -1) continue; swap(A[pivot], A[rank]); for (int row = 0; row < A.H; ++row) { if (row != rank && A[row][col]) A[row] ^= A[rank]; } ++rank; } return rank; } const int MD = 65; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; rep(ti, t) { int n; cin >> n; vector<ll> a(n); rep(i, n) cin >> a[i]; string s; cin >> s; BitMatrix A(n + 1, MD + 1); // 1 BitMatrix B(n + 1, MD + 1); // 0 rep(i, s.size()) { rep(j, MD) { A[i][j] = 0; B[i][j] = 0; } } int ans = 0; for (int i = s.size() - 1; i >= 0; i--) { if (s[i] == '1') { ll cv = 0; rep(j, 63) { if ((1LL << j) & a[i]) { if (((1LL << j) & cv) == 0) { rep(l, n) { // bs 可能? if (B[l][j]) { rep(k, 63) { if (B[l][k]) { cv ^= (1LL << k); } } break; } else if (l == n - 1) { ans = 1; } } } cv ^= (1LL << j); } } if (cv != 0) ans = 1; } else { rep(j, 63) { if (a[i] & (1LL << j)) B[n][j] = 1; } GaussJordan(B, true); } } cout << ans << endl; } return 0; }
replace
7
9
7
9
0
p02651
C++
Runtime Error
#include <bits/stdc++.h> #define ll long long using namespace std; const int MAXN = 71, B = 61; int t, n, flg; ll x, k, a[MAXN], b[MAXN]; char s[MAXN]; bool ins(ll x) { for (int i = B; i >= 0; i--) { if ((x & (1ll << i))) { if (b[i]) { x ^= b[i]; } else { b[i] = x; break; } } } if (x) { return 1; } else { return 0; } } int main() { scanf("%d", &t); for (int ii = 1; ii <= t; ii++) { memset(b, 0, sizeof(b)); scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%lld", &a[i]); } scanf("%s", s + 1); int flg = 0; for (int i = n; i >= 1; i--) { if (s[i] == '0') { ins(a[i]); } else { if (ins(a[i])) { flg = 1; break; } } } printf("%d\n", flg); } return 0; }
#include <bits/stdc++.h> #define ll long long using namespace std; const int MAXN = 271, B = 61; int t, n, flg; ll x, k, a[MAXN], b[MAXN]; char s[MAXN]; bool ins(ll x) { for (int i = B; i >= 0; i--) { if ((x & (1ll << i))) { if (b[i]) { x ^= b[i]; } else { b[i] = x; break; } } } if (x) { return 1; } else { return 0; } } int main() { scanf("%d", &t); for (int ii = 1; ii <= t; ii++) { memset(b, 0, sizeof(b)); scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%lld", &a[i]); } scanf("%s", s + 1); int flg = 0; for (int i = n; i >= 1; i--) { if (s[i] == '0') { ins(a[i]); } else { if (ins(a[i])) { flg = 1; break; } } } printf("%d\n", flg); } return 0; }
replace
3
4
3
4
0
p02651
C++
Runtime Error
#include <bits/stdc++.h> #include <cassert> typedef long long int ll; using namespace std; // @@ !! LIM(ftwo matrix debug) // --> ftwo f:power matrix f:<< debug // ---- inserted library file ftwo.cc struct Ftwo { int8_t val; Ftwo(ll t = 0) { val = (t == 0) ? 0 : 1; } Ftwo(const Ftwo &t) : val(t.val) {} Ftwo &operator=(const Ftwo &t) { val = t.val; return *this; } Ftwo &operator=(ll t) { val = (t == 0) ? 0 : 1; return *this; } Ftwo &operator=(int t) { val = (t == 0) ? 0 : 1; return *this; } Ftwo &operator+=(const Ftwo &t) { val ^= t.val; return *this; } Ftwo &operator-=(const Ftwo &t) { val ^= t.val; return *this; } Ftwo &operator*=(const Ftwo &t) { val &= t.val; return *this; } Ftwo inv() const { if (val == 0) { cerr << "inv() is called for zero." << endl; exit(1); } return Ftwo(1); } Ftwo &operator/=(const Ftwo &t) { return (*this) *= t.inv(); } Ftwo operator+(const Ftwo &t) const { return Ftwo(val) += t; } Ftwo operator-(const Ftwo &t) const { return Ftwo(val) -= t; } Ftwo operator*(const Ftwo &t) const { return Ftwo(val) *= t; } Ftwo operator/(const Ftwo &t) const { return Ftwo(val) /= t; } Ftwo operator-() const { return Ftwo(-val); } bool operator==(const Ftwo &t) const { return val == t.val; } bool operator!=(const Ftwo &t) const { return val != t.val; } operator ll() const { return val; } }; Ftwo operator+(int x, const Ftwo &y) { return Ftwo(x) + y; } Ftwo operator-(int x, const Ftwo &y) { return Ftwo(x) - y; } Ftwo operator*(int x, const Ftwo &y) { return Ftwo(x) * y; } Ftwo operator/(int x, const Ftwo &y) { return Ftwo(x) / y; } Ftwo operator+(ll x, const Ftwo &y) { return Ftwo(x) + y; } Ftwo operator-(ll x, const Ftwo &y) { return Ftwo(x) - y; } Ftwo operator*(ll x, const Ftwo &y) { return Ftwo(x) * y; } Ftwo operator/(ll x, const Ftwo &y) { return Ftwo(x) / y; } Ftwo operator+(const Ftwo &x, int y) { return x + Ftwo(y); } Ftwo operator-(const Ftwo &x, int y) { return x - Ftwo(y); } Ftwo operator*(const Ftwo &x, int y) { return x * Ftwo(y); } Ftwo operator/(const Ftwo &x, int y) { return x / Ftwo(y); } Ftwo operator+(const Ftwo &x, ll y) { return x + Ftwo(y); } Ftwo operator-(const Ftwo &x, ll y) { return x - Ftwo(y); } Ftwo operator*(const Ftwo &x, ll y) { return x * Ftwo(y); } Ftwo operator/(const Ftwo &x, ll y) { return x / Ftwo(y); } istream &operator>>(istream &is, Ftwo &t) { ll x; is >> x; t = x; return is; } ostream &operator<<(ostream &os, const Ftwo &t) { os << int(t.val); return os; } // ---- end ftwo.cc // ---- inserted function power from util.cc /* *** WARNING *** ll x = power(10, 12) does not work since it is interpreted as ll x = power<int>((int)10, 12) Use power<ll>(10, 12) or power(10LL, 12). */ template <typename T> T power(T a, ll b) { T twoPow = a; T rv(1); while (b > 0) { if (b & 1LL) rv *= twoPow; twoPow *= twoPow; b >>= 1; } return rv; } // ad-hoc power function template <typename T, typename Op> T ah_power(T a, ll b, const T &unit_t, Op op) { T two_pow = a; T ret = unit_t; while (b > 0) { if (b & 1LL) ret = op(ret, two_pow); two_pow = op(two_pow, two_pow); b >>= 1; } return ret; } // ---- end power // ---- inserted library file matrix.cc struct MyExc : exception {}; template <typename T> struct Matrix { // private: size_t dimI; size_t dimJ; vector<T> mem; static size_t defDimIJ; void init_from_vv(const vector<vector<T>> &vec) { dimI = vec.size(); dimJ = vec.at(0).size(); if (dimI == dimJ) defDimIJ = dimI; mem.resize(dimI * dimJ); for (size_t i = 0; i < dimI; i++) { assert(vec.at(i).size() == dimJ); for (size_t j = 0; j < dimJ; j++) at(i, j) = vec.at(i).at(j); } } // public: void precond(bool b, string msg) const { if (!b) { cerr << "**FATAL** " << msg << endl; exit(1); } } T &at(size_t i, size_t j) { return mem.at(i * dimJ + j); } const T &at(size_t i, size_t j) const { return mem.at(i * dimJ + j); } Matrix(size_t m, size_t n) : dimI(m), dimJ(n), mem(dimI * dimJ) { if (dimI == dimJ) defDimIJ = dimI; } Matrix(const vector<vector<T>> &vec) { init_from_vv(vec); } Matrix(initializer_list<vector<T>> il) { init_from_vv(vector<vector<T>>(il)); } /* They will be constructed as implicitly-defined constructors??? Matrix(const Matrix<T>& mat) : dimI(mat.dimI), dimJ(mat.dimJ), mem(mat.mem) {} Matrix(Matrix<T>&& mat) : dimI(mat.dimI), dimJ(mat.dimJ), mem(move(mat.mem)) {} */ Matrix(const T &t) { precond(defDimIJ != 0, "defDimIJ not set Matrix(T)"); dimI = dimJ = defDimIJ; mem.resize(dimI * dimJ, (T)0); for (size_t i = 0; i < dimI; i++) at(i, i) = t; } /* Matrix<T>& operator =(const Matrix<T>& r) { dimI = r.dimI; dimJ = r.dimJ; mem = r.mem; return *this; } */ Matrix<T> &operator+=(const Matrix<T> &r) { precond(dimI == r.dimI && dimJ == r.dimJ, "dimension mismatch"); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimJ; j++) at(i, j) += r.at(i, j); } return *this; } Matrix<T> &operator-=(const Matrix<T> &r) { precond(dimI == r.dimI && dimJ == r.dimJ, "dimension mismatch"); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimJ; j++) at(i, j) -= r.at(i, j); } return *this; } Matrix<T> operator+(const Matrix<T> &r) const { return Matrix<T>(*this) += r; } Matrix<T> operator-(const Matrix<T> &r) const { return Matrix<T>(*this) -= r; } // Unlike + and -, we anyway need a new object for multiplication. // Thus, we first define operator *, and then define operator *= // using operator *. Matrix<T> operator*(const Matrix<T> &r) const { precond(dimJ == r.dimI, "dimension mismatch"); Matrix<T> result(dimI, r.dimJ); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < r.dimJ; j++) { T s = 0; for (size_t k = 0; k < dimJ; k++) s += at(i, k) * r.at(k, j); result.at(i, j) = s; } } return result; } Matrix<T> &operator*=(const Matrix<T> &r) { return *this = *this * r; } bool operator==(const Matrix<T> &r) const { return dimI == r.dimI && dimJ == r.dimJ && mem == r.mem; } bool operator!=(const Matrix<T> &r) const { return !(*this == r); } ostream &ostr_out(ostream &os) const { vector<vector<T>> vec(dimI, vector<T>(dimJ)); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimJ; j++) vec.at(i).at(j) = at(i, j); } return os << vec; } Matrix<T> matpower(ll x) const { precond((defDimIJ = dimI) == dimJ, "only for square matrix"); return power(*this, x); } Matrix<T> transpose() const { Matrix<T> res(dimJ, dimI); for (size_t i = 0; i < dimI; i++) for (size_t j = 0; j < dimJ; j++) { res.at(j, i) = at(i, j); } return res; } /* aux functions for sweepout */ void basic_mult(int i, T t) { for (size_t j = 0; j < dimJ; j++) at(i, j) *= t; } void basic_xchg(int i1, int i2) { for (size_t j = 0; j < dimJ; j++) swap(at(i1, j), at(i2, j)); } void basic_mult_add(int i1, T t, int i2) { for (size_t j = 0; j < dimJ; j++) at(i2, j) += at(i1, j) * t; } bool is_zero(T t) const { return t == (T)0; } pair<size_t, size_t> find_nz(size_t i0, size_t j0) { for (; j0 < dimJ; j0++) { size_t i = i0; for (; i < dimI && is_zero(at(i, j0)); i++) ; if (i < dimI) return {i, j0}; } return {dimI, dimJ}; } /* Sweepout for the vertical direction. Returns a pair (rank, det) rank: the rank of the matrix det: internally used for determinant calculation WARNNIG: T should be a field. */ pair<size_t, T> self_sweepout() { T det = (T)1; size_t j0 = 0; size_t i0 = 0; for (; i0 < dimI; i0++) { auto [i1, j1] = find_nz(i0, j0); if (i1 == dimI) break; j0 = j1; if (i1 != i0) { det = -det; basic_xchg(i0, i1); } det *= at(i0, j0); basic_mult(i0, (T)1 / at(i0, j0)); for (size_t i = 0; i < dimI; i++) { if (i == i0) continue; basic_mult_add(i0, -at(i, j0), i); } } return {i0, det}; } pair<size_t, T> sweepout() const { Matrix<T> res1(*this); return res1.self_sweepout(); } /* WARNING: T should be a field. */ T determinant() const { precond((defDimIJ = dimI) == dimJ, "only for square matrix"); auto [rank, det] = sweepout(); return (rank == dimI) ? det : (T)0; } /* WARNING: T should be a field. */ Matrix<T> inverse() const { precond((defDimIJ = dimI) == dimJ, "only for square matrix"); Matrix<T> work(dimI, dimI * 2); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimI; j++) { work.at(i, j) = at(i, j); work.at(i, j + dimI) = (i == j) ? (T)1 : (T)0; } } work.self_sweepout(); if (!is_zero(work.at(dimI - 1, dimI - 1) - (T)1)) { cerr << "inverse() for non-regular matrix." << endl; throw MyExc(); } Matrix<T> ret(dimI, dimI); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimI; j++) ret.at(i, j) = work.at(i, j + dimI); } return ret; } }; template <typename T> size_t Matrix<T>::defDimIJ = 0; template <typename T> ostream &operator<<(ostream &os, const Matrix<T> &mat) { return mat.ostr_out(os); } // ---- end matrix.cc // ---- inserted function << from util.cc template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { os << "(" << p.first << ", " << p.second << ")"; return os; } template <typename T1, typename T2, typename T3> ostream &operator<<(ostream &os, const tuple<T1, T2, T3> &t) { os << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ")"; return os; } template <typename T1, typename T2, typename T3, typename T4> ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4> &t) { os << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ", " << get<3>(t) << ")"; return os; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << '['; for (auto it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } os << ']'; return os; } template <typename T, typename C> ostream &operator<<(ostream &os, const set<T, C> &v) { os << '{'; for (auto it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } os << '}'; return os; } template <typename T, typename C> ostream &operator<<(ostream &os, const unordered_set<T, C> &v) { os << '{'; for (auto it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } os << '}'; return os; } template <typename T, typename C> ostream &operator<<(ostream &os, const multiset<T, C> &v) { os << '{'; for (auto it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } os << '}'; return os; } template <typename T1, typename T2, typename C> ostream &operator<<(ostream &os, const map<T1, T2, C> &mp) { os << '['; for (auto it = mp.begin(); it != mp.end(); it++) { if (it != mp.begin()) os << ", "; os << it->first << ": " << it->second; } os << ']'; return os; } template <typename T1, typename T2, typename C> ostream &operator<<(ostream &os, const unordered_map<T1, T2, C> &mp) { os << '['; for (auto it = mp.begin(); it != mp.end(); it++) { if (it != mp.begin()) os << ", "; os << it->first << ": " << it->second; } os << ']'; return os; } template <typename T, typename T2> ostream &operator<<(ostream &os, const queue<T, T2> &orig) { queue<T, T2> que(orig); bool first = true; os << '['; while (!que.empty()) { T x = que.front(); que.pop(); if (!first) os << ", "; os << x; first = false; } return os << ']'; } template <typename T, typename T2, typename T3> ostream &operator<<(ostream &os, const priority_queue<T, T2, T3> &orig) { priority_queue<T, T2, T3> pq(orig); bool first = true; os << '['; while (!pq.empty()) { T x = pq.top(); pq.pop(); if (!first) os << ", "; os << x; first = false; } return os << ']'; } template <typename T> ostream &operator<<(ostream &os, const stack<T> &st) { stack<T> tmp(st); os << '['; bool first = true; while (!tmp.empty()) { T &t = tmp.top(); if (first) first = false; else os << ", "; os << t; tmp.pop(); } os << ']'; return os; } #if __cplusplus >= 201703L template <typename T> ostream &operator<<(ostream &os, const optional<T> &t) { if (t.has_value()) os << "v(" << t.value() << ")"; else os << "nullopt"; return os; } #endif // ---- end << // ---- inserted library file debug.cc template <class... Args> string dbgFormat(const char *fmt, Args... args) { size_t len = snprintf(nullptr, 0, fmt, args...); char buf[len + 1]; snprintf(buf, len + 1, fmt, args...); return string(buf); } template <class Head> void dbgLog(Head &&head) { cerr << head << endl; } template <class Head, class... Tail> void dbgLog(Head &&head, Tail &&...tail) { cerr << head << " "; dbgLog(forward<Tail>(tail)...); } #if DEBUG #define DLOG(...) dbgLog(__VA_ARGS__) #define DFMT(...) cerr << dbgFormat(__VA_ARGS__) << endl #define DCALL(func, ...) func(__VA_ARGS__) #else #define DLOG(...) #define DFMT(...) #define DCALL(func, ...) #endif #if DEBUG_LIB #define DLOG_LIB(...) dbgLog(__VA_ARGS__) #define DFMT_LIB(...) cerr << dbgFormat(__VA_ARGS__) << endl #define DCALL_LIB(func, ...) func(__VA_ARGS__) #else #define DLOG_LIB(...) #define DFMT_LIB(...) #define DCALL_LIB(func, ...) #endif // ---- end debug.cc // @@ !! LIM -- end mark -- int main(/* int argc, char *argv[] */) { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout << setprecision(20); #if DEBUG const ll msize = 8; #else const ll msize = 60; #endif auto i2vec = [](ll x) -> vector<Ftwo> { vector<Ftwo> vec(msize); for (ll i = 0; i < msize; i++) { vec[i] = Ftwo(x % 2); x /= 2; } return vec; }; auto solve = [&]() -> ll { ll N; cin >> N; vector<ll> A(N); for (ll i = 0; i < N; i++) cin >> A[i]; string S; cin >> S; reverse(A.begin(), A.end()); reverse(S.begin(), S.end()); if (S[0] == '1') return 1; ll idx = 0; Matrix<Ftwo> prev_mat(0, 0); ll prev_rank = 0; while (true) { ll prev_idx = idx; while (idx < N && S[idx] == '0') idx++; ll cnt0 = idx - prev_idx; while (idx < N && S[idx] == '1') idx++; ll cnt1 = idx - prev_idx - cnt0; if (cnt1 == 0) break; Matrix<Ftwo> mat0(prev_rank + cnt0, msize); for (ll i = 0; i < prev_rank; i++) { for (ll j = 0; j < msize; j++) mat0.at(i, j) = prev_mat.at(i, j); } for (ll i = 0; i < cnt0; i++) { auto vec = i2vec(A[prev_idx + i]); for (ll j = 0; j < msize; j++) mat0.at(prev_rank + i, j) = vec[j]; } DLOG("mat0=", mat0); auto [rank0, dummy0] = mat0.self_sweepout(); DLOG("swept: mat0=", mat0); DLOG("rank0=", rank0); Matrix<Ftwo> mat1(rank0 + cnt1, msize); for (ll i = 0; i < (ll)rank0; i++) { for (ll j = 0; j < msize; j++) mat1.at(i, j) = mat0.at(i, j); } for (ll i = 0; i < cnt1; i++) { auto vec = i2vec(A[prev_idx + cnt0 + i]); for (ll j = 0; j < msize; j++) mat1.at(prev_rank + rank0 + i, j) = vec[j]; } DLOG("mat1=", mat1); auto [rank1, dummy1] = mat1.self_sweepout(); DLOG("swept: mat1=", mat1); DLOG("rank1=", rank1); if (rank0 < rank1) return 1; prev_mat = move(mat0); prev_rank = rank0; } return 0; }; ll T; cin >> T; for (ll _t = 0; _t < T; _t++) cout << solve() << "\n"; return 0; }
#include <bits/stdc++.h> #include <cassert> typedef long long int ll; using namespace std; // @@ !! LIM(ftwo matrix debug) // --> ftwo f:power matrix f:<< debug // ---- inserted library file ftwo.cc struct Ftwo { int8_t val; Ftwo(ll t = 0) { val = (t == 0) ? 0 : 1; } Ftwo(const Ftwo &t) : val(t.val) {} Ftwo &operator=(const Ftwo &t) { val = t.val; return *this; } Ftwo &operator=(ll t) { val = (t == 0) ? 0 : 1; return *this; } Ftwo &operator=(int t) { val = (t == 0) ? 0 : 1; return *this; } Ftwo &operator+=(const Ftwo &t) { val ^= t.val; return *this; } Ftwo &operator-=(const Ftwo &t) { val ^= t.val; return *this; } Ftwo &operator*=(const Ftwo &t) { val &= t.val; return *this; } Ftwo inv() const { if (val == 0) { cerr << "inv() is called for zero." << endl; exit(1); } return Ftwo(1); } Ftwo &operator/=(const Ftwo &t) { return (*this) *= t.inv(); } Ftwo operator+(const Ftwo &t) const { return Ftwo(val) += t; } Ftwo operator-(const Ftwo &t) const { return Ftwo(val) -= t; } Ftwo operator*(const Ftwo &t) const { return Ftwo(val) *= t; } Ftwo operator/(const Ftwo &t) const { return Ftwo(val) /= t; } Ftwo operator-() const { return Ftwo(-val); } bool operator==(const Ftwo &t) const { return val == t.val; } bool operator!=(const Ftwo &t) const { return val != t.val; } operator ll() const { return val; } }; Ftwo operator+(int x, const Ftwo &y) { return Ftwo(x) + y; } Ftwo operator-(int x, const Ftwo &y) { return Ftwo(x) - y; } Ftwo operator*(int x, const Ftwo &y) { return Ftwo(x) * y; } Ftwo operator/(int x, const Ftwo &y) { return Ftwo(x) / y; } Ftwo operator+(ll x, const Ftwo &y) { return Ftwo(x) + y; } Ftwo operator-(ll x, const Ftwo &y) { return Ftwo(x) - y; } Ftwo operator*(ll x, const Ftwo &y) { return Ftwo(x) * y; } Ftwo operator/(ll x, const Ftwo &y) { return Ftwo(x) / y; } Ftwo operator+(const Ftwo &x, int y) { return x + Ftwo(y); } Ftwo operator-(const Ftwo &x, int y) { return x - Ftwo(y); } Ftwo operator*(const Ftwo &x, int y) { return x * Ftwo(y); } Ftwo operator/(const Ftwo &x, int y) { return x / Ftwo(y); } Ftwo operator+(const Ftwo &x, ll y) { return x + Ftwo(y); } Ftwo operator-(const Ftwo &x, ll y) { return x - Ftwo(y); } Ftwo operator*(const Ftwo &x, ll y) { return x * Ftwo(y); } Ftwo operator/(const Ftwo &x, ll y) { return x / Ftwo(y); } istream &operator>>(istream &is, Ftwo &t) { ll x; is >> x; t = x; return is; } ostream &operator<<(ostream &os, const Ftwo &t) { os << int(t.val); return os; } // ---- end ftwo.cc // ---- inserted function power from util.cc /* *** WARNING *** ll x = power(10, 12) does not work since it is interpreted as ll x = power<int>((int)10, 12) Use power<ll>(10, 12) or power(10LL, 12). */ template <typename T> T power(T a, ll b) { T twoPow = a; T rv(1); while (b > 0) { if (b & 1LL) rv *= twoPow; twoPow *= twoPow; b >>= 1; } return rv; } // ad-hoc power function template <typename T, typename Op> T ah_power(T a, ll b, const T &unit_t, Op op) { T two_pow = a; T ret = unit_t; while (b > 0) { if (b & 1LL) ret = op(ret, two_pow); two_pow = op(two_pow, two_pow); b >>= 1; } return ret; } // ---- end power // ---- inserted library file matrix.cc struct MyExc : exception {}; template <typename T> struct Matrix { // private: size_t dimI; size_t dimJ; vector<T> mem; static size_t defDimIJ; void init_from_vv(const vector<vector<T>> &vec) { dimI = vec.size(); dimJ = vec.at(0).size(); if (dimI == dimJ) defDimIJ = dimI; mem.resize(dimI * dimJ); for (size_t i = 0; i < dimI; i++) { assert(vec.at(i).size() == dimJ); for (size_t j = 0; j < dimJ; j++) at(i, j) = vec.at(i).at(j); } } // public: void precond(bool b, string msg) const { if (!b) { cerr << "**FATAL** " << msg << endl; exit(1); } } T &at(size_t i, size_t j) { return mem.at(i * dimJ + j); } const T &at(size_t i, size_t j) const { return mem.at(i * dimJ + j); } Matrix(size_t m, size_t n) : dimI(m), dimJ(n), mem(dimI * dimJ) { if (dimI == dimJ) defDimIJ = dimI; } Matrix(const vector<vector<T>> &vec) { init_from_vv(vec); } Matrix(initializer_list<vector<T>> il) { init_from_vv(vector<vector<T>>(il)); } /* They will be constructed as implicitly-defined constructors??? Matrix(const Matrix<T>& mat) : dimI(mat.dimI), dimJ(mat.dimJ), mem(mat.mem) {} Matrix(Matrix<T>&& mat) : dimI(mat.dimI), dimJ(mat.dimJ), mem(move(mat.mem)) {} */ Matrix(const T &t) { precond(defDimIJ != 0, "defDimIJ not set Matrix(T)"); dimI = dimJ = defDimIJ; mem.resize(dimI * dimJ, (T)0); for (size_t i = 0; i < dimI; i++) at(i, i) = t; } /* Matrix<T>& operator =(const Matrix<T>& r) { dimI = r.dimI; dimJ = r.dimJ; mem = r.mem; return *this; } */ Matrix<T> &operator+=(const Matrix<T> &r) { precond(dimI == r.dimI && dimJ == r.dimJ, "dimension mismatch"); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimJ; j++) at(i, j) += r.at(i, j); } return *this; } Matrix<T> &operator-=(const Matrix<T> &r) { precond(dimI == r.dimI && dimJ == r.dimJ, "dimension mismatch"); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimJ; j++) at(i, j) -= r.at(i, j); } return *this; } Matrix<T> operator+(const Matrix<T> &r) const { return Matrix<T>(*this) += r; } Matrix<T> operator-(const Matrix<T> &r) const { return Matrix<T>(*this) -= r; } // Unlike + and -, we anyway need a new object for multiplication. // Thus, we first define operator *, and then define operator *= // using operator *. Matrix<T> operator*(const Matrix<T> &r) const { precond(dimJ == r.dimI, "dimension mismatch"); Matrix<T> result(dimI, r.dimJ); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < r.dimJ; j++) { T s = 0; for (size_t k = 0; k < dimJ; k++) s += at(i, k) * r.at(k, j); result.at(i, j) = s; } } return result; } Matrix<T> &operator*=(const Matrix<T> &r) { return *this = *this * r; } bool operator==(const Matrix<T> &r) const { return dimI == r.dimI && dimJ == r.dimJ && mem == r.mem; } bool operator!=(const Matrix<T> &r) const { return !(*this == r); } ostream &ostr_out(ostream &os) const { vector<vector<T>> vec(dimI, vector<T>(dimJ)); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimJ; j++) vec.at(i).at(j) = at(i, j); } return os << vec; } Matrix<T> matpower(ll x) const { precond((defDimIJ = dimI) == dimJ, "only for square matrix"); return power(*this, x); } Matrix<T> transpose() const { Matrix<T> res(dimJ, dimI); for (size_t i = 0; i < dimI; i++) for (size_t j = 0; j < dimJ; j++) { res.at(j, i) = at(i, j); } return res; } /* aux functions for sweepout */ void basic_mult(int i, T t) { for (size_t j = 0; j < dimJ; j++) at(i, j) *= t; } void basic_xchg(int i1, int i2) { for (size_t j = 0; j < dimJ; j++) swap(at(i1, j), at(i2, j)); } void basic_mult_add(int i1, T t, int i2) { for (size_t j = 0; j < dimJ; j++) at(i2, j) += at(i1, j) * t; } bool is_zero(T t) const { return t == (T)0; } pair<size_t, size_t> find_nz(size_t i0, size_t j0) { for (; j0 < dimJ; j0++) { size_t i = i0; for (; i < dimI && is_zero(at(i, j0)); i++) ; if (i < dimI) return {i, j0}; } return {dimI, dimJ}; } /* Sweepout for the vertical direction. Returns a pair (rank, det) rank: the rank of the matrix det: internally used for determinant calculation WARNNIG: T should be a field. */ pair<size_t, T> self_sweepout() { T det = (T)1; size_t j0 = 0; size_t i0 = 0; for (; i0 < dimI; i0++) { auto [i1, j1] = find_nz(i0, j0); if (i1 == dimI) break; j0 = j1; if (i1 != i0) { det = -det; basic_xchg(i0, i1); } det *= at(i0, j0); basic_mult(i0, (T)1 / at(i0, j0)); for (size_t i = 0; i < dimI; i++) { if (i == i0) continue; basic_mult_add(i0, -at(i, j0), i); } } return {i0, det}; } pair<size_t, T> sweepout() const { Matrix<T> res1(*this); return res1.self_sweepout(); } /* WARNING: T should be a field. */ T determinant() const { precond((defDimIJ = dimI) == dimJ, "only for square matrix"); auto [rank, det] = sweepout(); return (rank == dimI) ? det : (T)0; } /* WARNING: T should be a field. */ Matrix<T> inverse() const { precond((defDimIJ = dimI) == dimJ, "only for square matrix"); Matrix<T> work(dimI, dimI * 2); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimI; j++) { work.at(i, j) = at(i, j); work.at(i, j + dimI) = (i == j) ? (T)1 : (T)0; } } work.self_sweepout(); if (!is_zero(work.at(dimI - 1, dimI - 1) - (T)1)) { cerr << "inverse() for non-regular matrix." << endl; throw MyExc(); } Matrix<T> ret(dimI, dimI); for (size_t i = 0; i < dimI; i++) { for (size_t j = 0; j < dimI; j++) ret.at(i, j) = work.at(i, j + dimI); } return ret; } }; template <typename T> size_t Matrix<T>::defDimIJ = 0; template <typename T> ostream &operator<<(ostream &os, const Matrix<T> &mat) { return mat.ostr_out(os); } // ---- end matrix.cc // ---- inserted function << from util.cc template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { os << "(" << p.first << ", " << p.second << ")"; return os; } template <typename T1, typename T2, typename T3> ostream &operator<<(ostream &os, const tuple<T1, T2, T3> &t) { os << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ")"; return os; } template <typename T1, typename T2, typename T3, typename T4> ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4> &t) { os << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ", " << get<3>(t) << ")"; return os; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << '['; for (auto it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } os << ']'; return os; } template <typename T, typename C> ostream &operator<<(ostream &os, const set<T, C> &v) { os << '{'; for (auto it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } os << '}'; return os; } template <typename T, typename C> ostream &operator<<(ostream &os, const unordered_set<T, C> &v) { os << '{'; for (auto it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } os << '}'; return os; } template <typename T, typename C> ostream &operator<<(ostream &os, const multiset<T, C> &v) { os << '{'; for (auto it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } os << '}'; return os; } template <typename T1, typename T2, typename C> ostream &operator<<(ostream &os, const map<T1, T2, C> &mp) { os << '['; for (auto it = mp.begin(); it != mp.end(); it++) { if (it != mp.begin()) os << ", "; os << it->first << ": " << it->second; } os << ']'; return os; } template <typename T1, typename T2, typename C> ostream &operator<<(ostream &os, const unordered_map<T1, T2, C> &mp) { os << '['; for (auto it = mp.begin(); it != mp.end(); it++) { if (it != mp.begin()) os << ", "; os << it->first << ": " << it->second; } os << ']'; return os; } template <typename T, typename T2> ostream &operator<<(ostream &os, const queue<T, T2> &orig) { queue<T, T2> que(orig); bool first = true; os << '['; while (!que.empty()) { T x = que.front(); que.pop(); if (!first) os << ", "; os << x; first = false; } return os << ']'; } template <typename T, typename T2, typename T3> ostream &operator<<(ostream &os, const priority_queue<T, T2, T3> &orig) { priority_queue<T, T2, T3> pq(orig); bool first = true; os << '['; while (!pq.empty()) { T x = pq.top(); pq.pop(); if (!first) os << ", "; os << x; first = false; } return os << ']'; } template <typename T> ostream &operator<<(ostream &os, const stack<T> &st) { stack<T> tmp(st); os << '['; bool first = true; while (!tmp.empty()) { T &t = tmp.top(); if (first) first = false; else os << ", "; os << t; tmp.pop(); } os << ']'; return os; } #if __cplusplus >= 201703L template <typename T> ostream &operator<<(ostream &os, const optional<T> &t) { if (t.has_value()) os << "v(" << t.value() << ")"; else os << "nullopt"; return os; } #endif // ---- end << // ---- inserted library file debug.cc template <class... Args> string dbgFormat(const char *fmt, Args... args) { size_t len = snprintf(nullptr, 0, fmt, args...); char buf[len + 1]; snprintf(buf, len + 1, fmt, args...); return string(buf); } template <class Head> void dbgLog(Head &&head) { cerr << head << endl; } template <class Head, class... Tail> void dbgLog(Head &&head, Tail &&...tail) { cerr << head << " "; dbgLog(forward<Tail>(tail)...); } #if DEBUG #define DLOG(...) dbgLog(__VA_ARGS__) #define DFMT(...) cerr << dbgFormat(__VA_ARGS__) << endl #define DCALL(func, ...) func(__VA_ARGS__) #else #define DLOG(...) #define DFMT(...) #define DCALL(func, ...) #endif #if DEBUG_LIB #define DLOG_LIB(...) dbgLog(__VA_ARGS__) #define DFMT_LIB(...) cerr << dbgFormat(__VA_ARGS__) << endl #define DCALL_LIB(func, ...) func(__VA_ARGS__) #else #define DLOG_LIB(...) #define DFMT_LIB(...) #define DCALL_LIB(func, ...) #endif // ---- end debug.cc // @@ !! LIM -- end mark -- int main(/* int argc, char *argv[] */) { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout << setprecision(20); #if DEBUG const ll msize = 8; #else const ll msize = 60; #endif auto i2vec = [](ll x) -> vector<Ftwo> { vector<Ftwo> vec(msize); for (ll i = 0; i < msize; i++) { vec[i] = Ftwo(x % 2); x /= 2; } return vec; }; auto solve = [&]() -> ll { ll N; cin >> N; vector<ll> A(N); for (ll i = 0; i < N; i++) cin >> A[i]; string S; cin >> S; reverse(A.begin(), A.end()); reverse(S.begin(), S.end()); if (S[0] == '1') return 1; ll idx = 0; Matrix<Ftwo> prev_mat(0, 0); ll prev_rank = 0; while (true) { ll prev_idx = idx; while (idx < N && S[idx] == '0') idx++; ll cnt0 = idx - prev_idx; while (idx < N && S[idx] == '1') idx++; ll cnt1 = idx - prev_idx - cnt0; if (cnt1 == 0) break; Matrix<Ftwo> mat0(prev_rank + cnt0, msize); for (ll i = 0; i < prev_rank; i++) { for (ll j = 0; j < msize; j++) mat0.at(i, j) = prev_mat.at(i, j); } for (ll i = 0; i < cnt0; i++) { auto vec = i2vec(A[prev_idx + i]); for (ll j = 0; j < msize; j++) mat0.at(prev_rank + i, j) = vec[j]; } DLOG("mat0=", mat0); auto [rank0, dummy0] = mat0.self_sweepout(); DLOG("swept: mat0=", mat0); DLOG("rank0=", rank0); Matrix<Ftwo> mat1(rank0 + cnt1, msize); for (ll i = 0; i < (ll)rank0; i++) { for (ll j = 0; j < msize; j++) mat1.at(i, j) = mat0.at(i, j); } for (ll i = 0; i < cnt1; i++) { auto vec = i2vec(A[prev_idx + cnt0 + i]); for (ll j = 0; j < msize; j++) mat1.at(rank0 + i, j) = vec[j]; } DLOG("mat1=", mat1); auto [rank1, dummy1] = mat1.self_sweepout(); DLOG("swept: mat1=", mat1); DLOG("rank1=", rank1); if (rank0 < rank1) return 1; prev_mat = move(mat0); prev_rank = rank0; } return 0; }; ll T; cin >> T; for (ll _t = 0; _t < T; _t++) cout << solve() << "\n"; return 0; }
replace
636
637
636
637
0
p02651
C++
Runtime Error
// A. #include <algorithm> #include <cstring> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <vector> using namespace std; typedef long long LL; bool possible(LL t, vector<LL> a) { LL x = 0; int st = 0; int sz = (int)a.size(); sort(a.rbegin(), a.rend()); for (LL b = 60; b >= 0; --b) { LL f = 1LL << b; if (!(a[st] & f)) continue; for (int i = 0; i < sz; ++i) { if (i != st && (a[i] & f) != 0) a[i] ^= a[st]; } ++st; if (st >= sz) break; sort(a.rbegin(), a.rbegin() + sz - st); } for (LL b = 60; b >= 0; --b) { LL f = 1LL << b; if ((f & t) != 0 && (f & x) == 0) { for (int i = 0; i < sz; ++i) { if (a[i] & f) { x ^= a[i]; break; } } } } return t == x; } int main(int argc, char *argv[]) { LL t, n; cin >> t; for (LL tt = 0; tt < t; ++tt) { cin >> n; vector<LL> a(n); for (LL i = 0; i < n; ++i) { cin >> a[i]; } string s; cin >> s; int ans = 0; vector<LL> x; for (LL i = n - 1; i >= 0; --i) { if (s[i] != '0') { if (!possible(a[i], x)) { ans = 1; break; } } else { x.emplace_back(a[i]); } } cout << ans << endl; } return 0; }
// A. #include <algorithm> #include <cstring> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <vector> using namespace std; typedef long long LL; bool possible(LL t, vector<LL> a) { if (a.empty()) return t == 0; LL x = 0; int st = 0; int sz = (int)a.size(); sort(a.rbegin(), a.rend()); for (LL b = 60; b >= 0; --b) { LL f = 1LL << b; if (!(a[st] & f)) continue; for (int i = 0; i < sz; ++i) { if (i != st && (a[i] & f) != 0) a[i] ^= a[st]; } ++st; if (st >= sz) break; sort(a.rbegin(), a.rbegin() + sz - st); } for (LL b = 60; b >= 0; --b) { LL f = 1LL << b; if ((f & t) != 0 && (f & x) == 0) { for (int i = 0; i < sz; ++i) { if (a[i] & f) { x ^= a[i]; break; } } } } return t == x; } int main(int argc, char *argv[]) { LL t, n; cin >> t; for (LL tt = 0; tt < t; ++tt) { cin >> n; vector<LL> a(n); for (LL i = 0; i < n; ++i) { cin >> a[i]; } string s; cin >> s; int ans = 0; vector<LL> x; for (LL i = n - 1; i >= 0; --i) { if (s[i] != '0') { if (!possible(a[i], x)) { ans = 1; break; } } else { x.emplace_back(a[i]); } } cout << ans << endl; } return 0; }
insert
16
16
16
18
0
p02651
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; // type alias typedef long long LL; typedef pair<int, int> II; typedef tuple<int, int, int> III; typedef vector<int> VI; typedef vector<string> VS; typedef unordered_map<int, int> MAPII; typedef unordered_set<int> SETI; template <class T> using VV = vector<vector<T>>; // minmax template <class T> inline T SMIN(T &a, const T b) { return a = (a > b) ? b : a; } template <class T> inline T SMAX(T &a, const T b) { return a = (a < b) ? b : a; } // repetition #define FORE(i, a, b) for (int i = (a); i <= (b); ++i) #define REPE(i, n) for (int i = 0; i <= (n); ++i) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) for (int i = 0; i < (n); ++i) #define FORR(x, arr) for (auto &x : arr) #define SZ(a) int((a).size()) // collection #define ALL(c) (c).begin(), (c).end() // DP #define MINUS(dp) memset(dp, -1, sizeof(dp)) #define ZERO(dp) memset(dp, 0, sizeof(dp)) // stdout #define println(args...) fprintf(stdout, ##args), putchar('\n'); // debug cerr template <class Iter> void __kumaerrc(Iter begin, Iter end) { for (; begin != end; ++begin) { cerr << *begin << ','; } cerr << endl; } void __kumaerr(istream_iterator<string> it) { (void)it; cerr << endl; } template <typename T, typename... Args> void __kumaerr(istream_iterator<string> it, T a, Args... args) { cerr << *it << "=" << a << ", ", __kumaerr(++it, args...); } template <typename S, typename T> std::ostream &operator<<(std::ostream &_os, const std::pair<S, T> &_p) { return _os << "{" << _p.first << ',' << _p.second << "}"; } #define __KUMATRACE__ true #ifdef __KUMATRACE__ #define dump(args...) \ { \ string _s = #args; \ replace(_s.begin(), _s.end(), ',', ' '); \ stringstream _ss(_s); \ istream_iterator<string> _it(_ss); \ __kumaerr(_it, args); \ } #define dumpc(ar) \ { \ cerr << #ar << ": "; \ FORR(x, (ar)) { cerr << x << ','; } \ cerr << endl; \ } #define dumpC(beg, end) \ { \ cerr << "~" << #end << ": "; \ __kumaerrc(beg, end); \ } #else #define dump(args...) #define dumpc(ar) #define dumpC(beg, end) #endif // $ cp-batch XorBattle | diff XorBattle.out - // $ g++ -std=c++14 -Wall -O2 -D_GLIBCXX_DEBUG -fsanitize=address XorBattle.cpp // && ./a.out template <class T> void gf2_GE(vector<T> &V) { // gaussian elimination in GF(2) int N = V.size(); for (int i = 0; i < N; ++i) { sort(V.begin() + i, V.end(), greater<T>()); if (V[i] == 0) break; T msb = 1; while ((msb << 1) <= V[i]) msb <<= 1; for (int j = i + 1; j < N; ++j) if (V[j] & msb) V[j] ^= V[i]; } } template <class T> int gf2_rank(vector<T> &V) { gf2_GE<T>(V); return (int)V.size() - count(V.begin(), V.end(), 0); } /* 6/7/2020 5:00-6:30 give up 16:00-18:15, 21:50- https://twitter.com/hanseilimak/status/1269799620579692549 https://twitter.com/satanic0258/status/1269638393975107587 https://twitter.com/satanic0258/status/1269654741346217984 https://twitter.com/chokudai/status/1269662729712750592 https://twitter.com/ngtkana/status/1269638258486464513 https://twitter.com/noshi91/status/1269660771086041088 https://twitter.com/kyort0n/status/1269712783852986368 */ const int MAX_N = 1e3 + 1; LL A[MAX_N]; int N; string S; int solve() { VI V(1, 0); for (int i = N - 1; i >= 0; --i) { if (S[i] == '0') { V.push_back(A[i]); gf2_GE(V); } else { int rank = gf2_rank(V); V.push_back(A[i]); int rank2 = gf2_rank(V); if (rank2 > rank) return 1; } } return 0; } VI s; int memo[MAX_N][1 << 5]; int f(int i, int cur) { int &res = memo[i][cur]; if (res >= 0) return res; if (i == N) { return cur != 0; } bool res1 = f(i + 1, cur); bool res2 = f(i + 1, cur ^ A[i]); if (s[i] == 0) { res = (!res1 || !res2) ? false : true; } else { res = (res1 || res2); } return res; } mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); int genRandNum(int lb, int ub) { assert(lb < ub); // Helper to generate random integer in range [lb, ub) int x = rnd() % (int)(ub - lb); return x + lb; } vector<int> genRandSeq(int size, int lb, int ub) { if (size == 0) return {}; vector<int> res(size); generate(res.begin(), res.end(), [&]() { return genRandNum(lb, ub); }); return res; } string n2bin(long long n) { assert(n >= 0); string res = ""; while (n > 0) res += (n % 2LL ? '1' : '0'), n /= 2LL; return string(res.rbegin(), res.rend()); } void test() { N = 8; VI as = genRandSeq(N, 1, 1 << 3); s = genRandSeq(N, 0, 2); vector<II> states(N); REP(i, N) states[i] = {s[i], as[i]}; sort(ALL(states)); VI ress; do { MINUS(memo); REP(i, N) A[i] = states[i].second, s[i] = states[i].first; bool res = f(0, 0); if (!res) { vector<pair<int, string>> xs; FORR(p, states) xs.emplace_back(p.first, n2bin(p.second)); dumpc(xs); } ress.push_back(res); } while (next_permutation(ALL(states))); set<int> S; FORR(s, ress) S.emplace(s); int ands[2] = {(1 << N) - 1, (1 << N) - 1}, ors[2] = {0, 0}; FORR(p, states) ands[p.first] &= p.second, ors[p.first] |= p.second; if (SZ(S) == 2) { dump(n2bin(ands[0] ^ ors[0]), n2bin(ands[1] ^ ors[1])); dumpc(ress); dumpc(states); } assert(SZ(S) == 1); dumpc(ress); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout << setprecision(12) << fixed; // while(true) test(); int t; cin >> t; while (t--) { cin >> N; REP(i, N) cin >> A[i]; cin >> S; cout << solve() << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; // type alias typedef long long LL; typedef pair<int, int> II; typedef tuple<int, int, int> III; typedef vector<int> VI; typedef vector<string> VS; typedef unordered_map<int, int> MAPII; typedef unordered_set<int> SETI; template <class T> using VV = vector<vector<T>>; // minmax template <class T> inline T SMIN(T &a, const T b) { return a = (a > b) ? b : a; } template <class T> inline T SMAX(T &a, const T b) { return a = (a < b) ? b : a; } // repetition #define FORE(i, a, b) for (int i = (a); i <= (b); ++i) #define REPE(i, n) for (int i = 0; i <= (n); ++i) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) for (int i = 0; i < (n); ++i) #define FORR(x, arr) for (auto &x : arr) #define SZ(a) int((a).size()) // collection #define ALL(c) (c).begin(), (c).end() // DP #define MINUS(dp) memset(dp, -1, sizeof(dp)) #define ZERO(dp) memset(dp, 0, sizeof(dp)) // stdout #define println(args...) fprintf(stdout, ##args), putchar('\n'); // debug cerr template <class Iter> void __kumaerrc(Iter begin, Iter end) { for (; begin != end; ++begin) { cerr << *begin << ','; } cerr << endl; } void __kumaerr(istream_iterator<string> it) { (void)it; cerr << endl; } template <typename T, typename... Args> void __kumaerr(istream_iterator<string> it, T a, Args... args) { cerr << *it << "=" << a << ", ", __kumaerr(++it, args...); } template <typename S, typename T> std::ostream &operator<<(std::ostream &_os, const std::pair<S, T> &_p) { return _os << "{" << _p.first << ',' << _p.second << "}"; } #define __KUMATRACE__ true #ifdef __KUMATRACE__ #define dump(args...) \ { \ string _s = #args; \ replace(_s.begin(), _s.end(), ',', ' '); \ stringstream _ss(_s); \ istream_iterator<string> _it(_ss); \ __kumaerr(_it, args); \ } #define dumpc(ar) \ { \ cerr << #ar << ": "; \ FORR(x, (ar)) { cerr << x << ','; } \ cerr << endl; \ } #define dumpC(beg, end) \ { \ cerr << "~" << #end << ": "; \ __kumaerrc(beg, end); \ } #else #define dump(args...) #define dumpc(ar) #define dumpC(beg, end) #endif // $ cp-batch XorBattle | diff XorBattle.out - // $ g++ -std=c++14 -Wall -O2 -D_GLIBCXX_DEBUG -fsanitize=address XorBattle.cpp // && ./a.out template <class T> void gf2_GE(vector<T> &V) { // gaussian elimination in GF(2) int N = V.size(); for (int i = 0; i < N; ++i) { sort(V.begin() + i, V.end(), greater<T>()); if (V[i] == 0) break; T msb = 1; while ((msb << 1) <= V[i]) msb <<= 1; for (int j = i + 1; j < N; ++j) if (V[j] & msb) V[j] ^= V[i]; } } template <class T> int gf2_rank(vector<T> &V) { gf2_GE<T>(V); return (int)V.size() - count(V.begin(), V.end(), 0); } /* 6/7/2020 5:00-6:30 give up 16:00-18:15, 21:50- https://twitter.com/hanseilimak/status/1269799620579692549 https://twitter.com/satanic0258/status/1269638393975107587 https://twitter.com/satanic0258/status/1269654741346217984 https://twitter.com/chokudai/status/1269662729712750592 https://twitter.com/ngtkana/status/1269638258486464513 https://twitter.com/noshi91/status/1269660771086041088 https://twitter.com/kyort0n/status/1269712783852986368 */ const int MAX_N = 1e3 + 1; LL A[MAX_N]; int N; string S; int solve() { vector<LL> V(1, 0); for (int i = N - 1; i >= 0; --i) { if (S[i] == '0') { V.push_back(A[i]); gf2_GE(V); } else { int rank = gf2_rank(V); V.push_back(A[i]); int rank2 = gf2_rank(V); if (rank2 > rank) return 1; } } return 0; } VI s; int memo[MAX_N][1 << 5]; int f(int i, int cur) { int &res = memo[i][cur]; if (res >= 0) return res; if (i == N) { return cur != 0; } bool res1 = f(i + 1, cur); bool res2 = f(i + 1, cur ^ A[i]); if (s[i] == 0) { res = (!res1 || !res2) ? false : true; } else { res = (res1 || res2); } return res; } mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); int genRandNum(int lb, int ub) { assert(lb < ub); // Helper to generate random integer in range [lb, ub) int x = rnd() % (int)(ub - lb); return x + lb; } vector<int> genRandSeq(int size, int lb, int ub) { if (size == 0) return {}; vector<int> res(size); generate(res.begin(), res.end(), [&]() { return genRandNum(lb, ub); }); return res; } string n2bin(long long n) { assert(n >= 0); string res = ""; while (n > 0) res += (n % 2LL ? '1' : '0'), n /= 2LL; return string(res.rbegin(), res.rend()); } void test() { N = 8; VI as = genRandSeq(N, 1, 1 << 3); s = genRandSeq(N, 0, 2); vector<II> states(N); REP(i, N) states[i] = {s[i], as[i]}; sort(ALL(states)); VI ress; do { MINUS(memo); REP(i, N) A[i] = states[i].second, s[i] = states[i].first; bool res = f(0, 0); if (!res) { vector<pair<int, string>> xs; FORR(p, states) xs.emplace_back(p.first, n2bin(p.second)); dumpc(xs); } ress.push_back(res); } while (next_permutation(ALL(states))); set<int> S; FORR(s, ress) S.emplace(s); int ands[2] = {(1 << N) - 1, (1 << N) - 1}, ors[2] = {0, 0}; FORR(p, states) ands[p.first] &= p.second, ors[p.first] |= p.second; if (SZ(S) == 2) { dump(n2bin(ands[0] ^ ors[0]), n2bin(ands[1] ^ ors[1])); dumpc(ress); dumpc(states); } assert(SZ(S) == 1); dumpc(ress); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout << setprecision(12) << fixed; // while(true) test(); int t; cin >> t; while (t--) { cin >> N; REP(i, N) cin >> A[i]; cin >> S; cout << solve() << endl; } return 0; }
replace
125
126
125
126
TLE
p02651
C++
Runtime Error
// 終局から考える。 // S[i] = '1'なるiについて、A[i]が{A[j], i+1≦j≦N-1, S[j] = '0'}と独立ならx≠0. // 全て従属とする。iが大きい方から考えると、最終的にx=0(従属)にできる。 // 独立性の判定: // ・各数を2進数ベクトルと考えて {A[j], i+1≦j≦N-1, S[j] = // '0'}について掃き出し法をおこない、 // 表現できるベクトル集合が同一のより単純な表現に直す // ・その表現では'1'の立つ最上位ビットの場所がdistinctだから、A[i]を作れるかを貪欲に判定できる // 計算量はO(TN^3). 厳しい? -> 定数倍が軽いので大丈夫そう. // 不安なら0ベクトルを取り除いておく. #include <iostream> #include <string> #include <vector> #define rep(i, n) for (i = 0; i < n; i++) #define int long long using namespace std; void sweep(vector<int> &vs) { int n = vs.size(); int row = 0; for (int i = 59; i >= 0; i--) { int pipot = -1; for (int j = row; j < n; j++) { if ((vs[j] >> i) & 1) { pipot = j; break; } } if (pipot == -1) continue; swap(vs[row], vs[pipot]); for (int j = row + 1; j < n; j++) { if ((vs[j] >> i) & 1) { vs[j] ^= vs[row]; } } row++; } while (*vs.rbegin() == 0) vs.pop_back(); } int solve(vector<int> a, string s) { int n = a.size(); vector<int> vs; for (int i = n - 1; i >= 0; i--) { if (s[i] == '0') { vs.push_back(a[i]); } else { sweep(vs); int val = a[i]; for (int j = 0; j < vs.size(); j++) { if ((val ^ vs[j]) < val) { val ^= vs[j]; } } if (val != 0) return 1; } } return 0; } signed main() { int T; cin >> T; while (T--) { int i, n; cin >> n; vector<int> a(n); rep(i, n) cin >> a[i]; string s; cin >> s; cout << solve(a, s) << endl; } return 0; }
// 終局から考える。 // S[i] = '1'なるiについて、A[i]が{A[j], i+1≦j≦N-1, S[j] = '0'}と独立ならx≠0. // 全て従属とする。iが大きい方から考えると、最終的にx=0(従属)にできる。 // 独立性の判定: // ・各数を2進数ベクトルと考えて {A[j], i+1≦j≦N-1, S[j] = // '0'}について掃き出し法をおこない、 // 表現できるベクトル集合が同一のより単純な表現に直す // ・その表現では'1'の立つ最上位ビットの場所がdistinctだから、A[i]を作れるかを貪欲に判定できる // 計算量はO(TN^3). 厳しい? -> 定数倍が軽いので大丈夫そう. // 不安なら0ベクトルを取り除いておく. #include <iostream> #include <string> #include <vector> #define rep(i, n) for (i = 0; i < n; i++) #define int long long using namespace std; void sweep(vector<int> &vs) { int n = vs.size(); int row = 0; for (int i = 59; i >= 0; i--) { int pipot = -1; for (int j = row; j < n; j++) { if ((vs[j] >> i) & 1) { pipot = j; break; } } if (pipot == -1) continue; swap(vs[row], vs[pipot]); for (int j = row + 1; j < n; j++) { if ((vs[j] >> i) & 1) { vs[j] ^= vs[row]; } } row++; } while (vs.size() > 0 && *vs.rbegin() == 0) vs.pop_back(); } int solve(vector<int> a, string s) { int n = a.size(); vector<int> vs; for (int i = n - 1; i >= 0; i--) { if (s[i] == '0') { vs.push_back(a[i]); } else { sweep(vs); int val = a[i]; for (int j = 0; j < vs.size(); j++) { if ((val ^ vs[j]) < val) { val ^= vs[j]; } } if (val != 0) return 1; } } return 0; } signed main() { int T; cin >> T; while (T--) { int i, n; cin >> n; vector<int> a(n); rep(i, n) cin >> a[i]; string s; cin >> s; cout << solve(a, s) << endl; } return 0; }
replace
41
42
41
42
0
p02651
C++
Runtime Error
#include <cstdio> #include <iostream> #include <math.h> #include <string> using namespace std; void reduce(int arr[64][64], int lead[64], int *d) { for (int i = 0; i < *d - 1; i++) { if (arr[*d - 1][lead[i]] == 1) { for (int k = lead[i]; k < 64; k++) { arr[*d - 1][k] = arr[*d - 1][k] ^ arr[i][k]; } } } int t = 0; for (int i = 0; i < 64; i++) { if (arr[*d - 1][i] != 0) { t = 1; lead[*d - 1] = i; break; } } if (t == 0) { *d = *d - 1; return; } for (int i = *d - 2; i >= 0; i--) { if (lead[i + 1] < lead[i]) { for (int j = 0; j < 64; j++) { t = arr[i][j]; arr[i][j] = arr[i + 1][j]; arr[i + 1][j] = t; } t = lead[i]; lead[i] = lead[i + 1]; lead[i + 1] = t; } else return; } return; } int solve() { int n; cin >> n; long *a = new long[n]; for (int i = 0; i < n; ++i) { cin >> a[i]; } string s; cin >> s; int arr[64][64]; int lead[64]; int d = 0; int t, temp; for (int i = s.length() - 1; i >= 0; i--) { t = d; temp = a[i]; for (int j = 63; j >= 0; j--) { arr[d][j] = temp % 2; temp /= 2; } d++; reduce(arr, lead, &d); if (s[i] == '1' && t != d) return 1; } return 0; } int main(void) { long t; cin >> t; string ans; for (int i = 0; i < t; i++) { cout << solve() << "\n"; } return 0; }
#include <cstdio> #include <iostream> #include <math.h> #include <string> using namespace std; void reduce(int arr[64][64], int lead[64], int *d) { for (int i = 0; i < *d - 1; i++) { if (arr[*d - 1][lead[i]] == 1) { for (int k = lead[i]; k < 64; k++) { arr[*d - 1][k] = arr[*d - 1][k] ^ arr[i][k]; } } } int t = 0; for (int i = 0; i < 64; i++) { if (arr[*d - 1][i] != 0) { t = 1; lead[*d - 1] = i; break; } } if (t == 0) { *d = *d - 1; return; } for (int i = *d - 2; i >= 0; i--) { if (lead[i + 1] < lead[i]) { for (int j = 0; j < 64; j++) { t = arr[i][j]; arr[i][j] = arr[i + 1][j]; arr[i + 1][j] = t; } t = lead[i]; lead[i] = lead[i + 1]; lead[i + 1] = t; } else return; } return; } int solve() { int n; cin >> n; long *a = new long[n]; for (int i = 0; i < n; ++i) { cin >> a[i]; } string s; cin >> s; int arr[64][64]; int lead[64]; int d = 0; int t; long temp; for (int i = s.length() - 1; i >= 0; i--) { t = d; temp = a[i]; for (int j = 63; j >= 0; j--) { arr[d][j] = temp % 2; temp /= 2; } d++; reduce(arr, lead, &d); if (s[i] == '1' && t != d) return 1; } return 0; } int main(void) { long t; cin >> t; string ans; for (int i = 0; i < t; i++) { cout << solve() << "\n"; } return 0; }
replace
57
58
57
59
0
p02651
C++
Time Limit Exceeded
#include <bits/stdc++.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> using namespace std; typedef long long ll; typedef pair<ll, ll> P; typedef pair<P, ll> T; typedef pair<long double, ll> Ps; const ll INF = 2e18; const ll fact_table = 3200008; long double Pi = 3.1415926535897932384626; priority_queue<ll> pql; priority_queue<P> pqp; priority_queue<P> bag; // big priority queue priority_queue<ll, vector<ll>, greater<ll>> pqls; priority_queue<P, vector<P>, greater<P>> pqps; // small priority queue // top pop ll dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; ll dy[8] = {0, 1, 0, -1, 1, -1, -1, 1}; char dir[] = "DRUL"; // ↓,→,↑,← #define endl "\n" #ifdef ENJAPMA #undef endl #endif #define p(x) cout << x << endl; #define el cout << endl; #define pe(x) cout << x << " "; #define ps(x) cout << fixed << setprecision(25) << x << endl; #define pu(x) cout << (x); #define pb push_back #define lb lower_bound #define ub upper_bound #define CLEAR(a) a = decltype(a)(); #define pc(x) cout << x << ","; #define rep(i, n) for (ll i = 0; i < (n); i++) // const ll mod = 998244353ll; const ll mod = 1000000007ll; ll mypow(ll a, ll b, ll mod) { ll x = 1; while (b) { while (!(b & 1)) { (a *= a) %= mod; b >>= 1; } (x *= a) %= mod; b--; } return x; } void YES(bool cond) { if (cond) { p("YES"); } else { p("NO"); } return; } void Yes(bool cond) { if (cond) { p("Yes"); } else { p("No"); } return; } /* ll fact[fact_table + 5],rfact[fact_table + 5]; void c3_init(){ fact[0] = rfact[0] = 1; for(ll i=1; i<=fact_table; i++){ fact[i] = (fact[i-1]*i) % mod; } rfact[fact_table] = mypow(fact[fact_table],mod - 2, mod); for(ll i=fact_table; i>=1; i--){ rfact[i-1] = rfact[i] * i; rfact[i-1] %= mod; } return;} ll c3(ll n,ll r){ return (((fact[n] * rfact[r]) % mod ) * rfact[n-r]) % mod;} */ bool multicase = true; ll n, m, num, a, b, c, d, e, h, q; ll w, k, ans; ll x[500005], y[500005], z[500005]; string s; const int MAX_ROW = 65; // to be set appropriately const int MAX_COL = 110000; // to be set appropriately struct BitMatrix { int H, W; bitset<MAX_COL> val[MAX_ROW]; BitMatrix(int m = 1, int n = 1) : H(m), W(n) {} inline bitset<MAX_COL> &operator[](int i) { return val[i]; } }; ostream &operator<<(ostream &s, BitMatrix A) { s << endl; for (int i = 0; i < A.H; ++i) { for (int j = 0; j < A.W; ++j) { s << A[i][j] << ", "; } s << endl; } return s; } int GaussJordan(BitMatrix &A, bool is_extended = false) { int rank = 0; for (int col = 0; col < A.W; ++col) { if (is_extended && col == A.W - 1) break; int pivot = -1; for (int row = rank; row < A.H; ++row) { if (A[row][col]) { pivot = row; break; } } if (pivot == -1) continue; swap(A[pivot], A[rank]); for (int row = 0; row < A.H; ++row) { if (row != rank && A[row][col]) A[row] ^= A[rank]; } ++rank; } return rank; } int linear_equation(BitMatrix A, vector<int> b) { int m = A.H, n = A.W; BitMatrix M(m, n + 1); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) M[i][j] = A[i][j]; M[i][n] = b[i]; } int rank = GaussJordan(M, true); // check if it has no solution for (int row = rank; row < m; ++row) if (M[row][n]) return -1; // answer return rank; } vector<int> v; void solve() { cin >> n; for (ll i = 0; i < n; i++) { cin >> x[i]; assert(x[i] != 0); } cin >> s; ll ones = 0; for (ll i = 0; i < n; i++) { if (s[i] == '1') ones++; } const int DIGIT = 61; BitMatrix A(DIGIT, n); ll cnt = 0; bool dame = false; for (ll i = n - 1; i >= 0; i--) { if (s[i] == '0') { // 列に追加する for (ll j = 0; j < 60; j++) { if (x[i] & 1) A[j][cnt] = 1; x[i] >>= 1; } cnt++; } else { v.clear(); for (ll j = 0; j < 60; j++) { if (x[i] & 1) { v.pb(1); } else { v.pb(0); } x[i] >>= 1; } int ans = linear_equation(A, v); if (ans == -1) { dame = true; break; } else if (ans >= 60) { break; } ones--; if (ones == 0) break; } } if (dame) { p(1); } else { p(0); } return; } int main() { // init(); ios::sync_with_stdio(false); cin.tie(nullptr); ll q, testcase = 1; if (multicase) { cin >> q; } else { q = 1; } while (q--) { // pu("Case ");pu("#");pu(testcase);pu(": "); solve(); testcase++; } // solve(); return 0; }
#include <bits/stdc++.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> using namespace std; typedef long long ll; typedef pair<ll, ll> P; typedef pair<P, ll> T; typedef pair<long double, ll> Ps; const ll INF = 2e18; const ll fact_table = 3200008; long double Pi = 3.1415926535897932384626; priority_queue<ll> pql; priority_queue<P> pqp; priority_queue<P> bag; // big priority queue priority_queue<ll, vector<ll>, greater<ll>> pqls; priority_queue<P, vector<P>, greater<P>> pqps; // small priority queue // top pop ll dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; ll dy[8] = {0, 1, 0, -1, 1, -1, -1, 1}; char dir[] = "DRUL"; // ↓,→,↑,← #define endl "\n" #ifdef ENJAPMA #undef endl #endif #define p(x) cout << x << endl; #define el cout << endl; #define pe(x) cout << x << " "; #define ps(x) cout << fixed << setprecision(25) << x << endl; #define pu(x) cout << (x); #define pb push_back #define lb lower_bound #define ub upper_bound #define CLEAR(a) a = decltype(a)(); #define pc(x) cout << x << ","; #define rep(i, n) for (ll i = 0; i < (n); i++) // const ll mod = 998244353ll; const ll mod = 1000000007ll; ll mypow(ll a, ll b, ll mod) { ll x = 1; while (b) { while (!(b & 1)) { (a *= a) %= mod; b >>= 1; } (x *= a) %= mod; b--; } return x; } void YES(bool cond) { if (cond) { p("YES"); } else { p("NO"); } return; } void Yes(bool cond) { if (cond) { p("Yes"); } else { p("No"); } return; } /* ll fact[fact_table + 5],rfact[fact_table + 5]; void c3_init(){ fact[0] = rfact[0] = 1; for(ll i=1; i<=fact_table; i++){ fact[i] = (fact[i-1]*i) % mod; } rfact[fact_table] = mypow(fact[fact_table],mod - 2, mod); for(ll i=fact_table; i>=1; i--){ rfact[i-1] = rfact[i] * i; rfact[i-1] %= mod; } return;} ll c3(ll n,ll r){ return (((fact[n] * rfact[r]) % mod ) * rfact[n-r]) % mod;} */ bool multicase = true; ll n, m, num, a, b, c, d, e, h, q; ll w, k, ans; ll x[500005], y[500005], z[500005]; string s; const int MAX_ROW = 65; // to be set appropriately const int MAX_COL = 205; // to be set appropriately struct BitMatrix { int H, W; bitset<MAX_COL> val[MAX_ROW]; BitMatrix(int m = 1, int n = 1) : H(m), W(n) {} inline bitset<MAX_COL> &operator[](int i) { return val[i]; } }; ostream &operator<<(ostream &s, BitMatrix A) { s << endl; for (int i = 0; i < A.H; ++i) { for (int j = 0; j < A.W; ++j) { s << A[i][j] << ", "; } s << endl; } return s; } int GaussJordan(BitMatrix &A, bool is_extended = false) { int rank = 0; for (int col = 0; col < A.W; ++col) { if (is_extended && col == A.W - 1) break; int pivot = -1; for (int row = rank; row < A.H; ++row) { if (A[row][col]) { pivot = row; break; } } if (pivot == -1) continue; swap(A[pivot], A[rank]); for (int row = 0; row < A.H; ++row) { if (row != rank && A[row][col]) A[row] ^= A[rank]; } ++rank; } return rank; } int linear_equation(BitMatrix A, vector<int> b) { int m = A.H, n = A.W; BitMatrix M(m, n + 1); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) M[i][j] = A[i][j]; M[i][n] = b[i]; } int rank = GaussJordan(M, true); // check if it has no solution for (int row = rank; row < m; ++row) if (M[row][n]) return -1; // answer return rank; } vector<int> v; void solve() { cin >> n; for (ll i = 0; i < n; i++) { cin >> x[i]; assert(x[i] != 0); } cin >> s; ll ones = 0; for (ll i = 0; i < n; i++) { if (s[i] == '1') ones++; } const int DIGIT = 61; BitMatrix A(DIGIT, n); ll cnt = 0; bool dame = false; for (ll i = n - 1; i >= 0; i--) { if (s[i] == '0') { // 列に追加する for (ll j = 0; j < 60; j++) { if (x[i] & 1) A[j][cnt] = 1; x[i] >>= 1; } cnt++; } else { v.clear(); for (ll j = 0; j < 60; j++) { if (x[i] & 1) { v.pb(1); } else { v.pb(0); } x[i] >>= 1; } int ans = linear_equation(A, v); if (ans == -1) { dame = true; break; } else if (ans >= 60) { break; } ones--; if (ones == 0) break; } } if (dame) { p(1); } else { p(0); } return; } int main() { // init(); ios::sync_with_stdio(false); cin.tie(nullptr); ll q, testcase = 1; if (multicase) { cin >> q; } else { q = 1; } while (q--) { // pu("Case ");pu("#");pu(testcase);pu(": "); solve(); testcase++; } // solve(); return 0; }
replace
104
106
104
106
TLE
p02652
C++
Time Limit Exceeded
#include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <vector> #define X first #define Y second #define PB push_back using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; const int N = 1e6 + 500; const int INF = 0x3f3f3f3f; const int MOD = 998244353; int mini = 0, maxi = 0, n; char s[N]; int desno[N]; int probaj(int x) { if (desno[0] < x) return n; int cur = 0, gran = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') { cur++; } else if (s[i] == '0') { cur--; } else { if (cur + desno[i + 1] > x) cur--; else cur++; } gran = max(cur, gran); } return gran - x; } int main() { scanf("%s", s); n = strlen(s); desno[n] = 0; for (int i = n - 1; i >= 0; i--) { if (s[i] == '1' || s[i] == '?') { desno[i] = min(desno[i + 1] + 1, 0); } else { desno[i] = desno[i + 1] - 1; } } if (n <= 1e4) { int bst = n, gdje = 0; for (int i = 0; 2 * i <= n; i++) bst = min(bst, probaj(-i)); printf("%d\n", bst); } else { int bst = n, gdje = 0; int lo = 0, hi = n; while (lo + 100 > hi) { int mid1 = (2 * lo + hi) / 3; int mid2 = (lo + 2 * hi) / 3; int s1 = probaj(-mid1), s2 = probaj(-mid2); bst = min(bst, min(s1, s2)); if (s1 == s2) { lo = mid1, hi = mid2; } else if (s1 < s2) { hi = mid2; } else { lo = mid1; } } for (int i = lo; i <= hi; i++) bst = min(bst, probaj(-i)); printf("%d\n", bst); } return 0; }
#include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <vector> #define X first #define Y second #define PB push_back using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; const int N = 1e6 + 500; const int INF = 0x3f3f3f3f; const int MOD = 998244353; int mini = 0, maxi = 0, n; char s[N]; int desno[N]; int probaj(int x) { if (desno[0] < x) return n; int cur = 0, gran = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') { cur++; } else if (s[i] == '0') { cur--; } else { if (cur + desno[i + 1] > x) cur--; else cur++; } gran = max(cur, gran); } return gran - x; } int main() { scanf("%s", s); n = strlen(s); desno[n] = 0; for (int i = n - 1; i >= 0; i--) { if (s[i] == '1' || s[i] == '?') { desno[i] = min(desno[i + 1] + 1, 0); } else { desno[i] = desno[i + 1] - 1; } } int sol = n; for (int x = desno[0]; x >= desno[0] - 50; x--) sol = min(sol, probaj(x)); printf("%d\n", sol); return 0; }
replace
56
81
56
60
TLE
p02652
C++
Runtime Error
#include "bits/stdc++.h" using namespace std; #define FAST \ ios_base::sync_with_stdio(false); \ cin.tie(0); #define pb push_back #define eb emplace_back #define ins insert #define f first #define s second #define cbr cerr << "hi\n" #define mmst(x, v) memset((x), v, sizeof((x))) #define siz(x) ll(x.size()) #define all(x) (x).begin(), (x).end() #define lbd(x, y) (lower_bound(all(x), y) - x.begin()) #define ubd(x, y) (upper_bound(all(x), y) - x.begin()) mt19937 rng(chrono::steady_clock::now() .time_since_epoch() .count()); // can be used by calling rng() or shuffle(A, A+n, rng) inline long long rand(long long x, long long y) { return rng() % (y + 1 - x) + x; } // inclusivesss string inline to_string(char c) { string s(1, c); return s; } template <typename T> inline T gcd(T a, T b) { return a == 0 ? llabs(b) : gcd(b % a, a); } using ll = long long; using ld = long double; #define FOR(i, s, e) for (ll i = s; i <= ll(e); ++i) #define DEC(i, s, e) for (ll i = s; i >= ll(e); --i) using pi = pair<ll, ll>; using spi = pair<ll, pi>; using dpi = pair<pi, pi>; #define llinf ((long long)1e18) #define inf int(1e9 + 1e6) #define maxn (300006) ll n, psum[maxn]; string A; int main() { FAST cin >> A; n = A.size(); A = '*' + A; FOR(i, 1, n) { psum[i] = psum[i - 1] + (A[i] == '1' ? 1 : -1); } ll Z = *max_element(psum, psum + n + 1); auto f = [&](ll x) { mmst(psum, 0); FOR(i, 1, n) { psum[i] = psum[i - 1] + (A[i] == '1' ? 1 : -1); } vector<ll> suf_max(n + 2, -llinf); DEC(i, n, 1) suf_max[i] = max(suf_max[i + 1], psum[i]); ll change = 0; FOR(i, 1, n) { if (A[i] == '?') { if (suf_max[i] + 2 * (change + 1) <= x) ++change; } psum[i] += 2 * change; } return *min_element(psum, psum + n + 1); }; cout << min(Z - f(Z), Z + 1 - f(Z + 1)) << '\n'; }
#include "bits/stdc++.h" using namespace std; #define FAST \ ios_base::sync_with_stdio(false); \ cin.tie(0); #define pb push_back #define eb emplace_back #define ins insert #define f first #define s second #define cbr cerr << "hi\n" #define mmst(x, v) memset((x), v, sizeof((x))) #define siz(x) ll(x.size()) #define all(x) (x).begin(), (x).end() #define lbd(x, y) (lower_bound(all(x), y) - x.begin()) #define ubd(x, y) (upper_bound(all(x), y) - x.begin()) mt19937 rng(chrono::steady_clock::now() .time_since_epoch() .count()); // can be used by calling rng() or shuffle(A, A+n, rng) inline long long rand(long long x, long long y) { return rng() % (y + 1 - x) + x; } // inclusivesss string inline to_string(char c) { string s(1, c); return s; } template <typename T> inline T gcd(T a, T b) { return a == 0 ? llabs(b) : gcd(b % a, a); } using ll = long long; using ld = long double; #define FOR(i, s, e) for (ll i = s; i <= ll(e); ++i) #define DEC(i, s, e) for (ll i = s; i >= ll(e); --i) using pi = pair<ll, ll>; using spi = pair<ll, pi>; using dpi = pair<pi, pi>; #define llinf ((long long)1e18) #define inf int(1e9 + 1e6) #define maxn (1000006) ll n, psum[maxn]; string A; int main() { FAST cin >> A; n = A.size(); A = '*' + A; FOR(i, 1, n) { psum[i] = psum[i - 1] + (A[i] == '1' ? 1 : -1); } ll Z = *max_element(psum, psum + n + 1); auto f = [&](ll x) { mmst(psum, 0); FOR(i, 1, n) { psum[i] = psum[i - 1] + (A[i] == '1' ? 1 : -1); } vector<ll> suf_max(n + 2, -llinf); DEC(i, n, 1) suf_max[i] = max(suf_max[i + 1], psum[i]); ll change = 0; FOR(i, 1, n) { if (A[i] == '?') { if (suf_max[i] + 2 * (change + 1) <= x) ++change; } psum[i] += 2 * change; } return *min_element(psum, psum + n + 1); }; cout << min(Z - f(Z), Z + 1 - f(Z + 1)) << '\n'; }
replace
42
43
42
43
0
p02652
C++
Runtime Error
#include <algorithm> #include <cstdlib> #include <iostream> template <typename T> void fin(T const &t) { std::cout << t << std::endl; exit(0); } char buf[100010]; int main() { std::cin.tie(0); std::ios::sync_with_stdio(false); std::cin >> buf; int a0 = 0, a1 = 1, b0 = 0, b1 = -1; int c0 = a0 - b0, c1 = a0 - b1, c2 = a1 - b0, c3 = a1 - b1; for (char *p = buf; *p; p++) { if (*p == '0') { --a0; --a1; --b0; --b1; } else if (*p == '1') { ++a0; ++a1; ++b0; ++b1; } else { --a0; --a1; ++b0; ++b1; } if (a0 < 0) a0 += 2; if (a1 < 0) a1 += 2; if (b0 > 0) b0 -= 2; if (b1 > 0) b1 -= 2; c0 = std::max(c0, a0 - b0); c1 = std::max(c1, a0 - b1); c2 = std::max(c2, a1 - b0); c3 = std::max(c3, a1 - b1); } fin(std::min(std::min(c0, c1), std::min(c2, c3))); return 0; }
#include <algorithm> #include <cstdlib> #include <iostream> template <typename T> void fin(T const &t) { std::cout << t << std::endl; exit(0); } char buf[1000010]; int main() { std::cin.tie(0); std::ios::sync_with_stdio(false); std::cin >> buf; int a0 = 0, a1 = 1, b0 = 0, b1 = -1; int c0 = a0 - b0, c1 = a0 - b1, c2 = a1 - b0, c3 = a1 - b1; for (char *p = buf; *p; p++) { if (*p == '0') { --a0; --a1; --b0; --b1; } else if (*p == '1') { ++a0; ++a1; ++b0; ++b1; } else { --a0; --a1; ++b0; ++b1; } if (a0 < 0) a0 += 2; if (a1 < 0) a1 += 2; if (b0 > 0) b0 -= 2; if (b1 > 0) b1 -= 2; c0 = std::max(c0, a0 - b0); c1 = std::max(c1, a0 - b1); c2 = std::max(c2, a1 - b0); c3 = std::max(c3, a1 - b1); } fin(std::min(std::min(c0, c1), std::min(c2, c3))); return 0; }
replace
7
8
7
8
0
p02652
C++
Runtime Error
#include <cstdio> #include <cstring> #include <iostream> using namespace std; #define N 100010 inline int read() { int x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); } return x * f; } int mx, n, a[N], b[N]; char s[N]; void init() { int sum = 0; for (int i = 1; i <= n; ++i) { sum += (s[i] == '1' ? 1 : -1); mx = max(mx, sum); a[i] = sum; } b[n] = a[n]; for (int i = n - 1; i >= 0; --i) { b[i] = max(a[i], b[i + 1]); } } int calc(int lim) { int mn = 0, sum = 0; for (int i = 1; i <= n; ++i) { if (s[i] == '1') ++sum; else if (s[i] == '0') --sum; else { if (b[i] - a[i - 1] + sum + 2 <= lim) ++sum; else --sum; } mn = min(mn, sum); } return mn; } int main() { scanf("%s", s + 1); n = strlen(s + 1); init(); printf("%d\n", min(mx - calc(mx), mx + 1 - calc(mx + 1))); return 0; }
#include <cstdio> #include <cstring> #include <iostream> using namespace std; #define N 1000010 inline int read() { int x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); } return x * f; } int mx, n, a[N], b[N]; char s[N]; void init() { int sum = 0; for (int i = 1; i <= n; ++i) { sum += (s[i] == '1' ? 1 : -1); mx = max(mx, sum); a[i] = sum; } b[n] = a[n]; for (int i = n - 1; i >= 0; --i) { b[i] = max(a[i], b[i + 1]); } } int calc(int lim) { int mn = 0, sum = 0; for (int i = 1; i <= n; ++i) { if (s[i] == '1') ++sum; else if (s[i] == '0') --sum; else { if (b[i] - a[i - 1] + sum + 2 <= lim) ++sum; else --sum; } mn = min(mn, sum); } return mn; } int main() { scanf("%s", s + 1); n = strlen(s + 1); init(); printf("%d\n", min(mx - calc(mx), mx + 1 - calc(mx + 1))); return 0; }
replace
4
5
4
5
0
p02652
C++
Runtime Error
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <ctime> #include <deque> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <utility> #include <vector> #define llint long long #define inf 1e18 #define rep(x, s, t) for (llint(x) = (s); (x) < (t); (x)++) #define Rep(x, s, t) for (llint(x) = (s); (x) <= (t); (x)++) #define chmin(x, y) (x) = min((x), (y)) #define chmax(x, y) (x) = max((x), (y)) using namespace std; typedef pair<llint, llint> P; struct BIT { int size; vector<llint> bit; BIT() { size = 0; } BIT(int s) { size = s; bit.resize(size + 1); init(); } void init() { for (int i = 1; i <= size; i++) bit[i] = 0; } llint query(int i) { llint ret = 0; while (i > 0) { ret += bit[i]; i -= i & (-i); } return ret; } void add(int i, llint x) { while (i <= size) { bit[i] += x; i += i & (-i); } } }; string s; BIT bit(1000005); void update(llint p, llint x) { llint v = bit.query(p), d = x - v; bit.add(p, d), bit.add(p + 1, -d); } llint get(llint l, llint r) { llint ub = r + 1, lb = l - 1, mid; while (ub - lb > 1) { mid = (ub + lb) / 2; llint res = bit.query(mid); if (res > 0) { if (res > inf / 2) { if (bit.query(mid + 1) > 0 || bit.query(mid - 1) > 0) lb = mid; else ub = mid; } else lb = mid; } else ub = mid; } return lb; } int main(void) { ios::sync_with_stdio(0); cin.tie(0); cin >> s; llint n = s.size(); s = "#" + s; bit.add(1, inf); update(1000002, 0); llint l = 1000002, r = 1000002, k = 1000002; for (int i = 1; i <= n; i++) { if (s[i] == '0') { llint res = get(l, r); // cout << res << endl; if (res >= l) bit.add(l, -1), bit.add(res + 1, 1); l--; update(l, inf); } if (s[i] == '1') { bit.add(l, 1), bit.add(r + 1, -1); l++; llint x = min(bit.query(l - 1), bit.query(l)); update(l, x); update(l - 1, inf); } if (s[i] == '?') { if (l == k) { llint x = min(bit.query(k), bit.query(k + 1)) + 1; llint res = get(l, r); // cout << "!" << res << endl; if (res >= l) bit.add(l, -1), bit.add(res + 1, 1); l--; k--; update(k, x); } else { llint x = bit.query(k + 1) + 1, y = bit.query(k) + 1; llint res = get(l, r); if (res >= l) bit.add(l, -1), bit.add(res + 1, 1); l--; k -= 2; update(k, y), update(k + 1, x); } } k = max(l, k); // for(int i = l; i <= r; i++) cout << bit.query(i) << " "; cout << endl; } llint ans = inf; for (int i = l; i <= r; i++) { ans = min(ans, bit.query(i) + (i - l)); } cout << ans << endl; return 0; }
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <ctime> #include <deque> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <utility> #include <vector> #define llint long long #define inf 1e18 #define rep(x, s, t) for (llint(x) = (s); (x) < (t); (x)++) #define Rep(x, s, t) for (llint(x) = (s); (x) <= (t); (x)++) #define chmin(x, y) (x) = min((x), (y)) #define chmax(x, y) (x) = max((x), (y)) using namespace std; typedef pair<llint, llint> P; struct BIT { int size; vector<llint> bit; BIT() { size = 0; } BIT(int s) { size = s; bit.resize(size + 1); init(); } void init() { for (int i = 1; i <= size; i++) bit[i] = 0; } llint query(int i) { llint ret = 0; while (i > 0) { ret += bit[i]; i -= i & (-i); } return ret; } void add(int i, llint x) { while (i <= size) { bit[i] += x; i += i & (-i); } } }; string s; BIT bit(1000005); void update(llint p, llint x) { llint v = bit.query(p), d = x - v; bit.add(p, d), bit.add(p + 1, -d); } llint get(llint l, llint r) { llint ub = r + 1, lb = l - 1, mid; while (ub - lb > 1) { mid = (ub + lb) / 2; llint res = bit.query(mid); if (res > 0) { if (res > inf / 2) { if (bit.query(mid + 1) > 0 || bit.query(mid - 1) > 0) lb = mid; else ub = mid; } else lb = mid; } else ub = mid; } return lb; } int main(void) { ios::sync_with_stdio(0); cin.tie(0); cin >> s; llint n = s.size(); s = "#" + s; bit.add(1, inf); update(1000002, 0); llint l = 1000002, r = 1000002, k = 1000002; for (int i = 1; i <= n; i++) { if (s[i] == '0') { llint res = get(l, r); // cout << res << endl; if (res >= l) bit.add(l, -1), bit.add(res + 1, 1); l--; update(l, inf); } if (s[i] == '1') { bit.add(l, 1), bit.add(r + 1, -1); if (l < r) l++; llint x = min(bit.query(l - 1), bit.query(l)); update(l, x); update(l - 1, inf); } if (s[i] == '?') { if (l == k) { llint x = min(bit.query(k), bit.query(k + 1)) + 1; llint res = get(l, r); // cout << "!" << res << endl; if (res >= l) bit.add(l, -1), bit.add(res + 1, 1); l--; k--; update(k, x); } else { llint x = bit.query(k + 1) + 1, y = bit.query(k) + 1; llint res = get(l, r); if (res >= l) bit.add(l, -1), bit.add(res + 1, 1); l--; k -= 2; update(k, y), update(k + 1, x); } } k = max(l, k); // for(int i = l; i <= r; i++) cout << bit.query(i) << " "; cout << endl; } llint ans = inf; for (int i = l; i <= r; i++) { ans = min(ans, bit.query(i) + (i - l)); } cout << ans << endl; return 0; }
replace
106
107
106
108
0
p02652
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; int n; char s[N]; int sum[N], pmx[N], pmi[N]; int main() { scanf("%s", s + 1); n = strlen(s + 1); sum[0] = 0; pmx[0] = 0; pmi[0] = 0; for (int i = 1; i <= n; i++) { sum[i] = sum[i - 1] + 1 - 2 * (s[i] == '0'); pmx[i] = max(pmx[i - 1], sum[i]); pmi[i] = min(pmi[i - 1], sum[i]); } int suf_mi = sum[n], suf_mx = sum[n]; int ans = pmx[n] - pmi[n]; for (int i = n; i; i--) { suf_mi = min(suf_mi, sum[i]); suf_mx = max(suf_mx, sum[i]); if (s[i] == '?') { if (pmx[i - 1] < suf_mx) { ans = min(ans, max(pmx[i - 1], suf_mx - 2) - min(pmi[i - 1], suf_mi - 2)); } if (pmx[i - 1] + 1 < suf_mx) { suf_mx -= 2; suf_mi -= 2; ans = min(ans, max(pmx[i - 1], suf_mx) - min(pmi[i - 1], suf_mi)); } } } suf_mi = sum[n], suf_mx = sum[n]; bool found = false; for (int i = n; i; i--) { suf_mi = min(suf_mi, sum[i]); suf_mx = max(suf_mx, sum[i]); if (s[i] == '?') { if (pmx[i - 1] + 1 == suf_mx) { ans = min(ans, max(pmx[i - 1], suf_mx - 2) - min(pmi[i - 1], suf_mi - 2)); if (!found) { suf_mi -= 2; suf_mx -= 2; found = true; } } else if (pmx[i - 1] + 1 < suf_mx) { assert(found); suf_mx -= 2; suf_mi -= 2; ans = min(ans, max(pmx[i - 1], suf_mx) - min(pmi[i - 1], suf_mi)); } } } printf("%d\n", ans); return 0; }
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; int n; char s[N]; int sum[N], pmx[N], pmi[N]; int main() { scanf("%s", s + 1); n = strlen(s + 1); sum[0] = 0; pmx[0] = 0; pmi[0] = 0; for (int i = 1; i <= n; i++) { sum[i] = sum[i - 1] + 1 - 2 * (s[i] == '0'); pmx[i] = max(pmx[i - 1], sum[i]); pmi[i] = min(pmi[i - 1], sum[i]); } int suf_mi = sum[n], suf_mx = sum[n]; int ans = pmx[n] - pmi[n]; for (int i = n; i; i--) { suf_mi = min(suf_mi, sum[i]); suf_mx = max(suf_mx, sum[i]); if (s[i] == '?') { if (pmx[i - 1] < suf_mx) { ans = min(ans, max(pmx[i - 1], suf_mx - 2) - min(pmi[i - 1], suf_mi - 2)); } if (pmx[i - 1] + 1 < suf_mx) { suf_mx -= 2; suf_mi -= 2; ans = min(ans, max(pmx[i - 1], suf_mx) - min(pmi[i - 1], suf_mi)); } } } suf_mi = sum[n], suf_mx = sum[n]; bool found = false; for (int i = n; i; i--) { suf_mi = min(suf_mi, sum[i]); suf_mx = max(suf_mx, sum[i]); if (s[i] == '?') { if (pmx[i - 1] + 1 == suf_mx) { ans = min(ans, max(pmx[i - 1], suf_mx - 2) - min(pmi[i - 1], suf_mi - 2)); if (!found) { suf_mi -= 2; suf_mx -= 2; found = true; } } else if (pmx[i - 1] + 1 < suf_mx) { suf_mx -= 2; suf_mi -= 2; ans = min(ans, max(pmx[i - 1], suf_mx) - min(pmi[i - 1], suf_mi)); } } } printf("%d\n", ans); return 0; }
delete
52
53
52
52
0
p02652
C++
Runtime Error
#include "algorithm" #include "cmath" #include "cstdio" #include "cstring" #include "iostream" #include "map" #include "queue" #include "set" #include "vector" using namespace std; #define MAXN 1000006 // #define int long long #define rep(i, a, b) for (int i = (a), i##end = (b); i <= i##end; ++i) #define per(i, a, b) for (int i = (a), i##end = (b); i >= i##end; --i) #define pii pair<int, int> #define fi first #define se second #define mp make_pair #define pb push_back #define eb emplace_back #define vi vector<int> #define all(x) (x).begin(), (x).end() #define mem(a) memset(a, 0, sizeof a) typedef long long ll; int n, m; char ch[MAXN]; int A[MAXN], a[MAXN], B[MAXN], mn[MAXN], mmn = 0x3f3f3f3f; bool us[MAXN]; void solve() { scanf("%s", ch + 1); n = strlen(ch + 1); int mx = 0, ps; rep(i, 1, n) { if (ch[i] == '?' || ch[i] == '0') A[i] = A[i - 1] - 1; else A[i] = A[i - 1] + 1; a[i] = A[i]; mx = max(mx, A[i]); } rep(i, 1, n) if (A[i] == mx) ps = i; B[n] = A[n]; per(i, n - 1, 1) B[i] = max(A[i], B[i + 1]); int t = 0; rep(i, ps, n) { if (ch[i] == '?' && B[i] + t <= mx - 2) t += 2, us[i] = 1; A[i] += t; } mmn = 0; rep(i, 1, n) mmn = min(mmn, A[i]); int as = mx - mmn, chp = 0; mem(us); rep(i, 1, n) A[i] = a[i]; t = 0; rep(i, ps, n) { if (ch[i] == '?' && B[i] + t <= mx - 1) t += 2, us[i] = 1; A[i] += t; } mmn = 0; rep(i, 1, n) mmn = min(mmn, A[i]); int as1 = mx + 1 - mmn, chp1 = 0; printf("%d\n", min(as1, as)); } signed main() { // int T;cin >> T;while( T-- ) solve(); solve(); }
#include "algorithm" #include "cmath" #include "cstdio" #include "cstring" #include "iostream" #include "map" #include "queue" #include "set" #include "vector" using namespace std; #define MAXN 1000006 // #define int long long #define rep(i, a, b) for (int i = (a), i##end = (b); i <= i##end; ++i) #define per(i, a, b) for (int i = (a), i##end = (b); i >= i##end; --i) #define pii pair<int, int> #define fi first #define se second #define mp make_pair #define pb push_back #define eb emplace_back #define vi vector<int> #define all(x) (x).begin(), (x).end() #define mem(a) memset(a, 0, sizeof a) typedef long long ll; int n, m; char ch[MAXN]; int A[MAXN], a[MAXN], B[MAXN], mn[MAXN], mmn = 0x3f3f3f3f; bool us[MAXN]; void solve() { scanf("%s", ch + 1); n = strlen(ch + 1); int mx = 0, ps; rep(i, 1, n) { if (ch[i] == '?' || ch[i] == '0') A[i] = A[i - 1] - 1; else A[i] = A[i - 1] + 1; a[i] = A[i]; mx = max(mx, A[i]); } rep(i, 0, n) if (A[i] == mx) ps = i; B[n] = A[n]; per(i, n - 1, 1) B[i] = max(A[i], B[i + 1]); int t = 0; rep(i, ps, n) { if (ch[i] == '?' && B[i] + t <= mx - 2) t += 2, us[i] = 1; A[i] += t; } mmn = 0; rep(i, 1, n) mmn = min(mmn, A[i]); int as = mx - mmn, chp = 0; mem(us); rep(i, 1, n) A[i] = a[i]; t = 0; rep(i, ps, n) { if (ch[i] == '?' && B[i] + t <= mx - 1) t += 2, us[i] = 1; A[i] += t; } mmn = 0; rep(i, 1, n) mmn = min(mmn, A[i]); int as1 = mx + 1 - mmn, chp1 = 0; printf("%d\n", min(as1, as)); } signed main() { // int T;cin >> T;while( T-- ) solve(); solve(); }
replace
40
41
40
41
0
p02653
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int mod = 1e9 + 7; int dp0[5005][5005], dp1[5005][5005], dp2[5005][5005], sum1[5005][5005]; int main() { int n, a, b; scanf("%d%d%d", &n, &a, &b); if (a > b) swap(a, b); dp1[0][0] = 1; for (int j = 0; j <= n; j++) sum1[0][j] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= a - 1; j++) dp0[i][0] = (dp0[i][0] + sum1[i - j][n]) % mod; for (int j = 0; j <= b - a - 1; j++) dp2[i][j + a] = (dp2[i][j + a] + dp1[i - a][j]) % mod; for (int j = 0; j < b - 1; j++) { dp2[i][j + 1] = (dp2[i][j + 1] + dp2[i - 1][j]) % mod; } for (int j = 0; j < b - 1; j++) { dp1[i][j + 1] = (dp1[i][j + 1] + dp0[i - 1][j]) % mod; dp1[i][j + 1] = (dp1[i][j + 1] + dp1[i - 1][j]) % mod; dp1[i][j + 1] = (dp1[i][j + 1] + dp2[i - 1][j]) % mod; } for (int j = 0; j <= n; j++) { if (j == 0) sum1[i][j] = dp1[i][j]; else sum1[i][j] = (sum1[i][j - 1] + dp1[i][j]) % mod; } } int ans = 1; for (int i = 1; i <= n; i++) ans = ans * 2 % mod; for (int j = 0; j <= n; j++) { ans = (ans - dp0[n][j] + mod) % mod; ans = (ans - dp1[n][j] + mod) % mod; ans = (ans - dp2[n][j] + mod) % mod; } printf("%d\n", ans); }
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int mod = 1e9 + 7; int dp0[5005][5005], dp1[5005][5005], dp2[5005][5005], sum1[5005][5005]; int main() { int n, a, b; scanf("%d%d%d", &n, &a, &b); if (a > b) swap(a, b); dp1[0][0] = 1; for (int j = 0; j <= n; j++) sum1[0][j] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= a - 1; j++) if (i - j >= 0) dp0[i][0] = (dp0[i][0] + sum1[i - j][n]) % mod; if (i >= a) for (int j = 0; j <= b - a - 1; j++) dp2[i][j + a] = (dp2[i][j + a] + dp1[i - a][j]) % mod; for (int j = 0; j < b - 1; j++) { dp2[i][j + 1] = (dp2[i][j + 1] + dp2[i - 1][j]) % mod; } for (int j = 0; j < b - 1; j++) { dp1[i][j + 1] = (dp1[i][j + 1] + dp0[i - 1][j]) % mod; dp1[i][j + 1] = (dp1[i][j + 1] + dp1[i - 1][j]) % mod; dp1[i][j + 1] = (dp1[i][j + 1] + dp2[i - 1][j]) % mod; } for (int j = 0; j <= n; j++) { if (j == 0) sum1[i][j] = dp1[i][j]; else sum1[i][j] = (sum1[i][j - 1] + dp1[i][j]) % mod; } } int ans = 1; for (int i = 1; i <= n; i++) ans = ans * 2 % mod; for (int j = 0; j <= n; j++) { ans = (ans - dp0[n][j] + mod) % mod; ans = (ans - dp1[n][j] + mod) % mod; ans = (ans - dp2[n][j] + mod) % mod; } printf("%d\n", ans); }
replace
15
18
15
20
-11
p02653
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; const int maxn = 5010, P = 1000000007; int n, A, B, ans, pw[maxn], f[maxn][maxn][2], pre[maxn][maxn][2], h[maxn]; int main() { scanf("%d %d %d", &n, &A, &B); if (A < B) swap(A, B); pw[0] = pw[1] = 1; for (int i = 2; i <= n; i++) { pw[i] = (pw[i - 1] + pw[i - 1]) % P; } f[0][0][0] = f[0][0][1] = 1, h[0] = 1; pre[0][0][0] = pre[0][0][1] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { (f[i][j][0] += pre[i - 1][i - j][1]) %= P; (f[i][j][1] += pre[i - B][i - j][0]) %= P; } for (int j = max(0, i - B + 1); j < i; j++) { (f[i][0][1] += h[j]) %= P; } for (int j = A; j <= i; j++) { int s = 1LL * (f[i][j][0] + f[i][j][1]) * pw[n - i] % P; (ans += s) %= P, f[i][j][0] = f[i][j][1] = 0; } for (int j = 0; j <= i; j++) { (h[i] += f[i][j][0]) %= P; pre[i][i - j][0] = (pre[i - 1][i - j][0] + f[i][j][0]) % P; pre[i][i - j][1] = (pre[i - 1][i - j][1] + f[i][j][1]) % P; } } printf("%d\n", (ans + P) % P); return 0; }
#include <bits/stdc++.h> using namespace std; const int maxn = 5010, P = 1000000007; int n, A, B, ans, pw[maxn], f[maxn][maxn][2], pre[maxn][maxn][2], h[maxn]; int main() { scanf("%d %d %d", &n, &A, &B); if (A < B) swap(A, B); pw[0] = pw[1] = 1; for (int i = 2; i <= n; i++) { pw[i] = (pw[i - 1] + pw[i - 1]) % P; } f[0][0][0] = f[0][0][1] = 1, h[0] = 1; pre[0][0][0] = pre[0][0][1] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { (f[i][j][0] += pre[i - 1][i - j][1]) %= P; if (i >= B) (f[i][j][1] += pre[i - B][i - j][0]) %= P; } for (int j = max(0, i - B + 1); j < i; j++) { (f[i][0][1] += h[j]) %= P; } for (int j = A; j <= i; j++) { int s = 1LL * (f[i][j][0] + f[i][j][1]) * pw[n - i] % P; (ans += s) %= P, f[i][j][0] = f[i][j][1] = 0; } for (int j = 0; j <= i; j++) { (h[i] += f[i][j][0]) %= P; pre[i][i - j][0] = (pre[i - 1][i - j][0] + f[i][j][0]) % P; pre[i][i - j][1] = (pre[i - 1][i - j][1] + f[i][j][1]) % P; } } printf("%d\n", (ans + P) % P); return 0; }
replace
19
20
19
21
-11
p02653
C++
Runtime Error
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count()); typedef long long ll; typedef long double ld; const int N = 5000 + 7; const int M = (int)1e9 + 7; int streak[N][2][2], dp_streak[N], dp_0[N]; int add(int a, int b) { a += b; if (a >= M) return a - M; if (a < 0) return a + M; return a; } int mul(int a, int b) { return a * (ll)b % M; } int pw(int a, int b) { int r = 1; while (b) { if (b & 1) r = mul(r, a); a = mul(a, a); b /= 2; } return r; } int dv(int a, int b) { return mul(a, pw(b, M - 2)); } int n, a, b; set<string> st; void bkt(string s) { if (st.count(s)) return; st.insert(s); for (int i = 0; i + a - 1 < n; i++) { string t = s; for (int j = i; j <= i + a - 1; j++) t[j] = '0'; bkt(t); } for (int i = 0; i + b - 1 < n; i++) { string t = s; for (int j = i; j <= i + b - 1; j++) t[j] = '1'; bkt(t); } } int dm(int _n, int _a, int _b) { n = _n; a = _a; b = _b; st.clear(); string base; for (int i = 1; i <= n; i++) base += "0"; bkt(base); return (int)st.size(); } int sm(int _n, int _a, int _b) { n = _n; a = _a; b = _b; if (a > b) swap(a, b); for (int i = 0; i <= n; i++) { for (int f = 0; f <= 1; f++) for (int s = 0; s <= 1; s++) streak[i][f][s] = 0; dp_streak[i] = dp_0[i] = 0; } for (int l0 = a; l0 <= n; l0++) streak[l0][0][0] = 1; for (int l1 = 1; l1 <= n; l1++) streak[l1][1][1] = 1; for (int l = 0; l <= n; l++) { for (int f = 0; f <= 1; f++) { /// s = 0, now = 1 for (int l1 = 1; l + l1 <= n; l1++) streak[l + l1][f][1] = add(streak[l + l1][f][1], streak[l][f][0]); /// s = 1, now = 0 for (int l0 = a; l0 <= n; l0++) streak[l + l0][f][0] = add(streak[l + l0][f][0], streak[l][f][1]); } } /// streak 0 streak 0 streak 0 streak /// streak 0 streak 0 streak 0 streak 0 /// 0 streak 0 streak 0 streak 0 streak /// 0 streak 0 streak 0 streak 0 streak 0 int bad = 0; /// stars with streak for (int ls = 1; ls < b; ls++) dp_streak[ls] = add(streak[ls][0][1], streak[ls][1][1]); /// starts with 0 for (int l0 = 1; l0 < a; l0++) dp_0[l0] = add(dp_0[l0], 1); for (int l = 1; l <= n; l++) { /// streak, 0 for (int l0 = 1; l + l0 <= n && l0 < a; l0++) { dp_0[l + l0] = add(dp_0[l + l0], dp_streak[l]); } /// 0, streak for (int ls = 1; l + ls <= n && ls < b; ls++) { if (l + ls == n) { dp_streak[l + ls] = add(dp_streak[l + ls], mul(dp_0[l], streak[ls][1][0])); dp_streak[l + ls] = add(dp_streak[l + ls], mul(dp_0[l], streak[ls][1][1])); } else { dp_streak[l + ls] = add(dp_streak[l + ls], mul(dp_0[l], streak[ls][1][1])); } } } bad = add(bad, dp_streak[n]); bad = add(bad, dp_0[n]); return add(pw(2, n), -bad); } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, a, b; cin >> n >> a >> b; cout << sm(n, a, b) << "\n"; return 0; }
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count()); typedef long long ll; typedef long double ld; const int N = 5000 + 7; const int M = (int)1e9 + 7; int streak[N][2][2], dp_streak[N], dp_0[N]; int add(int a, int b) { a += b; if (a >= M) return a - M; if (a < 0) return a + M; return a; } int mul(int a, int b) { return a * (ll)b % M; } int pw(int a, int b) { int r = 1; while (b) { if (b & 1) r = mul(r, a); a = mul(a, a); b /= 2; } return r; } int dv(int a, int b) { return mul(a, pw(b, M - 2)); } int n, a, b; set<string> st; void bkt(string s) { if (st.count(s)) return; st.insert(s); for (int i = 0; i + a - 1 < n; i++) { string t = s; for (int j = i; j <= i + a - 1; j++) t[j] = '0'; bkt(t); } for (int i = 0; i + b - 1 < n; i++) { string t = s; for (int j = i; j <= i + b - 1; j++) t[j] = '1'; bkt(t); } } int dm(int _n, int _a, int _b) { n = _n; a = _a; b = _b; st.clear(); string base; for (int i = 1; i <= n; i++) base += "0"; bkt(base); return (int)st.size(); } int sm(int _n, int _a, int _b) { n = _n; a = _a; b = _b; if (a > b) swap(a, b); for (int i = 0; i <= n; i++) { for (int f = 0; f <= 1; f++) for (int s = 0; s <= 1; s++) streak[i][f][s] = 0; dp_streak[i] = dp_0[i] = 0; } for (int l0 = a; l0 <= n; l0++) streak[l0][0][0] = 1; for (int l1 = 1; l1 <= n; l1++) streak[l1][1][1] = 1; for (int l = 0; l <= n; l++) { for (int f = 0; f <= 1; f++) { /// s = 0, now = 1 for (int l1 = 1; l + l1 <= n; l1++) streak[l + l1][f][1] = add(streak[l + l1][f][1], streak[l][f][0]); /// s = 1, now = 0 for (int l0 = a; l + l0 <= n; l0++) streak[l + l0][f][0] = add(streak[l + l0][f][0], streak[l][f][1]); } } /// streak 0 streak 0 streak 0 streak /// streak 0 streak 0 streak 0 streak 0 /// 0 streak 0 streak 0 streak 0 streak /// 0 streak 0 streak 0 streak 0 streak 0 int bad = 0; /// stars with streak for (int ls = 1; ls < b; ls++) dp_streak[ls] = add(streak[ls][0][1], streak[ls][1][1]); /// starts with 0 for (int l0 = 1; l0 < a; l0++) dp_0[l0] = add(dp_0[l0], 1); for (int l = 1; l <= n; l++) { /// streak, 0 for (int l0 = 1; l + l0 <= n && l0 < a; l0++) { dp_0[l + l0] = add(dp_0[l + l0], dp_streak[l]); } /// 0, streak for (int ls = 1; l + ls <= n && ls < b; ls++) { if (l + ls == n) { dp_streak[l + ls] = add(dp_streak[l + ls], mul(dp_0[l], streak[ls][1][0])); dp_streak[l + ls] = add(dp_streak[l + ls], mul(dp_0[l], streak[ls][1][1])); } else { dp_streak[l + ls] = add(dp_streak[l + ls], mul(dp_0[l], streak[ls][1][1])); } } } bad = add(bad, dp_streak[n]); bad = add(bad, dp_0[n]); return add(pw(2, n), -bad); } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, a, b; cin >> n >> a >> b; cout << sm(n, a, b) << "\n"; return 0; }
replace
91
92
91
92
0
p02653
C++
Time Limit Exceeded
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rng(i, l, r) for (int i = int(l); i < int(r); i++) #define rep(i, r) for (int i = 0; i < int(r); i++) #define rrng(i, l, r) for (int i = int(r) - 1; i >= int(l); i--) #define rrep(i, r) for (int i = int(r) - 1; i >= 0; i--) #define pb push_back #define eb emplace_back #define mp make_pair #define mt make_tuple #define one(x) memset(x, -1, sizeof(x)) #define zero(x) memset(x, 0, sizeof(x)) #define F first #define S second #define bg begin() #define ed end() #define all(x) x.bg, x.ed #define si(x) int(x.size()) #define inf INT_MAX / 2 - 100 #define infl LLONG_MAX / 3 #ifdef LOCAL #define dmp(x) cerr << __LINE__ << ' ' << #x << ' ' << x << endl #else #define dmp(x) void(0) #endif template <class t, class u> void chmax(t &a, u b) { if (a < b) a = b; } template <class t, class u> void chmin(t &a, u b) { if (b < a) a = b; } template <class t> using vc = vector<t>; template <class t> using vvc = vector<vector<t>>; using pi = pair<int, int>; using pl = pair<ll, ll>; using vi = vc<int>; using vl = vc<ll>; ll readl(void) { ll x; cin >> x; return x; } int readi(void) { int x; cin >> x; return x; } string readstr() { string s; cin >> s; return s; } vi readvi(int n, int off = 0) { vi v(n); rep(i, n) v[i] = readi(), v[i] += off; return v; } vl readvl(int n, int off = 0) { vl v(n); rep(i, n) v[i] = readl(), v[i] += off; return v; } template <class t> void print(t x, int suc = 1) { cout << x; if (suc == 1) cout << "\n"; if (suc == 2) cout << " "; } template <class t> void print(const vc<t> &v, int suc = 1) { rep(i, si(v)) print(v[i], i == int(si(v)) - 1 ? 1 : suc); } template <class t> bool inc(t a, t b, t c) { return !(c < b || b < a); } template <class t> void compress(vc<t> &v) { sort(all(v)); v.erase(unique(all(v)), v.ed); } template <class t> int lwb(const vc<t> &v, const t &a) { return lower_bound(all(v), a) - v.bg; } template <class t> struct Compress { vc<t> v; Compress() = default; Compress(const vc<t> &x) { add(x); } Compress(const initializer_list<vc<t>> &x) { for (auto &p : x) add(p); } void add(const t &x) { v.eb(x); } void add(const vc<t> &x) { copy(all(x), back_inserter(v)); } void build() { compress(v); } int get(const t &x) const { return lwb(v, x); } vc<t> get(const vc<t> &x) const { vc<t> res(x); for (auto &p : res) p = get(p); return res; } const t &operator[](int x) const { return v[x]; } }; void Yes(bool ex = true) { cout << "Yes\n"; if (ex) exit(0); } void YES(bool ex = true) { cout << "YES\n"; if (ex) exit(0); } void No(bool ex = true) { cout << "No\n"; if (ex) exit(0); } void NO(bool ex = true) { cout << "NO\n"; if (ex) exit(0); } void orYes(bool x, bool ex = true) { if (x) Yes(ex); else No(ex); } void orYES(bool x, bool ex = true) { if (x) YES(ex); else NO(ex); } void Possible(bool ex = true) { cout << "Possible\n"; if (ex) exit(0); } void POSSIBLE(bool ex = true) { cout << "POSSIBLE\n"; if (ex) exit(0); } void Impossible(bool ex = true) { cout << "Impossible\n"; if (ex) exit(0); } void IMPOSSIBLE(bool ex = true) { cout << "IMPOSSIBLE\n"; if (ex) exit(0); } void orPossible(bool x, bool ex = true) { if (x) Possible(ex); else Impossible(ex); } void orPOSSIBLE(bool x, bool ex = true) { if (x) POSSIBLE(ex); else IMPOSSIBLE(ex); } int gcd(int x, int y) { if (x < y) swap(x, y); if (x % y == 0) return y; return gcd(y, x % y); } using uint = unsigned; using ull = unsigned long long; template <uint const &MOD> struct Modular { static constexpr uint const &mod = MOD; uint v; Modular(long long x = 0) { c(x % mod + mod); } Modular &c(uint x) { v = x < mod ? x : x - mod; return *this; } Modular pow(int k) const { Modular res(1), tmp(v); while (k) { if (k & 1) res *= tmp; tmp *= tmp; k >>= 1; } return res; } Modular inv() const { return pow(mod - 2); } Modular operator-() const { return Modular(mod - v); } Modular &operator+=(const Modular &x) { return c(v + x.v); } Modular &operator-=(const Modular &x) { return c(v + mod - x.v); } Modular &operator*=(const Modular &x) { v = ull(v) * x.v % mod; return *this; } Modular &operator/=(const Modular &x) { return *this *= x.inv(); } Modular operator+(const Modular &x) const { return Modular(*this) += x; } Modular operator-(const Modular &x) const { return Modular(*this) -= x; } Modular operator*(const Modular &x) const { return Modular(*this) *= x; } Modular operator/(const Modular &x) const { return Modular(*this) /= x; } friend Modular operator+(long long x, const Modular &y) { return Modular(x) + y; } friend Modular operator-(long long x, const Modular &y) { return Modular(x) - y; } friend Modular operator*(long long x, const Modular &y) { return Modular(x) * y; } friend Modular operator/(long long x, const Modular &y) { return Modular(x) / y; } friend ostream &operator<<(ostream &os, const Modular &x) { return os << x.v; } friend istream &operator>>(istream &is, Modular &x) { long long p; is >> p; x = Modular(p); return is; } bool operator==(const Modular &x) const { return v == x.v; } bool operator!=(const Modular &x) const { return v != x.v; } bool operator<(const Modular &x) const { return v < x.v; } explicit operator bool() const { return v; } }; // uint MODULAR=998244353; uint MODULAR = 1000000007; using Mint = Modular<MODULAR>; vector<Mint> fact, finv, invs; void Initfact(int n = (1 << 21) + 10) { fact.resize(n + 1), finv.resize(n + 1), invs.resize(n + 1); fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = fact[i - 1] * i; } finv[n] = fact[n].inv(); for (int i = n - 1; i >= 0; i--) { finv[i] = finv[i + 1] * (i + 1); } invs[0] = 1; for (int i = 0; i <= n; i++) { invs[i] = finv[i] * fact[i - 1]; } } Mint comb(int n, int k) { return fact[n] * finv[n - k] * finv[k]; } Mint x[5005][5005], ans, s[5005], pw[5005]; int main(void) { cin.tie(0); ios::sync_with_stdio(0); int n, a, b; cin >> n >> a >> b; if (a < b) swap(a, b); x[0][0] = 1; pw[0] = 1; for (int i = 1; i <= n; i++) pw[i] = pw[i - 1] * 2; for (int l = 0; l <= n; l++) { for (int j = 0; j + l <= n; j++) s[j] = 0; for (int j = 0; j + l <= n; j++) { if (j >= a) { ans += x[l][j] * pw[n - (l + j)]; x[l][j] = 0; } if (j == a) { for (int k = b; k <= l + j; k++) { ans += x[l][j - k] * pw[n - (l + j)]; x[l][j - k] = 0; } } if (j > a) { ans += x[l][j - b] * Mint(2).pow(n - (l + j)); x[l][j - b] = 0; } s[j] += x[l][j]; if (j > 0) s[j] += s[j - 1]; if (j > 0) { x[l + j][1] += s[j - 1]; if (j - b >= 0) x[l + j][1] -= s[j - b]; } if (j - b >= 0 && j < a) { x[l][j + 1] += s[j - b]; } x[l][j + 1] += x[l][j]; } } print(ans); }
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rng(i, l, r) for (int i = int(l); i < int(r); i++) #define rep(i, r) for (int i = 0; i < int(r); i++) #define rrng(i, l, r) for (int i = int(r) - 1; i >= int(l); i--) #define rrep(i, r) for (int i = int(r) - 1; i >= 0; i--) #define pb push_back #define eb emplace_back #define mp make_pair #define mt make_tuple #define one(x) memset(x, -1, sizeof(x)) #define zero(x) memset(x, 0, sizeof(x)) #define F first #define S second #define bg begin() #define ed end() #define all(x) x.bg, x.ed #define si(x) int(x.size()) #define inf INT_MAX / 2 - 100 #define infl LLONG_MAX / 3 #ifdef LOCAL #define dmp(x) cerr << __LINE__ << ' ' << #x << ' ' << x << endl #else #define dmp(x) void(0) #endif template <class t, class u> void chmax(t &a, u b) { if (a < b) a = b; } template <class t, class u> void chmin(t &a, u b) { if (b < a) a = b; } template <class t> using vc = vector<t>; template <class t> using vvc = vector<vector<t>>; using pi = pair<int, int>; using pl = pair<ll, ll>; using vi = vc<int>; using vl = vc<ll>; ll readl(void) { ll x; cin >> x; return x; } int readi(void) { int x; cin >> x; return x; } string readstr() { string s; cin >> s; return s; } vi readvi(int n, int off = 0) { vi v(n); rep(i, n) v[i] = readi(), v[i] += off; return v; } vl readvl(int n, int off = 0) { vl v(n); rep(i, n) v[i] = readl(), v[i] += off; return v; } template <class t> void print(t x, int suc = 1) { cout << x; if (suc == 1) cout << "\n"; if (suc == 2) cout << " "; } template <class t> void print(const vc<t> &v, int suc = 1) { rep(i, si(v)) print(v[i], i == int(si(v)) - 1 ? 1 : suc); } template <class t> bool inc(t a, t b, t c) { return !(c < b || b < a); } template <class t> void compress(vc<t> &v) { sort(all(v)); v.erase(unique(all(v)), v.ed); } template <class t> int lwb(const vc<t> &v, const t &a) { return lower_bound(all(v), a) - v.bg; } template <class t> struct Compress { vc<t> v; Compress() = default; Compress(const vc<t> &x) { add(x); } Compress(const initializer_list<vc<t>> &x) { for (auto &p : x) add(p); } void add(const t &x) { v.eb(x); } void add(const vc<t> &x) { copy(all(x), back_inserter(v)); } void build() { compress(v); } int get(const t &x) const { return lwb(v, x); } vc<t> get(const vc<t> &x) const { vc<t> res(x); for (auto &p : res) p = get(p); return res; } const t &operator[](int x) const { return v[x]; } }; void Yes(bool ex = true) { cout << "Yes\n"; if (ex) exit(0); } void YES(bool ex = true) { cout << "YES\n"; if (ex) exit(0); } void No(bool ex = true) { cout << "No\n"; if (ex) exit(0); } void NO(bool ex = true) { cout << "NO\n"; if (ex) exit(0); } void orYes(bool x, bool ex = true) { if (x) Yes(ex); else No(ex); } void orYES(bool x, bool ex = true) { if (x) YES(ex); else NO(ex); } void Possible(bool ex = true) { cout << "Possible\n"; if (ex) exit(0); } void POSSIBLE(bool ex = true) { cout << "POSSIBLE\n"; if (ex) exit(0); } void Impossible(bool ex = true) { cout << "Impossible\n"; if (ex) exit(0); } void IMPOSSIBLE(bool ex = true) { cout << "IMPOSSIBLE\n"; if (ex) exit(0); } void orPossible(bool x, bool ex = true) { if (x) Possible(ex); else Impossible(ex); } void orPOSSIBLE(bool x, bool ex = true) { if (x) POSSIBLE(ex); else IMPOSSIBLE(ex); } int gcd(int x, int y) { if (x < y) swap(x, y); if (x % y == 0) return y; return gcd(y, x % y); } using uint = unsigned; using ull = unsigned long long; template <uint const &MOD> struct Modular { static constexpr uint const &mod = MOD; uint v; Modular(long long x = 0) { c(x % mod + mod); } Modular &c(uint x) { v = x < mod ? x : x - mod; return *this; } Modular pow(int k) const { Modular res(1), tmp(v); while (k) { if (k & 1) res *= tmp; tmp *= tmp; k >>= 1; } return res; } Modular inv() const { return pow(mod - 2); } Modular operator-() const { return Modular(mod - v); } Modular &operator+=(const Modular &x) { return c(v + x.v); } Modular &operator-=(const Modular &x) { return c(v + mod - x.v); } Modular &operator*=(const Modular &x) { v = ull(v) * x.v % mod; return *this; } Modular &operator/=(const Modular &x) { return *this *= x.inv(); } Modular operator+(const Modular &x) const { return Modular(*this) += x; } Modular operator-(const Modular &x) const { return Modular(*this) -= x; } Modular operator*(const Modular &x) const { return Modular(*this) *= x; } Modular operator/(const Modular &x) const { return Modular(*this) /= x; } friend Modular operator+(long long x, const Modular &y) { return Modular(x) + y; } friend Modular operator-(long long x, const Modular &y) { return Modular(x) - y; } friend Modular operator*(long long x, const Modular &y) { return Modular(x) * y; } friend Modular operator/(long long x, const Modular &y) { return Modular(x) / y; } friend ostream &operator<<(ostream &os, const Modular &x) { return os << x.v; } friend istream &operator>>(istream &is, Modular &x) { long long p; is >> p; x = Modular(p); return is; } bool operator==(const Modular &x) const { return v == x.v; } bool operator!=(const Modular &x) const { return v != x.v; } bool operator<(const Modular &x) const { return v < x.v; } explicit operator bool() const { return v; } }; // uint MODULAR=998244353; uint MODULAR = 1000000007; using Mint = Modular<MODULAR>; vector<Mint> fact, finv, invs; void Initfact(int n = (1 << 21) + 10) { fact.resize(n + 1), finv.resize(n + 1), invs.resize(n + 1); fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = fact[i - 1] * i; } finv[n] = fact[n].inv(); for (int i = n - 1; i >= 0; i--) { finv[i] = finv[i + 1] * (i + 1); } invs[0] = 1; for (int i = 0; i <= n; i++) { invs[i] = finv[i] * fact[i - 1]; } } Mint comb(int n, int k) { return fact[n] * finv[n - k] * finv[k]; } Mint x[5005][5005], ans, s[5005], pw[5005]; int main(void) { cin.tie(0); ios::sync_with_stdio(0); int n, a, b; cin >> n >> a >> b; if (a < b) swap(a, b); x[0][0] = 1; pw[0] = 1; for (int i = 1; i <= n; i++) pw[i] = pw[i - 1] * 2; for (int l = 0; l <= n; l++) { for (int j = 0; j + l <= n; j++) s[j] = 0; for (int j = 0; j + l <= n; j++) { if (j >= a) { ans += x[l][j] * pw[n - (l + j)]; x[l][j] = 0; } if (j == a) { for (int k = b; k <= l + j; k++) { ans += x[l][j - k] * pw[n - (l + j)]; x[l][j - k] = 0; } } if (j > a) { ans += x[l][j - b] * pw[n - (l + j)]; x[l][j - b] = 0; } s[j] += x[l][j]; if (j > 0) s[j] += s[j - 1]; if (j > 0) { x[l + j][1] += s[j - 1]; if (j - b >= 0) x[l + j][1] -= s[j - b]; } if (j - b >= 0 && j < a) { x[l][j + 1] += s[j - b]; } x[l][j + 1] += x[l][j]; } } print(ans); }
replace
305
306
305
306
TLE
p02653
C++
Runtime Error
/* by Natsu Kinmoe */ #include <bits/stdc++.h> using namespace std; #define loop(i, n) for (int i = 0; i < (n); i++) #define pool(i, n) for (int i = (n)-1; i >= 0; i--) #define cont(i, n) for (int i = 1; i <= (n); i++) #define tnoc(i, n) for (int i = (n); i >= 1; i--) #define circ(i, a, b) for (int i = (a); i <= (b); i++) #define cric(i, a, b) for (int i = (b); i >= (a); i--) #define sub(i, a) for (int i = a; i; i = ((i - 1) & (a))) #define subs(i, a) for (int i = a; i >= 0; i = (!i ? -1 : ((i - 1) & (a)))) #define subt(i, a) for (int i = ((a - 1) & a); i; i = ((i - 1) & (a))) #define subst(i, a) \ for (int i = ((a - 1) & a); i >= 0; i = (!i ? -1 : ((i - 1) & (a)))) #define range(i, a, b, c) \ for (int i = (a); ((c) > 0 ? i <= (b) : i >= (b)); i += (c)) #define foreach(it, v) \ for (__typeof((v).begin()) it = (v).begin(), _e_D_ = (v).end(); it != _e_D_; \ it++) #define parse(i, s) for (int i = 0; s[i]; i++) #define pub push_back #define pob pop_back #define puf push_front #define pof pop_front #define mak make_pair #define y0 y0O0OO00OO0OO0OO0OOO00OO0OO0O0O000OO0 #define y1 y1II11II11III11I1III11II111IIII1II1I1 #define ws WSrAkIoi2333wSraKIoIWSraKiOi #define left left_jTjTJtJtIoiiOiioIAuaU66666jtIOIau #define hash whYusEthiSnamE_caNyoUusEothERnaMesliKeHSH #define Mask(a) (1ll << (a)) #define Maskx(a, x) ((a) << (x)) #define Full(a) ((1ll << (a)) - 1) #define Bit(a, x) (((a) >> (x)) & 1) #define all(a) (a).begin(), (a).end() #define SZ(a) ((int)((a).size())) typedef long long ll; typedef long double lf; const int Inf = 0x3f3f3f3f; const ll INF = 0x3f3f3f3f3f3f3f3fll; const lf inF = 11451419198101145141919810.1145141919810; const lf pi = acosl(-1); /* Source code starts here */ int n, a, b; const int jt = 1000000007; int dp[5005][5005][2], qzh1[5005], qzh2[5005][5005]; void inline add(int &a, int b) { a += b; if (a >= jt) a -= jt; if (a < 0) a += jt; } int main() { scanf("%d%d%d", &n, &a, &b); if (a < b) swap(a, b); dp[0][0][1] = 1; loop(i, n + 1) { if (i) add(qzh1[i], qzh1[i - 1]); add(dp[i][0][0], qzh1[i]); loop(j, i + 1) { if (i) add(qzh2[i - j][i], qzh2[i - j][i - 1]); add(dp[i][j][0], qzh2[i - j][i]); if (j == a) { add(dp[i][j][1], dp[i][j][0]); dp[i][j][0] = 0; add(dp[i + 1][j][1], dp[i][j][1]); add(dp[i + 1][j][1], dp[i][j][1]); break; } add(dp[i + 1][j + 1][1], dp[i][j][0]); add(dp[i + 1][j + 1][1], dp[i][j][1]); add(qzh1[i + 1], dp[i][j][1]); add(qzh1[i + b], -dp[i][j][1]); if (j + b <= a) add(qzh2[i - j][i + b], dp[i][j][1]); else add(dp[i + b][a][1], dp[i][j][1]); } } add(dp[n][a][1], dp[n][a][0]); printf("%d\n", dp[n][a][1]); return 0; }
/* by Natsu Kinmoe */ #include <bits/stdc++.h> using namespace std; #define loop(i, n) for (int i = 0; i < (n); i++) #define pool(i, n) for (int i = (n)-1; i >= 0; i--) #define cont(i, n) for (int i = 1; i <= (n); i++) #define tnoc(i, n) for (int i = (n); i >= 1; i--) #define circ(i, a, b) for (int i = (a); i <= (b); i++) #define cric(i, a, b) for (int i = (b); i >= (a); i--) #define sub(i, a) for (int i = a; i; i = ((i - 1) & (a))) #define subs(i, a) for (int i = a; i >= 0; i = (!i ? -1 : ((i - 1) & (a)))) #define subt(i, a) for (int i = ((a - 1) & a); i; i = ((i - 1) & (a))) #define subst(i, a) \ for (int i = ((a - 1) & a); i >= 0; i = (!i ? -1 : ((i - 1) & (a)))) #define range(i, a, b, c) \ for (int i = (a); ((c) > 0 ? i <= (b) : i >= (b)); i += (c)) #define foreach(it, v) \ for (__typeof((v).begin()) it = (v).begin(), _e_D_ = (v).end(); it != _e_D_; \ it++) #define parse(i, s) for (int i = 0; s[i]; i++) #define pub push_back #define pob pop_back #define puf push_front #define pof pop_front #define mak make_pair #define y0 y0O0OO00OO0OO0OO0OOO00OO0OO0O0O000OO0 #define y1 y1II11II11III11I1III11II111IIII1II1I1 #define ws WSrAkIoi2333wSraKIoIWSraKiOi #define left left_jTjTJtJtIoiiOiioIAuaU66666jtIOIau #define hash whYusEthiSnamE_caNyoUusEothERnaMesliKeHSH #define Mask(a) (1ll << (a)) #define Maskx(a, x) ((a) << (x)) #define Full(a) ((1ll << (a)) - 1) #define Bit(a, x) (((a) >> (x)) & 1) #define all(a) (a).begin(), (a).end() #define SZ(a) ((int)((a).size())) typedef long long ll; typedef long double lf; const int Inf = 0x3f3f3f3f; const ll INF = 0x3f3f3f3f3f3f3f3fll; const lf inF = 11451419198101145141919810.1145141919810; const lf pi = acosl(-1); /* Source code starts here */ int n, a, b; const int jt = 1000000007; int dp[5005][5005][2], qzh1[5005], qzh2[5005][5005]; void inline add(int &a, int b) { a += b; if (a >= jt) a -= jt; if (a < 0) a += jt; } int main() { scanf("%d%d%d", &n, &a, &b); if (a < b) swap(a, b); dp[0][0][1] = 1; loop(i, n + 1) { if (i) add(qzh1[i], qzh1[i - 1]); add(dp[i][0][0], qzh1[i]); loop(j, i + 1) { if (i) add(qzh2[i - j][i], qzh2[i - j][i - 1]); add(dp[i][j][0], qzh2[i - j][i]); if (j == a) { add(dp[i][j][1], dp[i][j][0]); dp[i][j][0] = 0; add(dp[i + 1][j][1], dp[i][j][1]); add(dp[i + 1][j][1], dp[i][j][1]); break; } add(dp[i + 1][j + 1][1], dp[i][j][0]); add(dp[i + 1][j + 1][1], dp[i][j][1]); add(qzh1[i + 1], dp[i][j][1]); if (i + b <= n) { add(qzh1[i + b], -dp[i][j][1]); if (j + b <= a) add(qzh2[i - j][i + b], dp[i][j][1]); else add(dp[i + b][a][1], dp[i][j][1]); } } } add(dp[n][a][1], dp[n][a][0]); printf("%d\n", dp[n][a][1]); return 0; }
replace
84
89
84
91
-11
p02653
C++
Runtime Error
/** * author: otera **/ #include <algorithm> #include <bitset> #include <cassert> #include <ciso646> #include <cmath> #include <complex> #include <cstdio> #include <cstring> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <unordered_map> #include <utility> #include <vector> using namespace std; // #define int long long typedef long long ll; typedef unsigned long long ul; typedef unsigned int ui; typedef long double ld; const int inf = 1e9 + 7; const ll INF = 1LL << 60; const ll mod = 1e9 + 7; #define rep(i, n) for (int i = 0; i < n; i++) #define per(i, n) for (int i = n - 1; i >= 0; i--) #define Rep(i, sta, n) for (int i = sta; i < n; i++) #define rep1(i, n) for (int i = 1; i <= n; i++) #define per1(i, n) for (int i = n; i >= 1; i--) #define Rep1(i, sta, n) for (int i = sta; i <= n; i++) typedef complex<ld> Point; const ld eps = 1e-8; const ld pi = acos(-1.0); typedef pair<int, int> P; typedef pair<ld, ld> LDP; typedef pair<ll, ll> LP; #define fr first #define sc second #define all(c) c.begin(), c.end() #define pb push_back #define debug(x) cerr << #x << " = " << (x) << endl; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } template <int MOD> struct Fp { long long val; constexpr Fp(long long v = 0) noexcept : val(v % MOD) { if (val < 0) val += MOD; } constexpr int getmod() { return MOD; } constexpr Fp operator-() const noexcept { return val ? MOD - val : 0; } constexpr Fp operator+(const Fp &r) const noexcept { return Fp(*this) += r; } constexpr Fp operator-(const Fp &r) const noexcept { return Fp(*this) -= r; } constexpr Fp operator*(const Fp &r) const noexcept { return Fp(*this) *= r; } constexpr Fp operator/(const Fp &r) const noexcept { return Fp(*this) /= r; } constexpr Fp &operator+=(const Fp &r) noexcept { val += r.val; if (val >= MOD) val -= MOD; return *this; } constexpr Fp &operator-=(const Fp &r) noexcept { val -= r.val; if (val < 0) val += MOD; return *this; } constexpr Fp &operator*=(const Fp &r) noexcept { val = val * r.val % MOD; return *this; } constexpr Fp &operator/=(const Fp &r) noexcept { long long a = r.val, b = MOD, u = 1, v = 0; while (b) { long long t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v); } val = val * u % MOD; if (val < 0) val += MOD; return *this; } constexpr bool operator==(const Fp &r) const noexcept { return this->val == r.val; } constexpr bool operator!=(const Fp &r) const noexcept { return this->val != r.val; } friend constexpr ostream &operator<<(ostream &os, const Fp<MOD> &x) noexcept { return os << x.val; } friend constexpr istream &operator>>(istream &is, Fp<MOD> &x) noexcept { return is >> x.val; } friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, long long n) noexcept { if (n == 0) return 1; auto t = modpow(a, n / 2); t = t * t; if (n & 1) t = t * a; return t; } }; const int MOD = 1000000007; // const int MOD = 998244353; using mint = Fp<MOD>; void solve() { int n, a, b; cin >> n >> a >> b; if (a > b) swap(a, b); static mint dp[5050][5050][2][2]; rep(i, 5050) { rep(j, 5050) { rep(k, 2) { rep(l, 2) { dp[i][j][k][l] = 0; } } } } dp[0][0][1][0] = 1; rep(i, n) { for (int j = 0; j <= i; ++j) { // 0 if (j + 1 < a) dp[i + 1][j + 1][0][0] += dp[i][j][0][0]; if (j + 1 < b && j >= a) dp[i + 1][j + 1][0][1] += dp[i][j][0][1]; if (j < b && 1 < a) dp[i + 1][1][0][0] += dp[i][j][1][0]; if (j < b && j + a < b) dp[i + a][j + a][0][1] += dp[i][j][1][0]; // 1 if (j < a && 1 < b) dp[i + 1][1][1][0] += dp[i][j][0][0]; if (j + 1 < b) dp[i + 1][j + 1][1][0] += dp[i][j][0][1]; if (j + 1 < b) dp[i + 1][j + 1][1][0] += dp[i][j][1][0]; } } mint ans = modpow((mint)2, n); for (int i = 0; i <= n; ++i) { rep(j, 2) { rep(k, 2) { ans -= dp[n][i][j][k]; } } } cout << ans << endl; } signed main() { ios::sync_with_stdio(false); cin.tie(0); // cout << fixed << setprecision(10); // int t; cin >> t; rep(i, t)solve(); solve(); return 0; }
/** * author: otera **/ #include <algorithm> #include <bitset> #include <cassert> #include <ciso646> #include <cmath> #include <complex> #include <cstdio> #include <cstring> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <unordered_map> #include <utility> #include <vector> using namespace std; // #define int long long typedef long long ll; typedef unsigned long long ul; typedef unsigned int ui; typedef long double ld; const int inf = 1e9 + 7; const ll INF = 1LL << 60; const ll mod = 1e9 + 7; #define rep(i, n) for (int i = 0; i < n; i++) #define per(i, n) for (int i = n - 1; i >= 0; i--) #define Rep(i, sta, n) for (int i = sta; i < n; i++) #define rep1(i, n) for (int i = 1; i <= n; i++) #define per1(i, n) for (int i = n; i >= 1; i--) #define Rep1(i, sta, n) for (int i = sta; i <= n; i++) typedef complex<ld> Point; const ld eps = 1e-8; const ld pi = acos(-1.0); typedef pair<int, int> P; typedef pair<ld, ld> LDP; typedef pair<ll, ll> LP; #define fr first #define sc second #define all(c) c.begin(), c.end() #define pb push_back #define debug(x) cerr << #x << " = " << (x) << endl; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } template <int MOD> struct Fp { long long val; constexpr Fp(long long v = 0) noexcept : val(v % MOD) { if (val < 0) val += MOD; } constexpr int getmod() { return MOD; } constexpr Fp operator-() const noexcept { return val ? MOD - val : 0; } constexpr Fp operator+(const Fp &r) const noexcept { return Fp(*this) += r; } constexpr Fp operator-(const Fp &r) const noexcept { return Fp(*this) -= r; } constexpr Fp operator*(const Fp &r) const noexcept { return Fp(*this) *= r; } constexpr Fp operator/(const Fp &r) const noexcept { return Fp(*this) /= r; } constexpr Fp &operator+=(const Fp &r) noexcept { val += r.val; if (val >= MOD) val -= MOD; return *this; } constexpr Fp &operator-=(const Fp &r) noexcept { val -= r.val; if (val < 0) val += MOD; return *this; } constexpr Fp &operator*=(const Fp &r) noexcept { val = val * r.val % MOD; return *this; } constexpr Fp &operator/=(const Fp &r) noexcept { long long a = r.val, b = MOD, u = 1, v = 0; while (b) { long long t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v); } val = val * u % MOD; if (val < 0) val += MOD; return *this; } constexpr bool operator==(const Fp &r) const noexcept { return this->val == r.val; } constexpr bool operator!=(const Fp &r) const noexcept { return this->val != r.val; } friend constexpr ostream &operator<<(ostream &os, const Fp<MOD> &x) noexcept { return os << x.val; } friend constexpr istream &operator>>(istream &is, Fp<MOD> &x) noexcept { return is >> x.val; } friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, long long n) noexcept { if (n == 0) return 1; auto t = modpow(a, n / 2); t = t * t; if (n & 1) t = t * a; return t; } }; const int MOD = 1000000007; // const int MOD = 998244353; using mint = Fp<MOD>; void solve() { int n, a, b; cin >> n >> a >> b; if (a > b) swap(a, b); static mint dp[5050][5050][2][2]; rep(i, 5050) { rep(j, 5050) { rep(k, 2) { rep(l, 2) { dp[i][j][k][l] = 0; } } } } dp[0][0][1][0] = 1; rep(i, n) { for (int j = 0; j <= i; ++j) { // 0 if (j + 1 < a) dp[i + 1][j + 1][0][0] += dp[i][j][0][0]; if (j + 1 < b && j >= a) dp[i + 1][j + 1][0][1] += dp[i][j][0][1]; if (j < b && 1 < a) dp[i + 1][1][0][0] += dp[i][j][1][0]; if (j < b && j + a < b && i + a <= n) dp[i + a][j + a][0][1] += dp[i][j][1][0]; // 1 if (j < a && 1 < b) dp[i + 1][1][1][0] += dp[i][j][0][0]; if (j + 1 < b) dp[i + 1][j + 1][1][0] += dp[i][j][0][1]; if (j + 1 < b) dp[i + 1][j + 1][1][0] += dp[i][j][1][0]; } } mint ans = modpow((mint)2, n); for (int i = 0; i <= n; ++i) { rep(j, 2) { rep(k, 2) { ans -= dp[n][i][j][k]; } } } cout << ans << endl; } signed main() { ios::sync_with_stdio(false); cin.tie(0); // cout << fixed << setprecision(10); // int t; cin >> t; rep(i, t)solve(); solve(); return 0; }
replace
159
160
159
160
-11