solution
stringlengths
10
159k
difficulty
int64
0
3.5k
language
stringclasses
2 values
s = input() z = max(0, s.find('0')) print(s[:z]+s[z+1:])
1,100
PYTHON3
x = int(input()) first_steps = x // 5 remainder = x % 5 if remainder == 0: print(first_steps) else: print(first_steps + 1)
800
PYTHON3
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; const int INF = 0x3f3f3f3f; const long long INFF = 0x3f3f; const double pi = acos(-1.0); const double inf = 1e18; const double eps = 1e-4; const long long mod = 1e9 + 7; const unsigned long long mx = 133333331; inline void RI(int &x) { char c; while ((c = getchar()) < '0' || c > '9') ; x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; } void exgcd(long long a, long long b, long long &d, long long &x, long long &y) { if (!b) { x = 1; y = 0; d = a; return; } else { exgcd(b, a % b, d, y, x); y -= a / b * x; } } long long labs(long long a) { if (a < 0) return -a; return a; } int main() { long long a1, b1, a2, b2, L, R; while (cin >> a1 >> b1 >> a2 >> b2 >> L >> R) { long long x, y, d; exgcd(a1, a2, d, x, y); if ((b2 - b1) % d != 0) { cout << 0 << endl; continue; } x *= (b2 - b1) / d; x = (x % labs(a2 / d) + labs(a2 / d)) % labs(a2 / d); long long cnt = x * a1 + b1; long long tmp = labs(a1 * a2 / d); long long ans = 0; L = max(L, max(b1, b2)); if (L > R) { cout << 0 << endl; continue; } if (cnt <= R) ans += (R - cnt) / tmp + 1; if (cnt < L) ans -= (L - 1 - cnt) / tmp + 1; cout << ans << endl; } return 0; }
2,500
CPP
#include <bits/stdc++.h> using namespace std; int main() { int n, a, b; cin >> n >> a >> b; cout << n - max(a + 1, n - b) + 1; }
1,000
CPP
# Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n,m,b,mod=map(int,input().split()) arr=list(map(int,input().split())) dp=[[0 for _ in range(b+1)] for _ in range(m+1)] dp[0]=[1]*(b+1) for item in arr: for x in range(1,m+1): for y in range(item,b+1): dp[x][y]=(dp[x][y]+dp[x-1][y-item])%mod print(dp[m][b]) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main()
1,800
PYTHON3
#include <bits/stdc++.h> using namespace std; vector<pair<long long, long long> > findcs(vector<long long> &a) { unordered_map<long long, long long> m; vector<pair<long long, long long> > acs; long long cs = 0; for (long long i = 0; i <= a.size(); ++i) { if (i == a.size() || a[i] == 0) { if (cs > 0) { m[cs]++; cs = 0; } } else { cs++; } } for (auto p : m) { acs.push_back({p.first, p.second}); } return acs; } vector<pair<long long, long long> > findsizes(long long k) { vector<pair<long long, long long> > sizes; for (long long i = 1; i * i <= k; ++i) { if (k % i == 0) { sizes.push_back({i, k / i}); } } return sizes; } long long solve(long long n, long long m, long long k, vector<long long> &a, vector<long long> &b) { long long ans = 0; vector<pair<long long, long long> > acs = findcs(a); vector<pair<long long, long long> > bcs = findcs(b); long long dimx, dimy, cnt; vector<pair<long long, long long> > sizes = findsizes(k); for (long long i = 0; i < acs.size(); ++i) { for (long long j = 0; j < bcs.size(); ++j) { dimx = acs[i].first; dimy = bcs[j].first; cnt = acs[i].second * bcs[j].second; if (dimx * dimy == k) { ans += cnt; } else if (dimx * dimy > k) { long long subs = 0; for (auto s : sizes) { subs += cnt * max(0LL, (dimx - s.first + 1) * (dimy - s.second + 1)); if (s.first != s.second) { subs += cnt * max(0LL, (dimx - s.second + 1) * (dimy - s.first + 1)); } } ans += subs; } } } return ans; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); long long n, m, k; cin >> n >> m >> k; vector<long long> a(n), b(m); for (long long i = 0; i < n; ++i) cin >> a[i]; for (long long i = 0; i < m; ++i) cin >> b[i]; cout << solve(n, m, k, a, b) << "\n"; return 0; }
1,500
CPP
#include <bits/stdc++.h> using namespace std; const int M = 1e9 + 7; int main() { long long int t; cin >> t; while (t--) { long long int i, j, n, g = 0; cin >> n; string s[n]; for (i = 0; i < n; i++) cin >> s[i]; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - 1; j++) { if (s[i][j] == '1' && s[i + 1][j] == '0' && s[i][j + 1] == '0') { g++; break; } } if (g != 0) break; } if (g == 0) { cout << "YES" << "\n"; ; } else cout << "NO" << "\n"; ; } return 0; }
1,300
CPP
#include <bits/stdc++.h> using namespace std; inline int in() { int32_t x; scanf("%d", &x); return x; } inline string gets() { char ch[600]; scanf("%s", ch); return ch; } template <class P, class Q> inline P smin(P &a, Q b) { if (b < a) a = b; return a; } template <class P, class Q> inline P smax(P &a, Q b) { if (a < b) a = b; return a; } const int MAX_LG = 17; const long long maxn = 2000 + 10; const long long base = 29; const long long mod = 1e9 + 9; const long long INF = 1e9; const long long maxq = 2e5 + 10; const long long SQ = sqrt(maxn); int32_t main() { long long n = in(), x0 = in(); long long mini = 1e9, maxi = -1e9; for (long long i = 0; i < n; i++) { long long a = in(), b = in(); if (a > b) swap(a, b); mini = min(mini, b); maxi = max(maxi, a); } if (maxi > mini) { cout << -1 << "\n"; } else { long long res = 1e9; for (long long i = maxi; i <= mini; i++) res = min(res, abs(i - x0)); cout << res << "\n"; } }
1,000
CPP
#include <bits/stdc++.h> using std::cin; using std::cout; using std::deque; using std::endl; using std::map; using std::max; using std::min; using std::multiset; using std::pair; using std::queue; using std::set; using std::sort; using std::stack; using std::string; using std::vector; int main() { int n; cin >> n; int cnt[212345] = { 0, }; for (int i = 0; i < n; i++) { int x; scanf("%d", &x); cnt[x] = i + 1; } int answer = -1; int time = n + 1; for (int i = 0; i <= 200000; i++) { if (cnt[i] > 0 && cnt[i] < time) { answer = i; time = cnt[i]; } } cout << answer; return 0; }
1,000
CPP
m,k=map(int,input().split()) l=list(map(int,input().split())) l.sort(reverse=True) if k>m: print(-1) else: print(l[k-1],0)
900
PYTHON3
a = int(input()) for i in range(a): b,c = map(int,input().split()) firstb = b-1 secondb = b+1 for j in range(1,b): if c > j: c = c-j firstb -= 1 else: secondb -= c break #print(b,c,firstb,secondb) answer = str() if firstb == 1: answer = answer+"b" else: for k in range(1,firstb): answer = answer+"a" answer = answer+"b" if firstb == (secondb-1): answer = answer+"b" else: for k in range(firstb+1,secondb): answer = answer+"a" answer = answer+"b" if secondb == b: print(answer) else: for k in range(secondb+1,b+1): answer = answer+"a" print(answer)
1,300
PYTHON3
#include <bits/stdc++.h> using namespace std; int f(long long t, long long d1, long long d2); int f(long long t, long long d1, long long d2) { long long r = t + d2 - d1; long long m = r / 3; if ((!(r % 3)) && ((m >= d2)) && (m >= -d1) && (m >= 0)) return 1; return 0; } int main() { long long n; long long k; int t; cin >> t; long long d1, d2; while (t--) { cin >> n >> k >> d1 >> d2; int x = 0; if (!(n % 3)) { x |= f(k, d1, d2) && f(n - k, -d1, -d2); x |= f(k, -d1, d2) && f(n - k, d1, -d2); x |= f(k, d1, -d2) && f(n - k, -d1, d2); x |= f(k, -d1, -d2) && f(n - k, d1, d2); } cout << (x ? "yes" : "no") << endl; } return 0; }
1,700
CPP
t=int(input()) for i in range(t): s=input() #f=[0 for i in range(10)] pair=[] res=[] for i in range(10): for j in range(10): pair.append([i,j]) for i in range(100): turn=pair[i][0] c=0 for j in range(len(s)): if(int(s[j])!=turn): c+=1 else: if(turn==pair[i][0]): turn=pair[i][1] else: turn=pair[i][0] if((len(s)-c)%2==0): res.append(c) if((len(s)-c)%2!=0 and pair[i][0]==pair[i][1]): res.append(c) #print(pair[i],c) print(min(res))
1,500
PYTHON3
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip ############################################################################ # ACTUAL CODE ############################################################################ def solve(t): a, b = map(int, input().strip().split()) aa, bb = min(a, b), max(a, b) if 2*aa >= bb: return (2*aa)**2 else: return bb**2 def main(): tc = int(input().strip()) for t in range(1, tc+1): print(solve(t)) ############################################################################ # FAST-IO # PyRIVAL ############################################################################ BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ############################################################################ ## DRIVER # PROGRAM ######################################################## if __name__ == "__main__": main()
800
PYTHON3
from collections import defaultdict as dfd import math import sys def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def main(): x = II() A = LI() t = 0 maxi = 0 for i in range(len(A)): if(i==0): t+=1 maxi = max(t,maxi) else: if(A[i]>=A[i-1]): t+=1 maxi = max(t,maxi) else: t = 1 print(maxi) main()
900
PYTHON3
#include <bits/stdc++.h> using namespace std; int l[10][10], r[10][10], a[10][10]; int n; struct state { vector<int> rasb; int last; }; bool operator<(const state& a, const state& b) { if (a.rasb != b.rasb) return a.rasb < b.rasb; return a.last < b.last; } void norm(state& s) { s.last = 0; s.rasb.pop_back(); } map<state, int> t; const int inf = 1 << 25; int calc(state s) { if (s.rasb.back() < 0) return -inf; if (s.last == s.rasb.size()) { if (s.rasb.back() != 0) return -inf; norm(s); } if (s.rasb.size() <= 1) return 0; if (t.find(s) != t.end()) return t[s]; int& ans = t[s]; ans = -inf; int v = s.rasb.size() - 1; int to = s.last; s.last++; for (int i = l[v][to]; i <= r[v][to]; i++) { s.rasb[v] -= i; s.rasb[to] += i; ans = max(ans, calc(s) + a[v][to] * (i > 0) + i * i); s.rasb[v] += i; s.rasb[to] -= i; } return ans; } int main() { scanf("%d", &n); int m = n * (n - 1) / 2; for (int i = 0; i < m; i++) { int a, b, lf, rg, ac; cin >> a >> b >> lf >> rg >> ac; --a; --b; l[b][a] = lf; r[b][a] = rg; ::a[b][a] = ac; } state s; s.rasb.resize(n); s.last = 0; for (int i = 0; i <= 25; i++) { s.rasb.back() = i; int tmp = calc(s); t.clear(); if (tmp >= 0) { cout << i << " " << tmp << endl; return 0; } } cout << -1 << " " << -1 << endl; return 0; }
2,200
CPP
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) a=int(input()) s=Stack() x=[int(w) for w in input().split()] p=[0]*a for i in range(a-1,-1,-1): s.push(x[i]) y=[int(w) for w in input().split()] for i in y: num = 0 while not p[int(i) - 1]: p[s.peek() - 1] = 1 s.pop() num += 1 #print(p,s) print(num, end =' ')
1,000
PYTHON3
for _ in range(int(input())): n,m,k=map(int,input().split()) x=n//k arr=[0]*(k-1) if m<=x: print(m) continue maxi=x rem=m-maxi i=0 ##print(maxi,rem) while rem!=0: arr[i]+=1 ##print(arr) i+=1 rem-=1 if i==len(arr): i=0 z=max(arr) ##print(arr) if arr.count(z)==len(arr) and z==maxi: print(0) continue print(maxi-z)
1,000
PYTHON3
n=int(input()) for i in range(n): lst=[] n1=int(input()) n2=list(map(int,input().split())) for j in n2: if(j not in lst): lst.append(j) v=' '.join(str(i) for i in lst) print(v)
800
PYTHON3
'''for i in range(0, len(s) - 1): if s[i - 1] != s[i]: ans += s[i]''' s = input() meet = False #ans = '' for i in range(len(s) - 1): if s[i] == '/' and s[i + 1] != '/': # ans += '/' print('/', end='') elif s[i] != '/': #ans += s[i] print(s[i], end='') meet = True if s[len(s) - 1] != '/' or not meet: #ans += s[len(s) - 1] print(s[len(s)-1],end = '') #print(ans)
1,700
PYTHON3
import sys a = sys.stdin.read().split()[1].strip() ans = int(a); n = len(a) k = n // 2 m = 0 i = k while m<3 and i<n: if a[i] != '0': m+=1 s = int(a[:i]) + int(a[i:]) if s<ans: ans = s i+=1 m = 0 i = k while m<3 and i>0: if a[i] != '0': m+=1 s = int(a[:i]) + int(a[i:]) if s<ans: ans = s i-=1 print(ans)
1,500
PYTHON3
a,b = map(int,input().split()) x = y = z = 0 for i in range(1,7) : t = abs(a-i) - abs(b - i); x += t<0 y += t==0 z += t>0 print(x,y,z)
800
PYTHON3
#include <bits/stdc++.h> using namespace std; int n, i, j, r; string s, t = "RGB"; int main() { cin >> n >> s; for (i = 1; i < n; i++) if (s[i] == s[i - 1]) { r++; for (j = 0; j < 3; j++) if (t[j] != s[i - 1] && t[j] != s[i + 1]) s[i] = t[j]; } cout << r << endl << s; }
1,300
CPP
#include <bits/stdc++.h> const double PI = acos(-1.0); using namespace std; const int MAXN = 200117; int n, m, coor[MAXN * 4], cn, ansi, ansj; pair<int, int> t[16 * MAXN]; long long ans; pair<int, int> arr[MAXN]; pair<pair<int, int>, pair<int, int> > brr[MAXN]; map<int, int> cr; vector<pair<int, int> > e; set<pair<int, int> > q; bool cmp(pair<pair<int, int>, pair<int, int> > &a, pair<pair<int, int>, pair<int, int> > &b) { return a.first.second < b.first.second; } void upd(int v, int l, int r, int i, int d, int di) { if (r - l == 1) { if (t[v].first <= d) t[v] = make_pair(d, di); } else { int x = (l + r) >> 1; if (i < x) upd(v * 2, l, x, i, d, di); else upd(v * 2 + 1, x, r, i, d, di); if (t[v * 2].first > t[v * 2 + 1].first) t[v] = t[v * 2]; else if (t[v * 2].first < t[v * 2 + 1].first) t[v] = t[v * 2 + 1]; else t[v] = make_pair(t[v * 2].first, max(t[v * 2].second, t[v * 2 + 1].second)); } } pair<int, int> get(int v, int l, int r, int i) { if (l >= i) return t[v]; else if (r <= i) return make_pair(0, -1); else { int x = (l + r) >> 1; pair<int, int> rl = get(v * 2, l, x, i), rr = get(v * 2 + 1, x, r, i); if (rl.first > rr.first) return rl; else if (rl.first < rr.first) return rr; else return make_pair(rl.first, max(rl.second, rr.second)); } } int main() { scanf("%d %d", &n, &m); cn = 0; for (int i = 0; i < n; i++) { scanf("%d %d", &arr[i].first, &arr[i].second); coor[cn++] = arr[i].first; coor[cn++] = arr[i].second; } for (int i = 0; i < m; i++) { scanf("%d %d %d", &brr[i].first.first, &brr[i].first.second, &brr[i].second.first); brr[i].second.second = i + 1; coor[cn++] = brr[i].first.first; coor[cn++] = brr[i].first.second; } sort(coor, coor + cn); cn = unique(coor, coor + cn) - coor; for (int i = 0; i < cn; i++) cr[coor[i]] = i; for (int i = 0; i < 4 * cn + 1; i++) t[i] = make_pair(0, -1); for (int i = 0; i < n; i++) { arr[i].first = cr[arr[i].first]; arr[i].second = cr[arr[i].second]; e.push_back(make_pair(arr[i].first, -1 - i)); e.push_back(make_pair(arr[i].second, i)); } sort(e.begin(), e.end()); for (int i = 0; i < m; i++) { brr[i].first.first = cr[brr[i].first.first]; brr[i].first.second = cr[brr[i].first.second]; } ans = 0; sort(brr, brr + m); for (int i = ((int)(e).size()) - 1, j = m - 1; j >= 0; j--) { for (; i >= 0 && e[i].first >= brr[j].first.first; i--) { if (e[i].second >= 0) q.insert(make_pair(arr[e[i].second].second, e[i].second)); else q.erase(make_pair(arr[-1 - e[i].second].second, -1 - e[i].second)); } if (!q.empty()) { pair<int, int> tmp = *q.rbegin(); if (ans < 1LL * brr[j].second.first * (coor[min(brr[j].first.second, tmp.first)] - coor[brr[j].first.first])) { ans = 1LL * brr[j].second.first * (coor[min(brr[j].first.second, tmp.first)] - coor[brr[j].first.first]); ansi = tmp.second + 1; ansj = brr[j].second.second; } } } q.clear(); sort(brr, brr + m, cmp); for (int i = 0, j = 0; j < m; j++) { for (; i < ((int)(e).size()) && e[i].first <= brr[j].first.second; i++) { if (e[i].second < 0) q.insert(make_pair(arr[-1 - e[i].second].first, -1 - e[i].second)); else { q.erase(make_pair(arr[e[i].second].first, e[i].second)); upd(1, 0, cn, arr[e[i].second].first, coor[e[i].first] - coor[arr[e[i].second].first], e[i].second + 1); } } if (!q.empty()) { pair<int, int> tmp = *q.begin(); if (ans < 1LL * brr[j].second.first * (coor[brr[j].first.second] - coor[max(brr[j].first.first, tmp.first)])) { ans = 1LL * brr[j].second.first * (coor[brr[j].first.second] - coor[max(brr[j].first.first, tmp.first)]); ansi = tmp.second + 1; ansj = brr[j].second.second; } } pair<int, int> tmp = get(1, 0, cn, brr[j].first.first); if (ans < 1LL * brr[j].second.first * tmp.first) { ans = 1LL * brr[j].second.first * tmp.first; ansi = tmp.second; ansj = brr[j].second.second; } } printf( "%lld" "\n", ans); if (ans > 0) printf("%d %d\n", ansi, ansj); return 0; }
2,400
CPP
from math import ceil n2,k = map(int, input().split()) l = list(map(int, input().split())) l = sorted(l) d = {} for i in l: d[i] = 1 if k == 1: print(len(d)) else: used = {} ans = 0 for i in l: if i in used: continue n = i num = 0 while n in d: if n in used: break used[n] = 1 n *= k num += 1 ans += num//2 if num&1 > 0: ans += 1 print(ans)
1,500
PYTHON3
n = int(input()) op = set(map(int, input().split())) if 1 in op: print("HARD") else: print("EASY")
800
PYTHON3
n, h = map(int, input().split()) a = [(int(x) - 1) // h + 1 for x in input().split()] print(sum(a))
800
PYTHON3
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; int max(int a, int b) { return a > b ? a : b; } struct node { long long l, r; } a[100005]; long long cmp(node a, node b) { if (a.l == b.l) return a.r < b.r; return a.l < b.l; } int main() { int n; long long x, y; scanf("%d%lld%lld", &n, &x, &y); for (int i = 1; i <= n; i++) { scanf("%lld%lld", &a[i].l, &a[i].r); } sort(a + 1, a + n + 1, cmp); long long ans = (x + y * (a[1].r - a[1].l) % mod) % mod; map<long long, int> vis; set<long long> S; set<long long>::iterator it; S.insert(a[1].r); vis[a[1].r]++; for (int i = 2; i <= n; i++) { it = S.lower_bound(a[i].l); if (it == S.begin()) { ans = (ans + x + 1LL * y * (a[i].r - a[i].l) % mod) % mod; vis[a[i].r]++; } else { it--; if (a[i].l > (*it) && (a[i].l - *it) * y < x) { vis[*it]--; if (!vis[*it]) S.erase(*it); ans = (ans + 1LL * (a[i].r - *it) * y % mod) % mod; vis[a[i].r]++; } else { ans = (ans + x + 1LL * y * (a[i].r - a[i].l) % mod) % mod; vis[a[i].r]++; } } S.insert(a[i].r); } printf("%lld\n", ans % mod); return 0; }
2,000
CPP
#include <bits/stdc++.h> using namespace std; char a1[55], a2[55]; struct A { string a; string b; int num; } Aa[100005]; int main() { int n; int leap; int i, j, k; while (cin >> n) { leap = 0; for (i = 1; i <= n; i++) { scanf("%s%s", a1, a2); Aa[i].a = a1; Aa[i].b = a2; if (Aa[i].a > Aa[i].b) swap(Aa[i].a, Aa[i].b); } for (i = 1; i <= n; i++) scanf("%d", &Aa[i].num); int temp = Aa[1].num; string c = Aa[temp].a; for (i = 2; i <= n; i++) { if (Aa[Aa[i].num].a > c) c = Aa[Aa[i].num].a; else if (Aa[Aa[i].num].b <= c) { leap = 1; break; } else c = Aa[Aa[i].num].b; } if (leap) cout << "NO" << endl; else cout << "YES" << endl; } return 0; }
1,400
CPP
#include <cstdlib> #include <cstdarg> #include <cassert> #include <cctype> // tolower #include <ctime> #include <cmath> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <stdexcept> #include <map> #include <tuple> #include <unordered_map> #include <set> #include <list> #include <stack> #include <queue> #include <vector> #include <string> #include <limits> #include <utility> #include <memory> #include <numeric> #include <iterator> #include <algorithm> #include <functional> /* * g++ -g -std=c++11 -DBUG -D_GLIBCXX_DEBUG -Wall -Wfatal-errors -o cforce{,.cpp} * * TODO: * C++ dataframe * stl11 -> c++11 standard template lib in c++98 * overload >> for map and set, using (insert) iterator * chmod:: consider an algorithm stable to int64 overflow * shortest path algorithm * shortest path in a tree * maximum network flow * partial idx/iter sort * a prime number generator which traverses prime numbers w/ ++ * a divisor generator which traverses divisors efficiently * Apply1st ?! * Apply2nd and bind2nd ?! * count_if ( a.begin(), a.end(), a.second < x ) * Arbitrary-precision arithmetic / Big Integer / Fraction - rational num * tuple class --> cplusplus.com/reference/tuple * get<1>, get<2>, bind2nd ( foo ( get<2> pair ), val ) * isin( const T & val, first, last ) * fuinction composition in c++ * blogea.bureau14.fr/index.php/2012/11/function-composition-in-c11/ * cpp-next.com/archive/2010/11/expressive-c-fun-with-function-composition/ * TimeWrapper -- accumulate time of a function call * stackoverflow.com/questions/879408 * hash map -- possible hash value & obj % some_big_prime [ b272 ] * lower level can be a simple map to resolve hash collisions * add explicit everywhere necessary * bloom filters * heap -> how to update values in place / increase-key or decrease-key ... IterHeap ?! * median maintaince --> max_heap / min_heap * prim's min spaning tree alg. O ( m log n ) using heap contianing V - X vertices * kruskal algorithm minimum cost spanning tree with union find data structure * unique_ptr * hufman codes * simple arithmatic tests * longest common subsequence using seq. alignment type algorithm * longest common substring ( consequative subsequeance ) * Graham scan; en.wikipedia.org/wiki/Graham_scan * problem/120/F -- how to extend in order to calculate all-pair distances in a tree * compile time prime number calculator using templates * swith to type_cast < T1, T2 > for val2str & str2val * overload plus<> for two vectors?! * overloading operator << for tuple: * stackoverflow.com/questions/9247723 * bitmask class with iterator protocol * ??? segment tree +++ interval tree * ??? an lru cache: a heap which maintains last access, an a map which maintains key:value * ??? in lazy-union how to query size of a connected component( 437/D ) */ /* * @recepies * ---------------------------------------------- * odd / even * transform ( x.begin(), x.end(), x.begin(), bind2nd( modulus<int>(), 2 )); * count_if ( x.begin(), x.end(), bind2nd( modulus < int > (), 2)); * Apply2nd * max_element ( m.begin(), m.end(), Apply2nd < string, int , less < int > > ) * sort ( a.begin(), a.end(), Apply2nd < char, int , greater< int > > ) * count_if ( m.begin(), m.end(), Apply2nd < string, int, modulus < int > > ) * accumulate ( m.begin(), m.end(), 0.0, Apply2nd < int, double, plus < double > > ) * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ) * abs_diff * adjacent_difference ( a.begin(), a.end(), adj_diff.begin( ), abs_diff < int > ( ) ) * accumulate ( a.begin(), a.end(), 0, abs_diff < int > ( ) ) * erase * a.erase ( remove_if ( a.begin( ), a.end( ), bind2nd ( less < int >( ), 0 ) ), a.end( ) ) * a.erase ( remove ( a.begin( ), a.end( ), b.begin( ), b.end( ) ), a.end ( ) ) * binding * bind2nd ( mem_fun_ref (& ClassName::m_func ), arg ) // binds the argument of the object * iterator generators * generate_n ( back_inserter ( a ), n, rand ); // calls push_back * generate_n ( inserter( a, a.begin( ) + 5 ), 10, RandInt( 0 , 100 ) ) // calls insert * copy ( foo.begin( ), foo.end( ), insert_iterator < list < double > > ( bar, bar.begin( ) + 5 )) * copy ( a.begin( ), a.end( ), ostream_iterator < double > ( cout, ", " )) * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ) * transform (numbers.begin(), numbers.end(), lengths.begin(), mem_fun_ref(&string::length)); */ /* * @good read * ---------------------------------------------- * [ partial ] template specialization * cprogramming.com/tutorial/template_specialization.html * function composition * cpp-next.com/archive/2010/11/expressive-c-fun-with-function-composition */ /* * @prob set * ---------------------------------------------- * purification --> c330 */ /* * @limits * ---------------------------------------------- * int 31 2.14e+09 * long int 31 2.14e+09 * unsigned 32 4.29e+09 * long unsigned 32 4.29e+09 * size_t 32 4.29e+09 * long long int 63 9.22e+18 * long long unsigned 64 1.84e+19 */ /* * issues * ---------------------------------------------- * stackoverflow.com/questions/10281809 * mem_fun -> func_obj ( pointer to instance, origanal argument ) * bind1st ( mem_fun ( & ClassName::m_func ), this ) // binds obj of the class * bind1st takes 'const T &' as the first argument */ /* * typedef / define * ---------------------------------------------- */ typedef long long int int64; typedef unsigned long long int uint64; #ifndef M_PI #define M_PI 3.14159265358979323846L #endif #define DOUBLE_INF numeric_limits< double >::infinity() #define DOUBLE_NAN numeric_limits< double >::quiet_NaN() #define __STR__(a) #a #define STR(a) __STR__(a) #define ASSERT(expr, msg) \ if (!( expr )) \ throw runtime_error(__FILE__ ":" STR(__LINE__) " - " msg); #define DECLARE( X ) \ typedef shared_ptr < X > X ## _shared_ptr; \ typedef const shared_ptr < X > X ## _const_shared_ptr; #ifdef BUG #define DEBUG(var) { cout << #var << ": " << (var) << endl; } #define COND_DEBUG(expr, var) if (expr) \ { cout << #var << ": " << (var) << endl; } #define EXPECT(expr) if ( ! (expr) ) cerr << "Assertion " \ << #expr " failed at " << __FILE__ << ":" << __LINE__ << endl; #else #define DEBUG(var) #define COND_DEBUG(expr, var) #define EXPECT(expr) #endif #define DBG(v) copy( v.begin(), v.end(), ostream_iterator < typeof( *v.begin() )> ( cout, " " ) ) #if __cplusplus < 201100 #define move( var ) var #endif /* * http://rootdirectory.de/wiki/SSTR() * usage: * SSTR( "x^2: " << x*x ) */ #define SSTR( val ) dynamic_cast< ostringstream & >( ostringstream() << dec << val ).str() using namespace std; /* https://www.quora.com/C++-programming-language/What-are-some-cool-C++-tricks */ // template <typename T, size_t N> // char (&ArraySizeHelper(T (&array)[N]))[N]; // #define arraysize(array) (sizeof(ArraySizeHelper(array))) /* * forward decleration * ---------------------------------------------- */ class ScopeTimer; /* * functional utils * ---------------------------------------------- */ template < typename T > struct abs_diff : binary_function < T, T, T > { typedef T value_type; inline value_type operator( ) ( const value_type & x, const value_type & y ) const { return abs( x - y ); } }; // template < class InputIterator, class T > // class isin : public binary_function < InputIterator, InputIterator, bool > // { // public: // typedef T value_type; // // isin ( const InputIterator & first, const InputIterator & last ): // m_first ( first ), m_last ( last ) { } // // bool operator ( ) ( const value_type & val ) const // { // return find ( m_first, m_last, val ) != m_last; // } // private: // const InputIterator m_first, m_last; // } template < typename value_type, typename cont_type > class isin : public unary_function < value_type, bool > { public: isin( const cont_type & vals ): m_vals ( vals ) { }; bool operator ( ) ( const value_type & x ) const { return find ( m_vals.begin( ), m_vals.end( ), x ) != m_vals.end( ); } private: const cont_type m_vals; }; /* * max_element, min_element, count_if ... on the 2nd element * eg: max_element ( m.begin(), m.end(), Apply2nd < string, int , less < int > > ) */ template < class T1, class T2, class BinaryOperation > class Apply2nd : binary_function < typename std::pair < T1, T2 >, typename std::pair < T1, T2 >, typename BinaryOperation::result_type > { public: typedef T1 first_type; typedef T2 second_type; typedef typename BinaryOperation::result_type result_type; typedef typename std::pair < first_type, second_type > value_type; inline result_type operator( ) ( const value_type & x, const value_type & y ) const { return binary_op ( x.second , y.second ); } private: BinaryOperation binary_op; }; /* * algo utils * ---------------------------------------------- */ /** * count the number of inversions in a permutation; i.e. how many * times two adjacent elements need to be swaped to sort the list; * 3 5 2 4 1 --> 7 */ template < class InputIterator > typename iterator_traits<InputIterator>::difference_type count_inv ( InputIterator first, InputIterator last ) { typedef typename iterator_traits<InputIterator>::difference_type difference_type; typedef typename iterator_traits<InputIterator>::value_type value_type; list < value_type > l; /* list of sorted values */ difference_type cnt = 0; for ( difference_type n = 0; first != last; ++first, ++n ) { /* count how many elements larger than *first appear before *first */ typename list < value_type >::iterator iter = l.begin( ); cnt += n; for ( ; iter != l.end( ) && * iter <= * first; ++ iter, -- cnt ) ; l.insert( iter, * first ); } return cnt; } template < class ForwardIterator, class T > inline void fill_inc_seq ( ForwardIterator first, ForwardIterator last, T val ) { for ( ; first != last; ++first, ++val ) * first = val; } template <class ForwardIterator, class InputIterator > ForwardIterator remove ( ForwardIterator first, ForwardIterator last, InputIterator begin, InputIterator end ) { ForwardIterator result = first; for ( ; first != last; ++ first ) if ( find ( begin, end, *first ) == end ) { *result = *first; ++result; } return result; } /* stackoverflow.com/questions/1577475 */ template < class RAIter, class Compare > class ArgSortComp { public: ArgSortComp ( const RAIter & first, Compare comp ): m_first ( first ), m_comp( comp ) { } inline bool operator() ( const size_t & i, const size_t & j ) const { return m_comp ( m_first[ i ] , m_first[ j ] ); } private: const RAIter & m_first; const Compare m_comp; }; /*! * usage: * vector < size_t > idx; * argsort ( a.begin( ), a.end( ), idx, less < Type > ( ) ); */ template < class RAIter, class Compare=less< typename RAIter::value_type > > void argsort( const RAIter & first, const RAIter & last, vector < size_t > & idx, Compare comp = Compare()) // less< typename RAIter::value_type >() ) { const size_t n = last - first; idx.resize ( n ); for ( size_t j = 0; j < n; ++ j ) idx[ j ] = j ; stable_sort( idx.begin(), idx.end(), ArgSortComp< RAIter, Compare >( first, comp )); } template < class RAIter, class Compare > class IterSortComp { public: IterSortComp ( Compare comp ): m_comp ( comp ) { } inline bool operator( ) ( const RAIter & i, const RAIter & j ) const { return m_comp ( * i, * j ); } private: const Compare m_comp; }; /*! * usage: * vector < list < Type >::const_iterator > idx; * itersort ( a.begin( ), a.end( ), idx, less < Type > ( ) ); */ template <class INIter, class RAIter, class Compare> void itersort ( INIter first, INIter last, vector < RAIter > & idx, Compare comp ) { /* alternatively: stackoverflow.com/questions/4307271 */ idx.resize ( distance ( first, last ) ); for ( typename vector < RAIter >::iterator j = idx.begin( ); first != last; ++ j, ++ first ) * j = first; sort ( idx.begin( ), idx.end( ), IterSortComp< RAIter, Compare > (comp ) ); } /* * string utils * ---------------------------------------------- */ inline void erase ( string & str, const char & ch ) { binder2nd < equal_to < char > > isch ( equal_to< char >(), ch ); string::iterator iter = remove_if ( str.begin(), str.end(), isch ); str.erase ( iter, str.end() ); } inline void erase ( string & str, const string & chrs ) { isin < char, string > isin_chrs ( chrs ); string::iterator iter = remove_if ( str.begin(), str.end(), isin_chrs ); str.erase ( iter, str.end() ); } template < typename value_type> inline string val2str ( const value_type & x ) { ostringstream sout ( ios_base::out ); sout << x; return sout.str(); } template < typename value_type> inline value_type str2val ( const string & str ) { istringstream iss ( str, ios_base::in ); value_type val; iss >> val; return val; } vector< string > tokenize( const string & str, const char & sep ) { /*! * outputs empty tokens and assumes str does not start with sep * corner cases: * empty string, one char string, * string starting/ending with sep, all sep, end with two sep */ vector < string > res; string::const_iterator follow = str.begin(), lead = str.begin(); while ( true ) { while ( lead != str.end() && * lead != sep ) ++ lead; res.push_back ( string( follow, lead ) ); if ( lead != str.end () ) follow = 1 + lead ++ ; else break; } return res; } /*! * chunk a string into strings of size [ at most ] k */ void chunk ( const string::const_iterator first, const string::const_iterator last, const size_t k, const bool right_to_left, list < string > & str_list ) { str_list.clear( ); if ( right_to_left ) /* chunk from the end of the string */ for ( string::const_iterator i, j = last; j != first; j = i ) { i = first + k < j ? j - k : first; str_list.push_back ( string ( i, j ) ); } else /* chunk from the begining of the string */ for ( string::const_iterator i = first, j; i != last; i = j ) { j = i + k < last ? i + k : last; str_list.push_back ( string ( i, j ) ); } } /*! * next lexicographically smallest string * within char set a..z */ string & operator++( string & s ) { /* find the first char from right less than 'z' */ string::reverse_iterator j = find_if( s.rbegin( ), s.rend( ), bind2nd( less < char > ( ), 'z' )); if ( j != s.rend( )) { ++ *j; fill( s.rbegin( ), j, 'a' ); } else s.assign( s.length( ) + 1, 'a' ); return s; } /*! if a starts with b */ inline bool starts_with( const string & a, const string & b ) { return !( a.size() < b.size() || mismatch( begin(b), end(b), begin(a) ).first != end(b) ); } /*! prefix tree */ auto get_prefix_tree( const vector< string > & word ) -> vector< map< char, size_t > > { typedef map< char, size_t > node; /* empty string as the first element */ vector< node > tree(1); for( const auto & w: word ) { /* start with empty string as the root node */ size_t root = 0; for( const auto & a : w ) { auto & ref = tree[ root ][ a ]; if ( ref == 0 ) /* new prefix, add to the end of tree */ { ref = tree.size(); tree.push_back( node() ); } root = ref; } } return tree; } /*! * getline ( cin, str ) * requires ctrl-D * cin >> str; does not pass after space char */ /* * number utils * ---------------------------------------------- */ class BigInteger { #if ULONG_MAX <= 1 << 32 typedef long long unsigned val_type; #else typedef long unsigned val_type; #endif const static int WSIZE = 32; const static val_type BASE = 1LL << WSIZE; public: private: list < val_type > val; /* val[ 0 ] is most significant */ bool pos; /* true if sign is positive */ }; /** * greatest common divisor - Euclid's alg. */ template < typename value_type > inline value_type gcd ( value_type a, value_type b ) { return ! b ? a : gcd( b, a % b ); } /** * prime factorization */ template < class T > void prime_factors( T n, map < T, size_t > & fac ) { for ( T k = 2; n > 1; ++ k ) if ( ! ( n % k ) ) { size_t & ref = fac[ k ]; while ( ! ( n % k ) ) { ++ ref; n /= k; } } } /* abs diff - safe for unsigned types */ template < class T > inline T absdiff( T a, T b ) { return a < b ? b - a : a - b; } namespace { template < class T > pair < T, T > __extgcd ( const T & x0, const T & y0, const T & x1, const T & y1, const T & r0, const T & r1 ) { const T q = r0 / r1; const T r2 = r0 % r1; if ( ! ( r1 % r2 ) ) return make_pair < T, T > ( x0 - q * x1, y0 - q * y1 ); const T x2 = x0 - q * x1; const T y2 = y0 - q * y1; return __extgcd ( x1, y1, x2, y2, r1, r2 ); } } /** * extended euclidean algorithm: a x + b y = gcd( a, b) * en.wikipedia.org/wiki/Extended_Euclidean_algorithm */ template < class value_type > inline pair < value_type, value_type > extgcd ( value_type a, value_type b ) { return a % b ? __extgcd < value_type > ( 1, 0, 0, 1, a, b ) : make_pair < value_type, value_type > ( 0, 1 ); } /** * modular multiplicative inverse * en.wikipedia.org/wiki/Modular_multiplicative_inverse */ template < class value_type > inline value_type modinv ( value_type a, value_type m ) { const pair < value_type, value_type > coef ( extgcd( a, m ) ); /* a needs to be coprime to the modulus, or the inverse won't exist */ if ( a * coef.first + m * coef.second != 1 ) throw runtime_error ( val2str( a ) + " is not coprime to " + val2str( m )); /* return a pos num between 1 & m-1 */ return ( m + coef.first % m ) % m; } inline bool isnan ( const double & a ) { return ! ( a == a ); } template < typename value_type > inline value_type mini ( int n, ... ) { va_list vl; va_start (vl, n); value_type res = va_arg ( vl, value_type ); for ( int i = 1; i < n; ++i ) { const value_type val = va_arg ( vl, value_type ); res = min ( res, val ); } va_end( vl ); return res; } template < typename value_type > inline value_type maxi ( int n, ... ) { va_list vl; va_start (vl, n); value_type res = va_arg ( vl, value_type ); for ( int i = 1; i < n; ++i ) { const value_type val = va_arg ( vl, value_type ); res = max ( res, val ); } va_end( vl ); return res; } // XXX look this up how is this implemented template < class T > inline int sign ( const T & x ) { if ( x == T() ) return 0; else if ( x < T() ) return -1; else return 1; } /* * change moduluos from n to m */ string chmod ( string num, const unsigned n, const unsigned m ) { const char * digit = "0123456789abcdefghijklmnopqrstuvwxyz"; transform ( num.begin(), num.end(), num.begin(), ::tolower ); isin < char, string > is_alpha_num ( digit ); assert ( find_if ( num.begin( ), num.end( ), not1 ( is_alpha_num ) ) == num.end( )); unsigned long long int val ( 0 ); if ( n == 10U ) { istringstream iss ( num, ios_base::in ); iss >> val; } else for ( string::const_iterator iter = num.begin( ); iter != num.end( ); ++ iter ) val = val * n + ( 'a' <= *iter ? *iter - 'a' + 10U : *iter - '0'); if ( m == 10U ) { ostringstream sout ( ios_base::out ); sout << val; return sout.str ( ); } else { string res; for ( ; val ; val /= m ) res.push_back( digit [ val % m ] ); return res.length( ) ? string( res.rbegin( ), res.rend( )) : "0"; } } template < class value_type > /* a^n mod m */ value_type powmod ( value_type a, const value_type & n, const value_type & m ) { if ( a == 1 || ! n ) return m != 1 ? 1 : 0; value_type res = 1; for ( value_type k = 1; k <= n; a = a * a % m, k = k << 1 ) if ( k & n ) res = ( res * a ) % m; return res; } template < class T > inline T atan(const T & x, const T & y) { return atan( y / x ) + ( x < 0 ) * M_PI; } /* * Fermat pseudoprime test * www.math.umbc.edu/~campbell/Computers/Python/numbthy.py * NOTE: since return type is bool, and powmod may break for ints, * the argument is always casted to long long */ inline bool is_pseudo_prime ( const long long & a ) { /* all the primes less than 1000 ( 168 primes )*/ const long long p [ ] = { 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73, 79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157, 163,167,173,179,181,191,193,197,199,211,223,227,229,233,239, 241,251,257,263,269,271,277,281,283,293,307,311,313,317,331, 337,347,349,353,359,367,373,379,383,389,397,401,409,419,421, 431,433,439,443,449,457,461,463,467,479,487,491,499,503,509, 521,523,541,547,557,563,569,571,577,587,593,599,601,607,613, 617,619,631,641,643,647,653,659,661,673,677,683,691,701,709, 719,727,733,739,743,751,757,761,769,773,787,797,809,811,821, 823,827,829,839,853,857,859,863,877,881,883,887,907,911,919, 929,937,941,947,953,967,971,977,983,991,997 }; const size_t n = sizeof( p ) / sizeof ( p[ 0 ] ); if ( a < p[ n - 1 ] + 1) return binary_search ( p, p + n , a ); if ( find_if ( p, p + n, not1 ( bind1st ( modulus< long long >( ), a ))) != p + n ) return false; const size_t k = a < 9006401LL ? 3 : a < 10403641LL ? 4 : a < 42702661LL ? 5 : a < 1112103541LL ? 6 : 7; for ( size_t j = 0; j < k; ++ j ) if ( powmod ( p[ j ], a - 1, a ) != 1 ) return false; return true; } /* * returns a sorted vector of all primes less than or equal to n * maximum adj diff of all primes less than 1e5 is 72 ( 114 for 1e6 ) */ template < typename value_type > vector < value_type > get_primes ( const value_type n ) { #ifdef BUG ScopeTimer scope_timer ( "vector < value_type > get_primes ( const value_type n )" ); #endif // typedef typename vector < value_type >::iterator iterator; vector < value_type > primes; for ( value_type k = 2 ; k <= n; ++ k ) if ( is_pseudo_prime ( k ) ) { // FIXME this is very stupid // const value_type sqrt_k = 1 + static_cast < value_type > ( sqrt ( k + 1 ) ); // iterator iend = upper_bound ( primes.begin( ), primes.end( ), sqrt_k ); // if ( find_if ( primes.begin( ), iend, not1 ( bind1st ( modulus< value_type >( ), k ) ) ) != iend ) // continue; primes.push_back ( k ); } return primes; } template < class T > inline vector < pair < T, size_t > > get_prime_fact( T a ) { vector< pair < T, size_t > >fac; for ( T k = 2; a > 1; ++ k ) if ( ! ( a % k ) ) // no need to check if k is prime { size_t m = 0; for ( ; ! ( a % k ) ; ++m, a/= k ) ; fac.push_back ( pair < T, size_t > ( k, m ) ); } return fac; } template < class T > /* prime factorization */ vector < pair < T, size_t > > get_prime_fac( T a ) { vector < pair < T, size_t > > fac; size_t k = 0; while (!(a % 2)) { a /= 2; ++ k; } if ( k != 0 ) fac.push_back( make_pair(2, k)); k = 0; while (!(a % 3)) { a /= 3; ++ k; } if ( k != 0 ) fac.push_back( make_pair(3, k)); for ( T j = 5; j * j < a + 1 && a > 1 && j < a + 1; j += 4 ) { size_t k = 0; while (!(a % j)) { a /= j; ++ k; } if ( k != 0 ) fac.push_back( make_pair(j, k)); j += 2; k = 0; while (!(a % j)) { a /= j; ++ k; } if ( k != 0 ) fac.push_back( make_pair(j, k)); } if ( a > 1 ) fac.push_back( make_pair(a, 1)); return fac; } template < class T > /* generates all divisors from vector of prime factorization */ void gen_div( T a, vector < T > & divs, typename vector < pair < T, size_t > >::const_iterator iter, typename vector < pair < T, size_t > >::const_iterator last ) { if ( iter != last ) { auto next = iter + 1; const auto k = iter->second + 1; const auto prime = iter->first; for ( size_t j = 0; j < k; ++ j ) { gen_div(a, divs, next, last); a *= prime; } } else divs.push_back( a ); } template < class T > T n_choose_k ( T n, T k ) { if ( k > n ) return 0; const T lb = min ( k, n - k ) + 1; const T ub = n - lb + 1; T res = 1, j = 2; while ( n > ub && j < lb) { res *= n--; while ( j < lb and ! (res % j) ) res /= j++; } while ( n > ub ) res *= n--; return res; } /** * median calculator, using two heaps */ template < class InputIter > inline pair < typename InputIter::value_type, typename InputIter::value_type > median ( InputIter first, InputIter last ) { typedef typename InputIter::value_type value_type; typedef pair< value_type, value_type > result_type; /* * max_heap: * - the lower half of the elements * - the biggest of such elements is on the top */ vector < value_type > max_heap, min_heap; /* * comp argument to heap algorithm should provide * 'strict weak ordering'; in particular * not2 ( less < value_type > ) * does not have such a strict weak ordering; */ less < value_type > max_heap_comp; greater < value_type > min_heap_comp; if ( first == last ) /* corner case: empty vector */ throw runtime_error ( "median of an empty vector is undefined!" ); InputIter iter = first; max_heap.push_back ( * iter ); for ( ++iter ; iter != last; ++ iter ) if ( * iter < max_heap.front() ) { max_heap.push_back ( * iter ); push_heap ( max_heap.begin(), max_heap.end(), max_heap_comp ); if ( min_heap.size() + 1 < max_heap.size() ) { /* max_heap has got too large */ min_heap.push_back( max_heap.front() ); push_heap( min_heap.begin(), min_heap.end(), min_heap_comp ); pop_heap( max_heap.begin(), max_heap.end(), max_heap_comp ); max_heap.pop_back(); } } else { min_heap.push_back ( * iter ); push_heap ( min_heap.begin(), min_heap.end(), min_heap_comp ); if ( max_heap.size() + 1 < min_heap.size() ) { /* min_heap has got too large */ max_heap.push_back( min_heap.front() ); push_heap( max_heap.begin(), max_heap.end(), max_heap_comp ); pop_heap( min_heap.begin(), min_heap.end(), min_heap_comp ); min_heap.pop_back(); } } DEBUG( max_heap ); DEBUG( min_heap ); return min_heap.empty( ) /* corner case: ++first = last */ ? result_type ( *first, *first ) : result_type ( max_heap.size() < min_heap.size() ? min_heap.front() : max_heap.front(), min_heap.size() < max_heap.size() ? max_heap.front() : min_heap.front() ); } /* * geometry util * ---------------------------------------------- */ struct xyPoint { double x, y; xyPoint( const double & a = .0, const double & b = .0 ): x ( a ), y( b ) { }; }; struct xyCircle { xyPoint center; double radius; }; ostream & operator<< ( ostream & out, const xyPoint & p ) { out << '(' << p.x << ", " << p.y << ')'; return out; } istream & operator>> ( istream & ist, xyPoint & p ) { ist >> p.x >> p.y; return ist; } ostream & operator<< ( ostream & out, const xyCircle & o ) { out << "{(" << o.center.x << ", " << o.center.y << ") " << o.radius << '}'; return out; } istream & operator>> ( istream & ist, xyCircle & o ) { ist >> o.center.x >> o.center.y >> o.radius; return ist; } inline double cartesian_dist ( const xyPoint & a, const xyPoint & b ) { const double d = a.x - b.x; const double e = a.y - b.y; return sqrt ( d * d + e * e ); } class xyLine { public: xyLine ( const xyPoint & , const xyPoint & ); xyLine ( const double slope, const double intercept ); /* * 'signed' orthogonal distance; the sign is useful * to compare which side of the line the point is */ inline double orth_dist ( const xyPoint & ) const; private: double m_slope; double m_intercept; double m_normfac; /* normalization factor for orth_dist calc */ bool m_vertical; /* if the line is verticcal */ double m_xcross; /* x axis cross point for vertical line */ }; xyLine::xyLine ( const xyPoint & a, const xyPoint & b ) { if ( a.x == b.x ) /* vertical line */ { m_vertical = true; m_xcross = a.x; m_intercept = DOUBLE_NAN; m_slope = DOUBLE_INF; m_normfac = DOUBLE_NAN; } else { m_vertical = false; m_xcross = DOUBLE_NAN; m_slope = ( b.y - a.y ) / ( b.x - a.x ); m_intercept = a.y - m_slope * a.x; m_normfac = sqrt ( m_slope * m_slope + 1.0 ); } } xyLine::xyLine ( const double slope, const double intercept ): m_slope ( slope ), m_intercept ( intercept ) { m_vertical = false; m_xcross = DOUBLE_NAN; m_normfac = sqrt ( m_slope * m_slope + 1.0 ); } double xyLine::orth_dist ( const xyPoint & o ) const /* 'signed' orthogonal distance */ { if ( m_vertical ) return o.x - m_xcross; else return ( m_slope * o.x - o.y + m_intercept ) / m_normfac; } inline double triangle_area ( const xyPoint & a, const xyPoint & b, const xyPoint & c ) { const xyLine l ( a, b ); const double h = abs ( l.orth_dist ( c ) ); const double e = cartesian_dist ( a, b ); return h * e; } /* * operator<< overrides * ---------------------------------------------- */ namespace { /* helper function to output containers */ template < typename T > ostream & __output ( ostream & out, const T & a ) { typedef typename T::const_iterator const_iterator; out << "{ "; // does not work for 'pair' value type // copy ( a.begin( ), a.end( ), ostream_iterator < typename T::value_type > ( cout, ", " )); for ( const_iterator iter = a.begin(); iter != a.end(); ++ iter ) out << ( iter != a.begin( ) ? ", " : "" ) << *iter ; return out << " }"; } } template < typename key_type, typename value_type > ostream & operator<< ( ostream & out, const pair < key_type, value_type > & p) { out << "(" << p.first << ", " << p.second << ")"; return out; } template < typename T0, typename T1, typename T2 > ostream & operator<< ( ostream & out, const tuple < T0, T1, T2 > & t ) { out << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ")"; return out; } template < typename T0, typename T1 > ostream & operator<< ( ostream & out, const tuple < T0, T1 > & t ) { out << "(" << get<0>(t) << ", " << get<1>(t) << ")"; return out; } template < typename key_type, typename value_type, typename comp > ostream & operator<< ( ostream & out, const map < key_type, value_type, comp > & m ) { return __output ( out, m ); } template < typename value_type, typename comp > ostream & operator<< ( ostream & out, const set < value_type, comp > & s ) { return __output ( out, s ); } template < typename value_type > ostream & operator<< ( ostream & out, const vector < value_type > & a ) { return __output ( out, a ); } template < typename value_type > ostream & operator<< ( ostream & out, const list < value_type > & a ) { return __output ( out, a ); } template < typename value_type > ostream & operator<< ( ostream & out, const vector < vector < value_type > > & a ) { typedef typename vector < vector < value_type > >::const_iterator const_iterator; for ( const_iterator iter = a.begin( ); iter != a.end( ); ++ iter ) out << '\n' << *iter ; return out; } /* * operator>> overrides * ---------------------------------------------- */ template < typename key_type, typename value_type > istream & operator>> ( istream & in, pair < key_type, value_type > & p) { in >> p.first >> p.second; return in; } template < typename T0, typename T1, typename T2 > istream & operator>> ( istream & fin, tuple < T0, T1, T2 > & t ) { fin >> get<0>(t) >> get<1>(t) >> get<2>(t); return fin; } template < typename value_type > istream & operator>> ( istream & in, vector < value_type > & a ) { typedef typename vector < value_type >::iterator iterator; if ( ! a.size( ) ) { size_t n; in >> n; a.resize( n ); } for ( iterator iter = a.begin(); iter != a.end(); ++ iter ) in >> * iter; return in; } /* * readin quick utilities * ---------------------------------------------- */ // template < typename value_type > // inline void readin ( vector < value_type > & a, size_t n = 0, istream & in = cin ) // { // // if ( ! n ) cin >> n; // if ( ! n ) in >> n ; // a.resize ( n ); // // cin >> a; // in >> a; // } // XXX consider removing // template < typename key_type, typename value_type > // inline void readin (vector < pair < key_type , value_type > > & a, size_t n = 0 ) // { // if ( !n ) cin >> n; // a.resize( n ); // cin >> a; // } /* * pair utility * ---------------------------------------------- */ /* * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ); * stackoverflow.com/questions/18640152 */ template < typename T1, typename T2 > inline pair < T1, T2 > operator+ ( const pair < T1, T2 > & a, const pair < T1, T2 > & b ) { return make_pair < T1, T2 > ( a.first + b.first, a.second + b.second ); } template < typename T1, typename T2 > inline pair < T1, T2 > operator- ( const pair < T1, T2 > & a, const pair < T1, T2 > & b ) { return make_pair < T1, T2 > ( a.first - b.first, a.second - b.second ); } // template < class T1, class T2, class BinaryOperation > // class Apply2nd : binary_function < typename pair < T1, T2 >, // typename pair < T1, T2 >, // typename BinaryOperation::result_type > namespace { /*! * helper template to do the work */ template < size_t J, class T1, class T2 > struct Get; template < class T1, class T2 > struct Get < 0, T1, T2 > { typedef typename pair < T1, T2 >::first_type result_type; static result_type & elm ( pair < T1, T2 > & pr ) { return pr.first; } static const result_type & elm ( const pair < T1, T2 > & pr ) { return pr.first; } }; template < class T1, class T2 > struct Get < 1, T1, T2 > { typedef typename pair < T1, T2 >::second_type result_type; static result_type & elm ( pair < T1, T2 > & pr ) { return pr.second; } static const result_type & elm ( const pair < T1, T2 > & pr ) { return pr.second; } }; } template < size_t J, class T1, class T2 > typename Get< J, T1, T2 >::result_type & get ( pair< T1, T2 > & pr ) { return Get < J, T1, T2 >::elm( pr ); } template < size_t J, class T1, class T2 > const typename Get< J, T1, T2 >::result_type & get ( const pair< T1, T2 > & pr ) { return Get < J, T1, T2 >::elm( pr ); } /* * graph utils * ---------------------------------------------- */ /* maximum in sub-tree distance */ void get_indist( const size_t root, const vector < vector < size_t > > & tree, vector < tuple< size_t, size_t > > & indist ) { const auto NIL = numeric_limits< size_t >::max(); size_t a = 0, b = NIL; for ( const auto u: tree[ root ] ) { get_indist( u, tree, indist ); if ( a < 1 + get< 0 >( indist[ u ] ) ) { b = a; a = 1 + get< 0 >( indist[ u ] ); } else b = b != NIL ? max( b, 1 + get< 0 >( indist[ u ] )) : 1 + get< 0 >( indist[ u ] ); } indist[ root ] = make_tuple(a, b); } /* maximum out of subtree distance */ void get_outdist( const size_t root, const vector< vector< size_t > > & tree, const vector< tuple< size_t, size_t > > & indist, vector < size_t > & outdist ) { const auto NIL = numeric_limits< size_t >::max(); for( const auto u: tree[ root ] ) { if ( 1 + get< 0 >( indist[ u ] ) == get< 0 >( indist[ root ] ) ) outdist[ u ] = get< 1 >( indist[ root ] ) != NIL ? 1 + max( get< 1 >( indist[ root ] ), outdist[ root ] ) : 1 + outdist[ root ]; else outdist[ u ] = 1 + max( get< 0 >( indist[ root ] ), outdist[ root ] ); get_outdist( u, tree, indist, outdist ); } } /* * Dijkstra :: single-source shortest path problem for * a graph with non-negative edge path costs, producing * a shortest path tree * en.wikipedia.org/wiki/Dijkstra's_algorithm */ template < typename DistType > void Dijekstra ( const size_t & source, const vector < list < size_t > > & adj, // adjacency list const vector < vector < DistType > > & edge_len, // pair-wise distance for adjacent nodes vector < DistType > & dist, // distance from the source vector < size_t > prev ) // previous node in the shortest path tree { // TODO } // TODO http://en.wikipedia.org/wiki/Shortest_path_problem // TODO Graph class, Weighted graph, ... /* * maximum cardinality matching in a bipartite graph * G = G1 ∪ G2 ∪ {NIL} * where G1 and G2 are partition of graph and NIL is a special null vertex * https://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm */ class HopcroftKarp { public: HopcroftKarp ( const vector < list < size_t > > & adj, const vector < bool > & tag ); size_t get_npair ( ) { return npair; }; map < size_t, size_t > get_map ( ); private: bool mf_breadth_first_search ( ); // breadth first search from unpaired nodes in G1 bool mf_depth_first_search ( const size_t v ); // dfs w/ toggeling augmenting paths const vector < list < size_t > > & m_adj; // adjacency list for each node const vector < bool > & m_tag; // binary tag distinguishing partitions size_t npair; const size_t NIL; // special null vertex const size_t INF; // practically infinity distance vector < size_t > m_g1; // set of nodes with tag = true vector < size_t > m_dist; // dist from unpaired vertices in G1 vector < size_t > m_pair; }; map < size_t, size_t > HopcroftKarp::get_map ( ) { map < size_t, size_t > m; for ( size_t j = 0; j < m_pair.size( ); ++ j ) if ( m_pair[ j ] != NIL && m_tag[ j ]) m[ j ] = m_pair[ j ]; return m; } HopcroftKarp::HopcroftKarp ( const vector < list < size_t > > & adj, const vector < bool > & tag ): m_adj ( adj ), m_tag ( tag ), npair ( 0 ), NIL ( adj.size( )), INF ( adj.size( ) + 1 ), m_dist ( vector < size_t > ( adj.size( ) + 1, INF)), m_pair ( vector < size_t > ( adj.size( ), NIL )) // initially everything is paired with nil { assert ( m_adj.size() == m_tag.size() ); for ( size_t j = 0; j < tag.size( ); ++ j ) if ( tag[ j ] ) m_g1.push_back ( j ); while ( mf_breadth_first_search ( ) ) for ( vector < size_t >::const_iterator v = m_g1.begin( ); v != m_g1.end( ); ++ v ) if ( m_pair[ *v ] == NIL && mf_depth_first_search ( *v ) ) ++ npair; } bool HopcroftKarp::mf_breadth_first_search( ) { /* only nodes from g1 are queued */ queue < size_t > bfs_queue; /* initialize queue with all unpaired nodes from g1 */ for ( vector < size_t >::const_iterator v = m_g1.begin( ); v != m_g1.end( ); ++v ) if ( m_pair[ *v ] == NIL ) { m_dist[ *v ] = 0; bfs_queue.push ( *v ); } else m_dist[ *v ] = INF; m_dist[ NIL ] = INF; /* find all the shortest augmenting paths to node nil */ while ( ! bfs_queue.empty() ) { const size_t v = bfs_queue.front( ); bfs_queue.pop ( ); if ( m_dist[ v ] < m_dist[ NIL ] ) for ( list < size_t >::const_iterator u = m_adj[ v ].begin( ); u != m_adj[ v ].end( ); ++ u ) if ( m_dist[ m_pair[ * u ] ] == INF ) { m_dist[ m_pair[ * u ] ] = m_dist[ v ] + 1; bfs_queue.push ( m_pair[ * u ] ); } } return m_dist[ NIL ] != INF; } bool HopcroftKarp::mf_depth_first_search( const size_t v ) { if ( v == NIL ) return true; else { for ( list < size_t >::const_iterator u = m_adj[ v ].begin( ); u != m_adj[ v ].end( ); ++ u ) if ( m_dist[ m_pair[ *u ] ] == m_dist[ v ] + 1 && mf_depth_first_search( m_pair[ *u ] )) { /* * there is an augmenting path to nil from m_pair[ *u ] * and hence there is an augmenting path from v to u and * u to to nil; therefore v and u can be paired together */ m_pair [ *u ] = v; m_pair [ v ] = *u; return true; } m_dist[ v ] = INF; return false; } } /** * lazy all pairs shortest path in a tree with only one BFS * test case: 'book of evil' * codeforces.com/problemset/problem/337/D */ class All_Pairs_Tree_Shortest_Path { public: All_Pairs_Tree_Shortest_Path( const vector< list < size_t > > & adj ): n( adj.size( ) ), depth( vector < size_t > ( n, All_Pairs_Tree_Shortest_Path::INF ) ), parent( vector < size_t > ( n ) ), dist( vector < vector < unsigned short > > ( n ) ) { /* perform bfs from root node '0' and assign depth to each node */ /* XXX probably would be worth to set the root as node with highest degree */ queue< size_t > bfs_queue; bfs_queue.push( 0 ); depth[ 0 ] = 0; parent[ 0 ] = 0; while ( ! bfs_queue.empty( ) ) { const size_t u = bfs_queue.front( ); bfs_queue.pop( ); for ( list< size_t >::const_iterator j = adj[ u ].begin( ); j != adj[ u ].end( ); ++ j ) if ( depth[ u ] + 1 < depth[ *j ] ) { depth[ *j ] = depth[ u ] + 1; parent[ *j ] = u; bfs_queue.push( *j ); } } /* adjust pair-wise distance to zero along the diagonal */ for ( size_t j = 1; j < n; ++ j ) dist[ j ].resize( j, All_Pairs_Tree_Shortest_Path::INF ); } /* interface object function as to lazily look-up distances */ size_t operator( )( const size_t u, const size_t v ) { if ( u == v ) return 0; else if ( u < v) return (*this)( v, u ); else if ( dist[ u ][ v ] == All_Pairs_Tree_Shortest_Path::INF ) { if ( depth[ u ] < depth[ v ] ) /* u is in a lower level than v */ dist[ u ][ v ] = 1 + (*this)( u, parent[ v ]); else if ( depth[ v ] < depth[ u ] ) /* v is in a lower level than u */ dist[ u ][ v ] = 1 + (*this)( parent[ u ], v ); else /* u and v are at the same depth */ dist[ u ][ v ] = 2 + (*this)( parent[ u ], parent[ v ] ); } return dist[ u ][ v ]; } /* TODO populate; a method which populates pair-wise distances * and returns the matrix */ private: /* * constant infinity value for initializing distances * even though this is private it will be assigned outside of the class */ static const unsigned short INF; const size_t n; /* numbert of nodes in the tree */ vector < size_t > depth; /* distance to root node '0' */ vector < size_t > parent; /* parent of each node with root node '0' */ vector < vector < unsigned short > > dist; /* pair-wise shortest path distance */ }; const unsigned short All_Pairs_Tree_Shortest_Path::INF = numeric_limits< unsigned short >::max( ); /* * data-structure utility * ---------------------------------------------- */ template < class T, class Comp = less< T > > class Heap /* less< T > --> max-heap */ { typedef T value_type; typedef typename vector < value_type >::size_type size_type; public: /* * stackoverflow.com/questions/10387751 * possible work-around: a memebr pointer to m_val * TODO static/friend heapify ( val, & heap ) XXX O( n ) ?! * TODO implement insert iterator */ Heap(): m_val( vector < value_type >() ), m_comp( Comp() ) {} Heap( const Comp & comp ): m_val( vector< value_type >() ), m_comp( comp ){ } template < class InputIter > Heap ( InputIter first, InputIter last ): m_val ( vector < value_type > ( ) ), m_comp( Comp( ) ) { for ( ; first != last ; ++ first ) m_val.push_back ( * first ); make_heap( m_val.begin( ), m_val.end( ), m_comp ); } /*! * to avoid destroying heap property, front( ) * should always return a 'const' reference */ inline const value_type & front( ) const { return m_val.front( ); } inline bool empty( ) const { return m_val.empty( ); } inline size_type size( ) const { return m_val.size( ); } inline void push( const value_type & a ) { m_val.push_back( a ); push_heap( m_val.begin( ), m_val.end( ), m_comp ); } inline void pop( ) { pop_heap ( m_val.begin( ), m_val.end( ), m_comp ); m_val.pop_back( ); } // inline void swap( Heap< T, Comp> & other ) { m_val.swap( other.m_val ) }; // void sort( ) { sort_heap ( m_val.begin( ), m_val.end( ), m_comp ); } // template < class X, class Y > // friend ostream & operator<<( ostream & out, const Heap < X, Y> & heap ); private: vector < value_type > m_val; const Comp m_comp; }; /* * boost.org/doc/libs/1_54_0/libs/smart_ptr/shared_ptr.htm */ #if 1 < 0 template < class Type > class shared_ptr { typedef Type value_type; public: explicit shared_ptr ( value_type * p = NULL ) : ptr ( p ), count ( new size_t ( 1U ) ) { } shared_ptr ( const shared_ptr < value_type > & sp ): ptr ( sp.ptr ), count ( sp.count ) { ++ * count; } ~ shared_ptr ( ) { release( ); } bool operator== ( const shared_ptr < value_type > & sp ) { return ptr == sp.ptr; } bool operator!= ( const shared_ptr < value_type > & sp ) { return ptr != sp.ptr; } shared_ptr < value_type > & operator= ( const shared_ptr < value_type > & sp ) { if ( this != & sp && ptr != sp.ptr ) { release( ); ptr = sp.ptr; count = sp.count; ++ * count; } return * this; } value_type * operator-> ( ) { return ptr ; } value_type & operator* ( ) { return *ptr ; } const value_type * operator-> ( ) const { return ptr ; } const value_type & operator* ( ) const { return *ptr; } void swap ( shared_ptr < value_type > & sp ) { if ( this != &sp && ptr != sp.ptr ) { swap ( ptr, sp.ptr ); swap ( count, sp.count ); } } private: void release ( ) { /* stackoverflow.com/questions/615355 */ -- * count; if ( ! * count ) { delete count; delete ptr; count = NULL; ptr = NULL; } } value_type * ptr; size_t * count; }; #endif /*! * union find data structure with * - lazy unions * - union by rank * - path compression */ class UnionFind { public: UnionFind( const size_t n ): parent ( vector < size_t > ( n ) ), /* initialize each node as its own */ rank ( vector < size_t > ( n, 0 )) /* parent and set all the ranks to 0 */ { for ( size_t j = 0; j < n; ++ j ) parent[ j ] = j ; } inline size_t find( const size_t s ) { /* * perform path compresion and add shortcut * if parent[ s ] is not a root node */ const size_t p = parent[ s ]; return parent[ p ] == p ? p : parent[ s ] = find( p ) ; } inline void lazy_union ( size_t i, size_t j ) { /* unions should be done on root nodes */ i = find( i ); j = find( j ); if ( i != j ) { if ( rank [ i ] < rank[ j ] ) parent[ i ] = j; else { parent[ j ] = i; rank[ i ] += rank[ i ] == rank[ j ]; } } } private: vector < size_t > parent; vector < size_t > rank; }; // TODO XXX // template < class NumType > // unsigned num_hash_func ( const NumType & a ) // { // // XXX what will happen in case of overflow? // return static_cast < unsigned > ( a % 9973 ) % 9973 ; // } /* * XXX: HashMap: map< Key, T > data [ 9973 ] * data [ num_hash_func ( key ) ][ key ] */ /* * testing util * ---------------------------------------------- */ // TODO add a preprocessor which automatically includes the funciton name, or __line__ // and disables if not in debug mode /* prints the life length of the object when it goes out of scope */ class ScopeTimer { public: ScopeTimer ( const string & msg = "" ): tic ( clock ( )), m_msg( msg ) { }; ~ ScopeTimer ( ) { const clock_t toc = clock(); const uint64 dt = 1000L * ( toc - tic ) / CLOCKS_PER_SEC; const uint64 mil = dt % 1000L; const uint64 sec = ( dt / 1000L ) % 60L; const uint64 min = ( dt / 60000L ) % 60L; const uint64 hrs = ( dt / 3600000L ); cout << '\n' << m_msg << "\n\telapsed time: "; if ( hrs ) cout << hrs << " hrs, "; if ( min ) cout << min << " min, "; if ( sec ) cout << sec << " sec, "; cout << mil << " mil-sec\n"; } private: typedef unsigned long long int uint64; const clock_t tic; const string m_msg; }; class RandInt { public: RandInt ( int a = 0, int b = 100 ): m ( a ), f ( static_cast < double > ( b - a ) / RAND_MAX ) { } inline int operator() ( ) { return m + ceil ( f * rand( ) ); } private: const int m; const double f; }; class RandDouble { public: RandDouble ( double a = 0.0, double b = 1.0 ): m ( a ), f ( ( b - a ) / RAND_MAX ) { } inline double operator() ( ) { return m + f * rand( ); } private: const double m, f; }; class Noisy { public: Noisy ( string str ): msg ( str ) { cout << " Noisy ( " << msg << " )\t@ " << this << endl; } ~Noisy ( ) { cout << "~Noisy ( " << msg << " )\t@ " << this << endl; } void beep ( ) { cout << " beep ( " << msg << " )\t@ " << this << endl; } void beep ( ) const { cout << " const beep ( " << msg << " )\t@ " << this << endl; } private: const string msg; }; DECLARE ( Noisy ); /* * ---------------------------------------------- * ---------------------------------------------- */ /* * -- @@@ ------------------------------------------------- */ inline int minchar( const size_t j, const vector< int > & a ) { const auto n = a.size(); int k = 0; while( ( j + 1 < n && a[ j + 1 ] == k ) || ( j + 2 < n && a[ j + 2 ] == k )) ++ k; return k; } void probA() { size_t n; int k; cin >> n >> k; string str; cin >> str; vector< int > a( n ); transform(begin(str), end(str), a.rbegin(), bind(minus<char>(), placeholders::_1, 'a')); // first letter that can increase size_t j = 0; // find_if(begin(a), end(a), bind(less<int>(), placeholders::_1, k)) - begin(a); bool flag = false; while( j < n && ! flag ) { ++ a[ j ]; while( ( j + 1 < n && a[ j ] == a[ j + 1 ]) || ( j + 2 < n && a[ j ] == a[ j + 2 ] )) ++ a[ j ]; if( k < 1 + a[ j ] ) { ++ j; continue; } bool fail = false; for( size_t i = j; 0 < i && !fail; -- i ) { a[ i - 1 ] = minchar(i - 1, a); fail = k < 1 + a[ i - 1 ]; } flag = ! fail; } if( !flag ) cout << "NO"; else { for( auto iter = a.rbegin(); iter != a.rend(); ++ iter ) cout << (char)('a' + *iter); } } int main ( const int argc, char * argv [ ]) { probA(); // cout << setprecision( 10 ) return EXIT_SUCCESS; } /** * mislav.uniqpath.com/2011/12/vim-revisited/ * set encoding=utf-8 * %s/\(.\{60,70\}\) /\1\r/gc * %s/ / /gc * %s/10\([0-9]\{1,2\}\)/10^\1/gc */
1,700
CPP
alcohol = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"] n = int(input()) verify = 0 for i in range(n): inputDrinkOrAge = str(input()) if inputDrinkOrAge.isnumeric() == True: inputDrinkOrAge = int(inputDrinkOrAge) if inputDrinkOrAge < 18: verify += 1 else: if inputDrinkOrAge in alcohol: verify += 1 print("%d" % (verify))
1,000
PYTHON3
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; int n, dp[70][N]; long long a[N]; inline void umn(int &x, int y) { (x > y) && (x = y); } int main() { scanf("%d", &n); for (int i = (1); i <= (n); ++i) scanf("%lld", a + i); sort(a + 1, a + n + 1); for (int i = (1); i <= (n); ++i) a[i] = a[n] - a[i]; for (int i = (0); i <= (61); ++i) for (int j = (0); j <= (n); ++j) dp[i][j] = 1e9; dp[0][0] = 0; for (int i = (0); i <= (60); ++i) { int cnt = 0, cur = 0; sort(a + 1, a + n + 1, [&](long long x, long long y) { return (x & ((1ll << i) - 1)) > (y & ((1ll << i) - 1)); }); for (int j = (1); j <= (n); ++j) cnt += a[j] >> i & 1; for (int j = (0); j <= (n); ++j) { cur += a[j] >> i & 1; int A = cur, B = j - A, C = cnt - cur, D = n - j - C; umn(dp[i + 1][A + B + C], dp[i][j] + A + D); umn(dp[i + 1][A], dp[i][j] + B + C); } } printf("%d\n", dp[61][0]); return 0; }
3,100
CPP
#include <bits/stdc++.h> using namespace std; int main() { int n, i, j, m, zero = 0; cin >> n; if (n == 1) { cin >> m; cout << m; exit(0); } vector<int> pos, neg; for (i = 0; i < n; i++) { cin >> m; if (m == 0) zero++; else if (m > 0) pos.push_back(m); else neg.push_back(-m); } if (pos.size()) { for (i = 0; i < pos.size(); i++) { cout << pos[i] << " "; } } if (pos.size() == 0 && neg.size() <= 1 && zero > 0) { cout << "0"; exit(0); } if (neg.size() > 0) { sort(neg.begin(), neg.end()); for (i = neg.size() - 1; i >= 1; i--) { cout << -neg[i] << " "; } if (neg.size() % 2 == 0) { cout << -neg[0]; } } return 0; }
1,400
CPP
# your code goes here t=int(input()) for i in range(t): a,b,c,n=map(int,input().split()) if a==b==c: if n%3==0: print('YES') else: print('NO') else: d=max(a,b,c) n-=((d-a)+(d-b)+(d-c)) if n>=0: if n%3==0: print('YES') else: print('NO') else: print('NO')
800
PYTHON3
#include <bits/stdc++.h> int main() { int k, tk; long long n, ck, a; scanf("%I64d %d", &n, &k); long long menor = n; scanf("%I64d", &a); tk = 1; ck = n / a; menor = n % a; for (int i = 1; i < k; i++) { scanf("%I64d", &a); if (n % a < menor) { tk = i + 1; ck = n / a; menor = n % a; } } printf("%d %I64d", tk, ck); }
1,000
CPP
n = int(input()) seq = [int(x) for x in input().split()] # 坐标 #移偶数位置免费, 移奇数位置花1,求移到同一个坐标的最小花销 count = 0 for ele in seq: if ele%2 == 0: count += 1 print(min(count,(n-count)))
900
PYTHON3
import sys def Find(parent, x): if parent[x] != x: parent[x] = Find(parent, parent[x]) return parent[x] def Union(parent, rank, x, y): x_root = Find(parent, x) y_root = Find(parent, y) if x_root == y_root: return if rank[x_root] < rank[y_root]: parent[x_root] = y_root elif rank[x_root] > rank[y_root]: parent[y_root] = x_root else: parent[x_root] = y_root rank[y_root] += 1 hair_n, request_n, fav = map(int, sys.stdin.readline().split()) hair = [-1] + list(map(int, sys.stdin.readline().split())) parent_list = [i for i in range(hair_n + 1)] rank_list = [0 for i in range(hair_n + 1)] ans = 0 for i in range(1,hair_n): if hair[i] > fav and hair[i+1] > fav: Union(parent_list, rank_list, i, i+1) for i in range(1,hair_n+1): if i == parent_list[i] and hair[i] > fav: ans += 1 for r in range(request_n): query = list(map(int, sys.stdin.readline().split())) if query[0] == 1: growing_hair = query[1] change = query[2] prev_hair = hair[growing_hair] hair[growing_hair] += change if hair[growing_hair] > fav and prev_hair <= fav: ans += 1 if hair[growing_hair - 1] > fav: ans -= 1 if growing_hair < hair_n: if hair[growing_hair + 1] > fav: ans -= 1 else: print(ans)
1,300
PYTHON3
# Description of the problem can be found at http://codeforces.com/problemset/problem/472/A n = int(input()) a = 8 + n % 2 print(a, n- a)
800
PYTHON3
a = input() b = a.split() c = 0 i = 1 while i <= int(b[2]): c += i*int(b[0]) i+=1 print(c-int(b[1])) if c>int(b[1]) else print(0)
800
PYTHON3
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; int t; t = 1; for (int tc = 0; tc < t; tc++) { int n; cin >> n; map<int, int> mp; int arr[2 * n + 1][2 * n + 1]; map<int, pair<int, int> > mp_indx; vector<int> v; for (int i = 1; i <= 2 * n; i++) { for (int j = 1; j <= 2 * n; j++) arr[i][j] = -1; } for (int i1 = 2; i1 <= 2 * n; i1++) { for (int j = 1; j < i1; j++) { cin >> arr[i1][j]; mp_indx[arr[i1][j]] = make_pair(i1, j); v.push_back(arr[i1][j]); arr[j][i1] = arr[i1][j]; } } sort(v.begin(), v.end()); reverse(v.begin(), v.end()); vector<bool> vis(2 * n + 1, 0); for (int i = 0; i < v.size(); i++) { pair<int, int> p1 = mp_indx[v[i]]; if (!vis[p1.first] && !vis[p1.second]) { mp[p1.first] = p1.second; mp[p1.second] = p1.first; vis[p1.first] = 1; vis[p1.second] = 1; } } for (int i = 1; i <= 2 * n; i++) cout << mp[i] << " "; cout << "\n"; } return 0; }
1,300
CPP
#include <bits/stdc++.h> using namespace std; int N, M; struct element { int val, ind; element() {} bool operator<(const element& o) const { return val % M < o.val % M; } }; int main() { ios_base::sync_with_stdio(0), cin.tie(0); cin >> N; cin >> M; vector<element> a(N); vector<int> init(N); for (int i = 0; i < N; ++i) { cin >> a[i].val; init[i] = a[i].val; a[i].ind = i; } vector<int> amt_m(M, 0); vector<int> amt_add(N, 0); sort(a.begin(), a.end()); int j = 0; long long ans = 0; for (int i = 0; i < N; ++i) { while (j < a[i].val % M || amt_m[j % M] == N / M) ++j; amt_m[j % M]++; amt_add[a[i].ind] = (j - a[i].val % M) % M; ans += amt_add[a[i].ind]; } cout << ans << "\n"; for (int i = 0; i < N; ++i) { cout << amt_add[i] + init[i] << " "; } cout << endl; return 0; }
1,900
CPP
#include <bits/stdc++.h> using namespace std; template <class T, class L> bool smax(T& x, L y) { return x < y ? (x = y, 1) : 0; } template <class T, class L> bool smin(T& x, L y) { return x > y ? (x = y, 1) : 0; } const int maxn = 2e5 + 17, mod = 1e9 + 7; struct Seg { int lazy[maxn << 2], s[maxn << 2]; void build(int l = 0, int r = maxn, int id = 1) { s[id] = r - l; if (r - l < 2) return; int mid = l + r >> 1; build(l, mid, id << 1), build(mid, r, id << 1 | 1); } Seg() { fill(lazy, lazy + (maxn << 2), 1), build(); } void shift(int id) { lazy[id << 1] = (long long)lazy[id << 1] * lazy[id] % mod, lazy[id << 1 | 1] = (long long)lazy[id << 1 | 1] * lazy[id] % mod; s[id << 1] = (long long)s[id << 1] * lazy[id] % mod, s[id << 1 | 1] = (long long)s[id << 1 | 1] * lazy[id] % mod; lazy[id] = 1; } void add(int st, int en, int v, int l = 0, int r = maxn, int id = 1) { if (st <= l && r <= en) { s[id] = (long long)s[id] * v % mod, lazy[id] = (long long)lazy[id] * v % mod; return; } if (en <= l || r <= st) return; shift(id); int mid = l + r >> 1; add(st, en, v, l, mid, id << 1), add(st, en, v, mid, r, id << 1 | 1); s[id] = (s[id << 1] + s[id << 1 | 1]) % mod; } int get(int st, int en, int l = 0, int r = maxn, int id = 1) { if (st <= l && r <= en) return s[id]; if (en <= l || r <= st) return 0; shift(id); int mid = l + r >> 1; return (get(st, en, l, mid, id << 1) + get(st, en, mid, r, id << 1 | 1)) % mod; } void add(int l, int v) { add(l, l + 1, v); } int get(int l) { return get(l, l + 1); } } d, po, bad; struct Q { int t, p, v; } q[maxn]; int rev(int a) { int b = mod - 2, ans = 1; for (; b; b >>= 1) { if (b & 1) ans = (long long)ans * a % mod; a = (long long)a * a % mod; } return ans; } int tim, st[maxn], en[maxn], nq, deg[maxn], cnt = 1; vector<int> g[maxn]; void dfs(int v = 0) { st[v] = tim++; for (auto u : g[v]) dfs(u); en[v] = tim; } void DeemoLovesInit() { int tmp; cin >> tmp >> nq; po.add(0, tmp); bad.add(0, 0); fill(deg, deg + maxn, 1); for (int i = 0; i < nq && cin >> q[i].t; i++) if (q[i].t == 1) cin >> q[i].p >> q[i].v, g[--q[i].p].push_back(cnt++); else cin >> q[i].v, q[i].v--; dfs(); cnt = 1; } int main() { ios::sync_with_stdio(0), cin.tie(); DeemoLovesInit(); for (int i = 0, t = q[i].t, v = q[i].v, p = q[i].p; i < nq; i++, t = q[i].t, v = q[i].v, p = q[i].p) if (t == 1) { po.add(st[cnt], (long long)rev(po.get(st[cnt])) * v % mod * d.get(st[p]) % mod); bad.add(st[cnt], 0); deg[p]++; d.add(st[p], en[p], (long long)rev(deg[p] - 1) * deg[p] % mod); po.add(st[p], en[p], (long long)rev(deg[p] - 1) * deg[p] % mod); bad.add(st[p], en[p], (long long)rev(deg[p] - 1) * deg[p] % mod); cnt++; } else { cout << (long long)(po.get(st[v], en[v]) - bad.get(st[v], en[v]) + mod) % mod * rev(d.get(st[v])) % mod * deg[v] % mod << '\n'; } return 0; }
2,600
CPP
n=int(input()) v=list(map(int,input().split())) last_odd=-1 last_even=-1 count0,count1=0,0 for i in range(n): if(v[i]%2==1): count1+=1 last_odd=i else: count0+=1 last_even=i if(count0==1): print(last_even+1) else: print(last_odd+1)
1,300
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { string s; long long n, p, i, sum, r, j; vector<long long> v; vector<char> l, m; cin >> s; n = s.length(); p = 1; for (i = 0; i < n - 1; i++) { if (s[i] == s[i + 1]) { p++; } else { v.push_back(p); p = 1; } } v.push_back(p); sum = 0; for (i = 0; i < v.size(); i++) { if (v[i] > 2 && v[i + 1] < 2 && i < v.size() - 1) { l.push_back(s[sum]); l.push_back(s[sum]); sum += v[i]; } else if (v[i] >= 2 && v[i + 1] >= 2 && i < v.size() - 1) { l.push_back(s[sum]); l.push_back(s[sum]); l.push_back(s[sum + v[i]]); sum += v[i] + v[i + 1]; i++; } else if (v[i] >= 2) { l.push_back(s[sum]); l.push_back(s[sum]); sum += v[i]; } else { l.push_back(s[sum]); sum++; } } sum = n - 1; for (i = v.size() - 1; i >= 0; i--) { if (v[i] > 2 && v[i - 1] < 2 && i >= 1) { m.push_back(s[sum]); m.push_back(s[sum]); sum -= v[i]; } else if (v[i] >= 2 && v[i - 1] >= 2 && i >= 1) { m.push_back(s[sum]); m.push_back(s[sum]); m.push_back(s[sum - v[i]]); sum -= v[i] + v[i - 1]; i--; } else if (v[i] >= 2) { m.push_back(s[sum]); m.push_back(s[sum]); sum -= v[i]; } else { m.push_back(s[sum]); sum--; } } if (l.size() >= m.size()) { for (i = 0; i < l.size(); i++) { cout << l[i]; } } else { reverse(m.begin(), m.end()); for (i = 0; i < m.size(); i++) { cout << m[i]; } } }
1,400
CPP
#include <bits/stdc++.h> using namespace std; bool sortbysec(pair<long long, long long> &a, pair<long long, long long> &b) { return a.second > b.second; } int main() { long long int n, m, i, j, w, sum = 0, mn, ind, t, s3 = 0, b, c = 0, l, d, r, ans, x, y, mx = -1, k; cin >> n >> m; vector<pair<long long, long long> > v; pair<long long, long long> z; for (i = 0; i < m; i++) { cin >> x >> y; z = make_pair(x, y); v.push_back(z); } sort(v.begin(), v.end(), sortbysec); for (i = 0; i < v.size(); i++) { if (v[i].first <= n - sum) { c += (v[i].first) * (v[i].second); sum += v[i].first; } else { c += (n - sum) * (v[i].second); break; } } cout << c; }
900
CPP
#include <bits/stdc++.h> using namespace std; bool dig[15]; vector<int> divs; vector<int> pows; int n, k = 0; bool try_a(int a) { while (a > 0) { if (dig[a % 10]) { return true; } a /= 10; } return false; } void go(int p, int v) { if (p == divs.size()) { if (try_a(v)) { k++; } } else { go(p + 1, v); for (int i = 0; i < pows[p]; i++) { v *= divs[p]; go(p + 1, v); } } } void make_divs(int n) { for (int i = 2; i * i <= n; i++) { if (!(n % i)) { int p = 0; divs.push_back(i); while (!(n % i)) { n /= i; p++; } pows.push_back(p); } } if (n > 1) { divs.push_back(n); pows.push_back(1); } } int main() { cin >> n; make_divs(n); while (n > 0) { dig[n % 10] = true; n /= 10; } go(0, 1); cout << k << "\n"; return 0; }
1,300
CPP
#include <bits/stdc++.h> const int MAX_N = 2e5 + 5; int n, m, dsu[MAX_N], ans; int root(int x) { if (dsu[x] < 0) return x; else return dsu[x] = root(dsu[x]); } void connect(int x, int y) { x = root(x); y = root(y); if (x == y) return; if (x < y) std::swap(x, y); dsu[x] += dsu[y]; dsu[y] = x; } int main() { memset(dsu, 0xff, sizeof(dsu)); scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i) { int u, v; scanf("%d%d", &u, &v); connect(u, v); } for (int i = 1; i <= n;) { int p = root(i); for (int j = i + 1; j <= p; ++j) if (root(i) != root(j)) { ++ans; connect(i, j); p = std::max(p, root(i)); } i = p + 1; } printf("%d\n", ans); }
1,700
CPP
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") using namespace std; using ll = long long; using ii = pair<int, int>; const int N = 1e5 + 5, LG = 19, MOD = 998244353; const int SQ = 500; const long double EPS = 1e-7; ll k, q, f[6], n; ll dp[1000000]; void add(ll sz, ll val) { for (ll i = 999999; i >= sz; --i) dp[i] = max(dp[i], dp[i - sz] + val); } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> k; for (ll i = 0; i < 6; i++) cin >> f[i]; memset(dp, -63, sizeof dp); dp[0] = 0; cin >> q; ll l = 1, tot = (k - 1) * 3; while (l <= tot) { for (ll i = 0, cur = 3 * l; i < 6; i++, cur *= 10) add(cur, l * f[i]); tot -= l; l <<= 1; } for (ll i = 0, cur = 3 * tot; i < 6; i++, cur *= 10) add(cur, tot * f[i]); for (ll i = 0, cur = 1; i < 6; i++, cur *= 10) for (ll j = 999999; j; --j) for (ll k = 0; k < 10 && cur * k <= j; k++) dp[j] = max(dp[j], dp[j - cur * k] + (k % 3 == 0) * (k / 3 * f[i])); while (q--) { ll x; cin >> x; cout << dp[x] << '\n'; } return 0; }
2,900
CPP
#include <bits/stdc++.h> using namespace std; const int N = 20; int n, t, dor, ans, mark[N], low_bit[(1 << N)], m[N][N], dp[(1 << N)]; int F[N][(1 << N)]; string a, b; vector<int> g[N]; void make() { for (int mask = 1; mask < (1 << N); mask++) for (int i = 0; i < N; i++) if ((mask % (1 << (i + 1)) >= (1 << i))) { low_bit[mask] = i; return; } } void clear() { ans = N; fill(mark, mark + N, 0); for (int i = 0; i < N; i++) g[i].clear(); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) m[i][j] = 0; for (int i = 0; i < n; i++) if (a[i] != b[i]) { g[a[i] - 'a'].push_back(b[i] - 'a'), g[b[i] - 'a'].push_back(a[i] - 'a'); m[a[i] - 'a'][b[i] - 'a'] = 1; } } void dfs(int x) { mark[x] = 1; for (int i = 0; i < g[x].size(); i++) if (!mark[g[x][i]]) dfs(g[x][i]); } void solve(int x, int mask) { if ((mask % (1 << (x + 1)) >= (1 << x))) return; for (int i = 0; i < N; i++) if ((mask % (1 << (i + 1)) >= (1 << i))) { F[x][mask] = (F[x][mask - (1 << i)] || m[x][i]); return; } } void calc(int mask) { dp[mask] = N * N; for (int i = 0; i < N; i++) if ((mask % (1 << (i + 1)) >= (1 << i))) dp[mask] = min(dp[mask], dp[mask - (1 << i)] + F[i][mask - (1 << i)]); ; } void do_it() { for (int i = 0; i < N; i++) for (int mask = 1; mask < (1 << N); mask++) solve(i, mask); for (int i = 1; i < (1 << N); i++) calc(i); } void solve() { clear(); for (int i = 0; i < N; i++) if (!mark[i]) dfs(i), ans--; do_it(); cout << ans + dp[(1 << N) - 1] << '\n'; } int main() { make(); cin >> t; while (t--) { cin >> n; cin >> a >> b; solve(); } }
1,700
CPP
n=int(input()) i=5 j=1 while(n//i>=1): x=n//i if n//(i+j*2*5)<1: j=2*j break j=2*j i=i+j*5 if n>=5: d=n-i else: d=n if d==0: print('Howard') elif d>=1 and d<=j: print('Sheldon') elif d>=j+1 and d<=2*j: print('Leonard') elif d>=2*j+1 and d<=3*j: print('Penny') elif d>=3*j+1 and d<=4*j: print('Rajesh') elif d>=4*j+1 and d<=5*j: print('Howard')
1,100
PYTHON3
x=input() y=list() z="" y=x.split('+') y.sort() j=0 for i in range(len(y)*2-1): if i %2==0: z+=(y[j]) j+=1 else : z+=('+') print(z)
800
PYTHON3
t = int(input()) for ii in range(t): l, r = map(int, input().split()) if r % 2 == 0: print(r // 2, r) else: print(r // 2, r - 1)
800
PYTHON3
n = int(input()) s = input() ans = 0 for i in range(1,len(s)): if s[i-1]!=s[i]: continue else: ans+=1 print(ans)
800
PYTHON3
#include <bits/stdc++.h> using namespace std; int n; int col[5005]; vector<int> adj[5005]; bool vis[5005]; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); int mn = 1000000000; for (int i = 1; i < n; i++) { mn = min(mn, a[i] - a[i - 1]); } cout << mn << endl; } void querySolve() { int t; cin >> t; while (t--) { solve(); } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); querySolve(); }
800
CPP
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization("unroll-loops") using namespace std; const long long mod = 1e9 + 7; void preCal() {} void solve() { long long n, m, k; cin >> n >> m >> k; if (n % m == 0) { for (long long i = 1; i <= k; i++) { long long start = 1, val = n / m; for (long long j = 1; j <= m; j++) { cout << val << ' '; for (long long k = 1; k <= val; k++) { cout << start++ << ' '; } cout << '\n'; } } return; } long long block1 = n / m; long long freq1 = m - (n % m); long long block2 = (n + m - 1) / m; long long freq2 = m - freq1; long long turn = 1; for (long long i = 1; i <= k; i++) { set<long long> s; for (long long i = 1; i <= n; i++) { s.insert(i); } for (long long j = 1; j <= freq2; j++) { cout << block2 << ' '; for (long long k = 1; k <= block2; k++) { s.erase(turn); cout << turn++ << ' '; if (turn > n) { turn = 1; } } cout << '\n'; } for (long long j = 1; j <= freq1; j++) { cout << block1 << ' '; for (long long k = 1; k <= block1; k++) { cout << (*s.begin()) << ' '; s.erase(s.begin()); } cout << '\n'; } } cout << '\n'; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); preCal(); long long t = 1; cin >> t; for (long long i = 1; i <= t; i++) { solve(); } }
2,000
CPP
#include <bits/stdc++.h> using namespace std; int main() { string s, sum; int n, k; cin >> n >> k >> s; for (long long i = 0; i < n; i++) { if ('z' - s[i] > s[i] - 'a') { sum += (s[i] + min('z' - s[i], k)); k -= min('z' - s[i], k); } else { sum += (s[i] - min(s[i] - 'a', k)); k -= min(s[i] - 'a', k); } } if (k) cout << -1; else cout << sum; }
1,300
CPP
#include <bits/stdc++.h> const int N = 1e6 + 10; const int B = 113; const int HMOD = 1e9 + 9; int n; char a[N], b[N]; inline int ord(char ch) { if (ch == 'N') return 0; else if (ch == 'S') return 1; else if (ch == 'E') return 2; else return 3; } int main() { int i, x, y, pb; scanf("%d", &n); scanf("%s %s", a + 1, b + 1); n--; x = y = 0; pb = 1; for (i = int(n); i; i--) { x = (x + 1LL * pb * (ord(a[i]) ^ 1)) % HMOD; y = (1LL * y * B + ord(b[i])) % HMOD; if (x == y) { printf("NO\n"); return 0; } pb = 1LL * pb * B % HMOD; } printf("YES\n"); return 0; }
2,500
CPP
#include <bits/stdc++.h> using namespace std; int c[1111]; int main() { int N, M, u, v; int ans = 0; cin >> N >> M; for (int i = 0; i < N; i++) scanf("%d", c + i); for (int i = 0; i < M; i++) { scanf("%d%d", &u, &v); u--, v--; ans += min(c[u], c[v]); } cout << ans << endl; return 0; }
1,400
CPP
for t in range (int(input())): n,sum1=map(int,input().split()) l1=list(map(int,input().split())) l1.sort() l2=[] team=0 if(sum(l1)<sum1): print(0) continue while(len(l1)>0): l2.append(l1[len(l1)-1]) l1.pop(len(l1)-1) if(min(l2)*len(l2)>=sum1): team+=1 l2=[] print(team)
1,400
PYTHON3
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) d=dict() for i in range(n): x=bin(a[i]).replace("0b","") d.setdefault(len(x),0) d[len(x)]+=1 ans=0 for i in d: ans+=(d[i]*(d[i]-1)//2) print(ans)
1,200
PYTHON3
#include <bits/stdc++.h> using namespace std; int n; map<long long, long long> acc; long long u, v, w; int main() { cin >> n; for (int i = 0; i < n; i++) { int type; cin >> type; if (type == 1) { cin >> u >> v >> w; while (u != v) { if (u < v) { acc[v] += w; v /= 2; } else { acc[u] += w; u /= 2; } } } else { cin >> u >> v; w = 0; while (u != v) { if (u < v) { w += acc[v]; v /= 2; } else { w += acc[u]; u /= 2; } } cout << w << '\n'; } } return 0; }
1,500
CPP
#include <bits/stdc++.h> using namespace std; const int N = 222222; int n; vector<int> ppl[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); set<pair<int, int> > bbids; cin >> n; for (int i = 0; i < n; i++) { int p, a; cin >> p >> a; if (ppl[p].size()) { bbids.erase(bbids.find(make_pair(ppl[p].back(), p))); } ppl[p].push_back(a); bbids.insert(make_pair(a, p)); } int q; cin >> q; while (q--) { vector<pair<int, int> > deleted; int k; cin >> k; for (int i = 0; i < k; i++) { int p; cin >> p; if (ppl[p].size() == 0) { continue; } pair<int, int> bid = make_pair(ppl[p].back(), p); deleted.push_back(bid); bbids.erase(bbids.find(bid)); } if (bbids.size() == 0) { cout << "0 0" << endl; } else { pair<int, int> bid = *bbids.rbegin(); set<pair<int, int> >::iterator it = bbids.end(); --it; bbids.erase(it); int a = bid.first, p = bid.second; if (bbids.size() == 0) { cout << p << " " << ppl[p].front() << endl; } else { int la = bbids.rbegin()->first; int l = 0, r = ppl[p].size() - 1, id; while (r - l > 1) { int m = l + r >> 1; int val = ppl[p][m]; if (val < la) { l = m + 1; } else { r = m; } } if (ppl[p][l] > la) { id = l; } else { id = r; } cout << p << " " << ppl[p][id] << endl; } bbids.insert(bid); } for (int i = 0; i < deleted.size(); i++) { bbids.insert(deleted[i]); } } return 0; }
2,000
CPP
#include <bits/stdc++.h> struct trans_buff { long long x, v; trans_buff(long long x, long long v) : x(x), v(v) {} }; long long l[400010], q[400010], dp[400010 << 2]; std ::vector<trans_buff> e[400010 << 2]; std ::set<std ::pair<long long, long long> > H; int main() { int n; long long g, r, gr; scanf("%d%lld%lld", &n, &g, &r); gr = g + r; long long base(0); for (int i = 1; i <= n + 1; ++i) { scanf("%lld", l + i); base += l[i]; } int Q; scanf("%d", &Q); for (int i = 1; i <= Q; ++i) { scanf("%lld", q + i); H.insert(std ::make_pair(q[i] % gr, i)); } long long cur(0); for (int i = 1; i <= n; ++i) { cur = (cur + l[i]) % gr; long long tmp = (g + gr - cur) % gr; std ::set<std ::pair<long long, long long> >::iterator itl = H.lower_bound( std ::make_pair( tmp, 0)), itr; for (itr = itl; itr != H.end() && itr->first - tmp < r; ++itr) { e[Q + i].push_back(trans_buff(itr->second, r - (itr->first - tmp))); } if (itl != H.end()) H.erase(itl, itr); if (tmp + r > gr) { for (itr = H.begin(); itr != H.end() && itr->first + (gr - tmp) < r; ++itr) { e[Q + i].push_back( trans_buff(itr->second, r - (itr->first + (gr - tmp)))); } H.erase(H.begin(), itr); } H.insert(std ::make_pair((gr - cur) % gr, Q + i)); } for (int i = Q + n; i > Q; --i) for (std ::vector<trans_buff>::iterator it = e[i].begin(); it != e[i].end(); ++it) { dp[it->x] = dp[i] + it->v; } for (int i = 1; i <= Q; ++i) printf("%lld\n", base + dp[i] + q[i]); }
2,800
CPP
t = int(input()) for i in range(t): b, p, f = [int(i) for i in input().split()] maxb = b//2 h, c = [int(i) for i in input().split()] if h < c: h, c = c, h p, f = f, p hk = min(maxb, p) money = h * hk + c * min(maxb - hk, f) print(money)
800
PYTHON3
#include <bits/stdc++.h> using namespace std; int lst[100005], to[200005], pre[200005], tot; double x[100005], y[100005], sumx, sumy, ans; int sz[100005], n; inline void add_edge(int u, int v) { to[tot] = v; pre[tot] = lst[u]; lst[u] = tot++; } void dfs(int u, int fa = -1) { sz[u] = 1; for (int i = lst[u]; ~i; i = pre[i]) { if (to[i] == fa) continue; int v = to[i]; dfs(v, u); sz[u] += sz[v]; x[u] += x[v]; ans += sz[v] * x[v] * y[u]; } ans += (n - sz[u]) * (sumx - x[u]) * y[u]; } int main() { memset(lst, -1, sizeof(lst)); scanf("%d", &n); for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); add_edge(--u, --v); add_edge(v, u); } for (int i = 0; i < n; i++) { scanf("%lf%lf", x + i, y + i); sumx += x[i]; sumy += y[i]; } dfs(0); printf("%.12lf\n", ans / sumx / sumy); return 0; }
2,500
CPP
#include <bits/stdc++.h> using namespace std; int a[6], b[6], n; int main() { cin >> n; int x; for (int i = 1; i <= n; ++i) { cin >> x; ++a[x]; } for (int i = 1; i <= n; ++i) { cin >> x; ++b[x]; } x = 0; int y = 0, ok = 1; for (int i = 1; i <= 5; ++i) { if ((a[i] + b[i]) % 2 != 0) { ok = 0; i = 6; } if (a[i] - b[i] > 0) { x += a[i] - b[i]; } else { y += b[i] - a[i]; } } if (x == y && ok) { cout << x / 2; } else { cout << -1; } return 0; }
1,000
CPP
#include <bits/stdc++.h> using namespace std; int main() { long int n, i, Min = 10E6, x, y, req, total = 0, flag = 0; map<long int, long int> M1, M2; map<long int, long int>::iterator it, it1; cin >> n; if (n % 2 == 0) req = n / 2; else req = n / 2 + 1; for (i = 0; i < n; i++) { cin >> x >> y; if ((it = M1.find(x)) != M1.end()) it->second++; else M1.insert(pair<long int, long int>(x, 1)); if (x != y) { if ((it = M2.find(y)) != M2.end()) it->second++; else M2.insert(pair<long int, long int>(y, 1)); } } for (it1 = M1.begin(); it1 != M1.end(); it1++) if (it1->second >= req) { flag = 1; break; } if (flag == 0) { for (it1 = M1.begin(); it1 != M1.end(); it1++) { if ((it = M2.find(it1->first)) != M2.end()) if (it->second + it1->second >= req && req - it1->second < Min) { flag = 2; Min = req - it1->second; } } if (Min == 10E6) for (it1 = M2.begin(); it1 != M2.end(); it1++) if (it1->second >= req && req < Min) { flag = 2; Min = req; break; } } if (flag == 1) cout << 0; else if (flag == 2) cout << Min; else cout << -1; return 0; }
1,500
CPP
#include <bits/stdc++.h> int main() { long long int N, M, e, i, j, k, a, b, c, d, f, x, y, z, m, n, p, s, T; scanf("%lld", &N); for (i = 0; i < N; i++) { scanf("%lld %lld %lld", &a, &b, &c); s = 0; if ((b / 2) < a) { x = (b / 2) * 3; } else { x = a * 3; } if ((c / 2) < b) { y = (c / 2) * 3; } else { y = b * 3; } s = s + y; c = c - ((y / 3) * 2); b = b - (y / 3); if ((b / 2) < a) { d = (b / 2) * 3; } else { d = a * 3; } s += d; printf("%lld\n", s); } return 0; }
800
CPP
scores = {} arr = [] for _ in range(int(input().strip())): name, score = input().strip().split() score = int(score) arr.append((name, score)) if name not in scores.keys(): scores[name] = score else: scores[name] += score max_score = max(scores.values()) new = {} for name, score in arr: if name not in new.keys(): new[name] = score else: new[name] += score if new[name] >= max_score and scores[name] == max_score: print(name) break
1,500
PYTHON3
#include <bits/stdc++.h> using namespace std; namespace IO { void setIn(string s) { freopen(s.c_str(), "r", stdin); } void setOut(string s) { freopen(s.c_str(), "w", stdout); } void setIO(string s = "") { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); if (s.size()) { setIn(s + ".inp"); setOut(s + ".out"); } else { } } } // namespace IO using namespace IO; namespace Function { template <typename T1, typename T2> void amax(T1 &a, T2 b) { assert(!(typeid(a).name() == typeid(int).name() && typeid(b).name() == typeid(long long).name())); if (a < b) a = b; } template <typename T1, typename T2> void amin(T1 &a, T2 b) { if (a > b) a = b; } template <typename T> void compress(T &a) { sort(a.begin(), a.end()); a.resize(unique(a.begin(), a.end()) - a.begin()); } template <typename T1, typename T2, typename T3> int position(T1 Begin, T2 sz, T3 val) { return lower_bound(Begin, Begin + sz, val) - Begin; } template <typename T> long long sqr(T x) { return 1LL * x * x; } template <typename T1, typename T2> long long GCD(T1 a, T2 b) { return b == 0 ? a : GCD(b, a % b); } template <typename T1, typename T2> long long LCM(T1 a, T2 b) { return 1LL * a / GCD(a, b) * b; } } // namespace Function using namespace Function; namespace Output { void print(int x) { cout << x << "\n"; } void print(unsigned int x) { cout << x << "\n"; } void print(long unsigned int x) { cout << x << "\n"; } void print(long long x) { cout << x << "\n"; } void print(unsigned long long x) { cout << x << "\n"; } void print(float x) { cout << x << "\n"; } void print(double x) { cout << x << "\n"; } void print(long double x) { cout << x << "\n"; } void print(char x) { cout << x << "\n"; } void print(char *x) { cout << x << "\n"; } void print(unsigned char x) { cout << x << "\n"; } void print(const char *x) { cout << x << "\n"; } void print(string x) { cout << x << "\n"; } void print(bool x) { cout << x << "\n"; } template <class T, class... Ts> void print(T t, Ts... ts) { cout << t << " "; print(ts...); } template <typename T1, typename T2> void print(pair<T1, T2> a) { print(a.first, a.second); } template <typename T> void print(T a) { for (auto it : a) { print(it); } } template <class T, class... Ts> void prine(T t, Ts... ts) { print(t, ts...); exit(0); } } // namespace Output using namespace Output; const int dx[] = {1, -1, 0, 0}; const int dy[] = {0, 0, 1, -1}; const int INF = 1e9; const long long INFL = 1e18; const int MOD = 1e9 + 7; const int N = 3e5 + 10; int l[N], r[N]; int main() { setIO(); int T; cin >> T; while (T--) { int n; cin >> n; for (int i = 1; i <= n; i++) { l[i] = n + 1; } vector<int> a; for (int i = 1; i <= n; i++) { int x; cin >> x; a.push_back(x); amin(l[x], i); r[x] = i; } compress(a); int cur = 1; int res = (int)a.size() - 1; for (int i = 1; i < (int)a.size(); i++) { if (r[a[i - 1]] < l[a[i]]) { cur++; } else { cur = 1; } amin(res, (int)a.size() - cur); } print(res); } return 0; }
2,000
CPP
n = int(input()) ans = 2*n-1 while 2*n-3 > 0: n-= 1 ans += 4*n-2 print(ans)
800
PYTHON3
H,L=map(int,input().split()) x=((L*L)-(H*H))/(2*H) print(x)
1,000
PYTHON3
t = int(input()) for _ in range(t): n = int(input()) s = input() cnt = 0 for i in range(0, n): if s[i-1] == '-' or s[i] == '-': cnt += 1 if len(set(s)) == 1: cnt = n elif len(set(s)) == 2: if '-' in set(s): cnt = n print(cnt)
1,200
PYTHON3
#include <bits/stdc++.h> using namespace std; using ll = long long; inline int read(); const int M = 500016, MOD = 1000000007; int save[M]; int main(void) { int n = read(); int ax = read(), ay = read(); int bx = read(), by = read(); int cx = read(), cy = read(); printf("%s\n", (bx - ax) * (cx - ax) > 0 && (by - ay) * (cy - ay) > 0 ? "YES" : "NO"); return 0; } inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; }
1,000
CPP
i=0; lit=list() n=int(input()) for j in range(n): lit.append(str(2*n+i)) i+=1 print(' '.join(lit))
1,200
PYTHON3
#include <bits/stdc++.h> using namespace std; int n, a[5005][5005], b[5005][5005], res; string s; void Solve() { cin >> s; n = s.size(); s = " " + s; for (long long i = 1, _b = n; i <= _b; i++) { long long cur = 0; bool ok = true; for (long long j = i, _b = n; j <= _b; j++) { if (s[j] == ')') cur--; else cur++; if (cur < 0) ok = false; a[i][j] = ok; } } for (long long j = 1, _b = n; j <= _b; j++) { long long cur = 0; bool ok = true; for (long long i = j, _b = 1; i >= _b; i--) { if (s[i] == '(') cur--; else cur++; if (cur < 0) ok = false; b[i][j] = ok; } } for (long long i = 1, _b = n; i <= _b; i++) for (long long j = i + 1; j <= n; j += 2) { if (a[i][j] && b[i][j]) res++; } cout << res; } int main() { ios::sync_with_stdio(0); cin.tie(0); int Test_numbers = 1; while (Test_numbers--) Solve(); return 0; }
1,800
CPP
n=int(input()) m=int(input()) if n>=27: print(m) else: k=2**n print(m%k)
900
PYTHON3
#include <bits/stdc++.h> using namespace std; const int max_n = 555555; int n, ans, p[max_n], parent[max_n]; vector<int> g[max_n], all; vector<pair<int, int> > a[max_n]; set<pair<int, int> > q, q2; void dfs(int v, int pp) { p[v] = pp; all.push_back(v); for (int i = 0; i < g[v].size(); ++i) { if (g[v][i] != pp) { dfs(g[v][i], v); } } } int find_set(int v) { if (v == parent[v]) { return v; } return parent[v] = find_set(parent[v]); } void union_set(int v1, int v2) { v1 = find_set(v1); v2 = find_set(v2); if (a[v1].size() < a[v2].size()) { swap(v1, v2); } copy(a[v2].begin(), a[v2].end(), back_inserter(a[v1])); parent[v2] = v1; } int main() { scanf("%d", &n); for (int i = 0; i < 2; ++i) { for (int j = 1; j < n; ++j) { int u, v; scanf("%d%d", &u, &v); if (u > v) { swap(u, v); } if (i == 0) { q.insert(make_pair(u, v)); g[u].push_back(v); g[v].push_back(u); } else { q2.insert(make_pair(u, v)); if (!q.count(make_pair(u, v))) { ++ans; a[u].push_back(make_pair(u, v)); a[v].push_back(make_pair(u, v)); } } } } printf("%d\n", ans); for (int i = 1; i <= n; ++i) { parent[i] = i; } dfs(1, -1); q.clear(); for (int i = all.size() - 1; i > 0; --i) { int v1 = all[i]; int v2 = p[v1]; if (v1 > v2) { swap(v1, v2); } if (q2.count(make_pair(v1, v2))) { union_set(v1, v2); } else { int v = find_set(all[i]); pair<int, int> p; while (true) { p = a[v].back(); a[v].pop_back(); if (p.first > p.second) { swap(p.first, p.second); } if (!q.count(p)) { break; } } q.insert(p); printf("%d %d %d %d\n", v1, v2, p.first, p.second); union_set(p.first, p.second); } } return 0; }
3,200
CPP
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; vector<string> v; string s; cin >> n >> s; long long sq; if (n > 2) { cout << "YES" << endl; cout << 2 << endl; cout << s[0] << " "; for (int i = 1; i < n; i++) { cout << s[i]; } cout << endl; } else { if (n == 1) { cout << "YES" << endl; cout << 1 << endl; cout << s << endl; } else { if (s[0] >= s[1]) { cout << "NO" << endl; } else { cout << "YES" << endl; cout << 2 << endl; cout << s[0] << " " << s[1] << endl; } } } } }
900
CPP
n = int(input()) A = list(map(int, input().split())) print("YES" if all(abs(a - b) <= 1 for a, b in zip(A,A[1:])) else "NO")
1,600
PYTHON3
#include <bits/stdc++.h> using namespace std; template <typename A, typename B> ostream &operator<<(ostream &s, const pair<A, B> &p) { return s << "(" << p.first << "," << p.second << ")"; } template <typename T> ostream &operator<<(ostream &s, const vector<T> &c) { s << "[ "; for (auto it : c) s << it << " "; s << "]"; return s; } const int MAXN = 514; const string SA = "bac"; int N, M; bool arr[MAXN][MAXN]; int color[MAXN]; bool calc() { for (int i = 0; i < N; i++) arr[i][i] = 1; int v = -1; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (!arr[i][j]) v = i; if (v != -1) { set<int> stc, sta; for (int i = 0; i < N; i++) if (!arr[v][i]) stc.insert(i); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (!arr[i][j] && !stc.count(i)) sta.insert(i); for (auto u : stc) color[u] = 2; for (auto u : sta) color[u] = 1; for (auto w : sta) for (auto u : stc) if (arr[w][u]) return false; if ((int)(sta.size() * stc.size()) != N * (N - 1) / 2 - M) return false; } return true; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> N >> M; for (int i = 0; i < M; i++) { int a, b; cin >> a >> b; a--; b--; arr[a][b] = arr[b][a] = true; } bool res = calc(); if (res) { cout << "Yes" << endl; for (int i = 0; i < N; i++) cout << SA[color[i]]; cout << endl; } else cout << "No" << endl; return 0; }
1,800
CPP
#include <bits/stdc++.h> using namespace std; const int N = 1000 + 10; int n, ex, ey, px, py; int dir[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}}; bool check(int x, int y) { if (x == ex && y == ey) return true; return false; } int main() { cin >> ex >> ey; int x = 0, y = 0; int k = 0, num = 0; while (1) { if (check(x, y)) break; for (int i = 0; i < 4; ++i, num++) { if (i % 2 == 0) k++; switch (i) { case 0: px = x, x += k; if (px <= ex && x >= ex && y == ey) { cout << num << endl; return 0; } break; case 1: py = y, y += k; if (x == ex && py <= ey && y >= ey) { cout << num << endl; return 0; } break; case 2: px = x, x -= k; if (y == ey && px >= ex && x <= ex) { cout << num << endl; return 0; } break; case 3: py = y, y -= k; if (x == ex && py >= ey && y <= ey) { cout << num << endl; return 0; } break; } } } cout << num << endl; return 0; }
1,400
CPP
q = int(input()) for _ in range(q): n = int(input()) if n < 3: print(4-n) elif n % 2 == 0: print(0) else: print(1)
800
PYTHON3
#include <bits/stdc++.h> using namespace std; int q[4], qq[4]; vector<int> cl; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> q[0] >> q[1] >> q[2] >> q[3]; int tot = q[0] + q[1] + q[2] + q[3]; for (int st = 0; st < 4; ++st) { if (q[st] == 0) continue; memcpy(qq, q, sizeof(q)); cl.clear(); int cur = st; --qq[cur]; cl.push_back(cur); bool ok = true; for (int i = 0; i < tot - 1; ++i) { if (cur - 1 >= 0 && qq[cur - 1]) { --cur; cl.push_back(cur); --qq[cur]; } else if (cur + 1 <= 3 && qq[cur + 1]) { ++cur; cl.push_back(cur); --qq[cur]; } else { ok = false; break; } } if (ok && cl.size() == tot) { cout << "YES" << "\n"; for (auto y : cl) cout << y << " "; cout << "\n"; exit(0); } } cout << "NO" << "\n"; }
1,900
CPP
mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) S = sum(A) if S == 1: print(-1) exit() div_list = [S] for d in range(2, int(S ** 0.5) + 1): if S % d == 0: div_list.append(d) div_list.append(S // d) if len(div_list) > 2: if div_list[-1] == div_list[-2]: div_list.pop() ans_best = 10**10 for D in div_list: ans = 0 cnt = 0 i_list = [] for i, a in enumerate(A): if a == 1: i_list.append(i) cnt += 1 if cnt == D: cnt = 0 j = i_list[D // 2] for ii in i_list: ans += abs(ii - j) i_list = [] ans_best = min(ans_best, ans) print(ans_best) if __name__ == '__main__': main()
1,800
PYTHON3
#include <bits/stdc++.h> using namespace std; const int MOD = 1000000007; const int INF = 0x3f3f3f3f; const long long INFL = 0x3f3f3f3f3f3f3f3f; struct st { int x, y, z, id; } s[60000]; bool operator<(st a, st b) { return make_tuple(a.x, a.y, a.z) < make_tuple(b.x, b.y, b.z); } int main() { int n; cin >> n; set<st> se; map<int, int> x; map<int, map<int, int>> y; map<int, map<int, map<int, int>>> z; for (int i = 0; i < n; i++) { scanf("%d%d%d", &s[i].x, &s[i].y, &s[i].z); s[i].id = i + 1; se.insert(s[i]); x[s[i].x]++; y[s[i].x][s[i].y]++; z[s[i].x][s[i].y][s[i].z] = i + 1; } vector<pair<int, int>> ans; auto Erase = [&](st s) { se.erase(s); if (--x[s.x] == 0) x.erase(s.x); if (--y[s.x][s.y] == 0) y[s.x].erase(s.y); z[s.x][s.y].erase(s.z); }; while (!se.empty()) { auto s = *se.begin(); Erase(s); vector<st> cand; int X = x.begin()->first; auto it = y[X].lower_bound(s.y); if (it != y[X].end()) { int Y = it->first; auto it2 = z[X][Y].lower_bound(s.z); if (it2 != z[X][Y].end()) { cand.push_back({X, Y, it2->first, it2->second}); } if (it2 != z[X][Y].begin()) { cand.push_back({X, Y, prev(it2)->first, prev(it2)->second}); } } if (it != y[X].begin()) { it--; int Y = it->first; auto it2 = z[X][Y].lower_bound(s.z); if (it2 != z[X][Y].end()) { cand.push_back({X, Y, it2->first, it2->second}); } if (it2 != z[X][Y].begin()) { cand.push_back({X, Y, prev(it2)->first, prev(it2)->second}); } } for (int i = 0; i < cand.size(); i++) { bool ok = true; for (int j = 0; j < cand.size(); j++) { if (i == j) continue; if (s.x <= cand[j].x && cand[j].x <= cand[i].x && s.y <= cand[j].y && cand[j].y <= cand[i].y && s.z <= cand[j].z && cand[j].z <= cand[i].z) { ok = false; break; } } if (ok) { ans.push_back(pair<int, int>(s.id, cand[i].id)); Erase(cand[i]); break; } } } for (auto p : ans) { printf("%d %d\n", p.first, p.second); } }
1,900
CPP
#include <bits/stdc++.h> using namespace std; int n, a[100010]; long long k; long long s[100010]; struct TAP { long long t[100010]; void clear() { memset(t, 0, sizeof(long long) * (n + 1)); } void add(int x, long long c) { for (; x <= n; x += x & -x) t[x] += c; } long long query(int x) { long long r = 0; for (; x; x -= x & -x) r += t[x]; return r; } } cnt, sum; struct TAMN { long long t[100010]; void clear() { memset(t, 127, sizeof(long long) * (n + 1)); } void ins(int x, long long c) { for (; x <= n && c < t[x]; x += x & -x) t[x] = c; } long long query(int x) { long long r = LLONG_MAX; for (; x; x -= x & -x) r = min(r, t[x]); return r; } } far; int pre[100010], suc[100010]; int q[100010], re[100010]; long long val[100010]; bool cmpq(int x, int y) { return s[x - 1] < s[y - 1] || s[x - 1] == s[y - 1] && x < y; } int sep1[100010], sep2[100010]; long long mnl[100010]; long long ans; long long judge(long long lim) { cnt.clear(); long long res = 0; for (int i = 1; i <= n; ++i) { cnt.add(re[i], 1); long long x = upper_bound(val + 1, val + n + 1, s[i] - lim) - val - 1; res += cnt.query(x); } return res; } long long calc(long long lim, int *sep, bool need) { cnt.clear(); if (need) sum.clear(), far.clear(); long long res = 0; for (int i = 1; i <= n; ++i) { cnt.add(re[i], 1); if (need) sum.add(re[i], s[i - 1]), far.ins(re[i], i); long long x = upper_bound(val + 1, val + n + 1, s[i] - lim) - val - 1; int num = cnt.query(x); res += num; sep[i] = num; if (need) { ans += s[i] * num - sum.query(x), mnl[i] = far.query(x); } } return res; } void mend(long long lim, int *sep, bool need, long long rem) { cnt.clear(); if (need) far.clear(); for (int i = 1; i <= n && rem; ++i) { cnt.add(re[i], 1); if (need) far.ins(re[i], i); int x = upper_bound(val + 1, val + n + 1, s[i] - lim) - val - 1; int num = cnt.query(x); if (num - sep[i]) { int mn = min((long long)num - sep[i], rem); sep[i] += mn, rem -= mn; if (need) { ans += lim * mn; mnl[i] = far.query(x); } } } } void work(long long k, int *sep, bool need) { long long l = -5e9, r = 5e9, lim = 5e9; while (l <= r) { long long mid = l + r >> 1; long long tmp = judge(mid); if (tmp >= k) l = (lim = mid) + 1; else r = mid - 1; } long long rem = k - calc(lim + 1, sep, need); mend(lim, sep, need, rem); } struct Range { int l, r; } ls[100010]; int m; bool cmpls(Range x, Range y) { return s[x.r] - s[x.l - 1] > s[y.r] - s[y.l - 1]; } void find() { q[0] = q[n + 1] = 0; for (int i = 1; i <= n; ++i) pre[q[i]] = q[i - 1], suc[q[i]] = q[i + 1]; for (int i = n; i >= 1; --i) suc[pre[i]] = suc[i], pre[suc[i]] = pre[i]; cnt.clear(); for (int i = 1; i <= n; ++i) { suc[pre[i]] = i, pre[suc[i]] = i; cnt.add(re[i], 1); int l = 1, r = n, x = n; while (l <= r) { int mid = l + r >> 1; int tmp = cnt.query(mid); if (tmp >= sep2[i]) r = (x = mid) - 1; else l = mid + 1; } x = q[x]; for (int j = 0; j < sep2[i] - sep1[i]; ++j, x = pre[x]) ls[++m] = {x, i}; } sort(ls + 1, ls + m + 1, cmpls); } struct Double_Heap { int k; multiset<long long> S, T; long long sumS; void insert(long long v) { if (S.empty()) { S.insert(v); sumS += v; return; } if (k == 0) { T.insert(v); return; } if (S.size() < k) { S.insert(v); sumS += v; } else { auto p = S.begin(); if (v > *p) { long long u = *p; S.erase(p), T.insert(u); S.insert(v); sumS += v - u; } else T.insert(v); } } void erase(long long v) { if (S.empty()) { T.erase(v); return; } long long u = *S.begin(); if (v >= u) { S.erase(S.find(v)); sumS -= v; if (!T.empty()) { auto p = --T.end(); long long w = *p; T.erase(p), S.insert(w); sumS += w; } } else T.erase(T.find(v)); } void change(int _k) { for (; k > _k; --k) { if (S.size() < k) continue; auto p = S.begin(); long long u = *p; S.erase(p), T.insert(u); sumS -= u; } } long long query() { return sumS; } } dh; struct RMQ { long long f[100010][17], g[100010][17]; void init() { for (int i = 1; i <= n; ++i) { f[i][0] = s[i - 1]; g[i][0] = s[i]; } for (int i = 1; 1 << i <= n; ++i) for (int j = 1; j + (1 << i) - 1 <= n; ++j) { f[j][i] = min(f[j][i - 1], f[j + (1 << i - 1)][i - 1]); g[j][i] = max(g[j][i - 1], g[j + (1 << i - 1)][i - 1]); } } long long qmin(int l, int r) { int m = log2(r - l + 1); return min(f[l][m], f[r - (1 << m) + 1][m]); } long long qmax(int l, int r) { int m = log2(r - l + 1); return max(g[l][m], g[r - (1 << m) + 1][m]); } } rmq; inline bool operator<(Range x, Range y) { return x.l < y.l || x.l == y.l && x.r < y.r; } set<Range> ed; long long getv(int l, int r) { return max(rmq.qmax(l, r) - s[l - 1], 0ll) + max(s[r] - rmq.qmin(l, r), 0ll) - (s[r] - s[l - 1]); } long long getlv(int r) { return (r < n ? max(s[r] - rmq.qmin(1, r), 0ll) - s[r] : 0); } long long getrv(int l) { return max(rmq.qmax(l, n) - s[l - 1], 0ll) - (s[n] - s[l - 1]); } int blocks; void insert(int l, int r) { auto p = ed.lower_bound({l, 0}), q = p; if (p != ed.begin()) { --q; if (max(q->l, l) <= min(q->r, r) + 1) { l = min(q->l, l), r = max(q->r, r); if (q->l == 1) ans -= getlv(q->r); else if (q->r == n) ans -= getrv(q->l); else dh.erase(getv(q->l, q->r)); blocks += q->r - q->l + 1; ed.erase(q); } } for (; p != ed.end() && max(p->l, l) <= min(p->r, r) + 1;) { l = min(p->l, l), r = max(p->r, r); q = p, p++; if (q->l == 1) ans -= getlv(q->r); else if (q->r == n) ans -= getrv(q->l); else dh.erase(getv(q->l, q->r)); blocks += q->r - q->l + 1; ed.erase(q); } ed.insert({l, r}); if (l == 1) ans += getlv(r); else if (r == n) ans += getrv(l); else dh.insert(getv(l, r)); blocks -= r - l + 1; } int bz[100010]; void init() { blocks = n; for (int i = 1; i <= n; ++i) bz[mnl[i]]++, bz[i + 1]--; for (int i = 1; i <= n + 1; ++i) bz[i] += bz[i - 1]; for (int i = 1, fir = 0; i <= n + 1; ++i) if (bool(bz[i]) != bool(bz[i - 1])) { if (bz[i]) fir = i; else { insert(fir, i - 1); fir = i + 1; } } } int main() { scanf("%d%lld", &n, &k); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]), s[i] = s[i - 1] + a[i]; for (int i = 1; i <= n; ++i) q[i] = i; sort(q + 1, q + n + 1, cmpq); q[0] = 0, q[n + 1] = 0; for (int i = 1; i <= n; ++i) { val[i] = s[q[i] - 1]; re[q[i]] = i; } memset(mnl, 127, sizeof(long long) * (n + 1)); if (k > n) work(k - n, sep1, 1); for (int i = 1; i <= n; ++i) mnl[i] = min(mnl[i], i + 1ll); work(k, sep2, 0); find(); rmq.init(); dh.k = k - max(k - n, 0ll) - 1; init(); long long res = -1e19; for (long long x = max(k - n, 0ll), i = 1; x < k; ++x, ++i) { if (k - x <= blocks) { dh.change(k - x - 1); res = max(res, ans + dh.query() + s[n]); } insert(ls[i].l, ls[i].r); ans += s[ls[i].r] - s[ls[i].l - 1]; } if (ed.size() == 1 && ed.begin()->l == 1 && ed.begin()->r == n) res = max(res, ans); printf("%lld\n", res); return 0; }
3,100
CPP
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int t; cin >> t; while (t--) { long long int n, m, k; cin >> n >> m >> k; if (m <= n / k) cout << m << "\n"; else { long long int x = n / k; m -= x; k -= 1; if (m % k == 0) { cout << x - (m / k) << "\n"; } else { cout << x - (m / k + 1) << "\n"; } } } }
1,000
CPP
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> tab(n); for (int i = 0; i < n; i++) cin >> tab[i]; for (int i = 0; i < n; i++) { if (tab[i] % 2 == 0) continue; else { if (i == (n - 1) || tab[i + 1] == 0) { cout << "NO"; return 0; } else tab[i + 1] -= 1; } } cout << "YES"; return 0; }
1,100
CPP
#include <bits/stdc++.h> using namespace std; const int CONST = 1e9 + 7; const int MAX = 100005; const double pi = 3.14159265358979323846; int n, m; vector<int> pop(MAX); vector<int> hap(MAX); vector<int> adj[MAX]; vector<int> totals(MAX, 0); vector<bool> vis(MAX, false); vector<int> good(MAX, 0), bad(MAX, 0); bool ans = true; bool solve(int node, int par) { if (vis[node]) return false; vis[node] = true; int chbad = 0, chgood = 0; int total = pop[node]; for (auto &child : adj[node]) { if (child != par) { if (solve(child, node)) { return true; } total += totals[child]; chbad += bad[child]; chgood += good[child]; } } totals[node] = total; if ((hap[node] + total) & 1 == 1) { ans = false; return true; } good[node] = (total + hap[node]) / 2; bad[node] = total - good[node]; if (good[node] < 0 || bad[node] < 0 || good[node] > total || bad[node] > total) { ans = false; return true; } if (adj[node].size() == 0) { return false; } long long int badleft, goodleft; if (pop[node] - bad[node] < 0) { badleft = bad[node] - pop[node]; goodleft = good[node]; } else { badleft = 0; goodleft = good[node] - (pop[node] - bad[node]); } if (badleft > chbad) { ans = false; return true; } if (goodleft < chbad - badleft + chgood) { ans = false; return true; } return false; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long t; cin >> t; while (t--) { cin >> n >> m; for (int i = 1; i < n + 1; ++i) { cin >> pop[i]; } for (int i = 1; i < n + 1; ++i) { cin >> hap[i]; } for (int i = 0; i < n - 1; ++i) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } solve(1, -1); for (int i = 1; i < n + 1; ++i) { adj[i].clear(); vis[i] = false; } if (ans) cout << "YES\n"; else cout << "NO\n"; ans = true; } return 0; }
1,800
CPP
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; const int INF = 1e9 + 7; int n; int Head[maxn], To[2 * maxn], Next[2 * maxn], W[2 * maxn], tot; int Fa[maxn][20], Deep[maxn], numv[maxn], vnum[maxn], cnt; long long dis[maxn]; void link(int u, int v, int c) { To[++tot] = v; Next[tot] = Head[u]; W[tot] = c; Head[u] = tot; } void dfs(int u, int fa) { numv[cnt] = u; vnum[u] = cnt++; Fa[u][0] = fa; for (int i = Head[u], v; i; i = Next[i]) { v = To[i]; if (v != Fa[u][0]) { dis[v] = dis[u] + W[i]; Deep[v] = Deep[u] + 1; dfs(v, u); } } } int LCA(int u, int v) { if (Deep[u] > Deep[v]) swap(u, v); int dv = Deep[v], du = Deep[u]; for (int j = 19; j >= 0; j--) if (dv - (1 << j) >= du) v = Fa[v][j], dv -= (1 << j); if (u == v) return u; for (int j = 19; j >= 0; j--) { if (Fa[u][j] == Fa[v][j]) continue; u = Fa[u][j]; v = Fa[v][j]; } return Fa[u][0]; } set<int> S1; set<int> S2; int main() { scanf("%d", &n); for (int i = 1, a, b, c; i < n; i++) { scanf("%d%d%d", &a, &b, &c); link(a, b, c); link(b, a, c); } dfs(1, 0); for (int j = 1; j < 20; j++) for (int i = 1; i <= n; i++) Fa[i][j] = Fa[Fa[i][j - 1]][j - 1]; int Q, x; char cmp[2]; S1.insert(INF); S2.insert(INF); long long ans = 0; int u, v, i, j, lca; scanf("%d", &Q); while (Q--) { scanf("%s", cmp); if (cmp[0] == '?') { if (S1.size() <= 2) printf("0\n"); else { i = *(S2.upper_bound(-INF)); j = *(S1.upper_bound(-INF)); u = numv[-i]; v = numv[j]; lca = LCA(u, v); printf("%I64d\n", (ans + dis[u] + dis[v] - 2 * dis[lca]) / 2); } } else if (cmp[0] == '+') { scanf("%d", &x); i = *(S1.upper_bound(vnum[x])); if (i != INF) { u = numv[i]; lca = LCA(u, x); ans += (dis[u] + dis[x] - 2 * dis[lca]); } j = *(S2.upper_bound(-vnum[x])); if (j != INF) { v = numv[-j]; lca = LCA(v, x); ans += (dis[v] + dis[x] - 2 * dis[lca]); } if (i != INF && j != INF) { lca = LCA(u, v); ans -= (dis[u] + dis[v] - 2 * dis[lca]); } S1.insert(vnum[x]); S2.insert(-vnum[x]); } else { scanf("%d", &x); i = *(S1.upper_bound(vnum[x])); if (i != INF) { u = numv[i]; lca = LCA(u, x); ans -= (dis[u] + dis[x] - 2 * dis[lca]); } j = *(S2.upper_bound(-vnum[x])); if (j != INF) { v = numv[-j]; lca = LCA(v, x); ans -= (dis[v] + dis[x] - 2 * dis[lca]); } if (i != INF && j != INF) { lca = LCA(u, v); ans += (dis[u] + dis[v] - 2 * dis[lca]); } S1.erase(vnum[x]); S2.erase(-vnum[x]); } } return 0; }
3,100
CPP
from math import ceil def solve(n, m, a): i, t, r = 0, 0, [] for k in a: r.append(str((i + k) // m)) i = (i + k) % m return ' '.join(r) def main(): n, m = list(map(int, input().split())) a = list(map(int, input().split())) print(solve(n, m, a)) main()
900
PYTHON3
#include <bits/stdc++.h> using namespace std; string a; int n, k; priority_queue<pair<string, int>, vector<pair<string, int> >, greater<pair<string, int> > > q; int main() { cin >> a >> k; n = a.length(); if (k > 1LL * n * (n + 1) / 2) return puts("No such line.") && 0; for (int i = 0; i < n; i++) { pair<string, int> t; t.first += a[i]; t.second = i; q.push(t); } while (!q.empty()) { pair<string, int> t = q.top(); q.pop(); k--; if (!k) { cout << t.first << endl; break; } if (t.second + 1 < n) q.push(pair<string, int>(t.first + a[t.second + 1], t.second + 1)); } return 0; }
2,100
CPP
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); long long n, ans; cin >> n; vector<long long> a = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8092, 16184, 32368, 64736, 129472, 258944, 517888, 1035776, 2071552, 4143104, 8286208, 16572416, 33144832, 66289664, 132579328, 265158656, 530317312, 1060634624, 2121269248, 4242538496, 8485076992, 16970153984, 33940307968}; ans = a[n]; cout << ans << "\n"; return 0; }
1,900
CPP
from math import ceil t = int(input()) for _ in range(t): A,B,n = tuple(map(int,input().split())) a = list(map(int,input().split())) b = list(map(int,input().split())) for i in range(n): B -= ceil(b[i]/A)*a[i] won = False for i in range(n): if(B + a[i] > 0): won = True break if(won): print("YES") else: print("NO")
900
PYTHON3
import math def factorial(n): for i in range(1, n + 1): factorial = factorial * i return factorial def f(n): l = factorial(n) * n ans = l * (l - n + 2) // 2 for i in range(1, n): ans -= factorial(n) // factorial(i + 1) n(i * (n - i) - 1) return ans def solve(n): M = 998244353 p = n a = 0 for i in range(n, 1, -1): a = (a + p * (i - 1) * (n - i + 1) - p) % M p = p * i % M a = (p * (p - n + 2) - 2 * a) % M if a & 1: a += M return a // 2 x = int(input()) ans = solve(x) print(ans)
3,300
PYTHON3
from math import ceil, sqrt EPS = 1e-7 t = int(input()) for _ in range(t): x = int(input()) n = (-1 + sqrt(8 * x + 1)) / 2 if abs(n - ceil(n)) < EPS: # целое print(int(n)) continue else: n = ceil(n) if (n * (n + 1)) / 2 - x == 1: print(n + 1) continue else: print(n)
1,200
PYTHON3
#include <bits/stdc++.h> using namespace std; int main(void) { char t[4][4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) cin >> t[i][j]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { int w = 0, b = 0; for (int l = 0; l < 2; l++) for (int k = 0; k < 2; k++) if (t[i + l][j + k] == '#') w++; else b++; if (w >= 3 || b >= 3) { cout << "YES" << endl; return 0; } } cout << "NO" << endl; }
1,100
CPP
n,k=map(int,input().split()) print(['NO','YES'][(n//k)%2])
800
PYTHON3
import math n,x,y=list(map(int,input().split())) a=math.ceil(n*y/100) if a>x: print(a-x) else: print(0)
900
PYTHON3