solution
stringlengths
10
983k
difficulty
int64
0
25
language
stringclasses
2 values
#include <bits/stdc++.h> using namespace std; const int mods = 1e9 + 7; const int maxn = 2e5 + 10; const int N = 1e5 + 10; const int E = 1e6 + 10; int q; string s; int cnt[maxn][30]; void solve(string s) { for (int i = 1; i <= s.size(); i++) { for (int j = 0; j < 26; j++) cnt[i][j] = cnt[i - 1][j]; cnt[i][s[i - 1] - 'a'] = cnt[i - 1][s[i - 1] - 'a'] + 1; } } int main() { cin >> s; cin >> q; solve(s); int l, r, num, flg; while (q--) { cin >> l >> r; if (l == r) { printf("Yes\n"); continue; } num = 0; flg = 0; if (s[l - 1] != s[r - 1]) { flg = 1; } else { for (int i = 0; i < 26; i++) { if (cnt[r][i] - cnt[l - 1][i]) num++; if (num >= 3) { flg = 1; break; } } } if (flg) printf("Yes\n"); else printf("No\n"); } }
8
CPP
#include <bits/stdc++.h> using namespace std; long long a[1005], b[1005]; long long _pow(long long aa, long long nn) { long long ans = 1; while (nn) { if (nn & 1) ans = (ans * aa); aa = (aa * aa); nn >>= 1; } return ans; } int getnum(int i) { return _pow(10, i) - _pow(10, i - 1); } long long getc(long long s) { long long w = 0; while (s) { w++; s /= 10; } return w == 0 ? 1 : w; } int main() { ios::sync_with_stdio(false); cin.tie(0); ; for (long long i = 1; i <= 9; i++) { long long num = getnum(i); a[i] = a[i - 1] + num * i; b[i] = b[i - 1] + (a[i - 1] + i) * num + (num - 1) * num / 2 * i; } int q; cin >> q; while (q--) { long long n; cin >> n; int k = 1; for (int i = 1; i <= 9; i++) { if (b[i] >= n) { k = i; break; } } long long l = 1, r = getnum(k); long long ans = 0; while (l <= r) { long long mid = (l + r) >> 1; long long sum = b[k - 1] + (a[k - 1] + k) * mid + (mid - 1) * mid / 2 * k; if (sum < n) { l = mid + 1; } else { ans = mid; r = mid - 1; } } n -= b[k - 1] + (a[k - 1] + k) * (ans - 1) + (ans - 2) * (ans - 1) / 2 * k; l = 1, r = ans + _pow(10, k - 1) - 1; long long vs; while (l <= r) { long long mid = (l + r) >> 1; long long len = getc(mid); long long sum = a[len - 1] + (mid - _pow(10, len - 1) + 1) * len; if (sum < n) { l = mid + 1; } else { vs = mid; r = mid - 1; } } long long len = getc(vs - 1); long long sum = a[len - 1] + (vs - _pow(10, len - 1)) * len; ans = vs; n -= sum; int s; n = getc(ans) - n + 1; while (n) { s = ans % 10; ans /= 10; n--; } printf("%d\n", s); } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; int main() { string s, r; getline(cin, s); for (int i = 0; i < s.size(); i++) { if (s[i] == ' ') continue; else if (s[i] == ',') { r += s[i]; if (i != s.size() - 1) r += ' '; } else if (s[i] == '.' && s[i + 1] == '.' && s[i + 2] == '.') { if (i != 0 && r[r.size() - 1] != ' ') r += ' '; r += s[i++], r += s[i++], r += s[i]; } else { if (r[r.size() - 1] >= '0' && r[r.size() - 1] <= '9' && s[i - 1] == ' ') r += ' '; r += s[i]; } } cout << r; return 0; }
8
CPP
#include <bits/stdc++.h> using namespace std; const int N = 500005, M = 1000000007; int n, m, i, j, sd[2005][2005], sr[2005][2005], l, r; long long f[2005][2005][2], nd[2005][2005], nr[2005][2005]; char c[2005][2005]; long long qpow(long long a, long long b) { long long s = a, ans = 1; while (b) { if (b & 1) ans = ans * s; s = s * s; b >>= 1; } return ans; } int main() { scanf("%d %d", &n, &m); for (i = 1; i <= n; i++) scanf("%s", c[i] + 1); for (i = n; i >= 1; i--) for (j = m; j >= 1; j--) { sd[i][j] = sd[i + 1][j]; sr[i][j] = sr[i][j + 1]; if (c[i][j] == 'R') { sd[i][j]++; sr[i][j]++; } } if (n == 1 && m == 1) { cout << 1; return 0; } f[1][1][0] = f[1][1][1] = 1; for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { if (i != 1 || j != 1) { l = 1; r = i; while (l < r) { int mid = l + r >> 1; if (sd[mid + 1][j] <= n - i) r = mid; else l = mid + 1; } if (l <= i) f[i][j][0] = (nd[i - 1][j] - nd[l - 1][j]) % M; l = 1; r = j; while (l < r) { int mid = l + r >> 1; if (sr[i][mid + 1] <= m - j) r = mid; else l = mid + 1; } if (l <= j) f[i][j][1] = (nr[i][j - 1] - nr[i][l - 1]) % M; } nd[i][j] = (nd[i - 1][j] + f[i][j][1]) % M; nr[i][j] = (nr[i][j - 1] + f[i][j][0]) % M; } cout << ((f[n][m][0] + f[n][m][1]) % M + M) % M; }
11
CPP
import math def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True n = int(input()) r=0 p=-1 if isPrime(n) or n==1: print(n) exit() for i in range(2,int(math.sqrt(n))+1): if n%i==0: p=i break while n%p==0: n=n//p if n==1: print(p) else: print(1)
9
PYTHON3
matrix =[] for i in range(5): data = list(map(int,input().split())) if 1 in data: line = i+1 row = data.index(1)+1 matrix.append(data) print(abs(3-line) + abs(3 - row))
7
PYTHON3
a = input() j = int(a[len(a)-1]) if j %2 == 0: print("0") else: print("1")
10
PYTHON3
n = int(input()) matrix = [0]*n for i in range(n): entrada = str(input()) matrix[i] = list(entrada) crosses_counter = 0 def M(i,j): return matrix[i][j] for i in range(1,n-1): for j in range(1,n-1): #print(i,j,'and now', M(i,j), M(i-1,j-1), M(i-1,j+1), M(i+1, j-1), M(i+1, j+1)) if M(i,j) == M(i-1, j-1) == M(i-1, j+1) == M(i+1, j-1) == M(i+1, j+1) == 'X': crosses_counter += 1 print(crosses_counter)
7
PYTHON3
n = int(input()) l = list(map(int,input().split())) k,h = l.index(max(l)),l.index(min(l)) print([k-h+max(n-k-1,h),h-k+max(n-h-1,k)][k<h])
7
PYTHON3
a=int(input()) c=[] for i in range(a): b=int(input()) c.append(b) j=1 for i in range(a-1): if c[i]!=c[i+1]: j+=1 print (j)
7
PYTHON3
#include <bits/stdc++.h> using namespace std; #define rep(i,a,n) for (int i=a;i<n;i++) #define per(i,a,n) for (int i=n-1;i>=a;i--) #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second #define SZ(x) ((int)(x).size()) typedef vector<int> VI; typedef long long ll; typedef pair<int,int> PII; const ll mod=1000000007; ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;} ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;} // head const int N=210000,V=301000,E=2010000; int s,t,vtot,n,vis[N],pl[N],pr[N]; vector<PII> ed[N]; vector<pair<int,PII>> ans; VI eg[N]; struct edge{int v,ne;ll f;}e[E*2];int g[V],et; void ae(int u,int v,ll f){ e[et]={v,g[u],f};g[u]=et++; e[et]={u,g[v],0};g[v]=et++; } int d[V],cu[V]; bool lb(){ rep(i,0,vtot)d[i]=0,cu[i]=g[i]; static int qu[V]; int p=0,q=0; qu[q++]=s,d[s]=1; while(p!=q){ int u=qu[p++]; for (int i=g[u];~i;i=e[i].ne)if(e[i].f && !d[e[i].v]){ d[e[i].v]=d[u]+1; if(e[i].v==t)return 1; qu[q++]=e[i].v; } }return 0; } ll aug(int u,ll m){ if(u==t)return m; ll su=0,f; for (int i=cu[u];~i;cu[u]=i=e[i].ne)if(e[i].f && d[e[i].v]==d[u]+1){ f=aug(e[i].v,min(m,e[i].f)); e[i].f-=f; e[i^1].f+=f; m-=f; su+=f; if(!m)break; } if(!su)d[u]=-1; return su; } ll dinic(){ ll su=0; while(lb())su+=aug(s,1<<30); return su; } void init(){ rep(i,0,vtot)g[i]=-1; et=0; } void dfs(int u) { vis[u]=1; for (auto v:eg[u]) if (v!=pr[u]&&!vis[pl[v]]) { ans.pb(mp(v,mp(u,pl[v]))); dfs(pl[v]); } } int main() { scanf("%d",&n); s=2*n-1, t=2*n; vtot=2*n+1; init(); rep(i,0,n-1) { ae(n+i,t,1); int t,x; scanf("%d",&t); rep(j,0,t) { scanf("%d",&x); --x; ed[i].pb(mp(et,x)); eg[x].pb(i); ae(x,n+i,1); } } rep(i,0,n) ae(s,i,1); int w=dinic(); if (w!=n-1) { puts("-1"); return 0; } rep(i,0,n) pr[i]=-1; rep(i,0,n-1) { for (auto p:ed[i]) { if (e[p.fi].f==0) { pl[i]=p.se; pr[p.se]=i; } } } int rt=-1; rep(i,0,n) if (pr[i]==-1) { rt=i; } dfs(rt); if (SZ(ans)!=n-1) { puts("-1"); return 0; } sort(all(ans)); for (auto p:ans) { printf("%d %d\n",p.se.fi+1,p.se.se+1); } }
0
CPP
#include <bits/stdc++.h> using namespace std; #define e1 first #define e2 second #define pb push_back #define mp make_pair #define boost {ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } #define eb emplace_back #define OUT(x) {cout << x; exit(0); } #define FOR(i,a,b) for(int i=(a);i<=(b);++i) #define scanf(...) scanf(__VA_ARGS__)?:0 typedef long long int ll; typedef unsigned long long ull; typedef pair <int, int> PII; typedef pair <ll, ll> PLL; typedef pair <PLL, int> PLLI; typedef pair <PII, PII> PP; typedef pair <PII, int> PPI; typedef pair <int, PII> PIP; typedef pair <ll, int> PLI; typedef unsigned int ui; const int inf = 1e9+9; const ll MOD = 1e9+69696; template<class T> int size(T &&x) { return int(x.size()); } template<class A, class B> ostream& operator<<(ostream &out, const pair<A, B> &p) { return out << '(' << p.first << ", " << p.second << ')'; } template<class T> auto operator<<(ostream &out, T &&x) -> decltype(x.begin(), out) { out << '{'; for(auto it = x.begin(); it != x.end(); ++it) out << *it << (it == prev(x.end()) ? "" : ", "); return out << '}'; } void dump() {} template<class T, class... Args> void dump(T &&x, Args... args) { cerr << x << "; "; dump(args...); } #ifdef DEBUG struct Nl{~Nl(){cerr << '\n';}}; # define debug(x...) cerr << (strcmp(#x, "") ? #x ": " : ""), dump(x), Nl(), cerr << "" #else # define debug(...) 0 && cerr #endif mt19937_64 rng(0); int random(int l, int r) { return uniform_int_distribution<int>(l, r)(rng); } #define rep(i, a, b) for(int i = a; i < (b); ++i) #define trav(a, x) for(auto& a : x) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() typedef long long LL; typedef pair<int, int> pii; typedef vector<int> vi; //taken from UWarsaw template // Works for POSITIVE integers up to 1e18 LL mul_bin(LL a, LL b, LL P) { LL res = 0; while (b) { if (b % 2 == 1) { res = (res + a) % P; } a = (a + a) % P; b /= 2; } return res; } LL gcd(LL a, LL b, LL& x, LL& y){ if (a < b) return gcd(b, a, y, x); if (b == 0) { x = 1; y = 0; return a; } LL xp; LL pom = gcd(b, a % b, xp, x); y = xp - x * (a / b); return pom; } inline LL Adjust(LL a, LL mod) { return (a % mod + mod) % mod; } LL INF = 1e18; // Works for POSITIVE integers up to 1e18 pair<LL, LL> nww(LL a, LL b, LL r1, LL r2) { r1 = Adjust(r1, a); r2 = Adjust(r2, b); LL x, y; LL d = gcd(a, b, x, y); x = Adjust(x, b); if (r1 % d != r2 % d) { return {-1, -1}; } if (a / d > INF / b + 2) { return {-1, -1}; } LL N = a / d * b; LL s = mul_bin(Adjust(r2 - r1, b) / d, x, b); LL new_r = (r1 + mul_bin(a, s, N)) % N; assert(new_r % a == r1 && new_r % b == r2); return {N, new_r}; } // Elements of vec are equations of form x = p.second (mod p.first) // If solution exists than this returns a pair (N, r) such that // x = r (mod N); (−1, −1) otherwise // Works for POSITIVE integers up to 1e18 pair<LL, LL> CRT(vector<pair<LL, LL>>& vec) { LL N = 1, r = 0; for (auto& p : vec) { assert(p.e1 > 0 && p.e2 >= 0); pair<LL, LL> new_pair = nww(N, p.first, r, p.second); if (new_pair.first == -1) { return {-1LL, -1LL}; } N = new_pair.first; r = new_pair.second; } return {N, r}; } const int maxn = 1000100; int pos[maxn]; int pos2[maxn], maxx; PLL solutions[maxn]; inline ll sufit(ll x, ll y ){ if (x <= 0) return 0; if (x % y == 0) return x/y; return 1+x/y; } inline ll cnt(ll value) { ll ok_days = 0; for (int i=1; i<=maxx; ++i) { if (solutions[i] != make_pair(-1LL, -1LL)) { ok_days += sufit(value - solutions[i].e2 + 1, solutions[i].e1); } } return value - ok_days; } void solveone() { int n, m; ll k; cin >> n >> m >> k; maxx = 2 * max(n, m); FOR(i, 1, n) { int a; cin >> a; pos[a] = i; } FOR(i, 1, m) { int a; cin >> a; pos2[a] = i; } FOR(i, 1, maxx) { solutions[i] = {-1, -1}; vector <PLL> eqs; if (pos2[i] != 0 && pos[i] != 0) { eqs.push_back({n, pos[i] % n}); eqs.push_back({m, pos2[i] % m}); solutions[i] = CRT(eqs); if (solutions[i].e2 == 0) solutions[i].e2 = solutions[i].e1; //debug(solutions[i]); } } //cout << cnt(3) << ' ' << cnt(4) << endl; ll x = 0, y = INF; while (x < y) { ll mid = (x + y) / 2; if (cnt(mid) < k) x = ++mid; else y = mid; } cout << x << "\n"; } int main() { boost; int tests; tests = 1; //cin >> tests; FOR(_, 1, tests) solveone(); }
8
CPP
#include <bits/stdc++.h> int main() { short n, m, N, M, c, i; scanf("%hd%hd%hd", &n, &m, &c); int *a, *b; a = (int *)malloc(n * sizeof(int)); b = (int *)malloc(m * sizeof(int)); for (N = 0; N < n; ++N) scanf("%d", &a[N]); for (N = 0; N < m; ++N) scanf("%d", &b[N]); for (N = 0; N < n - m + 1; ++N) { i = N; for (M = 0; M < m; ++M) { a[i] += b[M]; a[i++] %= c; } } for (N = 0; N < n; ++N) printf("%d ", a[N]); return 0; }
10
CPP
#include <bits/stdc++.h> using namespace std; struct pkt { double x, y; int nr; }; bool por(pkt a, pkt b) { if (a.x < b.x) return true; if (a.x > b.x) return false; if (a.y < b.y) return true; if (a.y > b.y) return false; return (a.nr < b.nr); } double Odl(pkt a, pkt b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); } double Wek(pkt a, pkt b, pkt c) { pkt w1 = {b.x - a.x, b.y - a.y}; pkt w2 = {c.x - a.x, c.y - a.y}; return w1.x * w2.y - w2.x * w1.y; } bool NaOdc(pkt a, pkt b, pkt s) { if (a.x == b.x) { if (a.y > b.y) swap(a, b); return (s.x == a.x && s.y >= a.y && s.y <= b.y); } if (a.y == b.y) { if (a.x > b.x) swap(a, b); return (s.y == a.y && s.x >= a.x && s.x <= b.x); } if (a.x > b.x) swap(a, b); return (Wek(a, b, s) == 0 && s.x >= a.x && s.x <= b.x); } bool WTrojkacie(vector<pkt>& tr, pkt sr) { int dod = 0, uj = 0; for (int i = 0; i < 3; ++i) { double wek = Wek(tr[i], tr[(i + 1) % 3], sr); if (wek > 0.0) ++dod; if (wek < 0.0) ++uj; } return (dod == 3 || uj == 3); } pkt PrzeOdc(pkt a, pkt b, pkt c, pkt d) { if (a.x == b.x) { double a1 = (d.y - c.y) / (d.x - c.x); double b1 = c.y - a1 * c.x; return {a.x, a1 * a.x + b1}; } if (c.x == d.x) { double a1 = (b.y - a.y) / (b.x - a.x); double b1 = a.y - a1 * a.x; return {c.x, a1 * c.x + b1}; } double a1 = (b.y - a.y) / (b.x - a.x); double b1 = a.y - a1 * a.x; double a2 = (d.y - c.y) / (d.x - c.x); double b2 = c.y - a2 * c.x; double X = (b2 - b1) / (a1 - a2); double Y = a2 * X + b2; return {X, Y, 0}; } int main() { ios_base::sync_with_stdio(0); int n; cin >> n; vector<vector<pkt> > p(n, vector<pkt>(3)); for (int i = 0; i < n; ++i) for (int j = 0; j < 3; ++j) cin >> p[i][j].x >> p[i][j].y; double odp = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < 3; ++j) odp += Odl(p[i][j], p[i][(j + 1) % 3]); for (int i = 0; i < n; ++i) { for (int j = 0; j < 3; ++j) { pkt a = p[i][j], b = p[i][(j + 1) % 3]; vector<pkt> przec; przec.push_back(a); przec.push_back(b); for (int k = 0; k < n; ++k) { if (k == i) continue; for (int l = 0; l < 3; ++l) { pkt c = p[k][l], d = p[k][(l + 1) % 3]; int ile = 0; if (NaOdc(a, b, c)) { ++ile; przec.push_back(c); } if (NaOdc(a, b, d)) { ++ile; przec.push_back(d); } if (ile != 0) continue; int dod = 0, uj = 0; if (Wek(a, b, c) > 0) ++dod; if (Wek(a, b, c) < 0) ++uj; if (Wek(a, b, d) > 0) ++dod; if (Wek(a, b, d) < 0) ++uj; if (dod != 1 || uj != 1) continue; dod = 0; uj = 0; if (Wek(c, d, a) > 0) ++dod; if (Wek(c, d, a) < 0) ++uj; if (Wek(c, d, b) > 0) ++dod; if (Wek(c, d, b) < 0) ++uj; if (dod != 1 || uj != 1) continue; przec.push_back(PrzeOdc(a, b, c, d)); } } for (int k = 0; k < przec.size(); ++k) przec[k].nr = k; sort(przec.begin(), przec.end(), por); for (int k = 1; k < przec.size(); ++k) { pkt sr = {(przec[k].x + przec[k - 1].x) / 2.0, (przec[k].y + przec[k - 1].y) / 2.0, 0}; bool jest = false; for (int l = 0; l < n; ++l) if (l != i && WTrojkacie(p[l], sr)) jest = true; if (jest) odp -= Odl(przec[k], przec[k - 1]); } } } cout << fixed << setprecision(6); cout << odp; return 0; }
9
CPP
#include <bits/stdc++.h> using namespace std; const int maxn = 210; int ans, dist[maxn][2], t[maxn][maxn], v[maxn][maxn], k[maxn], n, d; void solve(int p1, int p2) { int l = 0, nowp1 = 1, nowp2 = 1, nowt = 0, nowd1 = 0, nowd2 = 0; while (nowp1 <= k[p1] && nowp2 <= k[p2]) { if (t[p1][nowp1] < t[p2][nowp2]) { nowd1 += (t[p1][nowp1] - nowt) * v[p1][nowp1]; nowd2 += (t[p1][nowp1] - nowt) * v[p2][nowp2]; nowt = t[p1][nowp1]; nowp1++; } else { nowd1 += (t[p2][nowp2] - nowt) * v[p1][nowp1]; nowd2 += (t[p2][nowp2] - nowt) * v[p2][nowp2]; nowt = t[p2][nowp2]; nowp2++; } int p = l; while (p && dist[p][0] == dist[p][1]) p--; if (p) { if (dist[p][0] < dist[p][1] && nowd1 > nowd2) ans++; if (dist[p][1] < dist[p][0] && nowd2 > nowd1) ans++; } l++; dist[l][0] = nowd1; dist[l][1] = nowd2; } } int main() { scanf("%d%d", &n, &d); for (int a = 1; a <= n; a++) { scanf("%d", &k[a]); for (int b = 1; b <= k[a]; b++) { scanf("%d%d", &v[a][b], &t[a][b]); t[a][b] += t[a][b - 1]; } } for (int a = 1; a <= n; a++) for (int b = a + 1; b <= n; b++) solve(a, b); printf("%d\n", ans); return 0; }
11
CPP
print([i for i in range(int(input()) + 1, 10235) if len(set(str(i))) == len(str(i))][0])
7
PYTHON3
#include <bits/stdc++.h> using namespace std; long long int a[1010]; int main() { long long int n, i, ans = 0, current = 0, count = 1; bool change; cin >> n; for (i = 0; i < n; i++) { cin >> a[i]; } while (1) { change = false; if (count % 2 == 1) { for (i = 0; i < n; i++) { if (a[i] != (-1) && a[i] <= current) { change = true; a[i] = (-1); current++; } } } else if (count % 2 == 0) { for (i = n - 1; i >= 0; i--) { if (a[i] != (-1) && a[i] <= current) { change = true; a[i] = (-1); current++; } } } if (!change) break; else { ans++; count++; } } ans--; printf("%I64d\n", ans); return 0; }
8
CPP
#include <bits/stdc++.h> using namespace std; const int MAXN = 7005; int n; long long a[MAXN]; long long b[MAXN]; vector<int> edges[MAXN]; map<long long, int> cnt; int vis[MAXN]; long long ans = 0; void dfs(int i) { if (vis[i]) return; vis[i] = 1; ans += b[i]; for (auto nex : edges[i]) dfs(nex); } int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; cnt[a[i]] = cnt[a[i]] + 1; } for (int i = 1; i <= n; i++) cin >> b[i]; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { long long x = a[i]; long long y = a[j]; if (x == y) continue; if ((x & y) == x) { edges[j].push_back(i); } else if ((x & y) == y) { edges[i].push_back(j); } } } for (int i = 1; i <= n; i++) { if (cnt[a[i]] > 1) { dfs(i); } } cout << ans << endl; return 0; }
8
CPP
n = int(input()) count = 0 for i in range(n): c = 0 p = [int(k) for k in input().split()] for j in p: if j == 1: c+=1 if c >=2: count+=1 print(count)
7
PYTHON3
#include <bits/stdc++.h> using namespace std; using ll = long long; const int N = 300500; ll fact[N]; ll invFact[N]; const int mod = 1e9 + 7; ll fast_pow(ll a, ll p) { ll res = 1; while (p) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } ll nCk(int n, int k) { if (k > n) { return 0; } return fact[n] * invFact[k] % mod * invFact[n - k] % mod; } void solve() { int n, m; cin >> n >> m; cout << nCk(n + 2 * m - 1, 2 * m) << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); fact[0] = invFact[0] = 1; for (int i = 1; i < N; i++) { fact[i] = (fact[i - 1] * i) % mod; invFact[i] = fast_pow(fact[i], mod - 2); } int t = 1; while (t--) { solve(); } }
9
CPP
#include <bits/stdc++.h> using namespace std; const int nmax = 1e6 + 50; const int qmax = 2e5 + 50; struct Que { int l, r, c, p; }; Que query[qmax]; bool cmp(Que A, Que B) { return A.p < B.p; } vector<int> in[nmax], out[nmax]; vector<int> pp; map<int, int> mp; struct Seg { long long cnt, val, tag; Seg() { cnt = val = tag = 0; } }; Seg tree[nmax * 4]; int n, k, m; void pushup(int rt) { tree[rt].val = tree[rt << 1].val + tree[rt << 1 | 1].val; tree[rt].cnt = tree[rt << 1].cnt + tree[rt << 1 | 1].cnt; } void update(int rt, int l, int r, int qid, int cc) { if (qid < l || qid > r) return; if (l == r && qid == l) { tree[rt].cnt += cc; tree[rt].val += (long long)cc * pp[l - 1]; return; } int mid = (l + r) / 2; update(rt << 1, l, mid, qid, cc); update(rt << 1 | 1, mid + 1, r, qid, cc); pushup(rt); } long long qu(int rt, int l, int r, int ql, int qr) { if (qr < l || ql > r) return 0; if (ql <= l && qr >= r) { return tree[rt].cnt; } int mid = (l + r) / 2; return qu(rt << 1, l, mid, ql, qr) + qu(rt << 1 | 1, mid + 1, r, ql, qr); } long long sum(int rt, int l, int r, int ql, int qr) { if (qr < l || ql > r) return 0; if (ql <= l && qr >= r) { return tree[rt].val; } int mid = (l + r) / 2; return sum(rt << 1, l, mid, ql, qr) + sum(rt << 1 | 1, mid + 1, r, ql, qr); } int main() { long long cc = 0; scanf("%d%d%d", &n, &k, &m); for (int i = 0; i < m; i++) { scanf("%d%d%d%d", &query[i].l, &query[i].r, &query[i].c, &query[i].p); in[query[i].l].push_back(i); out[query[i].r].push_back(i); pp.push_back(query[i].p); } sort(pp.begin(), pp.end()); int tot = unique(pp.begin(), pp.end()) - pp.begin(); for (int i = 0; i < tot; i++) mp[pp[i]] = i + 1; for (int i = 1; i <= n; i++) { for (int j = 0; j < in[i].size(); j++) { int id = in[i][j]; update(1, 1, tot, mp[query[id].p], query[id].c); } int l = 1, r = tot, ans = r; while (l <= r) { int mid = (l + r) / 2; if (qu(1, 1, tot, 1, mid) >= k) { ans = mid; r = mid - 1; } else l = mid + 1; } long long ss = qu(1, 1, tot, 1, ans - 1); cc += sum(1, 1, tot, 1, ans - 1) + (min((long long)k, qu(1, 1, tot, 1, ans)) - ss) * pp[ans - 1]; for (int j = 0; j < out[i].size(); j++) { int id = out[i][j]; update(1, 1, tot, mp[query[id].p], -query[id].c); } } cout << cc << endl; return 0; }
9
CPP
#include <bits/stdc++.h> using namespace std; const int MAXN = 2000005; class PalinTree { public: char s[MAXN]; int head[MAXN], nxt[MAXN], ch[MAXN], m; char nx[MAXN]; int fail[MAXN], len[MAXN], cnt[MAXN]; int last, sz, n; inline int newnode(int L) { cnt[sz] = 0, len[sz] = L; head[sz] = 0; return sz++; } inline void init() { m = n = sz = 0; last = 1; newnode(0); newnode(-1); s[0] = -1, fail[0] = 1; } inline int GetFail(int v) { while (s[n - len[v] - 1] != s[n]) v = fail[v]; return v; } inline int add(int c) { s[++n] = c; int cur = GetFail(last), i, j; for (i = head[cur]; i; i = nxt[i]) if (nx[i] == c) break; if (!i) { int now = newnode(len[cur] + 2); int failcur = GetFail(fail[cur]); for (j = head[failcur]; j; j = nxt[j]) if (nx[j] == c) break; if (j) fail[now] = ch[j]; else fail[now] = 0; nxt[++m] = head[cur]; head[cur] = m; nx[m] = c; ch[m] = now; cnt[now] = cnt[fail[now]] + 1; last = now; } else last = ch[i]; return cnt[last]; } }; PalinTree P; const long long MOD = 51123987; int n; char second[MAXN]; long long sum[MAXN]; int main() { ios::sync_with_stdio(false); scanf("%d", &n); scanf("%s", second); sum[n] = 0; P.init(); for (int i = n - 1; i >= 0; --i) { sum[i] = (sum[i + 1] + P.add(second[i] - 'a')) % MOD; } P.init(); long long delta = 0; for (int i = 0; i < n; ++i) { delta = (delta + 1ll * P.add(second[i] - 'a') * sum[i + 1]) % MOD; } printf("%I64d\n", ((1ll * sum[0] * sum[0] - sum[0]) / 2 - delta + MOD) % MOD); return 0; }
11
CPP
#include<bits/stdc++.h> #define all(v) v.begin(),v.end() using namespace std; typedef long long ll; typedef pair<int,int> P; const ll MOD=1000000007; const ll INF=1000000000; const ll LINF=4000000000000000010; ll dp[200010],x[200010]; struct Segtree{ int n; vector<ll> node; Segtree(int n_){ n=1; while(n<n_)n*=2; node.resize(2*n,LINF); } void update(int k,ll x){ k+=n-1; node[k]=x; while(k>0){ k=(k-1)/2; node[k]=min(node[2*k+1],node[2*k+2]); } } ll getmin(int a,int b,int k=0,int l=0,int r=-1){ if(r<0)r=n; if(r<=a||b<=l)return LINF; if(a<=l&&r<=b)return node[k]; ll vl=getmin(a,b,2*k+1,l,(l+r)/2); ll vr=getmin(a,b,2*k+2,(l+r)/2,r); return min(vl,vr); } }; int main(){ int n,q,a,b;cin>>n>>q>>a>>b; for(int i=1;i<=q;i++)cin>>x[i]; x[0]=a; fill(dp,dp+q+2,LINF); Segtree tree1(2*n); Segtree tree2(2*n); tree1.update(b,-b); tree2.update(b,b); ll sum=0; for(int i=0;i<q;i++){ dp[i]=min(tree1.getmin(0,x[i+1]+1)+x[i+1],tree2.getmin(x[i+1],n+1)-x[i+1]); tree1.update(x[i],dp[i]-x[i]-abs(x[i+1]-x[i])); tree2.update(x[i],dp[i]+x[i]-abs(x[i+1]-x[i])); sum+=abs(x[i+1]-x[i]); } ll ans=LINF; for(ll i=0;i<=n;i++){ ans=min(ans,tree2.getmin(i,i+1)-i); } cout<<ans+sum<<endl; }
0
CPP
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } vector<int> b; for (int i = 0; i < n; i++) { if ((int)b.size() > 0 && a[i] % 2 == b.back()) { b.pop_back(); } else { b.push_back(a[i] % 2); } } cout << ((int)b.size() < 2 ? "YES" : "NO") << '\n'; return 0; }
10
CPP
import sys a = list(map(int, sys.stdin.readline().split())) print((2**(a[0]+a[1])) % 998244353 )
9
PYTHON3
t=int(input()) for _ in range(t): c=list(map(int,input().split())) o,e=0,0 for i in c: if i%2==0: e+=1 else: o+=1 if c[0] == 0 or c[1] == 0 or c[2] == 0 : if o>1: print('No') else: print('Yes') else: if o==2: print('No') else: print('Yes')
7
PYTHON3
# from (x,y) to SW (0,0) by (-1,-1) def raySW(x,y): return x - y n,w,d=map(int,input().split()) def toRange(xyf): sx,sy,f = xyf x=int(sx) y=int(sy) if f == 'S': s = raySW(x,y) t = w - raySW(w-x,y) # flip in X return (s,t) if f == 'E': s = w - raySW(w-x,y) # flip in X t = w + d + raySW(w-x,d-y) # flip in both X and Y return (s,t) if f == 'N': s = w + d + raySW(w-x,d-y) # flip in both X and Y t = w + d + w - raySW(x,d-y) # flip in Y return (s,t) if f == 'W': s = w + d + w - raySW(x,d-y) # flip in Y t = w + d + w + d + raySW(x,y) return (s,t) if t <= w+d+w+d else (s-w-w-d-d,t-w-w-d-d) exit(-1) xyfs=[input().split() for _ in range(n)] def swap(xy): x,y=xy return (y,x) stso=list(map(swap,list(map(toRange,xyfs)))) sts=sorted(stso) def contains(s,t,r): if t <= r <= s: return True if t <= r+d+d+w+w <= s: return True if t <= r-d-d-w-w <= s: return True return False def findMin(sts): c = 0 r = w+w+d+d+w+w+d+d+w+w+d+d for s,t in sts: if not contains(s,t,r): # put a new clock at t c += 1 r = s return c # stupid concat? mins=[findMin(sts[i:] + sts[:i]) for i in range(n)] print(min(mins))
0
PYTHON3
#include <bits/stdc++.h> using namespace std; bool cmp(int a, int b) { return a > b; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n, m; cin >> n; vector<int> a(n), a_f(n); for (int i = 0; i < n; i++) { cin >> a[i]; a_f[i] = a[i]; } sort(a_f.begin(), a_f.end(), cmp); cin >> m; for (int i = 0; i < m; i++) { int k, pos; cin >> k >> pos; multiset<int> A; for (int j = 0; j < k; j++) { A.insert(a_f[j]); } vector<bool> used(n); int now = 0; for (int now = 0; now < n; now++) { if (A.find(a[now]) != A.end()) { A.erase(A.find(a[now])); used[now] = true; } } vector<int> ans1; for (int j = 0; j < n; j++) { if (used[j]) { ans1.push_back(a[j]); } } cout << ans1[pos - 1] << endl; } }
10
CPP
t=int(input()) while(t): n,m=map(int,input().split()) a=[] count=0 for i in range(n): x=list(input()) a.append(x) for i in range(n): if(a[i][m-1]=='R'): count+=1 for i in range(m): if(a[n-1][i]=='D'): count+=1 print(count) t-=1
8
PYTHON3
x,y,z=map(int,input().split()) s = 0 s = (z*(x+(x*z)))//2 if(s>y): print(s-y) else: print("0")
7
PYTHON3
def team(n): i=0 cnt=0 while i < n: pvt=list(map(int,input().split())) i +=1 if pvt.count(1)>=2: cnt+=1 return cnt print(team(int(input())))
7
PYTHON3
#include <bits/stdc++.h> #include <algorithm> #include <string> using namespace std; int main() { int N, M; cin >> N >> M; pair<int, int> A[100010]; for(int i = 0; i < M; i++){ int a, b; cin >> a >> b; A[i].first = b, A[i].second = a; } sort(A, A+M); int count = 0, R = 0; for(int i = 0; i < M; i++){ if(A[i].second >= R){ count ++; R = A[i].first; } } cout << count << endl; }
0
CPP
import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] # testCases = int(input()) # answers = [] # for _ in range(testCases): #take input n, m = input_split() grid = [] for _ in range(n): grid.append([int(i) for i in input()]) # def binary(a): # def is_good_square(grid, row, col): # ans = 0 # for i in range(row, row + 2): # for j in range(col, col + 2): # if grid[i][j] == '1': # ans += 1 # return ans if n >= 4 and m >= 4: ans = -1 elif n< 2 or m < 2: ans = 0 else: # oss = list(range(2**(n*m))) if n == 2 or m == 2: if n == 2: arr = [] for i in range(m): arr.append((grid[0][i] + grid[1][i])%2) elif m == 2: arr = [] for i in range(n): arr.append((grid[i][0] + grid[i][1])%2) cost1 = 0 cost2 = 0 current = 0 for i in range(len(arr)): cost1 += abs(current - arr[i]) cost2 += abs((1-current) - arr[i]) current = 1 - current ans = min(cost1, cost2) elif n == 3 or m == 3: if n == 3: arr1 = [] arr2 = [] for i in range(m): arr1.append((grid[0][i] + grid[1][i])%2) arr2.append((grid[1][i] + grid[2][i])%2) else: #m must be 3 arr1 = [] arr2 = [] for i in range(n): arr1.append((grid[i][0] + grid[i][1])%2) arr2.append((grid[i][1] + grid[i][2])%2) #analysis #case1 # start = 0 # cost1 = 0 cost1 = 0 cost2 = 0 cost3 = 0 cost4 = 0 current = 0 for i in range(len(arr1)): cost1 += max(abs(current - arr1[i]),abs(current - arr2[i]) ) cost3 += max(abs(current - arr1[i]),abs((1-current) - arr2[i]) ) cost2 += max(abs((1-current) - arr1[i]), abs((1-current) - arr2[i])) cost4 += max(abs((1-current) - arr1[i]), abs((current) - arr2[i])) current = 1 - current ans = min(cost1, cost2, cost3, cost4) print(ans) # answers.append(ans) # print(*answers, sep = '\n')
10
PYTHON3
#include <bits/stdc++.h> using namespace std; int f[600000 * 2][22], deep[600000 * 2]; int start, endt, maxlen; void init() { int i; start = 2, endt = 4, maxlen = 2; for (i = 0; i < 22; i++) f[1][i] = 1, f[2][i] = 1, f[3][i] = 1, f[4][i] = 1; memset(deep, 0, sizeof(deep)); deep[1] = 1, deep[2] = 2, deep[3] = 2, deep[4] = 2; } void add(int a, int fa) { int i; f[a][0] = fa; for (i = 1; i < 22; i++) f[a][i] = f[f[a][i - 1]][i - 1]; deep[a] = deep[fa] + 1; } int search(int a, int co) { int i; if (deep[a] < deep[co]) swap(a, co); int k = deep[a] - deep[co]; for (i = 0; i < 22; i++) { if ((1 << i) & k) { a = f[a][i]; } } int temp = deep[a], lq; for (i = 22 - 1; i >= 0; i--) { if (f[a][i] == f[co][i]) { lq = f[a][i]; } else { a = f[a][i], co = f[co][i]; } } return 2 * (temp - deep[lq]) + k; } int main() { int t, v; while (scanf("%d", &t) != EOF) { init(); int n = 5; while (t--) { scanf("%d", &v); add(n++, v); add(n++, v); int bt = endt; int temp = search(n - 1, start); if (temp > maxlen) { maxlen = temp; endt = start, start = n - 1; } temp = max(temp, search(n - 1, bt)); if (temp > maxlen) { maxlen = temp; endt = bt, start = n - 1; } printf("%d\n", maxlen); } } return 0; }
12
CPP
#include <bits/stdc++.h> using namespace std; int main() { int n; while (~scanf("%d", &n)) { int num[n]; for (int i = 0; i < n; i++) { scanf("%d", &num[i]); } sort(num, num + n); if (num[n - 1] == 1) num[n - 1] = 2; else num[n - 1] = 1; sort(num, num + n); printf("%d", num[0]); for (int i = 1; i < n; i++) printf(" %d", num[i]); printf("\n"); } return 0; }
7
CPP
n = int(input()) s = input() answer = 0 for i in range(n - 1): if s[i] == s[i +1]: answer += 1 print(answer)
7
PYTHON3
from sys import stdin,stdout import math n=int(stdin.readline()) li=list(map(int,stdin.readline().split())) d={} for i in range(1,8): d[i]=li.count(i) li2=[] while True: if d[1]>0 and d[2]>0 and d[4]>0: li2.append([1,2,4]) d[1]-=1 d[2]-=1 d[4]-=1 elif d[1]>0 and d[2]>0 and d[6]>0: li2.append([1,2,6]) d[1]-=1 d[2]-=1 d[6]-=1 elif d[1]>0 and d[3]>0 and d[6]>0: li2.append([1,3,6]) d[1]-=1 d[3]-=1 d[6]-=1 else: break #print(d) #print(li2) if(len(li2)*3==n): for i in range(len(li2)): print(li2[i][0],li2[i][1],li2[i][2]) else: print(-1)
7
PYTHON3
#include <bits/stdc++.h> using namespace std; const int maxn = 50; int k, n, m, bel[maxn], sz[maxn], id[maxn], p[maxn], col[maxn]; bool g[maxn][maxn]; char s[maxn][maxn]; void dfs(int u) { bel[u] = m; for (int v = 0; v < n; ++v) if (s[u][v] == 'A' && !bel[v]) dfs(v); return; } int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%s", s + i); for (int u = 0; u < n; ++u) if (!bel[u]) { ++m; dfs(u); } for (int u = 0; u < n; ++u) for (int v = 0; v < n; ++v) { if (s[u][v] == 'A' && bel[u] != bel[v]) { puts("-1"); exit(0); } if (s[u][v] == 'X' && bel[u] == bel[v]) { puts("-1"); exit(0); } } for (int u = 0; u < n; ++u) ++sz[bel[u]]; for (int u = 1; u <= m; ++u) if (sz[u] >= 2) id[u] = k++; else id[u] = -1; if (!k) { printf("%d\n", n - 1); return 0; } for (int u = 0; u < n; ++u) for (int v = 0; v < n; ++v) if (s[u][v] == 'X') { int x = id[bel[u]], y = id[bel[v]]; if (~x && ~y) g[x][y] = g[y][x] = 1; } for (int i = 0; i < k; ++i) p[i] = i; int T = 0, ans = k; while (T <= 700000000) { random_shuffle(p, p + k); int cnt = 0; for (int i = 0; i < k; ++i) { ++T; int &u = p[i]; if (!i) { col[i] = cnt++; continue; } int S = 0; for (int j = 0; j < i; ++j) { ++T; if (g[u][p[j]]) S |= (1 << col[j]); } S ^= (1 << cnt + 1) - 1; for (;;) { int t = (rand()) % (cnt + 1); T += 5; if ((S >> t) & 1) { col[i] = t; break; } } cnt = max(cnt, col[i] + 1); } ++T; ans = min(ans, cnt); } --ans; for (int i = 1; i <= m; ++i) if (sz[i] >= 2) ans += sz[i]; printf("%d\n", ans + m - k); return 0; }
14
CPP
#include <bits/stdc++.h> using namespace std; long long n, mp[100][100], c[100], K, ans, dp[15][100]; void solve() { memset(dp, 0x3f, sizeof dp); dp[0][1] = 0; for (int k = 1; k <= K; k++) for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (c[i] != c[j] && dp[k - 1][j] != 0x3f3f3f3f3f3f3f3f) dp[k][i] = min(dp[k][i], dp[k - 1][j] + mp[j][i]); ans = min(ans, dp[K][1]); } int main() { cin >> n >> K; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) cin >> mp[i][j]; ans = 0x3f3f3f3f3f3f3f3f; int t = 5000; srand(time(0)); while (t--) { for (int i = 1; i <= n; i++) c[i] = rand() % 2; solve(); } cout << ans << '\n'; }
10
CPP
#include <bits/stdc++.h> using namespace std; int n, sn, q, a, b, c; vector<vector<int> > graph; vector<int> p, g, h; void dfs(int u, int d) { if (d % sn == 0) g[u] = p[u]; else g[u] = g[p[u]]; h[u] = d; for (int v : graph[u]) { if (!p[v]) { p[v] = u; dfs(v, d - 1); } } } int lca(int u, int v) { while (h[g[u]] < h[v]) { u = g[u]; } while (h[g[v]] < h[u]) { v = g[v]; } while (h[u] < h[v]) { u = p[u]; } while (h[v] < h[u]) { v = p[v]; } while (g[u] != g[v]) { u = g[u], v = g[v]; } while (u != v) { u = p[u], v = p[v]; } return u; } int main() { ios::sync_with_stdio(false); cin >> n >> q; sn = (int)sqrt(n); p.assign(n + 1, 0), g.assign(n + 1, 0), graph.resize(n + 1), h.resize(n + 1); for (int i = 2; i <= n; ++i) { int pin; cin >> pin; graph[pin].push_back(i); graph[i].push_back(pin); } p[1] = 1; dfs(1, 0); for (int i = 1; i <= q; ++i) { cin >> a >> b >> c; int x = lca(a, b), y = lca(b, c), z = lca(c, a); int out = 0; if (x == y) { out = max(out, h[x] - h[b] + h[x] - h[z] + 1); out = max(out, max(h[z] - h[a] + 1, h[z] - h[c] + 1)); } else if (x == z) { out = max(out, h[x] - h[a] + h[x] - h[y] + 1); out = max(out, max(h[y] - h[b] + 1, h[y] - h[c] + 1)); } else if (z == y) { out = max(out, h[z] - h[c] + h[z] - h[x] + 1); out = max(out, max(h[x] - h[a] + 1, h[x] - h[b] + 1)); } cout << out << endl; } return 0; }
10
CPP
s=input() ans=[] ab=[0] bb=[0] for i in range(len(s)): if(s[i]=='a'): ab.append(ab[-1]+1) bb.append(bb[-1]) if(s[i]=='b'): bb.append(bb[-1]+1) ab.append(ab[-1]) maxa=0 l=0 r=0 for l in range(len(ab)): for r in range(l,len(ab)): maxa=max(ab[l]+(ab[-1]-ab[r])+(bb[r]-bb[l]),maxa) print(maxa)
8
PYTHON3
X, N = input(), int(input()) S = len(X) if S // N != S / N: print("NO");exit() S = S // N print("NO" if any([(True if X[i * S:i * S + S] != X[i * S:i * S + S][::-1] else False) for i in range(N)]) else "YES") # Come together for getting better !!!!
7
PYTHON3
n, k, q = map(int, input().split()) data = list(map(int, input().split())) data1 = set() for i in range(q): typ, fr = map(int, input().split()) fr -= 1 if typ == 2: if data[fr] in data1: print("YES") else: print("NO") else: if len(list(data1)) < k: data1.add(data[fr]) elif data[fr] >= min(list(data1)): data1.add(data[fr]) data1.remove(min(list(data1)))
8
PYTHON3
#include <bits/stdc++.h> using namespace std; int n, k; map<char, int> mp; int main() { string in; ios::sync_with_stdio(0); cin >> n >> k; for (int i = 0; i < n; ++i) { char t; cin >> t; if (mp[t] == 0) { in.push_back(t); mp[t]++; } } sort(in.begin(), in.end()); long ans = INT_MAX; for (int j = 0; j < in.size(); ++j) { int l = k; long a = in[j] - 'a' + 1; int f = j; int s = j; l--; while (l--) { while (s < n && in[s] <= in[f] + 1) s++; if (s >= n) break; a += (in[s] - 'a' + 1) * mp[in[s]]; f = s; } if (l == -1) ans = min(a, ans); } if (ans == INT_MAX) cout << -1; else cout << ans; }
7
CPP
#include <bits/stdc++.h> using namespace std; const int Maxn = 1000 + 9; int n, m, cnt; long long Ans; int Dx[Maxn], Dy[Maxn], cx[Maxn], cy[Maxn]; char s[Maxn]; inline void calc_x() { for (int i = 1; i <= n; i++) if (Dx[i]) { int tmp = Dx[i]; for (int j = i + 1; j <= n && Dx[j] && Dx[j] < Dx[j - 1]; j++) Ans += 2 * 2 * (m - tmp) * (Dx[j] - 1); for (int j = i + 1; j <= n && Dx[j] && Dx[j] > Dx[j - 1]; j++) Ans += 2 * 2 * (m - Dx[j]) * (tmp - 1); Ans += 2 * 2 * (tmp - 1) * (m - tmp); } } inline void calc_y() { for (int i = 1; i <= m; i++) if (Dy[i]) { int tmp = Dy[i]; for (int j = i + 1; j <= m && Dy[j] && Dy[j] < Dy[j - 1]; j++) Ans += 2 * 2 * (n - tmp) * (Dy[j] - 1); for (int j = i + 1; j <= m && Dy[j] && Dy[j] > Dy[j - 1]; j++) Ans += 2 * 2 * (n - Dy[j]) * (tmp - 1); Ans += 2 * 2 * (tmp - 1) * (n - tmp); } } int main() { scanf("%d%d", &n, &m); cnt = n * m; for (int i = 1; i <= n; i++) { scanf("%s", s); for (int j = 1; j <= m; j++) if (s[j - 1] == 'X') Dx[i] = j, Dy[j] = i, cnt--; else cx[i]++, cy[j]++; } for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) Ans += abs(i - j) * cx[i] * cx[j]; for (int i = 1; i <= m; i++) for (int j = 1; j <= m; j++) Ans += abs(i - j) * cy[i] * cy[j]; calc_x(); calc_y(); printf("%.6lf\n", 1.0 * Ans / (1.0 * cnt * cnt)); }
10
CPP
m=input() n=input() rev=''.join(reversed(n)) if rev==m: print("YES") else: print("NO")
7
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int b, p, c, h1, h2; cin >> b >> p >> c >> h1 >> h2; if (b == 0 || (p == 0 && c == 0)) { cout << 0 << endl; } else if (p == 0) { int mx = -1; for (int i = 1; i <= c; i++) { if ((i * 2) <= b) { mx = max(mx, (i * h2)); } else { break; } } cout << mx << endl; } else if (c == 0) { int mx = -1; for (int i = 1; i <= p; i++) { if ((i * 2) <= b) { mx = max(mx, (i * h1)); } else { break; } } cout << mx << endl; } else { int mx = -1; for (int i = 0; i <= p; i++) { for (int j = 0; j <= c; j++) { if ((i + j) * 2 <= b) { mx = max(mx, (h1 * i) + (h2 * j)); } } } cout << mx << endl; } } return 0; }
7
CPP
n = int(input()) A = list(map(int,input().split())) flag = 0 for i in range(len(A)): if A[i] == 1: print('HARD') flag += 1 break if flag == 0: print('EASY')
7
PYTHON3
n = input().split(); n,k = int(n[0]),int(n[1]); boxes = input().split() boxes = list(map(int,boxes)) array = [] for i in range(k): array.append(n%boxes[i]); minimum = 0; for j in range(k): if ( array[j] <= array[minimum] ) : minimum = j; print (str(minimum+1)+" "+str(n//boxes[minimum]))
8
PYTHON3
#include <bits/stdc++.h> using namespace std; const int N = 1006; const long long MOD = 1000 * 1000 * 1000 + 7; bool dzn(char k) { if (k == 'a' || k == 'u' || k == 'i' || k == 'o' || k == 'e') return true; return false; } int n; long long dp[N][N][2]; void solve(int bac, int pak) { if (pak == n) return; if (dp[bac][pak][1]) return; if (pak == bac) { solve(bac + 1, pak); dp[bac][pak][1] = max(dp[bac + 1][pak][0] + 1, dp[bac + 1][pak][1]); dp[bac][pak][0] = dp[bac + 1][pak][1]; dp[bac][pak][0] %= MOD; dp[bac][pak][1] %= MOD; } else if (bac == n) { solve(bac, pak + 1); dp[bac][pak][1] = max(dp[bac][pak + 1][0] + 1, dp[bac][pak + 1][1]); dp[bac][pak][0] = dp[bac][pak + 1][1]; dp[bac][pak][0] %= MOD; dp[bac][pak][1] %= MOD; } else { solve(bac + 1, pak); solve(bac, pak + 1); dp[bac][pak][0] = dp[bac + 1][pak][1] + dp[bac][pak + 1][1]; dp[bac][pak][1] = max(dp[bac][pak][0], max(dp[bac + 1][pak][0] + dp[bac][pak + 1][1] + 1, dp[bac + 1][pak][1] + dp[bac][pak + 1][0] + 1)); dp[bac][pak][0] %= MOD; dp[bac][pak][1] %= MOD; } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); cin >> n; solve(0, 0); cout << dp[0][0][1] << endl; return 0; }
10
CPP
#include <bits/stdc++.h> using namespace std; template <typename T> inline void read(T &x) { char c; bool nega = 0; while ((!isdigit(c = getchar())) && (c != '-')) ; if (c == '-') { nega = 1; c = getchar(); } x = c - 48; while (isdigit(c = getchar())) x = x * 10 + c - 48; if (nega) x = -x; } template <typename T> inline void writep(T x) { if (x > 9) writep(x / 10); putchar(x % 10 + 48); } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } writep(x); } template <typename T> inline void writeln(T x) { write(x); putchar('\n'); } int FMAX[100001]; int a[100001]; int n, k; void solve(int l, int r, int k) { if (l == r - 1 || k == 1) return; int m = (l + r) / 2; reverse(a + l, a + r); reverse(a + l, a + m); reverse(a + m, a + r); if (k - 2 > FMAX[m - l]) { solve(l, m, FMAX[m - l]); solve(m, r, k - 1 - FMAX[m - l]); } else { solve(l, m, k - 2); solve(m, r, 1); } } int main() { read(n); read(k); for (int i = 1; i <= n; i++) FMAX[i] = i * 2 - 1; if ((FMAX[n] < k) || (k % 2 == 0)) { write(-1); return 0; } if (n == 1) { write(1); return 0; } for (int i = 0; i < n; i++) a[i] = i + 1; solve(0, n, k); for (int i = 0; i < n; i++) { if (i) putchar(' '); write(a[i]); } }
10
CPP
#include <bits/stdc++.h> using namespace std; int read() { int x = 0, f = 1; char ch = getchar(); while (!isdigit(ch) && ch != '-') ch = getchar(); if (ch == '-') f = -1, ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar(); return x * f; } void write(long long x) { char ch[20]; int f = 0; if (!x) { putchar('0'), putchar('\n'); return; } if (x < 0) putchar('-'), x = -x; while (x) ch[++f] = x % 10 + '0', x /= 10; while (f) putchar(ch[f--]); putchar('\n'); } int n, m, cnte, a, b, fir[200007], v[500007 << 1], nxt[500007 << 1], vis[200007], suma, sumb; void ade(int u1, int v1) { v[cnte] = v1, nxt[cnte] = fir[u1], fir[u1] = cnte++; } void dfs(int u, int ban, int& s) { if (!vis[u]) vis[u] = 1, s--; for (int k = fir[u]; ~k; k = nxt[k]) if (v[k] != ban && !vis[v[k]]) dfs(v[k], ban, s); } int main() { int t = read(); while (t--) { n = read(), m = read(), a = read(), b = read(); cnte = suma = sumb = 0; for (int i = (1); i <= (n); ++i) fir[i] = -1, vis[i] = 0; for (int i = (1); i <= (m); ++i) { int x = read(), y = read(); ade(x, y), ade(y, x); } suma = n - 2, vis[a] = 1, dfs(a, b, suma); for (int i = (1); i <= (n); ++i) vis[i] = 0; sumb = n - 2, vis[b] = 1, dfs(b, a, sumb); write((long long)suma * sumb); } return (~(0 - 0) + 1); }
8
CPP
#include <bits/stdc++.h> using namespace std; int main() { ios_base ::sync_with_stdio(false); int n, k, pos1, pos2; string s; pos1 = -1; cin >> n >> k >> s; int i; for (i = (0); i < (n); ++i) { if (s[i] == 'T' || s[i] == 'G') { if (pos1 == -1) { pos1 = i; } else { pos2 = i; } } } int pos = pos1; while (pos < n) { if (s[pos] == '#') { break; } if (pos == pos2) { cout << "YES" << endl; return 0; } pos += k; } cout << "NO" << endl; }
7
CPP
from heapq import heapify,heappush, heappop def solve(items,builds): inf = 10**12 sol = [0]*len(items) scores= [] heapify(scores) max_score = -sum([items[i][sol[i]][1] for i in range(len(items))]) heappush(scores, max_score) score_to_build = {} score_to_build[max_score] = set([" ".join([str(x) for x in sol])]) for _ in range(len(builds)+1): cur_score = heappop(scores) while len(score_to_build[cur_score]) > 0: b = [int(x) for x in score_to_build[cur_score].pop().split(" ")] # check if sol build = get_build(items, b) if build not in builds: return build # b = [int(x) for x in build.split(" ")] # create new score for i,x in enumerate(b): new_sol = b[:] if x < len(items[i]) -1: new_sol[i] = x+1 this_score = cur_score - (items[i][x+1][0]-items[i][x][0]) # if this_score == cur_score: # print("why") if this_score not in score_to_build: score_to_build[this_score] = set() heappush(scores, this_score) new_b = " ".join([str(x) for x in new_sol]) score_to_build[this_score].add(new_b) def get_build(items, sol): build = " ".join([str(items[i][sol[i]][1]) for i in range(len(items))]) return build import os import io import time if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input().decode().strip()) items=[] for i in range(n): ci =[int(x) for x in input().decode().strip().split(" ")] ci.pop(0) ci = [(ci[j],j+1) for j in range(len(ci))] ci.sort(reverse=True) items.append(ci) m = int(input().decode().strip()) builds = set() for i in range(m): b = input().decode().strip() builds.add(b) a = solve(items, builds) print(a)
10
PYTHON3
def main(): x=0 y=0 z=0 for i in range(int(input())): dx,dy,dz=map(int,input().split()) x+=dx y+=dy z+=dz if(x==0 and y==0 and z==0): print("YES") else: print("NO") main()
7
PYTHON3
i = -1 mas0 = [] mas1 = [] mas2 = [] mas3 = [] mas = [] r = 0 b = 0 y = 0 g = 0 n = input() # done # for element in n: mas.append(element) for element in mas: i += 1 if i == 0 or i % 4 == 0: mas0.append(element) if i % 4 == 1: mas1.append(element) if i % 4 == 2: mas2.append(element) if i % 4 == 3: mas3.append(element) # for R # if 'R' in mas0: for element in mas0: if element == '!': r += 1 elif 'R' in mas1: for element in mas1: if element == '!': r += 1 elif 'R' in mas2: for element in mas2: if element == '!': r += 1 elif 'R' in mas3: for element in mas3: if element == '!': r += 1 # for B # if 'B' in mas0: for element in mas0: if element == '!': b += 1 elif 'B' in mas1: for element in mas1: if element == '!': b += 1 elif 'B' in mas2: for element in mas2: if element == '!': b += 1 elif 'B' in mas3: for element in mas3: if element == '!': b += 1 # for Y # if 'Y' in mas0: for element in mas0: if element == '!': y += 1 elif 'Y' in mas1: for element in mas1: if element == '!': y += 1 elif 'Y' in mas2: for element in mas2: if element == '!': y += 1 elif 'Y' in mas3: for element in mas3: if element == '!': y += 1 # for G # if 'G' in mas0: for element in mas0: if element == '!': g += 1 elif 'G' in mas1: for element in mas1: if element == '!': g += 1 elif 'G' in mas2: for element in mas2: if element == '!': g += 1 elif 'G' in mas3: for element in mas3: if element == '!': g += 1 #print(mas0) #print(mas1) #print(mas2) #print(mas3) #print('broken lamps') #print('r b y g') print(r, b, y, g)
8
PYTHON3
# testCaseNum = int(input()) # for testCase in range(testCaseNum): # n = map(int ,input().split()) # print(min(n-1 ,abs(a - b)+x)) n1 ,n2 ,k1 ,k2 = map(int ,input().split()) if n2 >= n1: print("Second") else: print("First")
7
PYTHON3
n =int(input()) c=0 b = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA','VODKA', 'WHISKEY', 'WINE'] for i in range(n): a = input() if a.isdigit(): if int(a)<18: c+=1 else: if a in b: c+=1 print(c)
7
PYTHON3
import sys q=int(input()) while q: n=int(input()) s='' while n: if n%2!=0: n-=3 s+='7' else: n-=2 s+='1' print(s) q-=1
7
PYTHON3
while True: n = int(input()) if n==0: break if n==1: print(int(input())) continue op = "+*" f = [input() for i in range(n)] f = f[::-1] stack = [] for i in range(n): if f[i][-1] not in op: stack.append(f[i]) else: nest = f[i].count(".") if f[i][-1]=="*": cur = 1 while len(stack): if stack[-1].count(".")!=nest+1: break else: t = stack.pop().strip(".") cur *= int(t) stack.append("."*(nest)+str(cur)) else: cur = 0 while len(stack): if stack[-1].count(".")!=nest+1: break else: t = stack.pop().strip(".") cur += int(t) stack.append("."*(nest)+str(cur)) print(stack[0])
0
PYTHON3
#include <bits/stdc++.h> using namespace std; const int MAX = 1e5 + 5; using ll = long long; ll ask(int t, int i, int j, int k) { printf("%d %d %d %d\n", t, i, j, k); fflush(stdout); ll ret; scanf("%lld", &ret); return ret; } vector<int> getPoints(int x, int y, const vector<int> &pp) { vector<int> ret; vector<pair<ll, int>> areas; for (int v : pp) { areas.push_back({ask(1, x, y, v), v}); } sort(areas.begin(), areas.end()); vector<int> now; int upper = areas.back().second; for (auto z : areas) { int v = z.second; if (v == upper or ask(2, x, upper, v) == -1) { ret.push_back(v); } else { now.push_back(v); } } reverse(now.begin(), now.end()); for (int v : now) { ret.push_back(v); } return ret; } int main() { int n; scanf("%d", &n); vector<int> clk, aclk; for (int i = 3; i <= n; i++) { if (ask(2, 1, 2, i) == 1) { clk.push_back(i); } else { aclk.push_back(i); } } vector<int> up = getPoints(2, 1, clk); vector<int> down = getPoints(1, 2, aclk); printf("0 1"); down.push_back(2); for (int v : down) { printf(" %d", v); } for (int v : up) { printf(" %d", v); } return 0; }
12
CPP
s = input() t = input() s = s.lower() t = t.lower() print((s > t) - (s < t))
7
PYTHON3
n = int(input()) ar = [int(i) for i in input().split()] goal = sorted(ar) for i in range(n-1): if ar[i+1] < ar[i]: for j in range(i+1, n-1): if ar[j+1] > ar[j]: ar[i:j+1] = reversed(ar[i:j+1]) if ar == goal: print("yes") print("%d %d"%(i+1, j+1)) else: print("no") quit() ar[i:] = reversed(ar[i:]) if ar == goal: print("yes") print("%d %d"%(i+1, n)) else: print("no") quit() print("yes") print("1 1")
8
PYTHON3
P=[1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51] K=int(input()) print(P[K-1])
0
PYTHON3
import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest # sys.setrecursionlimit(111111) INF=999999999999999999999999 alphabets="abcdefghijklmnopqrstuvwxyz" class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class SegTree: def __init__(self, n): self.N = 1 << n.bit_length() self.tree = [0] * (self.N<<1) def update(self, i, j, v): i += self.N j += self.N while i <= j: if i%2==1: self.tree[i] += v if j%2==0: self.tree[j] += v i, j = (i+1) >> 1, (j-1) >> 1 def query(self, i): v = 0 i += self.N while i > 0: v += self.tree[i] i >>= 1 return v def SieveOfEratosthenes(limit): """Returns all primes not greater than limit.""" isPrime = [True]*(limit+1) isPrime[0] = isPrime[1] = False primes = [] for i in range(2, limit+1): if not isPrime[i]:continue primes += [i] for j in range(i*i, limit+1, i): isPrime[j] = False return primes from collections import Counter def gcd(x, y): """greatest common divisor of x and y""" while y: x, y = y, x % y return x def memodict(f): """memoization decorator for a function taking a single argument""" class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ def pollard_rho(n): """returns a random factor of n""" if n & 1 == 0: return 2 if n % 3 == 0: return 3 s = ((n - 1) & (1 - n)).bit_length() - 1 d = n >> s for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]: p = pow(a, d, n) if p == 1 or p == n - 1 or a % n == 0: continue for _ in range(s): prev = p p = (p * p) % n if p == 1: return gcd(prev - 1, n) if p == n - 1: break else: for i in range(2, n): x, y = i, (i * i + 1) % n f = gcd(abs(x - y), n) while f == 1: x, y = (x * x + 1) % n, (y * y + 1) % n y = (y * y + 1) % n f = gcd(abs(x - y), n) if f != n: return f return n @memodict def prime_factors(n): """returns a Counter of the prime factorization of n""" if n <= 1: return Counter() f = pollard_rho(n) return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f) def distinct_factors(n): """returns a list of all distinct factors of n""" factors = [1] for p, exp in prime_factors(n).items(): factors += [p**i * factor for factor in factors for i in range(1, exp + 1)] return factors def all_factors(n): """returns a sorted list of all distinct factors of n""" small, large = [], [] for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1): if not n % i: small.append(i) large.append(n // i) if small[-1] == large[-1]: large.pop() large.reverse() small.extend(large) return small # N = 200000 # # array to store inverse of 1 to N # factorialNumInverse = [None] * (N + 1) # # array to precompute inverse of 1! to N! # naturalNumInverse = [None] * (N + 1) # # array to store factorial of # # first N numbers # fact = [None] * (N + 1) # # Function to precompute inverse of numbers # def InverseofNumber(p): # naturalNumInverse[0] = naturalNumInverse[1] = 1 # for i in range(2, N + 1, 1): # naturalNumInverse[i] = (naturalNumInverse[p % i] * # (p - int(p / i)) % p) # # Function to precompute inverse # # of factorials # def InverseofFactorial(p): # factorialNumInverse[0] = factorialNumInverse[1] = 1 # # precompute inverse of natural numbers # for i in range(2, N + 1, 1): # factorialNumInverse[i] = (naturalNumInverse[i] * # factorialNumInverse[i - 1]) % p # # Function to calculate factorial of 1 to N # def factorial(p): # fact[0] = 1 # # precompute factorials # for i in range(1, N + 1): # fact[i] = (fact[i - 1] * i) % p # # Function to return nCr % p in O(1) time # def nCr(N, R, p): # # n C r = n!*inverse(r!)*inverse((n-r)!) # ans = ((fact[N] * factorialNumInverse[R])% p * # factorialNumInverse[N - R])% p return ans def main(): mod=1000000007 mod1=998244353 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") tc=1 # Did you look at the constraints dummy? Read problem again carefully understand it correctly # Are base cases correct n=0,n=1,n=N or string is all 0 or all 1? # 1.Greedy? What matters what doesnt? Does my implementation correctly implements the greedy i thought of? # Dictionary? keep a count of values if constraint on something is low(like only alphabets(26) count)? # 2.DP? Think about state's ranges maybe one of the states have lesser possible values than it may look like? # Obviously think about order of evaluation # 3.Binary Search?(Monotonic? any one directed order in which we have to perform something?) # 4.Graph?Edge property or Vertex property Read carefully? Bipartitenes Property??? Cycle Property??? # Hidden but dependency ordering of values(in 1d array or 2d Table/Array) is that of a graph??? # 5.Number Theory?(GCD subtraction?) # 6.Bruteforce?(Redundant part of N which may not give answer?Constraints?) # 7.Range Queries? # 8.Any Equivalency?(We have A and B and have to do # something between them maybe difficult if there was A~C and C~B then A~B # C could be max or min or some other thing) # 9.Reverse Engineering?(From Answer to quesn or last step to first step) #10.Constructive? Mod? Bruteforce for smaller case and analyze patterns? #11.String? Constructive Greedy example- # Bracket sequence make first part unknown open and second part unknown closed # Remember always only n//2 open and n//2 closed brackets are there #12.Combinatorics?--> (n to i-1 index ways) * (ith index ways) * Ways (for i-1 till 0 index)? #13.Look for patterns and dependency of the patterns(maybe only first row or column matters to construct other rows and columns) # for smaller cases maybe make bruteforce solution and analyze the patterns pow2=[1] for i in range(300005): pow2.append((pow2[-1]*2)%mod1) tc=ri() for _ in range(tc): n=ri() a=ria() cur=a[0] for i in range(1,n): cur=cur&a[i] wi(cur) #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) 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, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) 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() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main()
7
PYTHON3
# print("Input number of test cases") t = int(input()) for i in range(t): # print("Input the length") n = int(input()) # print("Input the string") st = input() if n < 11 or not "8" in st: print("NO") else: index = 0 while st[index] != "8": index += 1 if len(st) - index >= 11: print("YES") else: print("NO")
7
PYTHON3
#include <bits/stdc++.h> using namespace std; void FAST() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); } int main() { FAST(); long long n; cin >> n; long long sum = 0; long long mn = -1; for (long long i = 0; i < n; i++) { long long temp; cin >> temp; sum += temp; mn = max(mn, temp); } cout << max(mn, (2 * sum) / n + 1) << endl; return 0; } struct Query { long long L, R, idx; }; bool compare(long long a0, long long a1) { return (a0 > a1); } long long power(long long x, long long y, long long p) { long long ans = 1; x = x % p; while (y > 0) { if (y & 1) ans = (ans * x) % p; y = y >> 1; x = (x * x) % p; } return ans; } long long x, y, g; void extendedEuclid(long long a, long long b) { if (b == 0) { g = a; x = 1; y = 0; } else { extendedEuclid(b, a % b); long long temp = x; x = y; y = temp - (a / b) * y; } } long long moduloInverse(long long a, long long p) { extendedEuclid(a, p); if (g == 1 && p != 1) return (x + p) % p; else return -1; }
7
CPP
n = int(input()) a = [int(x) for x in input().split()] a.sort(reverse=True) mask = 2**30 while mask and len([ai for ai in a if ai & mask])!=1: mask>>=1 for i in range(n): if mask&a[i]: break a[i], a[0] = a[0], a[i] print (*a)
7
PYTHON3
n,m=map(int,input().split());print(1)if m==0 else print(min(n-m,m))
7
PYTHON3
#include <bits/stdc++.h> using namespace std; int n, m, a[3005]; int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) scanf("%d", &a[i]); sort(a + 1, a + m + 1); if (a[1] == 1) { printf("NO"); return 0; } for (int i = 1; i <= m; i++) if (a[i] == n) { printf("NO"); return 0; } for (int i = 1; i <= m - 2; i++) { if (a[i + 1] == a[i] + 1 && a[i + 2] == a[i] + 2) { printf("NO"); return 0; } } printf("YES"); return 0; }
8
CPP
#include <bits/stdc++.h> using namespace std; vector<int> v[4000]; map<int, int> mymap; int main() { int n; while (scanf("%d ", &n) != EOF) { mymap.clear(); int m = 0; for (int i = 0; i < n; ++i) { int x; scanf("%d ", &x); if (mymap.find(x) == mymap.end()) { mymap[x] = m; v[m].clear(); v[m++].push_back(i); } else { v[mymap[x]].push_back(i); } } int ans = 0; for (int i = 0; i < m; ++i) { ans = max(ans, (int)v[i].size()); for (int j = i + 1; j < m; ++j) { int a = 0, b = 0; int now = -1; int nxt; if (v[i][0] < v[j][0]) nxt = i; else nxt = j; int t = 0; while (true) { if (nxt == i) { if (a == v[i].size()) break; else if (v[i][a] > now) { now = v[i][a]; nxt = j; ++t; } ++a; } else { if (b == v[j].size()) break; else if (v[j][b] > now) { now = v[j][b]; nxt = i; ++t; } ++b; } } ans = max(ans, t); } } cout << ans << endl; } }
7
CPP
n = input() a = len(n) b = 10 ** (a - 1) n = int(n) print((n // b + 1) * b - n)
7
PYTHON3
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios::sync_with_stdio(false); cin.tie(0); int N, K; cin >> N >> K; vector<vector<int>> TD(N); for (int i = 0; i < N; i++) { int t, d; cin >> t >> d; TD[--t].push_back(d); } vector<int> y0, y1; for (int i = 0; i < N; i++) { if (TD[i].size() == 0) continue; sort(TD[i].begin(), TD[i].end()); y1.push_back(TD[i].back()); TD[i].pop_back(); y0.insert(y0.end(), TD[i].begin(), TD[i].end()); } sort(y0.begin(), y0.end(), greater<int>()); sort(y1.begin(), y1.end(), greater<int>()); int Y = max(0, (int)(K - y0.size())); ll res = 0, X = 0; for (int i = 0; i < Y; i++) X += y1[i]; for (int i = 0; i < K - Y; i++) X += y0[i]; while (true) { res = max(res, X + 1LL * Y * Y); if (Y >= K || Y >= y1.size()) break; X += y1[Y]; X -= y0[K - Y - 1]; Y++; } cout << res << '\n'; return 0; }
0
CPP
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 10; int n, v, u, c, ce = -1, r = -1, le = 1e9, cnt[N]; long long ans; vector<pair<int, int> > g[N]; void dfs(int v, int p){ cnt[v]++; bool f = true; for (auto q : g[v]){ int u = q.first, c = q.second; if(u != p){ dfs(u, v); ans += (1LL * 2 * min(cnt[u], n - cnt[u]) * c); if(2 * min(cnt[u], n - cnt[u]) == n) ce = c; f &= ((2 * cnt[u]) <= n); cnt[v] += cnt[u]; } } f &= ((2 * (n - cnt[v])) <= n); if(f) r = v; } int main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin >> n; for (int i = 0; i + 1 < n; i++){ cin >> v >> u >> c; v--;u--; g[v].push_back({u, c}); g[u].push_back({v, c}); } dfs(0, 0); if(r != -1) for (auto u : g[r]) le = min(le, u.second); if(ce != -1) cout << ans - ce; else cout << ans - le; }
0
CPP
s1=input() s2=input() s3=input() d1={} d2={} for i in s1: d1[i]=d1.get(i,0)+1 for i in s2: d1[i]=d1.get(i,0)+1 for i in s3: d2[i]=d2.get(i,0)+1 if d1==d2: print('YES') else: print('NO')
7
PYTHON3
from collections import defaultdict as dc n,k=[int(i) for i in input().split()] s=str(input()) p=dc(list) q=[] c=1 l=0 for i in range(n-1): if s[i]==s[i+1]: c=c+1 else: p[s[i]].append(c) c=1 p[s[n-1]].append(c) for i,j in p.items() : c=0 for m in range(len(j)): c=c+j[m]//k q.append(c) print(max(q))
8
PYTHON3
n = int(input()) array = list(map(int,input().split(" "))) even = 0; odd = 0; even_index = 0 odd_index = 0 for i in range(len(array)): if(array[i]%2==0): even += 1 even_index = i+1 else: odd += 1 odd_index = i+1 if(even>1): print(odd_index) else: print(even_index)
7
PYTHON3
// I'm the Topcoder //C #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #include <time.h> //C++ #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <cctype> #include <stack> #include <string> #include <list> #include <queue> #include <map> #include <vector> #include <deque> #include <set> using namespace std; //*************************OUTPUT************************* #ifdef WIN32 #define INT64 "%I64d" #define UINT64 "%I64u" #else #define INT64 "%lld" #define UINT64 "%llu" #endif //**************************CONSTANT*********************** #define INF 0x7F7F7F7F #define eps 1e-8 #define PI acos(-1.) #define PI2 asin (1.); typedef long long LL; //typedef __int64 LL; //codeforces typedef unsigned int ui; typedef unsigned long long ui64; #define MP make_pair typedef vector<int> VI; typedef pair<int, int> PII; #define pb push_back #define mp make_pair //***************************SENTENCE************************ #define CL(a,b) memset (a, b, sizeof (a)) #define sqr(a,b) sqrt ((double)(a)*(a) + (double)(b)*(b)) //****************************FUNCTION************************ template <typename T> double DIS(T va, T vb) { return sqr(va.x - vb.x, va.y - vb.y); } template <class T> inline T INTEGER_LEN(T v) { int len = 1; while (v /= 10) ++len; return len; } template <typename T> inline T square(T va, T vb) { return va * va + vb * vb; } // aply for the memory of the stack #pragma comment (linker, "/STACK:1024000000,1024000000") //end #define CY 105 typedef int typec; bool inset[CY], vis[CY]; typec wage[CY]; int g[CY][CY]; int N, M; typec Search(int n, int &s, int &t) { memset(vis, false, n * sizeof(vis[0])); memset(wage, 0, n * sizeof(wage[0])); s = t = -1; typec cf, mx; int u = 0; for (int i = 0; i < n; ++i) { mx = -INF; for (int j = 0; j < n; ++j) { if (!inset[j] && !vis[j] && mx < wage[j]) { mx = wage[u = j]; } } if (u == t) return cf; s = t; t = u; cf = mx; vis[u] = true; for (int v = 0; v < n; ++v) { if (!inset[v] && !vis[v]) { wage[v] += g[u][v]; } } } return cf; } typec Stoer_Wagner(int n) { int s, t; typec ans = INF, cf; memset(inset, false, n * sizeof(inset[0])); for (int i = 1; i < n; ++i) { cf = Search(n, s, t); ans = min(ans, cf); if (ans == 0) return ans; inset[t] = true; for (int j = 0; j < n; ++j) { if (!inset[j] && j != s) { g[s][j] += g[t][j]; g[j][s] += g[j][t]; } } } return ans; } int main(void) { while (2 == scanf("%d%d", &N, &M)) { if (N == 0 && M == 0) break; memset(g, 0, sizeof(g)); int ans = 0, u, v, c; for (int i = 0; i < M; ++i) { scanf("%d%d%d", &u, &v, &c); if (c > 0) g[u][v] += c, g[v][u] += c; else ans += c; } printf("%d\n", ans + Stoer_Wagner(N)); } return 0; }
0
CPP
#include <bits/stdc++.h> using namespace std; const long long INF = 1e9 + 7; const int N = 1e6 + 10; int dis[N]; int pre[N]; void init(int n) { map<int, int> mc; queue<int> q; q.push(0); dis[0] = 1; vector<int> v; for (int i = 0; i < n; i++) { for (int j = 1; i + 2 * j < n; j++) { int x, y, z; x = 1 << i; y = 1 << (i + j); z = 1 << (i + 2 * j); v.push_back(x | y | z); } } int maxv = 0; while (!q.empty()) { int x = q.front(); q.pop(); maxv = max(maxv, dis[x]); for (auto &o : v) { if (!dis[x ^ o]) { pre[x ^ o] = x; dis[x ^ o] = dis[x] + 1; q.push(x ^ o); } } } } vector<tuple<int, int, int>> vp; void init2() { vector<int> v; int tot = 1 << 9; int mask = tot - 1; vp.push_back({0, 0, 0}); for (int i = 0; i < 9; i++) { for (int j = 1; i + 2 * j < 18; j++) { int x = 1 << i; int y = 1 << (i + j); int z = 1 << (i + 2 * j); v.push_back({x | y | z}); } } for (int i = 1; i < tot; i++) { int flag = 0; for (auto &x : v) { if (((i ^ x) & mask) == 0) { vp.push_back({x, 0, 0}); break; } for (auto &y : v) { if (((i ^ x ^ y) & mask) == 0) { vp.push_back({x, y, 0}); flag = 1; break; } for (auto &z : v) { if (((i ^ x ^ y ^ z) & mask) == 0) { vp.push_back({x, y, z}); flag = 1; break; } } if (flag) break; } if (flag) break; } } } int a[N]; vector<tuple<int, int, int>> ans; void check(int l, int r) { int tot = 0; int n = r - l + 1; int o = 0; for (int i = l; i <= r; i++) { tot |= a[i] << o; o++; } while (tot) { int x = pre[tot]; int o = x ^ tot; vector<int> v; for (int i = 0; i < n; i++) { if ((o >> i) & 1) { v.push_back(i + l); a[i + l] ^= 1; } } tot = x; if (!v.empty()) ans.push_back({v[0], v[1], v[2]}); } } int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; init(min(n, 9)); if (n <= 9) { int tot = 0; for (int i = 1; i <= n; i++) { tot |= a[i] << (i - 1); } if (dis[tot] == 0) { puts("NO"); return 0; } check(1, n); puts("YES"); printf("%d\n", ans.size()); for (auto &p : ans) { int x, y, z; tie(x, y, z) = p; printf("%d %d %d\n", x, y, z); } return 0; } init2(); int c = 1; for (int i = 1; i + 18 - 1 <= n; i += 9) { c = i + 9; int cur = 0; for (int j = 0; j < 9; j++) { cur |= a[i + j] << j; } int x, y, z; tie(x, y, z) = vp[cur]; vector<int> v; v.push_back(x); v.push_back(y); v.push_back(z); for (auto &x : v) { vector<int> vv; for (int o = 0; o < 18; o++) { if (x >> o & 1) { vv.push_back(i + o); a[i + o] ^= 1; } } if (!vv.empty()) ans.push_back({vv[0], vv[1], vv[2]}); } } check(c, min(c + 9 - 1, n)); check(n - 9 + 1, n); puts("YES"); printf("%d\n", ans.size()); for (auto &p : ans) { int x, y, z; tie(x, y, z) = p; printf("%d %d %d\n", x, y, z); } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; template <class T> inline bool RD(T &ret) { char c; int sgn; if (c = getchar(), c == EOF) return 0; while (c != '-' && (c < '0' || c > '9')) c = getchar(); sgn = (c == '-') ? -1 : 1, ret = (c == '-') ? 0 : (c - '0'); while (c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + (c - '0'); ret *= sgn; return 1; } template <class T> inline void PT(T x) { if (x < 0) putchar('-'), x = -x; if (x > 9) PT(x / 10); putchar(x % 10 + '0'); } const int N = 33; const int M = 222; double dp[M][N][N]; int a[N]; int main() { int n, m; cin >> n >> m; for (int i = 1; i <= int(n); i++) RD(a[i]); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (a[i] > a[j]) dp[0][i][j] = 1.0; double P = 2.0 / ((n + 1) * n); for (int c = 1; c <= int(m); c++) for (int l = 1; l <= n; l++) for (int r = l; r <= n; r++) for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { int ii = i, jj = j; if (l <= ii && ii <= r) ii = l + r - ii; if (l <= jj && jj <= r) jj = l + r - jj; dp[c][ii][jj] += dp[c - 1][i][j] * P; } double ans = 0; for (int i = 1; i <= n; i++) for (int j = i + 1; j <= n; j++) ans += dp[m][i][j]; printf("%.10f\n", ans); }
13
CPP
# https://codeforces.com/problemset/problem/20/C import heapq import math class Node: def __init__(self): self.visited = False self.adj = [] self.prev = -1 self.dist = math.inf N, M = map(int, input().split()) nodes = [Node() for i in range(N + 1)] # first node is redundant for i in range(M): u, v, w = map(int, input().split()) nodes[u].adj.append((v, w)) nodes[v].adj.append((u, w)) def path(end: int) -> []: node = nodes[end] p = [end] while node.prev != -1: p.append(node.prev) node = nodes[node.prev] p.reverse() return p def dijkstra(start: int, end: int) -> []: to_visit = [(0, start)] nodes[start].dist = 0 heapq.heapify(to_visit) while len(to_visit) > 0: dist, n = heapq.heappop(to_visit) node = nodes[n] if node.visited: continue node.visited = True # node.prev = prev if n == end: # print('found end!') return path(end) for v, d in node.adj: if nodes[v].dist > dist + d: nodes[v].dist = dist + d nodes[v].prev = n heapq.heappush(to_visit, (dist + d, v)) return [-1] p = dijkstra(1, N) print(*p)
9
PYTHON3
#include<bits/stdc++.h> using namespace std; #define fs first #define sc second #define pb push_back #define mp make_pair #define eb emplace_back #define ALL(A) A.begin(),A.end() #define RALL(A) A.rbegin(),A.rend() typedef long long LL; typedef pair<LL,LL> P; template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } const LL mod=1000000007; const LL LINF=1LL<<62; const int INF=1<<30; int dx[]={1,0,-1,0,1,-1,1,-1}; int dy[]={0,1,0,-1,1,-1,-1,1}; const int M_N=200001; struct UnionFind{ int par[M_N]; int rank[M_N]; int sz[M_N]; void init(int n){ for(int i=0;i<n;i++){ par[i]=i; rank[i]=0; sz[i]=1; } } int find(int x){ if(par[x]==x){ return x; } else{ return par[x]=find(par[x]); } } void unite(int x,int y){ x=find(x); y=find(y); if(x==y) return; if(rank[x]<rank[y]){ par[x]=y; sz[y]+=sz[x]; } else{ par[y]=x; sz[x]+=sz[y]; if(rank[x]==rank[y]) rank[x]++; } } bool same(int x,int y){ return find(x)==find(y); } int get_sz(int x){ return sz[find(x)]; } }; int main(){ int n,m;cin >> n >> m; UnionFind uf; uf.init(n); for (int i = 0; i < m; i++) { int a,b;cin >> a >> b; a--,b--; uf.unite(a,b); } LL s=uf.get_sz(0),t=uf.get_sz(1); if(s < t) swap(s,t); for (int i = 0; i < n; i++) { int k = uf.find(i); if(k != uf.find(0) && k != uf.find(1) && k == i){ s += uf.get_sz(i); } } LL ans = s * (s - 1) / 2 + t * (t - 1) / 2 - m; cout << ans << endl; return 0; }
0
CPP
n=int(input()) s=input() def check(a,b): for i in range(26): if a[i]<b[i]: return False return True a=[[0 for i in range(26)] for i in range(n+1)] for i in range(1,n+1): for j in range(26): if ord(s[i-1])==ord('a') + j: a[i][j]=a[i-1][j] + 1 else: a[i][j]=a[i-1][j] for _ in range(int(input())): t=input() b=[0]*(26) for i in t: b[ord(i)-ord('a')]+=1 l=0 r=n while l<r: mid=(l+r)//2 if check(a[mid],b): r=mid else: l=mid+1 print(l)
8
PYTHON3
import sys def main(): n = int(input()) s = list(map(int, sys.stdin.readline().split())) x = [i + 1 for i in range(n)] p1 = (0, 0) x0 = 0 for z in range(2): for i in range(1, n): k = (s[i] - s[0]) / (x[i] - x[0]) oka = True okp = False for j in range(1, n): if i == j: continue c = (s[j] - s[0]) / (x[j] - x[0]) if c != k: if not okp: p1 = (x[j], s[j]) okp = True else: k2 = (s[j] - p1[1]) / (x[j] - p1[0]) if k != k2: oka = False break if oka and okp: print("Yes") return s[1], s[0] = s[0], s[1] x[1], x[0] = x[0], x[1] print("No") main()
8
PYTHON3
#include <bits/stdc++.h> template <typename T> inline void read(T &x) { char c; bool nega = 0; while ((!isdigit(c = getchar())) && (c != '-')) ; if (c == '-') { nega = 1; c = getchar(); } x = c - 48; while (isdigit(c = getchar())) x = x * 10 + c - 48; if (nega) x = -x; } template <typename T> inline void writep(T x) { if (x > 9) writep(x / 10); putchar(x % 10 + 48); } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } writep(x); putchar(' '); } template <typename T> inline void writeln(T x) { write(x); putchar('\n'); } using namespace std; int t, x, y, d, m, a[100005], b[100005]; long long suma[100005], sumb[100005], ans; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(); if (fopen(".inp", "r")) freopen(".inp", "r", stdin); cin >> t >> d >> m; for (int i = (1); i <= (t); ++i) { int u; cin >> u; if (u > m) b[++y] = u; else a[++x] = u; } sort(a + 1, a + x + 1); sort(b + 1, b + y + 1); for (int i = (1); i <= (x); ++i) { suma[i] = suma[i - 1] + a[i]; } for (int i = (1); i <= (y); ++i) { sumb[i] = sumb[i - 1] + b[i]; } for (int i = (x + 1); i >= (1); --i) { long long temp = suma[x] - suma[i - 1]; int remain = y + i - 1; if (!remain) { ans = max(ans, temp); continue; } int need = (remain - 1) / (d + 1) + 1; if (need <= y) { temp += sumb[y] - sumb[y - need]; } else { need -= y; temp += sumb[y]; temp += suma[i - 1] - suma[i - 1 - need]; } ans = max(ans, temp); } cout << ans; return 0; }
7
CPP
t = int(input()) for _ in range(t): n,k = map(int, input().split()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] a.sort() b.sort(reverse = True) for i in range(k): if(a[i]< b[i]): a[i] = b[i] else: break print(sum(a))
8
PYTHON3
#include <bits/stdc++.h> using namespace std; enum class Word { ADJECTIVE, NOUN, VERB }; bool ends_with(const string& s, const string& prefix) { if (prefix.size() > s.size()) { return false; } int start_index = s.size() - prefix.size(); for (int i = 0; i < prefix.size(); ++i) { if (s[start_index + i] != prefix[i]) { return false; } } return true; } int main() { string in; vector<string> v; while (cin >> in) { v.push_back(in); } if (v.size() == 1) { const string& s = v[0]; if (ends_with(s, "lios") || ends_with(s, "liala") || ends_with(s, "etr") || ends_with(s, "etra") || ends_with(s, "initis") || ends_with(s, "inites")) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0; } bool has_gender = false; bool is_male; Word expected_word = Word::ADJECTIVE; for (const string& s : v) { switch (expected_word) { case Word::ADJECTIVE: if (ends_with(s, "lios")) { if (has_gender) { if (!is_male) { cout << "NO" << endl; return 0; } } else { has_gender = true; is_male = true; } break; } if (ends_with(s, "liala")) { if (has_gender) { if (is_male) { cout << "NO" << endl; return 0; } } else { has_gender = true; is_male = false; } break; } expected_word = Word::NOUN; case Word::NOUN: if (ends_with(s, "etr")) { if (has_gender) { if (!is_male) { cout << "NO" << endl; return 0; } } else { has_gender = true; is_male = true; } expected_word = Word::VERB; break; } if (ends_with(s, "etra")) { if (has_gender) { if (is_male) { cout << "NO" << endl; return 0; } } else { has_gender = true; is_male = false; } expected_word = Word::VERB; break; } cout << "NO" << endl; return 0; case Word::VERB: if (ends_with(s, "initis")) { if (!is_male) { cout << "NO" << endl; return 0; } break; } if (ends_with(s, "inites")) { if (is_male) { cout << "NO" << endl; return 0; } break; } cout << "NO" << endl; return 0; } } if (expected_word == Word::VERB) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0; }
7
CPP
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pi; typedef pair<ll, ll> pl; typedef pair<string, string> pss; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<pi> vpi; typedef vector<pl> vpl; typedef vector<ll> vl; typedef vector<vl> vvl; typedef map<int,int > mpi; typedef queue<int> qi; typedef priority_queue<int> pqi; typedef priority_queue <int, vector<int>, greater<int>> minpq; #define ff first #define ss second #define pb push_back #define mkp make_pair #define endline "\n" #define print(a,b) cout<<a<<" "<<b<<endline #define mod 1000000007 #define mxN 10000000 #define all(v) v.begin(),v.end() #define rall(v) v.rbegin(),v.rend() #define fio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0) // int uint64_log10(uint64_t n) // { // #define S(k, m) if (n >= UINT64_C(m)) { i += k; n /= UINT64_C(m); } // int i = -(n == 0); // S(16,10000000000000000); S(8,100000000); S(4,10000); S(2,100); S(1,10); // return i; // #undef S // } // int uint64_log2(uint64_t n) // { // #define S(k) if (n >= (UINT64_C(1) << k)) { i += k; n >>= k; } // int i = -(n == 0); S(32); S(16); S(8); S(4); S(2); S(1); return i; // #undef S // } // ll fact[mxN]; // void factorial() { // fact[0] = 1 ; // for(ll i = 1;i< mxN;++i) // fact[i] = ( i * fact[i-1] ) % mod ; // } ll power(int a,int b) { a %= mod ; if(b == 0 ) return 1; ll p = power(a,b/2) % mod ; p = p * p % mod ; return b & 1 ? p * a % mod : p ; } ll invMod(ll a) { return power(a,mod-2) % mod ; } int gcd(int a, int b) { if (a < b)swap(a, b); while (b) { int r = a % b; a = b; b = r; } return a; } // ll ncr(int n, int k) { // ll res = 1; // if (k > n - k) // k = n - k; // for (int i = 0; i < k; ++i) { // res = (res* (n - i))%mod; // res = (res *invMod(i+1))%mod; // } // return res; // } void prt(vi v){ for (int i=0;i<v.size();i++){ cout<<v[i]<<" "; } cout<<endl; } void prt2d(vvi v){ for (int i=0;i<v.size();i++){ for(int j=0;j<v[0].size();j++) cout<<v[i][j]<<" "; cout<<endl; } } void solve(){ ll i,j,n; ll a,b,c; cin>>a>>b>>c; ll g=1; ll nc,na,nb; na=power(10,a-1); nb=power(10,b-1); nc=power(10,c-1); while(g<= nc)g*=2; ll x=g,y=g; while(x<=na) x*=3; while(y<=nb) y*=10; print(x,y); } //bool compare( int a[2], int b[2]) { return (a[1]<=a[1]) ; } int main(){ fio; #ifndef ONLINE_JUDGE freopen("input.txt","r", stdin); freopen("output.txt","w", stdout); #endif int i,j,t=1; cin>>t; while(t--){ solve(); } return 0; }
8
CPP
#include <bits/stdc++.h> using namespace std; const int N = 550; int n, m, u, v; double maxn, num[N], w; int main() { ios::sync_with_stdio(false); while (cin >> n >> m) { memset(num, 0, sizeof num); double maxx = 0; for (int i = 1; i <= n; i++) cin >> num[i]; for (int i = 0; i < m; i++) { cin >> u >> v >> w; maxx = max(maxx, (num[u] + num[v]) / (double)w); } cout << fixed << setprecision(15) << maxx << endl; } return 0; }
7
CPP
#include <cstdio> #include <algorithm> #include <cstdlib> #include <cmath> #include <cstring> #include <cctype> #include <set> #define R register #define IN inline #define W while #define IN inline #define gc getchar() #define MX 200500 template <class T> IN void in(T &x) { x = 0; R char c = gc; W (!isdigit(c)) c = gc; W (isdigit(c)) x = (x << 1) + (x << 3) + c - 48, c = gc; } int col[MX][2], fat[MX], bel[MX], dot; struct Vertex {int id;}; IN bool operator < (const Vertex &x, const Vertex &y) { int x0 = col[x.id][0], x1 = col[x.id][1], y0 = col[y.id][0], y1 = col[y.id][1]; return 1ll * x0 * y1 > 1ll * x1 * y0 || (1ll * x0 * y1 == 1ll * x1 * y0 && x.id > y.id); } std::set <Vertex> st; long long ans; namespace DSU { int find(R int now) {return bel[now] == now ? now : bel[now] = find(bel[now]);} IN void combine(const int &from, const int &to) {bel[from] = find(to); col[to][0] += col[from][0], col[to][1] += col[from][1];} } int main(void) { in(dot); R int a, now, fa; for (R int i = 2; i <= dot; ++i) in(fat[i]); for (R int i = 1; i <= dot; ++i) in(a), ++col[i][a], bel[i] = i; for (R int i = 2; i <= dot; ++i) st.insert({i}); W (!st.empty()) { now = DSU::find(st.begin() -> id); st.erase(st.begin()); fa = DSU::find(fat[now]); st.erase({fa}); ans += 1ll * col[fa][1] * col[now][0]; DSU::combine(now, fa); if(fa != 1) st.insert({fa}); } printf("%lld", ans); }
0
CPP
I=input n=int(I()) d=dict(zip(I().split(),range(n))) r=0 for x in I().split()[::-1]:r+=d[x]>n;n=min(n,d[x]) print(r)
8
PYTHON3
def fact(n): mul=1 i=n while(i>0): mul=mul*i i=i-1 return mul a,b=(map(int,input().split(" "))) print(fact(min(a,b)))
7
PYTHON3
a=[] x=0 y=0 n=0 for i in range(5): a.append([int(x) for x in input().strip().split()]) for j in range(5): if a[-1][j]==1: x=i y=j n=1 break if n==1: break print(abs(x-2)+abs(y-2))
7
PYTHON3
n=int(input())-1 print(2*n*(n+1)+1)
7
PYTHON3
#include <bits/stdc++.h> using namespace std; void __print(int x) { cerr << x; } void __print(long x) { cerr << x; } void __print(long long x) { cerr << x; } void __print(unsigned x) { cerr << x; } void __print(unsigned long x) { cerr << x; } void __print(unsigned long long x) { cerr << x; } void __print(float x) { cerr << x; } void __print(double x) { cerr << x; } void __print(long double x) { cerr << x; } void __print(char x) { cerr << '\'' << x << '\''; } void __print(const char *x) { cerr << '\"' << x << '\"'; } void __print(const string &x) { cerr << '\"' << x << '\"'; } void __print(bool x) { cerr << (x ? "true" : "false"); } template <typename T, typename V> void __print(const pair<T, V> &x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; } template <typename T> void __print(const T &x) { int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; } void _print() { cerr << "]\n"; } template <typename T, typename... V> void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); } mt19937_64 rng(std::chrono::steady_clock::now().time_since_epoch().count()); long long mod1 = 1000000007; const long long INF = 1e18; const long double pi = 3.14159265358979323846; long long n, m, k, q, l, r, x, y, z; const long long template_array_size = 200005; long long a[template_array_size]; long long b[template_array_size]; long long c[template_array_size]; string s, t; long long ans = 0; template <class T> bool ckmin(T &a, const T &b) { return b < a ? a = b, 1 : 0; } template <class T> bool ckmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } int solve() { cin >> n; for (int i = 0; i < (int)(n); ++i) cin >> b[i]; for (int i = 0; i < min(n, 1000LL); i++) { bool ok = true; for (int j = 2; j <= min(1000, i + 2); j++) { if (b[i] % j != 0) ok = false; } if (ok) { cout << "NO\n"; return 0; } } cout << "YES\n"; return 0; } int main() { ios::sync_with_stdio(false); cin.tie(0); int q; q = 1; cin >> q; while (q--) { solve(); } return 0; }
9
CPP
m = int(input()) x, t = 10**18-1, m-18*45*10**17 % m print(t, t+x)
9
PYTHON3
s = int(input()) MOD = 10**9 + 7 C = [0]*(s + 1) C[0] = 1 for n in range(3, s+1): C[n] = (C[n-1] + C[n-3]) % MOD print(C[s])
0
PYTHON3
#include <bits/stdc++.h> using namespace std; int mid(int x, int y, int z) { if (x < y && y < z) return true; if (x > y && y > z) return true; return false; } int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); vector<int> ans; for (int i = n; i--;) { int p; scanf("%d", &p); if (ans.size() < 2) { ans.push_back(p); } else { if (mid(ans[ans.size() - 2], ans.back(), p)) { ans.pop_back(); } ans.push_back(p); } } printf("%lu\n", ans.size()); for (int i = 0; i < ans.size(); i++) { printf("%d%c", ans[i], i == ans.size() - 1 ? '\n' : ' '); } } }
8
CPP
#include <bits/stdc++.h> #define syosu(x) fixed<<setprecision(x) using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; typedef pair<int,int> P; typedef pair<double,double> pdd; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<string> vs; typedef vector<P> vp; typedef vector<vp> vvp; typedef vector<pll> vpll; typedef pair<int,P> pip; typedef vector<pip> vip; const int inf=1<<30; const ll INF=1ll<<60; const double pi=acos(-1); const double eps=1e-11; const ll mod=1e9+7; const int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1}; int n; vs a; void dfs(int id,int d){ int t=id; for(int i=id+1;i<n&&d<a[i].size()&&a[i][d]=='.';i++){ if(isalpha(a[i][d+1])){ dfs(i,d+1); a[i][d]='+'; t=i; } } for(int i=id+1;i<t;i++) if(a[i][d]=='.') a[i][d]='|'; } int main(){ ios::sync_with_stdio(0); cin.tie(0); while(1){ cin>>n; if(n==0) break; a=vs(n); for(int i=0;i<n;i++) cin>>a[i]; dfs(0,0); for(int i=0;i<n;i++){ for(auto c:a[i]) cout<<(c=='.'?' ':c); cout<<endl; } } }
0
CPP
### INPUT n = int(input()) words = [] for i in range(n): words.append(input()) ### CALC shorts = ["" for i in range(n)] for i in range(n): if len(words[i]) > 10: shorts[i] = words[i][0]+str(len(words[i])-2)+words[i][len(words[i])-1] else: shorts[i] = words[i] ### OUTPUT for i in range(n): print(shorts[i])
7
PYTHON3