solution
stringlengths 10
983k
| difficulty
int64 0
25
| language
stringclasses 2
values |
---|---|---|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string text, pat;
cin >> text >> pat;
int n = text.size();
int k = pat.size();
vector<int> failure(k + 1);
failure[0] = 0;
for(int i = 1; i <= k; i++) {
int v = i - 1;
while(v > 0) {
v = failure[v];
if(pat[v] == pat[i - 1]) {
failure[i] = v + 1;
v = -1;
break;
}
}
if(v == 0) {
failure[i] = 0;
}
//printf("failure[%d] = %d\n", i, failure[i]);
}
int state = 0;
vector<int> ans;
for(int pos = 0; pos < n; pos++) {
if(state < k && pat[state] == text[pos]) {
state += 1;
if(state == k) {
ans.push_back(pos + 1 - k);
}
continue;
}
if(state > 0) {
state = failure[state];
pos -= 1;
}
}
ios::sync_with_stdio(false);
for(auto a : ans) {
cout << a << "\n";
}
return 0;
}
| 0 | CPP |
#include <cstdio>
using namespace std;
inline double fabs(double x){return x>0?x:-x;}
int a[110];
int main ()
{
int n,ans; scanf("%d",&n);
double sum=0,mi=1e18;
for(int i=1;i<=n;i++) scanf("%d",&a[i]),sum+=a[i];
sum/=n;
for(int i=1;i<=n;i++)
if(fabs(a[i]-sum)<mi) mi=fabs(a[i]-sum),ans=i;
printf("%d",ans-1);
return 0;
} | 0 | CPP |
#include <bits/stdc++.h>
using namespace std;
using ld = long double;
using ll = long long;
using vi = vector<long long>;
using vll = vector<ll>;
const ld eps = 1e-8l;
const long long INF = 1e9 + 10;
const ll INFL = 9 * 1e18;
const ll MOD = 1e9 + 7;
const ld Pi = acosl(-1.0l);
ll n, k;
long long rev(long long a) {
for (long long i = 0; i < (long long)(k); i++) {
a ^= (1 << i);
}
return a;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.precision(9);
cout << fixed;
cin >> n >> k;
vi v(n);
for (long long& i : v) cin >> i;
map<long long, long long> mp;
ll ans = 0, curx = 0;
mp[0] = 1;
for (long long i = 0; i < (long long)(n); i++) {
curx ^= v[i];
long long gd = mp[rev(curx)], bd = mp[curx];
;
;
;
;
;
;
;
;
ans += min(gd, bd);
if (gd <= bd) curx = rev(curx);
mp[curx]++;
};
;
cout << n * (n + 1) / 2 - ans;
}
| 10 | CPP |
n, h = input().split()
n = int(n); h = int(h)
a = [int(i) for i in input().split()]
total = 0
for i in range(n):
if a[i] <= h:
total += 1
else:
total += 2
print(total) | 7 | PYTHON3 |
#include <iostream>
#include <stdio.h>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <set>
#include <math.h>
#include <utility>
#include <stack>
#include <string.h>
#include <complex>
using namespace std;
const int INF = 1<<29;
const double EPS = 1e-8;
typedef vector<int> vec;
typedef pair<int,int> P;
struct edge{int to,cost;};
int main(){
while(1){
int b,r,g,c,s,t;
scanf("%d%d%d%d%d%d",&b,&r,&g,&c,&s,&t);
if(!b&&!r&&!g&&!c&&!s&&!t)break;
cout << 100 + b*15 + b*5*13 + r*15 + r*3*13 + g*7 + c*2 - 3*(t - (b*5 + r*3 + s)) << endl;
}
return 0;
} | 0 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
string ss;
cin >> ss;
int ls = -1;
int count1 = 0;
for (int i = 0; i < ss.size(); i++) {
if (count1 == 0 and ss[i] == '[')
count1 = 1;
else if (count1 == 1 and ss[i] == ':') {
ls = i;
break;
}
}
int fs = -1;
int cnt = 0;
for (int i = ss.size() - 1; i > ls; i--) {
if (cnt == 0 and ss[i] == ']')
cnt = 1;
else if (cnt == 1 and ss[i] == ':') {
fs = i;
break;
}
}
int ans = 0;
if (ls == -1 or fs == -1) {
cout << "-1"
<< "\n";
} else {
ans = 4;
for (int i = ls; i <= fs; i++) {
if (ss[i] == '|') ans++;
}
cout << ans << "\n";
}
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int N = 500000;
const int mo = 998244353;
int n;
int dp[N + 5][2];
vector<int> G[N + 5];
int fpm(int x, int y) {
int res = 1;
for (; y > 0; y >>= 1) {
if (y & 1) res = (long long)res * x % mo;
x = (long long)x * x % mo;
}
return res;
}
int ans;
int dfs(int u, int f = 0) {
int sz = 1;
dp[u][0] = 1;
for (auto v : G[u]) {
if (v == f) continue;
sz += dfs(v, u);
dp[u][1] = ((long long)dp[u][1] * (dp[v][0] + dp[v][1]) % mo +
(long long)dp[u][0] * dp[v][0]) %
mo;
dp[u][0] = (long long)dp[u][0] * dp[v][1] % mo;
}
ans = (ans + (long long)fpm(2, n - sz + 1) * dp[u][1]) % mo;
dp[u][1] = (dp[u][1] * 2 % mo + dp[u][0]) % mo;
return sz;
}
int main() {
scanf("%d", &n);
for (int i = 1; i < n; ++i) {
static int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v), G[v].push_back(u);
}
dfs(1);
printf("%d\n", ans);
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <class T>
int size(const T &a) {
return int(a.size());
}
template <class T>
T sqr(const T &a) {
return a * a;
}
struct Edge {
int l, h, a;
void scan() { scanf("%d %d %d", &l, &h, &a); }
} a[6][6];
map<int, int> dp[6];
int t[6];
int b[6];
int w[6] = {6, 11, 16, 21, 26, 1};
int mw[6];
int geth(int *t) {
int h = 0;
for (int i = 0; i < 6; i++) {
h += t[i];
h *= w[i];
}
return h;
}
void extr(int *b, int h) {
for (int i = 5; i >= 1; i--) {
b[i] = h % w[i - 1];
h /= w[i - 1];
}
b[0] = h;
}
void gen(int *b, int i, int j, int s) {
if (i == j) {
t[0] = 6;
int h = geth(t);
dp[j][h] = max(dp[j][h], s);
return;
}
for (int w = a[i][j].l; w <= a[i][j].h && w <= b[i]; w++) {
t[i] = b[i] - w;
t[j] += w;
gen(b, i + 1, j, s + w * w + (w ? a[i][j].a : 0));
t[j] -= w;
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n * (n - 1) / 2; i++) {
int v1, v2;
scanf("%d %d", &v1, &v2);
v1--, v2--;
a[v1][v2].scan();
}
t[0] = 6;
dp[0][geth(t)] = 0;
for (int i = 1; i < n; i++) {
for (map<int, int>::iterator it = dp[i - 1].begin(); it != dp[i - 1].end();
it++) {
extr(b, it->first);
gen(b, 0, i, it->second);
}
}
for (int i = 0; i < 6; i++) {
t[i] = 0;
}
t[0] = 6;
for (int w = 0; w <= 5 * (n - 1); w++) {
t[n - 1] = w;
int h = geth(t);
if (dp[n - 1].find(h) == dp[n - 1].end()) continue;
printf("%d %d\n", w, dp[n - 1][h]);
return 0;
}
printf("-1 -1\n");
return 0;
}
| 9 | CPP |
cin=lambda: map(int,input().split())
n=int(input())
st=input()
a=list(cin())
dp=[0]*(n+2)
mn=[10**4]*(n+2)
mx=1
dp[0]=1
dp[-1]=1
mn[0]=1
mn[-1]=0
mod=int(1e9)+7
for i in range(1,n):
c=10**4
for j in range(i,-1,-1):
ind=ord(st[j])-ord('a')
c=min(c,a[ind])
if c<i-j+1:break
dp[i] += dp[j-1]
mn[i] = min(mn[i],mn[j-1]+1)
mx=max(mx,i-j+1)
print('\n'.join(map(str,[dp[n-1]%mod,mx,mn[n-1]])))
| 9 | PYTHON3 |
def solve(x, y, a, b):
num = y - x
den = a + b
t_f = num / den
t_i = num // den
return t_i if t_f == t_i else -1
if __name__ == "__main__":
for i in range(int(input())):
x, y, a, b = map(int, input().split())
print(solve(x, y, a, b)) | 7 | PYTHON3 |
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <cmath>
#include <complex>
#include <queue>
#include <functional>
#include <sstream>
#include <climits>
#include <map>
using namespace std;
typedef long long LL;
const char *P;
LL aexpr();
LL xexpr();
LL oexpr();
LL expr();
LL term();
LL fact();
LL oexpr(){
LL x = xexpr();
while(*P == '|'){
++P;
x |= xexpr();
}
return x;
}
LL xexpr(){
LL x = aexpr();
while(*P == '^'){
++P;
x ^= aexpr();
}
return x;
}
LL aexpr(){
LL x = expr();
while(*P == '&'){
++P;
x &= expr();
}
return x;
}
LL expr(){
LL x = term();
while(1){
if(*P == '+'){
++P;
x += term();
}
else if(*P == '-'){
++P;
x -= term();
}
else{
break;
}
}
return x;
}
LL term(){
LL x = fact();
while(*P == '*'){
++P;
x *= fact();
}
return x;
}
LL fact(){
if(*P == '('){
++P;
LL x = oexpr();
if(*P != ')'){
throw 0;
}
++P;
return x;
}
if(*P == '0' || !isdigit(*P)){
throw "";
}
char *endp;
LL x = strtoll(P, &endp, 10);
P = endp;
return x;
}
const string chs = "0123456789*+-&^|";
inline void update(LL &x, LL y, bool fst){
if(fst){
x = max(x, y);
}
else{
x = min(x, y);
}
}
LL solve(int n, const string &s, bool fst){
LL ret;
if(fst){
ret = LLONG_MIN;
}
else{
ret = LLONG_MAX;
}
try{
P = s.c_str();
LL t = oexpr();
if(*P){ throw 0; }
if(!n){
return t;
}
}catch(...){
if(fst){
ret = LLONG_MAX;
}
else{
ret = LLONG_MIN;
}
return ret;
}
for(int i = 0; i < s.size(); ++i){
if(s[i] == '(' || s[i] == ')'){ continue; }
string t = s;
t.erase(t.begin() + i);
LL x = solve(n - 1, t, !fst);
update(ret, x, fst);
}
for(int i = 0; i <= s.size(); ++i){
for(int j = 0; j < chs.size(); ++j){
string t = s;
t.insert(t.begin() + i, chs[j]);
LL x = solve(n - 1, t, !fst);
update(ret, x, fst);
}
}
return ret;
}
int main(){
int n;
int cnt = 0;
string s;
while(cin >> n >> s, n){
if(n % 2){ n = 1; }
else{ n = 2; }
cout << solve(n, s, true) << endl;
}
} | 0 | CPP |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vll = vector<ll>;
using vpii = vector<pii>;
using vpll = vector<pll>;
template <class T>
inline bool setmin(T &a, T b) {
if (a > b) return a = b, 1;
return 0;
}
template <class T>
inline bool setmax(T &a, T b) {
if (a < b) return a = b, 1;
return 0;
}
namespace fastio {
template <class T>
istream &operator>>(istream &os, vector<T> &container) {
for (auto &u : container) os >> u;
return os;
}
template <class T>
ostream &operator<<(ostream &os, const vector<T> &container) {
for (auto &u : container) os << u << " ";
return os;
}
template <class T1, class T2>
inline istream &operator>>(istream &os, pair<T1, T2> &p) {
return os >> p.first >> p.second;
}
template <class T1, class T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
return os << p.first << " " << p.second;
}
template <class T>
ostream &operator<<(ostream &os, set<T> const &con) {
for (auto &u : con) os << u << " ";
return os;
}
void re() {}
template <typename T, typename... args>
void re(T &x, args &...tail) {
cin >> x;
re(tail...);
}
void pr() {}
template <typename T, typename... args>
void pr(T x, args... tail) {
cout << x << " ";
pr(tail...);
}
template <typename... args>
void prln(args... tail) {
pr(tail...);
cout << "\n";
}
} // namespace fastio
using namespace fastio;
namespace debug {
template <typename _T>
inline void _debug(const char *s, _T x) {
cerr << s << " = " << x << "\n";
}
template <typename _T, typename... args>
void _debug(const char *s, _T x, args... a) {
while (*s != ',') cerr << *s++;
cerr << " = " << x << ',';
_debug(s + 1, a...);
}
} // namespace debug
using namespace debug;
constexpr int MOD = 1e9 + 7;
constexpr int INF = INT_MAX;
constexpr ll LLINF = LLONG_MAX;
const int N = 1e6 + 7;
int n, x, a[N], minn[N], maxx[N];
bitset<N> pocz, kon;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
re(n, x);
for (int i = (1); i <= (n); i++) re(a[i]);
for (int i = (1); i <= (x); i++) {
maxx[i] = 0;
minn[i] = INF;
}
set<int> A = {0, INF};
for (int i = (n); i >= (1); i--) {
auto it1 = ++A.begin();
auto it2 = A.lower_bound(a[i]);
if (it1 != A.end() and *it1 != INF and *it1 < a[i]) {
setmin(minn[*it1], a[i]);
setmax(maxx[*it1], a[i]);
}
if (it2 != A.begin() and *(--it2) != INF and *it2 < a[i]) {
setmin(minn[*it2], a[i]);
setmax(maxx[*it2], a[i]);
}
A.insert(a[i]);
}
for (int i = (1); i <= (x); i++) {
1999;
}
int maks = 0;
for (int i = (1); i <= (x); i++) {
if (minn[i] != INF) {
pocz[i] = 1;
setmax(maks, i);
kon[minn[i]] = 1;
}
}
ll res = 0;
for (int i = (1); i <= (x); i++) {
int temp = max(i, maks);
res += x - temp + 1;
if (pocz[i]) {
kon[maxx[i]] = 1;
setmax(maks, maxx[i]);
}
if (kon[i]) {
break;
}
}
prln(res);
exit(0);
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
ll K, A, B;
cin >> K >> A >> B;
if (A >= B-1 || K <= A) cout << K+1 << endl;
else cout << A + (K-A+1)/2*(B-A) + (K-A+1)%2 << endl;
return 0;
}
| 0 | CPP |
#include <iostream>
#include <string>
using namespace std;
int main(){
string s;
cin >> s;
int L = s.rfind("Z") - s.find("A") + 1;
cout << L << endl;
return 0;
}
| 0 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
double templ, ans, a, v, l, d, w;
cin >> a >> v >> l >> d >> w;
if (w <= v) {
templ = w * w / 2 / a;
if (templ < d) {
ans = sqrt(2 * templ / a);
double dis = d - templ;
dis /= 2;
if ((v * v - w * w) / 2 / a <= dis) {
double t = (v - w) / a;
t += (dis - (v * v - w * w) / 2 / a) / v;
ans += 2 * t;
templ = d;
} else {
double t = sqrt(2 * (templ + dis) / a) - ans;
ans += 2 * t;
templ = d;
}
} else if (templ >= d && templ <= l) {
ans = sqrt(2 * templ / a);
} else if (templ > l) {
ans = sqrt(2 * l / a);
templ = l;
}
if (templ < l) {
double dis = (v * v - w * w) / 2 / a;
if (templ + dis <= l) {
ans += (v - w) / a;
ans += (l - templ - dis) / v;
} else {
ans += (sqrt(2 * a * (l - templ) + w * w) - w) / a;
}
}
} else {
templ = v * v / 2 / a;
if (templ < l) {
ans = sqrt(2 * templ / a) + (l - templ) / v;
} else if (templ > l) {
ans = sqrt(2 * l / a);
}
}
printf("%lf", ans);
}
| 10 | CPP |
#include <bits/stdc++.h>
using namespace std;
long long f[20001];
int n,h;
int main()
{
int x,y;
cin>>h>>n;
for(int i=1;i<=20000;i++)
f[i]=1e18;
f[0]=0;
for(int i=1;i<=n;i++)
{
cin>>x>>y;
for(int j=0;j<h;j++)
f[j+x]=min(f[j+x],f[j]+y);
}
long long minn=1e18;
for(int i=h;i<=20000;i++)
minn=min(minn,f[i]);
cout<<minn<<endl;
return 0;
} | 0 | CPP |
a=eval(input())
b,p=[a//100,(a%100)//10,a%10],0
for i in range(3):
if i==2 or p==1 or b[i]>0:
p=1
print('+'*(b[i]+48)+'.')
print('-'*(b[i]+48))
| 13 | PYTHON3 |
print(sum(2 ** (i + (d == '7')) for i, d in enumerate(reversed(input())))) | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const long long k = 1e10;
void show(vector<long long> a) {
for (auto i : a) {
cout << i << ' ';
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
vector<long long> a(3);
for (auto& i : a) {
cin >> i;
}
cout << "First" << endl;
cout << k << endl;
int pos;
cin >> pos;
if (!pos) {
return 0;
}
a[pos - 1] += k;
auto sa = a;
sort(sa.begin(), sa.end());
long long b = sa[1] - sa[0], c = sa[2] - sa[1];
cout << b + c + c << endl;
cin >> pos;
a[pos - 1] += b + c + c;
if (!pos) {
return 0;
}
auto sb = a;
sort(sb.begin(), sb.end());
cout << sb[1] - sb[0] << endl;
cin >> pos;
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n - 1); }
const int MN = 100100;
struct Node {
using NP = Node*;
NP l, r;
int sz, d;
int de, up;
int query(int h) {
if (up <= h) return -1;
if (sz == 1) return d;
if (h < r->up) return r->query(h);
return l->query(h - r->up + r->de);
}
void set(int k, int x) {
if (sz == 1) {
if (x == -1) {
d = -1;
de = 1;
up = 0;
} else {
d = x;
de = 0;
up = 1;
}
return;
}
if (k < l->sz)
l->set(k, x);
else
r->set(k - sz / 2, x);
de = l->de + max(0, r->de - l->up);
up = max(0, l->up - r->de) + r->up;
}
Node(int sz) : sz(sz) {
d = 0;
de = up = 0;
if (sz == 1) return;
l = new Node(sz / 2);
r = new Node(sz - sz / 2);
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n;
cin >> n;
auto tr = new Node(n);
for (int i = 0; i < n; i++) {
int p;
cin >> p;
p--;
int t;
cin >> t;
if (t == 0) {
tr->set(p, -1);
} else {
int x;
cin >> x;
tr->set(p, x);
}
cout << tr->query(0) << endl;
}
return 0;
}
| 9 | CPP |
#!/usr/bin/env python3
import io
import os
import sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def printd(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
print(*args, **kwargs)
pass
def get_str():
return input().decode().strip()
def rint():
return map(int, input().split())
def oint():
return int(input())
t = oint()
for _ in range(t):
n = oint()
s = []
for i in range(n):
s += list(get_str())
ss = set(s)
cnt = []
for c in ss:
cnt.append(s.count(c))
#print(s)
#print(cnt)
for i in range(len(cnt)):
if cnt[i]%n:
print('NO')
break
else:
print('YES')
| 7 | PYTHON3 |
N = int(input())
a = list(map(int,input().split()))
print(sum(i%2 for i in a[::2])) | 0 | PYTHON3 |
from bisect import bisect
from collections import defaultdict
# l = list(map(int,input().split()))
# map(int,input().split()))
from math import gcd,sqrt,ceil,inf
from collections import Counter
import sys
sys.setrecursionlimit(10**9)
n = int(input())
l = []
hash = defaultdict(int)
count1 = 0
count2 = 0
la = []
for i in range(n):
l.append(int(input()))
la.append(l[i]//2)
z = sum(la)
if z == 0:
for i in la:
print(i)
else:
for i in range(n):
if z<0 and l[i]%2!=0:
la[i] = ceil(l[i]/2)
z+=1
elif z == 0:
break
for i in la:
print(i)
| 7 | PYTHON3 |
#include <cstdio>
#define NO {puts("NO"); return 0;}
long long n, n2, s, k, d, a[100005];
int main() {
int i;
scanf("%d", &n);
for(i=0; i<n; i++) scanf("%d", a+i), s += a[i];
n2 = n*(n+1)/2;
if(s%n2) NO;
k = s/n2;
for(i=s=0; i<n; i++) {
d = a[(i+1)%n] - a[i];
if(k<d || (k-d)%n) NO;
s += (k-d)/n;
}
puts(s==k ? "YES":"NO");
return 0;
} | 0 | CPP |
import os
import sys
from io import BytesIO, IOBase
import math
import bisect
import heapq
def main():
pass
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")
def binary(n):
return (bin(n).replace("0b", ""))
def decimal(s):
return (int(s, 2))
def pow2(n):
p = 0
while (n > 1):
n //= 2
p += 1
return (p)
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
l.append(i)
n = n / i
if n > 2:
l.append(int(n))
return (l)
def isPrime(n):
if (n == 1):
return (False)
else:
root = int(n ** 0.5)
root += 1
for i in range(2, root):
if (n % i == 0):
return (False)
return (True)
def maxPrimeFactors(n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
def countcon(s, i):
c = 0
ch = s[i]
for i in range(i, len(s)):
if (s[i] == ch):
c += 1
else:
break
return (c)
def lis(arr):
n = len(arr)
lis = [1] * n
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
maximum = 0
for i in range(n):
maximum = max(maximum, lis[i])
return maximum
def isSubSequence(str1, str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j < m and i < n:
if str1[j] == str2[i]:
j = j + 1
i = i + 1
return j == m
def maxfac(n):
root = int(n ** 0.5)
for i in range(2, root + 1):
if (n % i == 0):
return (n // i)
return (n)
def p2(n):
c=0
while(n%2==0):
n//=2
c+=1
return c
def seive(n):
primes=[True]*(n+1)
primes[1]=primes[0]=False
for i in range(2,n+1):
if(primes[i]):
for j in range(i+i,n+1,i):
primes[j]=False
p=[]
for i in range(0,n+1):
if(primes[i]):
p.append(i)
return(p)
pr=seive(1000000)
n=int(input())
l=list(map(int,input().split()))
for i in l:
if(i==1):
print(1)
else:
t=i
ind=bisect.bisect(pr,int(i**0.5))
indr=bisect.bisect(pr,i)
print(1+indr-ind) | 16 | PYTHON3 |
def solve(n,k,d,a):
#if n == d:
# return len(set(a))
m = {}
s = list(set(a))
ans = float("inf")
for i in s:
m[i] = 0
sm = 0
for i in range(d):
m[a[i]] += 1
if m[a[i]] == 1:
sm += 1
ans = sm
#print(m)
for i in range(d,n):
# print(m)
x = a[i-d]
y = a[i]
# print(x,y, i, d)
m[x] -= 1
if m[x] == 0:
sm -= 1
if m[y] == 0:
sm += 1
m[y] += 1
ans = min(ans,sm)
return ans
def main():
t = int(input())
for i in range(t):
n,k,d = map(int,input().split())
a = list(map(int,input().split()))
print(solve(n,k,d,a))
main()
| 8 | PYTHON3 |
# Author : raj1307 - Raj Singh
# Date : 14.01.2020
from __future__ import division, print_function
import os,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
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def msi(): return map(str,input().strip().split(" "))
def li(): return list(mi())
def dmain():
sys.setrecursionlimit(100000000)
threading.stack_size(40960000)
thread = threading.Thread(target=main)
thread.start()
#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
from math import ceil,floor,log,sqrt,factorial
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading
#from itertools import permutations
#Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[1]
def sort2(l):return sorted(l, key=getKey,reverse=True)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]
def powerMod(x,y,p):
res = 1
x %= p
while y > 0:
if y&1:
res = (res*x)%p
y = y>>1
x = (x*x)%p
return res
def gcd(x, y):
while y:
x, y = y, x % y
return x
def isPrime(n) : # Check Prime Number or not
if (n <= 1) : return False
if (n <= 3) : return True
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
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def main():
for _ in range(ii()):
n,d=mi()
if d<=n:
print('YES')
continue
f=int(sqrt(d))+1
ff=0
for i in range(1,f+1):
if i+ ceil(d/(i+1))<=n:
ff=1
break
if ff:
print('YES')
else:
print('NO')
# 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")
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")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read()
| 7 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int n, p, g, b, o, r, y;
string a[7];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
if (a[i] == "purple") {
p++;
} else if (a[i] == "green") {
g++;
} else if (a[i] == "blue") {
b++;
} else if (a[i] == "orange") {
o++;
} else if (a[i] == "red") {
r++;
} else if (a[i] == "yellow") {
y++;
}
}
cout << 6 - n << endl;
if (p == 0) {
cout << "Power" << endl;
}
if (g == 0) {
cout << "Time" << endl;
}
if (b == 0) {
cout << "Space" << endl;
}
if (o == 0) {
cout << "Soul" << endl;
}
if (r == 0) {
cout << "Reality" << endl;
}
if (y == 0) {
cout << "Mind" << endl;
}
}
| 7 | CPP |
#include <algorithm>
#include <cassert>
#include <bitset>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#define repi(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,a) repi(i,0,a)
#define repd(i,a,b) for(int i=(a);i>=(b);i--)
#define repit(i,a) for(__typeof((a).begin()) i=(a).begin();i!=(a).end();i++)
#define all(u) (u).begin(),(u).end()
#define rall(u) (u).rbegin(),(u).rend()
#define UNIQUE(u) (u).erase(unique(all(u)),(u).end())
#define pb push_back
#define mp make_pair
#define INF 1e9
#define EPS 1e-9
#define PI acos(-1.0)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
using namespace std;
const double inf = 1e9;
// constants and eps-considered operators
const double eps = 1e-4; // choose carefully!
const double pi = acos(-1.0);
inline bool lt(double a, double b) { return a < b - eps; }
inline bool gt(double a, double b) { return lt(b, a); }
inline bool le(double a, double b) { return !lt(b, a); }
inline bool ge(double a, double b) { return !lt(a, b); }
inline bool ne(double a, double b) { return lt(a, b) or lt(b, a); }
inline bool eq(double a, double b) { return !ne(a, b); }
// points and lines
typedef complex<double> point;
inline double dot(point a, point b) { return real(conj(a) * b); }
inline double cross(point a, point b) { return imag(conj(a) * b); }
struct line {
point a, b;
line(point a, point b) : a(a), b(b) {}
};
/*
* Here is what ccw(a, b, c) returns:
*
* 1
* ------------------
* 2 |a 0 b| -2
* ------------------
* -1
*
* Note: we can implement intersectPS(p, s) as !ccw(s.a, s.b, p).
*/
int ccw(point a, point b, point c) {
b -= a, c -= a;
if (gt(cross(b, c), 0.0)) return +1;
if (lt(cross(b, c), 0.0)) return -1;
if (lt(dot(b, c), 0.0)) return 0; // c -- a -- b
if (lt(norm(b), norm(c))) return 0; // a -- b -- c
return 0;
}
bool intersectLS(const line& l, const line& s) {
return ccw(l.a, l.b, s.a) * ccw(l.a, l.b, s.b) < 0;
}
bool intersectSS(const line& s, const line& t) {
return intersectLS(s, t) and intersectLS(t, s);
}
bool intersectLL(const line& l, const line& m) {
return ne(cross(l.b - l.a, m.b - m.a), 0.0) // not parallel
or eq(cross(l.b - l.a, m.a - l.a), 0.0); // overlap
}
point crosspointLL(const line& l, const line& m) {
double p = cross(l.b - l.a, m.b - m.a);
double q = cross(l.b - l.a, m.a - l.a);
if (eq(p, 0.0) and eq(q, 0.0)) return m.a; // overlap
//assert(ne(p, 0.0)); // parallel
return m.a - q / p * (m.b - m.a);
}
point proj(const line& l, point p) {
double t = dot(l.b - l.a, p - l.a) / norm(l.b - l.a);
return l.a + t * (l.b - l.a);
}
point reflection(const line& l, point p) { return 2.0 * proj(l, p) - p; }
int n;
vector<line> mirror;
point s, target;
inline point in() { double x, y; cin >> x >> y; return point(x, y); }
inline line in2() { point a = in(), b = in(); return line(a, b); }
void input()
{
mirror.clear();
rep(i, n) mirror.pb(in2());
target = in();
s = in();
}
vector<point> cands;
void prepare()
{
cands.clear();
cands.pb(target);
vector<point> curr(cands), next;
rep(i, 5) {
repit(it, curr) repit(itm, mirror) {
next.pb(reflection(*itm, *it));
}
cands.insert(cands.end(), all(next));
curr = next;
next.clear();
}
}
double simulate(point s, point t, int cnt)
{
if (cnt >= 6) return inf;
if(abs(s-t) < eps) return inf;
int id = -1;
point m = t;
rep(i, n) if (intersectLS(line(s, t), mirror[i])) {
point x = crosspointLL(line(s, t), mirror[i]);
if (le(dot(t - s, x - s), 0.0)) continue;
if (ge(abs(x - s), abs(m - s))) continue;
id = i, m = x;
}
if (id < 0) {
if (abs(target - t) < eps) return abs(t-s);
else return inf;
}
if (abs(target - t) < eps and le(abs(t - s), abs(m - s))) {
return abs(t-s);
}
double ret = abs(m - s);
ret += simulate(m, reflection(mirror[id], t), cnt + 1);
return min(ret, inf);
}
void solve()
{
prepare();
double ans = inf;
double tmp;
repit(it, cands) {
tmp = simulate(s, *it, 0);
// if(tmp < ans) cout << "a " << *it << " " << tmp << endl;
ans = min(ans, tmp);
}
printf("%.14f\n", ans);
}
int main()
{
while (cin >> n and n) {
input();
solve();
}
return 0;
} | 0 | CPP |
t=int(input())
dic={}#learning dictonary
for i in range(0,t):
s=input()
x=dic.get(s,0)#if there is no s in dic it will return 0
if x==0:
print("OK")
dic[s]=1#appending s in dic
else:
dic[s]=x+1
print("%s%d"%(s,x))
| 9 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++) cout << (i + 1) % n + 1 << " ";
}
| 9 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int flag = 0;
int n, k1, k2;
cin >> n >> k1 >> k2;
while (k1--) {
int b;
cin >> b;
if (b == n) {
flag = 1;
}
}
while (k2--) {
int b;
cin >> b;
if (b == n) flag = 0;
}
if (flag)
cout << "YES";
else
cout << "NO";
cout << endl;
}
return 0;
}
| 7 | CPP |
from collections import defaultdict
def rp():
s = input().split()
return (s[0], int(s[1]))
ps = {}
n = int(input())
for i in range(n):
p = rp()
d = []
for _ in range(int(input())):
d += [rp()]
ps[p] = d
if i != n - 1:
input()
root = list(ps.keys())[0]
q = [(root, 0)]
u = {root[0]: (root[1], 0)}
for i, l in q:
isp = i
if isp[0] in u and isp[1] != u[isp[0]][0]:
continue
for p in ps[i]:
psp = p
if psp[0] not in u or u[psp[0]][1] == l + 1 and u[psp[0]][0] < psp[1]:
u[psp[0]] = (psp[1], l + 1)
q.append((psp, l + 1))
del u[root[0]]
print(len(u))
for i in sorted(u):
print(i, u[i][0])
| 9 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int inf = (int)1e9;
const double INF = 1e12, EPS = 1e-9;
const int B = 1000;
const int dy[] = {-1, 0, 1, 0}, dx[] = {0, -1, 0, 1};
int h, w, q;
int qs[100000][4];
char in[100010][12], dir[256];
int dp[100010 * 12], vis[100010][12];
inline int to(int y, int x) {
int &res = dp[y * 12 + x];
if (res != -1) return res;
if (y == 0 || x == 0 || x == w + 1) return res = y * 12 + x;
res = -2;
int d = dir[in[y][x]];
return res = to(y + dy[d], x + dx[d]);
}
int main() {
dir['<'] = 1;
dir['^'] = 0;
dir['>'] = 3;
scanf("%d%d%d", &h, &w, &q);
for (int i = 0; i < (int)h; i++) scanf("%s", in[i + 1] + 1);
for (int i = 0; i < (int)q; i++) {
char c, d;
int y, x;
scanf(" %c%d%d", &c, &y, &x);
qs[i][0] = c == 'A';
qs[i][1] = y;
qs[i][2] = x;
if (c == 'C') {
scanf(" %c", &d);
qs[i][3] = d;
}
}
memset(vis, -1, sizeof(vis));
for (int it = 0; it < (int)q; it++) {
if (it % B == 0) {
memset(dp, -1, sizeof(dp));
for (int i = it; i < it + B && i < q; i++)
if (qs[i][0] == 0) {
int y = qs[i][1], x = qs[i][2];
dp[y * 12 + x] = y * 12 + x;
}
}
int y = qs[it][1], x = qs[it][2];
if (!qs[it][0]) {
in[y][x] = (char)qs[it][3];
continue;
}
int iter = 0;
while (1) {
if (x == 0 || x == w + 1 || y == 0) {
printf("%d %d\n", y, x);
break;
}
if (vis[y][x] == it) {
puts("-1 -1");
break;
}
vis[y][x] = it;
int ny = to(y, x), nx;
if (ny < 0) {
puts("-1 -1");
break;
}
nx = ny % 12;
ny /= 12;
if (nx == 0 || nx == w + 1 || ny == 0) {
printf("%d %d\n", ny, nx);
break;
}
int d = dir[in[ny][nx]];
y = ny + dy[d];
x = nx + dx[d];
}
}
return 0;
}
| 10 | CPP |
#include <cstdio>
using namespace std;
int n;
char cond[3005];
long long arr[3005],pre[3005];
const long long mod=1000000007;
int main(){
//freopen("input.txt","r",stdin);
scanf("%d",&n);
for (int x=1;x<=n;x++) cond[x]=getchar();
arr[1]=1;
for (int x=1;x<=n;x++) pre[x]=1;
for (int x=2;x<=n;x++){
for (int y=1;y<=x;y++){
if (cond[x]=='<') arr[y]=pre[y-1];
else arr[y]=(pre[n]-pre[y-1]+mod)%mod;
}
for (int y=1;y<=n;y++) pre[y]=(pre[y-1]+arr[y])%mod;
//for (int y=1;y<=n;y++) printf("%d ",arr[y]);
//printf("\n");
}
printf("%d\n",pre[n]);
}
| 0 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long q;
cin >> q;
while (q--) {
int x, y, a, b;
cin >> x >> y >> a >> b;
long long t = (y - x) / (a + b);
if ((y - x) % (a + b) != 0)
cout << -1 << endl;
else {
cout << t << endl;
}
}
return 0;
}
| 7 | CPP |
#include <bits/stdc++.h>
using namespace std;
long long int x, y;
long long int gcd(long long int a, long long int b) {
if (a == 0) {
x = 0;
y = 1;
return b;
}
long long int gc = gcd(b % a, a);
long long int temp;
temp = x;
x = y - (b / a) * temp;
y = temp;
return gc;
}
long long int a[200005];
long long int val[200005];
long long int ser[200005];
int main() {
ios::sync_with_stdio(false);
cout.tie(0);
cin.tie(0);
long long int n, q, i, j;
cin >> n;
long long int k;
for (i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n);
cin >> q;
ser[0] = a[0];
for (i = 1; i < n; i++) {
ser[i] = ser[i - 1] + a[i];
}
val[n] = ser[n - 2];
for (k = 1; k < n; k++) {
val[k] = 0;
j = 1;
for (i = n - 2; i >= 0; i -= j) {
val[k] += ser[i];
j *= k;
}
}
for (j = 0; j < q; j++) {
cin >> i;
if (i <= n)
cout << val[i] << " ";
else
cout << ser[n - 2] << " ";
}
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
bitset<4000000> arr;
int start = 0;
int flip = 0;
int main(){
ios_base::sync_with_stdio(false);
int n, k; cin >> n >> k;
string s; cin >> s;
for(int i = 0;i < n;i++) arr[i] = (s[i] == 'B');
while(k > 0){
if(arr[start] ^ flip){
flip ^= 1;
arr[start + n] = flip;
start++;
}
else arr[start] = (1 ^ flip);
k--;
if(start >= n+2) break;
}
if(n&k&1) arr[start] = arr[start] ^ 1;
for(int i = start;i < start + n;i++) cout << (char) ('A' + (arr[i] ^ flip));
}
| 0 | CPP |
#include <bits/stdc++.h>
using namespace std;
int n, s, k;
long long ans;
vector<pair<int, int> > T[101];
int main() {
scanf("%d%d", &n, &s);
for (int i = 0; i < n; i++) {
int tot = 0;
for (scanf("%d", &k); k--;) {
int speed, time;
scanf("%d%d", &speed, &time);
tot += time;
T[i].push_back(make_pair(speed, tot));
}
}
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
int di = 0, dj = 0;
int t = 0, pi = 0, pj = 0, ddi = 0, ddj = 0;
while (pi < (int)T[i].size() && pj < (int)T[j].size()) {
int dt = min(T[i][pi].second, T[j][pj].second) - t;
bool which = T[i][pi].second < T[j][pj].second;
ddi += T[i][pi].first * dt, ddj += T[j][pj].first * dt;
int ndi = di + ddi, ndj = dj + ddj;
if ((di - dj) * (long long)(ndi - ndj) < 0) ans++;
if (which)
pi++;
else
pj++;
t += dt;
if (ndi != ndj) di = ndi, dj = ndj, ddi = ddj = 0;
}
}
printf("%I64d\n", ans);
}
| 11 | CPP |
def choose(a, b):
flag = 0
for i in a:
for j in b:
if i+j not in a and i+j not in b:
flag = 1
print(i, j)
break
if flag:
break
n1 = int(input())
a = list(map(int, input().split()))
n2 = int(input())
b = list(map(int, input().split()))
choose(a, b) | 7 | PYTHON3 |
import math
from functools import reduce
from bisect import bisect_left,bisect,bisect_right
from itertools import accumulate
from math import sqrt
from math import gcd
def transformer(i):
if i=='d' or i=='f':
return 1
return 0
def changer(s):
l=[]
for i in s:
if i=='H':
l.append(1)
elif i=='T':
l.append(0)
return l
def lcm(i,j):
#print('calc gcd of',i,j)
return ((i*j)//gcd(i,j))
def Prime_factors(n):
s=sqrt(n)
l=[]
while (n%2)==0:
n=n>>1
i=3
while i<(int(s)+1) and n>1:
if n%i==0:
l.append(i)
while n%i==0:
n=n//i
i+=2
return l
def Prime_factorization(n):#with count of powers of each variable
l=[]
i=2
c=0
while n&1==0:
n=n>>1
c+=1
#print('factoring 2')
if c!=0:
l.append([i,c])
q=int(math.sqrt(n))
i=3
#print(n)
while i<=q+1:
c=0
#print('i is',i)
while n%i==0:
n=n//i
c+=1
if c:
l.append([i,c])
i+=1
if n!=1:
l.append([n,1])
return l
def leapyear(n):
if n%100==0:
if n%400==0:
return True
return False
if n%4==0:
return True
return False
st=''
p=pow(10,9)+7
li=[0 for _ in range(202)]
def func(n,x,l1):
l=li[:]
for i in l1:
l[i-1]=1
i=c=0
while i<202:
if l[i]:
c+=1
else:
x-=1
c+=1
if x<0:
return c-1
i+=1
return
for _ in range(int(input())):
n,x=map(int,input().split())
#n = int(input())
#inp=input().split()
#s=input()
#l1 = list(map(transformer, input()))
#l=[]
l1=list(map(int,input().split()))
#l2 = list(map(int, input().split()))
#l1=input().split()
#l2=input().split()
#func(n,k)
st+=str((func(n,x,l1)))+'\n'
print(st) | 7 | PYTHON3 |
"""
-----------------------------Pseudo---------------------------------
"""
import sys, bisect
from collections import defaultdict, Counter,deque
def input(): return sys.stdin.readline()
def print(arg, *argv, end=None):
sys.stdout.write(str(arg))
for i in argv: sys.stdout.write(" "+str(i))
sys.stdout.write(end) if end or end=="" else sys.stdout.write("\n")
#
#sys.setrecursionlimit(20000)
#PI = 3.1415926535897932384626433832795
#
def mapi(): return map(int,input().split())
def maps(): return map(str,input().split())
#---------------------------------------------------------------#
def solve():
t = 1
t = int(input())
for _ in range(t):
n = int(input())
s = input().strip()
st = (0,0)
mp = {}
id1 = 0
id2 = 0
fl1 = True
fl2 =True
mp[st] = 0
last = float('inf')
id1 = -1
id2 = -1
for i in range(1,n+1):
x, y= st
if s[i-1]=="U":
y-=1
elif s[i-1]=="D":
y+=1
elif s[i-1]=="L":
x-=1
elif s[i-1]=="R":
x+=1
"""
try:
mp[(x,y)]+=1
except:
mp[(x,y)]=1
"""
if (x,y) in mp:
if i-mp[(x,y)]+1<last:
id1,id2= mp[(x,y)],i
last = id2-id1+1
mp[(x,y)]=i
else:
mp[(x,y)]=i
st = (x,y)
#print(mp)
if id1==id2:
#print(id1,id2)
print(-1)
else:
print(id1+1,id2)
#print(mp)
#---------------------------------------------------------------#
if __name__ == '__main__':
solve()
| 9 | PYTHON3 |
def divisors(n):
div = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
div.append(i)
if i**2 != n:
div.append(n//i)
div.sort()
return div
n,k = map(int, input().split())
a = list(map(int, input().split()))
d = divisors(sum(a))
d.reverse()
for x in d:
b = []
for i in range(n):
b.append(x-a[i]%x)
b.sort()
c = sum(b)//x
if sum(b[:-c]) <= k:
print(x)
exit()
| 0 | PYTHON3 |
h, w = map(int, input().split())
S = []
S.append('.' * (w + 2))
for _ in range(h):
S.append('.' + input() + '.')
S.append('.' * (w + 2))
for i in range(1, h+1):
l = []
for j in range(1, w+1):
if S[i][j] == '#':
l.append('#')
continue
_s = S[i-1][j-1:j+2] + S[i][j-1] + S[i][j+1] + S[i+1][j-1:j+2]
l.append(_s.count('#'))
print(''.join(map(str, l)))
| 0 | PYTHON3 |
d = {
'U': (0, 1),
'D': (0, -1),
'L': (-1, 0),
'R': (1, 0)
}
def compute_delta(s, head_idx, tail_idx):
x = y = 0
for i in range(head_idx, tail_idx):
x, y = x + d[s[i]][0], y + d[s[i]][1]
return [x, y]
n = int(input())
s = input()
dsc = list(map(int, input().split()))
total = compute_delta(s, 0, n)
l, r = 0, n
current_sol = -1
while l <= r:
local_len = (r + l) // 2
initial_diff = compute_delta(s, 0, local_len)
local = [total[0] - initial_diff[0], total[1] - initial_diff[1]]
is_possible = False
diff = abs(dsc[0] - local[0]) + abs(dsc[1] - local[1])
if diff <= local_len and (diff + local_len) % 2 == 0:
is_possible = True
for i in range(local_len, n):
if is_possible:
break
d_old, d_new = d[s[i]], d[s[i - local_len]]
local = [local[0] - d_old[0] + d_new[0], local[1] - d_old[1] + d_new[1]]
diff = abs(dsc[0] - local[0]) + abs(dsc[1] - local[1])
if diff <= local_len and (diff + local_len) % 2 == 0:
is_possible = True
if is_possible:
current_sol = local_len
r = local_len - 1
else:
l = local_len + 1
print(current_sol)
| 9 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int N = 105;
const long long mod = 1e9 + 7;
int n, m, tmp, k, now, last, dp[2][N][N][N], ans, K, c[N][N];
int main() {
scanf("%d%d%d", &n, &m, &K);
c[0][0] = 1;
for (int i = 1; i <= K; i++)
for (int j = 0; j <= i; j++) {
c[i][j] = (j ? c[i - 1][j - 1] : 0) + c[i - 1][j];
if (c[i][j] > K) c[i][j] = K + 1;
}
n++;
now = 1;
last = 0;
dp[now][0][1][1] = 1;
for (int i = 0; i <= m; i++) {
last = now;
now ^= 1;
if (i) {
tmp = 0;
for (int j = 2; j <= n; j++)
for (int l = 1; l <= K; l++) tmp = (tmp + dp[last][j][0][l]) % mod;
ans = (ans + (long long)tmp * (m - i + 1) % mod) % mod;
}
if (i == m) break;
memset(dp[now], 0, sizeof(dp[now]));
for (int j = 0; j <= n; j++)
for (int k = 1; k <= n; k++)
for (int l = 1; l <= K; l++)
if (dp[last][j][k][l])
for (int t = k; t <= n - j; t++)
if (l * c[t - 1][k - 1] <= K)
dp[now][j + t][t - k][l * c[t - 1][k - 1]] =
(dp[now][j + t][t - k][l * c[t - 1][k - 1]] +
dp[last][j][k][l]) %
mod;
}
printf("%d\n", ans);
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
map<int, vector<int> > mp;
vector<int> cnt(10000), tmp(10000);
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, m, tk, steps = 0;
cin >> n >> m;
vector<long long> vc, k;
for (int i = 0; i < n; i++) {
cin >> tk, vc.push_back(tk);
if (tk == 1) mp[tk].push_back(i);
cnt[tk]++;
}
for (int i = 0; i < m; i++) {
cin >> tk, k.push_back(tk), steps += tk;
}
for (int i = 0; i < vc.size(); i++) {
long long cnt = 0;
int arr[10005];
memset(arr, 0, 10005);
for (int j = i; j < vc.size() && cnt < steps; cnt++, j++) {
arr[vc[j]]++;
}
bool flag = false;
for (int i = 0; i < m; i++) {
if (arr[i + 1] == k[i])
flag = true;
else {
flag = false;
break;
}
}
if (flag) puts("YES"), exit(0);
}
puts("NO");
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
long long f(long long x) {
if (x % 2 == 0) return x / 2;
return 0;
}
int main() {
ios::sync_with_stdio(!cin.tie(0));
long long n, k;
cin >> n >> k;
long long s = 0, z = 0;
while (k--) {
long long x, y;
cin >> x >> y;
s += y;
z = (z + x * y) % n;
}
cout << (s < n || (s == n && z == f(n)) ? 1 : -1) << '\n';
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
char s[N + 5];
int vis[20];
int main() {
scanf("%s", s);
int t = 0, p = 0;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == '?') t++;
if (s[i] >= 'A' && s[i] <= 'J') {
if (vis[s[i] - 'A'] == 0) p++, vis[s[i] - 'A']++;
}
}
int ans = 1;
for (int i = 1; i <= p; i++) ans *= (10 - i + 1);
if (s[0] == '?') t--, ans *= 9;
if (s[0] >= 'A' && s[0] <= 'J') ans /= 10, ans *= 9;
printf("%d", ans);
for (int i = 1; i <= t; i++) printf("0");
printf("\n");
return 0;
}
| 7 | CPP |
#include <bits/stdc++.h>
using namespace std;
int dp[2020][2020];
int n, h, l, r;
int a[2020];
int check(int x) {
if (x >= l && x <= r) return 1;
return 0;
}
int main() {
cin >> n >> h >> l >> r;
for (int i = 1; i <= n; i++) cin >> a[i];
int s = 0;
for (int i = 1; i <= n; i++) {
s += a[i];
for (int j = 0; j <= i; j++) {
dp[i][j] = max(dp[i][j], dp[i - 1][j] + check((s - j) % h));
if (j >= 1)
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + check((s - j) % h));
}
}
int ans = 0;
for (int i = 0; i <= n; i++) ans = max(ans, dp[n][i]);
cout << ans << endl;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
int A[100000];
int main() {
ios_base::sync_with_stdio(0);
multiset<int> s;
int n, b = 0, r = 0, m = 0, inp;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> inp;
s.insert(inp);
A[r++] = inp;
while (*s.rbegin() > 1 + *s.begin()) s.erase(s.find(A[b++]));
m = max(m, (int)s.size());
}
cout << m;
return 0;
}
| 8 | CPP |
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<stack>
#include<cmath>
#include<vector>
using namespace std;
int n,m;
int p[120000],y[120000];
vector<int> o[120000];
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)scanf("%d%d",p+i,y+i),p[i]--;
for(int i=0;i<m;i++)o[p[i]].push_back(y[i]);
for(int i=0;i<n;i++)sort(o[i].begin(), o[i].end());
for(int i=0;i<m;i++)printf("%06d%06d\n",p[i]+1,lower_bound(o[p[i]].begin(), o[p[i]].end(),y[i])-o[p[i]].begin()+1);
return 0;
} | 0 | CPP |
def solve():
n, m = map(int, input().split())
a = []
dp = []
for i in range(n):
a.append(['']*m)
dp.append([0]*m)
for i in range(n):
s = input()
for j in range(m):
a[n-i-1][j] = s[j]
for i in range(m):
if a[0][i]=='*':
dp[0][i]=1
else:
dp[0][i]=0
for i in range(1,n):
for j in range(m):
if a[i][j]=='*':
dp[i][j]=1
if j>0 and j<m-1:
dp[i][j] = 1+min(dp[i-1][j-1],dp[i-1][j],dp[i-1][j+1])
else:
dp[i][j]=0
ans = 0
for i in range(n):
for j in range(m):
ans+=dp[i][j]
print(ans)
tests = int(input())
while (tests > 0):
solve()
tests = tests - 1 | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
void mxe(int &a, int b) {
if (b > a) a = b;
}
int main() {
int n;
cin >> n;
vector<vector<int>> div(n + 1);
vector<vector<int>> num(n + 1);
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j += i) {
div[j].push_back(i);
num[i].push_back(j);
}
}
vector<int> max_div(n + 1, -1);
vector<bool> u(n + 1);
vector<int> ans = {-1};
int cur_num = 0;
for (int d = 1; d <= n; d++) {
for (int x : num[d]) {
if (u[x] || max_div[x] > d) continue;
u[x] = true;
cur_num++;
for (int i = (int)div[x].size() - 1; div[x][i] > d; i--) {
int dd = div[x][i];
for (int xx : num[dd]) {
mxe(max_div[xx], dd);
}
}
}
while ((int)ans.size() <= cur_num) ans.push_back(d);
}
for (int i = 2; i <= n; i++) {
cout << ans[i] << " ";
}
}
| 12 | CPP |
import os
import sys
from io import BytesIO, IOBase
import math
from collections import Counter
def a(x):
print(3*len(x))
for i in range(0, len(x), 2):
for j in range(3):
print(f"2 {i+1} {i+2}")
print(f"1 {i+1} {i+2}")
def main():
q = int(parse_input())
r = []
for _ in range(q):
n = int(parse_input())
x = [int(i) for i in parse_input().split()]
a(x)
parse_input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main() | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
long long int a[500005];
long long int cnt[500005];
vector<long long int> v;
long long int pre[500005];
vector<long long int> vv;
long long int taken[500005];
long long int prime[500005];
bool pr[500005];
set<char> st;
priority_queue<long long int> bob;
priority_queue<long long int> ali;
priority_queue<long long int> bth;
queue<long long int> q;
map<long long int, long long int> mp;
map<long long int, long long int>::iterator it;
map<long long int, vector<long long int> > ck;
string ss, tt[500005];
int main() {
long long int n, i, j, k, t, pos, m;
cin >> t;
long long int minis;
long long int res;
long long int x, y;
long long int pp;
string fg;
long long int l, r;
long long int ans;
long long int h;
while (t--) {
cin >> n;
res = n;
long long int mxx = -10e10;
long long int mxd = -10e11;
for (i = 0; i < n; i++) {
cin >> a[i];
if (a[i] > mxx) mxx = a[i];
mxd = max(mxd, mxx - a[i]);
}
long long int po = 1;
res = 0;
while (1) {
if (mxd <= 0) break;
mxd = mxd - po;
po = po * 2;
res++;
}
cout << res << '\n';
}
return 0;
}
| 9 | CPP |
from collections import Counter
import string
import math
import sys
# sys.setrecursionlimit(10**6)
from fractions import Fraction
def array_int():
return [int(i) for i in sys.stdin.readline().split()]
def vary(arrber_of_variables):
if arrber_of_variables==1:
return int(sys.stdin.readline())
if arrber_of_variables>=2:
return map(int,sys.stdin.readline().split())
def makedict(var):
return dict(Counter(var))
testcases=1
# testcases=vary(1)
for _ in range(testcases):
n,k=vary(2)
ki=[0]*11
su=0
for x in input().split():
t=int(x)
ki[10-t%10]+=1
su+=t//10
for i in range(1,10):
t=min(k//i,ki[i])
su+=t
k-=t*i
t=k//10
su+=min(t,n*10-su)
print(su)
| 9 | PYTHON3 |
def f(x):
s=str(x)
mn=12
mx=0
for i in s:
mx=max(mx,int(i))
mn=min(mn,int(i))
return mn*mx
for _ in range(int(input())):
a,k=map(int,input().split())
k-=1
prev=-1
while(k>0):
if(prev==a):
break
prev=a
a+=f(a)
k-=1
print(a)
| 7 | PYTHON3 |
n=int(input())
mat=map(int,input().split())
a,b,c=[],[],[]
for i in mat:
if i<0:
a.append(i)
elif i>0:
b.append(i)
else:
c.append(i)
if len(b)==0:
b.append(a.pop())
b.append(a.pop())
if len(a)%2==0:
c.append(a.pop())
print(len(a), *a,sep=" ")
print(len(b), *b,sep=" ")
print(len(c), *c,sep=" ") | 7 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
long long int cost[4][4], dp[50][4][4];
int main() {
long long int i, j, n, src, dest, aux;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) cin >> cost[i][j];
}
cin >> n;
for (i = 1; i <= n; i++) {
for (src = 1; src <= 3; src++) {
for (dest = 1; dest <= 3; dest++) {
aux = src ^ dest;
dp[i][src][dest] =
dp[i - 1][src][aux] + cost[src][dest] + dp[i - 1][aux][dest];
dp[i][src][dest] =
min(dp[i][src][dest], dp[i - 1][src][dest] + cost[src][aux] +
dp[i - 1][dest][src] + cost[aux][dest] +
dp[i - 1][src][dest]);
}
}
}
cout << dp[n][1][3];
return 0;
}
| 8 | CPP |
t = int(input())
for cnt in range(t):
n = int(input())
a = list(map(int, input().split()))
a.sort()
res = 1
for i in range(n - 1):
if (a[i] == a[i + 1] - 1):
res = 2
break
print(res)
| 7 | PYTHON3 |
n=int(input())
a=list(input())
b=list(input())
comp=[]
cost=0
for i in range(n):
if i==n-1:
if a[i]!=b[i]:
cost+=1
else:
if a[i]!=b[i]:
if a[i+1]!=b[i+1]and a[i]!=a[i+1]:
cost+=1
a[i+1]=b[i+1]
else:
cost+=1
print(cost) | 9 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int maxn = 262144;
const int mod = 998244353;
const int G = 3, I = 332748118;
inline int add(int a, int b) {
a += b;
if (a >= mod) a -= mod;
return a;
}
inline int mult(int a, int b) {
long long t = 1ll * a * b;
if (t >= mod) t %= mod;
return t;
}
inline int dec(int a, int b) {
a -= b;
if (a < 0) a += mod;
return a;
}
inline int power(int a, int b) {
int out = 1;
while (b) {
if (b & 1) out = mult(out, a);
a = mult(a, a);
b >>= 1;
}
return out;
}
namespace polynomial {
int R[maxn], pw[maxn], inv[maxn];
void init2() {
for (int i = 1; i < maxn; i++)
pw[i] = power(G, (mod - 1) / (i << 1)),
inv[i] = power(I, (mod - 1) / (i << 1));
}
void init(int cnt) {
for (int i = 0; i < (1 << cnt); i++)
R[i] = (R[i >> 1] >> 1) | ((i & 1) << (cnt - 1));
}
void ntt(vector<int> &A, int flag, int len, bool reinit = 1) {
int tlen = 1, tcnt = 0;
while (tlen < len) tlen <<= 1, ++tcnt;
if (reinit) init(tcnt);
A.resize(tlen);
for (int i = 0; i < tlen; i++)
if (i < R[i]) swap(A[i], A[R[i]]);
for (int i = 1; i < tlen; i <<= 1) {
int bas = pw[i];
if (flag == -1) bas = inv[i];
for (int j = 0; j < tlen; j += (i << 1)) {
int t = 1;
for (int k = 0; k < i; k++, t = mult(t, bas)) {
int tx = A[j + k], ty = mult(A[i + j + k], t);
A[j + k] = add(tx, ty);
A[i + j + k] = dec(tx, ty);
}
}
}
if (flag == -1) {
int I = power(tlen, mod - 2);
for (int i = 0; i < tlen; i++) A[i] = mult(A[i], I);
}
A.resize(len);
}
vector<int> Mult(vector<int> A, vector<int> B, int len1, int len2) {
A.resize(len1);
B.resize(len2);
int len = len1 + len2 - 1;
int tlen = 1;
while (tlen < len) tlen <<= 1;
vector<int> ret;
ret.clear();
ret.resize(tlen);
ntt(A, 1, tlen);
ntt(B, 1, tlen, 0);
for (int i = 0; i < tlen; i++) ret[i] = mult(A[i], B[i]);
ntt(ret, -1, tlen, 0);
ret.resize(len);
return ret;
}
vector<int> Mult(vector<int> A, vector<int> B) {
return Mult(A, B, A.size(), B.size());
}
vector<int> Add(vector<int> A, vector<int> B) {
vector<int> ret;
ret.resize(max(A.size(), B.size()));
for (int i = 0; i < ret.size(); i++) {
if (i < A.size()) ret[i] = A[i];
if (i < B.size()) ret[i] = add(ret[i], B[i]);
}
return ret;
}
} // namespace polynomial
using namespace polynomial;
int n, K, siz[100010], fac[100010], ans[100010], ifac[100010];
vector<int> v[100010], f[100010];
inline vector<int> solve(int l, int r, const vector<int> &t) {
if (l == r) return vector<int>({1, t[l]});
int mid = (l + r) >> 1;
return Mult(solve(l, mid, t), solve(mid + 1, r, t));
}
inline vector<int> getpoly(const vector<int> &t) {
if (!t.size()) return vector<int>({1});
return solve(0, t.size() - 1, t);
}
int S = 0, S1 = 0, res;
void dfs(int np, int fath) {
siz[np] = 1;
for (int &x : v[np]) {
if (x == fath) continue;
dfs(x, np);
siz[np] += siz[x];
}
vector<int> cur;
for (int &x : v[np]) {
if (x == fath) continue;
cur.push_back(siz[x]);
}
f[np] = getpoly(cur);
for (int i = 0; i < f[np].size() && i <= K; i++)
ans[np] = add(ans[np], mult(f[np][i], mult(fac[K], ifac[K - i])));
S = add(S, ans[np]);
S1 = add(S1, mult(ans[np], ans[np]));
}
void dfs2(int np, int fath) {
vector<pair<int, int> > c;
int t = ans[np];
for (int &x : v[np]) {
if (x == fath) continue;
dfs2(x, np);
ans[np] = add(ans[np], ans[x]);
c.push_back(make_pair(siz[x], ans[x]));
}
res = dec(res, mult(t, dec(ans[np], t)));
sort(c.begin(), c.end());
f[np].push_back(0);
for (int i = f[np].size() - 1; i >= 1; i--)
f[np][i] = add(f[np][i], mult(f[np][i - 1], n - siz[np]));
int lst = -1;
for (int i = 0; i < c.size(); i++) {
if (!i || c[i].first != c[i - 1].first) {
vector<int> cur(f[np].size());
cur[0] = 1;
for (int j = 1; j < cur.size(); j++)
cur[j] = dec(f[np][j], mult(cur[j - 1], c[i].first));
lst = 0;
for (int j = 0; j < cur.size() && j <= K; j++)
lst = add(lst, mult(cur[j], mult(fac[K], ifac[K - j])));
}
res = add(res, mult(lst, c[i].second));
}
}
int main() {
init2();
scanf("%d%d", &n, &K);
for (int i = 1, ti, tj; i < n; i++) {
scanf("%d%d", &ti, &tj);
v[ti].push_back(tj);
v[tj].push_back(ti);
}
if (K == 1) {
printf("%d\n", mult(mult(n, n - 1), (mod + 1) / 2));
return 0;
}
fac[0] = 1;
for (int i = 1; i <= 100000; i++) fac[i] = mult(fac[i - 1], i);
ifac[100000] = power(fac[100000], mod - 2);
for (int i = 100000 - 1; i >= 0; i--) ifac[i] = mult(ifac[i + 1], i + 1);
dfs(1, 0);
res = mult(dec(mult(S, S), S1), (mod + 1) / 2);
dfs2(1, 0);
printf("%d\n", res);
return 0;
}
| 14 | CPP |
n, m = map(int, input().split(" "))
ans = []
ref = []
res = []
for _ in range(m):
p, q = input().split(" ")
ref.append(p)
if len(p) == len(q):
ans.append(p)
elif len(p) < len(q):
ans.append(p)
elif len(p) > len(q):
ans.append(q)
s = list(input().split(" "))
for ii in range(n):
res.append(ans[ref.index(s[ii])])
print(*res)
| 8 | PYTHON3 |
t=int(input())
s=set(input().upper())
if(len(s)==26):
print('YES')
else:
print('NO')
| 7 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
struct $ {
$() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
} $;
int main() {
int n;
cin >> n;
vector<int> s(n);
for (auto &ss : s) cin >> ss;
string str;
getline(cin, str);
bool ok = true;
for (int i = 0; i < n; ++i) {
getline(cin, str);
int cnt = 0;
for (char c : str) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
++cnt;
}
}
if (cnt != s[i]) ok = false;
}
cout << (ok ? "YES\n" : "NO\n");
return 0;
}
| 8 | CPP |
mod = 10 ** 9 + 7
def solve():
n = int(input())
cnt = [0 for i in range(26)]
ok = True
for i in range(n):
s = input()
for c in s:
cnt[ord(c) - ord('a')] += 1
for i in range(26):
if cnt[i] % n > 0:
ok = False
print('YES' if ok else 'NO')
t = int(input())
while t > 0:
solve()
t -= 1 | 7 | PYTHON3 |
n,m=[int(i) for i in input().split()]
k=n
p1=0
while True:
p=k//m
p=p-p1
if p==0: break
k=k+p
p1=p1+p
print(k) | 7 | PYTHON3 |
dicti={}
s=input()
for ch in s:
dicti[ch]=1
if len(dicti)%2==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!") | 7 | PYTHON3 |
for n in str(eval(input())):
for _ in range(ord(n)):
print('+',sep='',end='')
print('.>') | 13 | PYTHON3 |
n, k = map(int, input().split())
s = [i for i in input()]
s.sort()
ok = True
for i in range(26):
cnt = s.count(chr(97 + i))
if (cnt > k):
ok = False
break
if (ok): print("YES")
else: print("NO")
| 7 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
int steps = 0;
while (t--) {
string s;
cin >> s;
pair<int, int> xy = {0, 0};
int n = s.size();
int l = 0;
int u = 0;
int r = 0;
int d = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'L') {
l++;
}
if (s[i] == 'U') {
u++;
}
if (s[i] == 'R') {
r++;
}
if (s[i] == 'D') {
d++;
}
}
int du = min(d, u);
int lr = min(l, r);
if (min(du, lr) == 0) {
if (du == 0) {
lr = min(lr, 1);
cout << 2 * lr << endl << string(lr, 'L') + string(lr, 'R') << endl;
} else {
du = min(du, 1);
cout << 2 * du << endl << string(du, 'U') + string(du, 'D') << endl;
}
} else {
string s2 =
string(lr, 'L') + string(du, 'U') + string(lr, 'R') + string(du, 'D');
cout << s2.size() << endl << s2 << endl;
}
}
return 0;
}
| 8 | CPP |
import sys
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()
import bisect,string,math,time,functools,random,fractions
from bisect import*
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def I():return int(input())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def AI():return map(int,open(0).read().split())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def NLI(n):return [[int(i) for i in input().split()] for i in range(n)]
def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def INP():
N=10
n=random.randint(1,N)
a=RLI(n,0,n-1)
return n,a
def Rtest(T):
case,err=0,0
for i in range(T):
inp=INP()
a1=naive(*inp)
a2=solve(*inp)
if a1!=a2:
print(inp)
print('naive',a1)
print('solve',a2)
err+=1
case+=1
print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
org_inp=[];g=[[] for i in range(V)]
FromStdin=True if ls==None else False
for i in range(E):
if FromStdin:
inp=LI()
org_inp.append(inp)
else:
inp=ls[i]
if len(inp)==2:a,b=inp;c=1
else:a,b,c=inp
if index==1:a-=1;b-=1
aa=(a,c);bb=(b,c);g[a].append(bb)
if not Directed:g[b].append(aa)
return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
mp=[boundary]*(w+2);found={}
for i in R(h):
s=input()
for char in search:
if char in s:
found[char]=((i+1)*(w+2)+s.index(char)+1)
mp_def[char]=mp_def[replacement_of_found]
mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
mp+=[boundary]*(w+2)
return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
rt=[0]
for i in ls:rt+=[rt[-1]+i]
return rt
def bit_combination(n,base=2):
rt=[]
for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
return rt
def gcd(x,y):
if y==0:return x
if x%y==0:return y
while x%y!=0:x,y=y,x%y
return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
if show_flg:print(*inp,end=end)
mo=10**9+7
#mo=998244353
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
alp=[chr(ord('a')+i)for i in range(26)]
#sys.setrecursionlimit(10**7)
def gcj(c,x):
print("Case #{0}:".format(c+1),x)
show_flg=False
show_flg=True
## Segment Tree ##
## Test case: ABC 146 F
## https://atcoder.jp/contests/abc146/tasks/abc146_f
## Initializer Template ##
# Range Sum: sg=SegTree(n)
# Range Minimum: sg=SegTree(n,inf,min,inf)
class SegTree:
def __init__(self,n,ls,init_val=1,function=lambda a,b:a+b,ide=0):
self.size=n
self.ls=ls
self.ide_ele=ide
self.num=1<<(self.size-1).bit_length()
self.table=[self.ide_ele]*2*self.num
self.index=[0]*2*self.num
def function(a,b,k):
if self.ls[k]==1:
res=self.table[k*2+1]
elif self.ls[k]==0:
res=self.table[k*2+2]
else:
res=self.table[k*2+1]+self.table[k*2+2]
return res
self.func=function
#set_val
if not hasattr(init_val,"__iter__"):
init_val=[init_val]*self.size
for i,val in enumerate(init_val):
self.table[i+self.num-1]=val
self.index[i+self.num-1]=i
#build
for i in range(self.num-2,-1,-1):
self.table[i]=self.func(self.table[2*i+1],self.table[2*i+2],i)
if self.table[i]==self.table[i*2+1]:
self.index[i]=self.index[i*2+1]
else:
self.index[i]=self.index[i*2+2]
def build(self):
for i in range(self.num-2,-1,-1):
self.table[i]=self.func(self.table[2*i+1],self.table[2*i+2],i)
if self.table[i]==self.table[i*2+1]:
self.index[i]=self.index[i*2+1]
else:
self.index[i]=self.index[i*2+2]
def update(self,k,x):
self.ls[k]=x
while k>-1:
res=self.func(self.table[k*2+1],self.table[k*2+2],k)
self.table[k]=res
k=(k-1)//2
def query(self):
if q<=p:
return self.ide_ele
p+=self.num-1
q+=self.num-2
res=self.ide_ele
while q-p>1:
if p&1==0:
res=self.func(res,self.table[p])
if q&1==1:
res=self.func(res,self.table[q])
q-=1
p=p>>1
q=(q-1)>>1
if p==q:
res=self.func(res,self.table[p])
else:
res=self.func(self.func(res,self.table[p]),self.table[q])
return res
def __str__(self):
# 生配列を表示
rt=self.table[self.num-1:self.num-1+self.size]
return str(rt)
n=int(input())
dc=dict(zip('01?',[0,1,2]))
s=[dc[i]for i in input()][::-1]
sg=SegTree(2**n,s)
y=2**n-1
for i in range(int(input())):
x,c=input().split()
x=int(x)-1
c=dc[c]
sg.update(y-x-1,c)
ans=sg.table[0]
print(ans) | 10 | PYTHON3 |
n , m = map(int , input().split(" "))
code = list(map(int , input().split(" ")))
fingerprints = list(map(int , input().split(" ")))
for i in code :
if i in fingerprints :
print(i , end = " " )
| 7 | PYTHON3 |
#include<bits/stdc++.h>
using namespace std;
int a[100000], N, T;
int main() {
scanf("%d %d", &N, &T);
for(int i = 0; i<N; ++i) scanf("%d", a+i);
int mn = a[0], best = 0;
for(int i = 1; i<N; ++i) {
best = max(best, a[i]-mn);
mn = min(mn, a[i]);
}
int ans = 0;
mn = a[0];
for(int i = 1; i<N; ++i) {
if( a[i]-mn == best ) ++ans;
mn = min(mn, a[i]);
}
printf("%d\n", ans);
}
| 0 | CPP |
#include <bits/stdc++.h>
using namespace std;
map<long long, long long> cnt;
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
long long n, k;
cin >> n >> k;
vector<long long> a(555555, -1);
for (long long i = 0; i < n; i++) {
cin >> a[i];
}
long long p1 = 0, p2 = 0;
cnt[a[0]]++;
long long ans = 0;
while (p2 < n) {
if (cnt[a[p2]] < k) {
p2++;
cnt[a[p2]]++;
} else {
ans += n - p2;
cnt[a[p1]]--;
p1++;
}
}
cout << ans << "\n";
}
| 10 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, h, t, j;
cin >> n;
int a[n], b[n];
for (i = 0; i < n; i++) cin >> a[i];
b[0] = a[n - 1];
t = 1;
for (i = n - 2; i >= 0; i--) {
h = 0;
for (j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
h = 1;
break;
}
}
if (h == 0) {
b[t] = a[i];
t++;
}
}
cout << t << endl;
for (i = t - 1; i >= 0; i--) cout << b[i] << " ";
}
| 7 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
long long evens = 0, odds = 0;
long long e[2], o[2];
e[0] = e[1] = o[0] = o[1] = 0;
for (int i = 0; i < s.size(); i++) {
odds++;
if (i % 2 == 0) {
odds += e[s[i] - 'a'];
evens += o[s[i] - 'a'];
e[s[i] - 'a']++;
} else {
odds += o[s[i] - 'a'];
evens += e[s[i] - 'a'];
o[s[i] - 'a']++;
}
}
cout << evens << " " << odds << endl;
return 0;
}
| 10 | CPP |
n = int(input())
m = []
for _ in range(n):
m.append(input())
v = [[0, 1], [0, -1], [1, 0], [-1, 0]]
ans = 'YES'
for i in range(n):
for j in range(n):
cnt = 0
for x, y in v:
if i + x in range(n) and j + y in range(n) and m[i + x][j + y] == 'o':
cnt += 1
if cnt % 2 != 0:
ans = 'NO'
print(ans) | 7 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
unsigned long long int n;
cin >> n;
unsigned long long int ans = n * (n - 1) * (n - 2) * (n - 3) * (n - 4) / 120;
cout << n * (n - 1) * (n - 2) * (n - 3) * (n - 4) * ans << endl;
return 0;
}
| 14 | CPP |
from sys import stdin
from bisect import *
inp = lambda: stdin.readline().strip()
n = int(inp())
arrays = []
arrays2=[]
ascent=0
for _ in range(n):
x = [int(x) for x in inp().split()[1:]]
for i in range(1,len(x)):
if x[i] > x[i-1]:
ascent+=1
break
else:
arrays.append(x[0])
arrays2.append(x[-1])
ans=0
for i in range(ascent):
ans+=(n-1)*2-i*2+1
arrays.sort()
arrays2.sort()
for i in arrays:
ans+=bisect_right(arrays2,i-1)
# for i in arrays2:
# ans+=len(arrays2)-bisect_left(arrays,i+1)
print(ans)
| 8 | PYTHON3 |
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def main():
n,m = LI()
c = collections.Counter(LI())
r = min(c[i] for i in range(1,n+1))
return r
print(main())
| 7 | PYTHON3 |
t = int(input())
for test in range(t):
n = int(input())
sub = 1001
ar = list(map(int, input().strip().split()[:n]))
for first_loop in range(0, n-1):
for second_loop in range(first_loop+1, n):
if abs(ar[first_loop] - ar[second_loop]) < sub:
sub = abs(ar[first_loop] - ar[second_loop])
print(sub) | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline T abs(T t) {
return t < 0 ? -t : t;
}
const long long modn = 1000000007;
inline long long mod(long long x) { return x % modn; }
const int N = 200009;
int x[N], y[N];
const int tmp = N - 1;
struct cmp {
bool operator()(int i, int j) {
if (y[i] != y[j]) return y[i] < y[j];
return i < j;
}
};
set<pair<int, int> > tr[N << 2];
inline int L(int i) { return i << 1; }
inline int R(int i) { return (i << 1) + 1; }
int bn;
void add_t(int i, int l, int r, int p) {
tr[i].insert(pair<int, int>(y[p], p));
if (l == r) return;
int m = (l + r) / 2;
if (x[p] <= m)
add_t(L(i), l, m, p);
else
add_t(R(i), m + 1, r, p);
}
void rem_t(int i, int l, int r, int p) {
tr[i].erase(pair<int, int>(y[p], p));
if (l == r) return;
int m = (l + r) / 2;
if (x[p] <= m)
rem_t(L(i), l, m, p);
else
rem_t(R(i), m + 1, r, p);
}
void collect(int i, int l, int r, int x1, int x2, int y1, int y2,
vector<int> &v) {
if (r < x1 || l > x2) return;
if (l >= x1 && r <= x2) {
auto it = tr[i].lower_bound(pair<int, int>(y1, INT_MIN));
auto it2 = tr[i].upper_bound(pair<int, int>(y2, INT_MAX));
while (it != it2) {
v.push_back(it->second);
++it;
}
return;
}
int m = (l + r) / 2;
collect(L(i), l, m, x1, x2, y1, y2, v);
collect(R(i), m + 1, r, x1, x2, y1, y2, v);
}
vector<int> pos;
int nx[N];
void proc(int p) {
vector<int> aux;
collect(1, 0, bn - 1, x[2 * p], bn - 1, y[2 * p], INT_MAX, aux);
for (int i : aux) {
int pp = i / 2;
pos.push_back(pp);
rem_t(1, 0, bn - 1, i);
nx[pp] = p;
}
}
int b[N], d[N], can[N];
int main() {
int n, i;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d %d %d %d", &x[2 * i], &y[2 * i], &x[2 * i + 1], &y[2 * i + 1]);
b[2 * i] = x[2 * i];
b[2 * i + 1] = x[2 * i + 1];
}
sort(b, b + 2 * n);
bn = unique(b, b + 2 * n) - b;
for (i = 0; i < n; i++) {
x[2 * i] = lower_bound(b, b + bn, x[2 * i]) - b;
x[2 * i + 1] = lower_bound(b, b + bn, x[2 * i + 1]) - b;
if (i != n - 1) add_t(1, 0, bn - 1, 2 * i + 1);
}
pos.push_back(n - 1);
int dist = 0;
while (!pos.empty()) {
dist++;
vector<int> v;
v.swap(pos);
for (int u : v) {
d[u] = dist;
can[u] = true;
proc(u);
}
}
int ba = -1, best = INT_MAX;
for (i = 0; i < n; i++)
if (can[i] && x[2 * i] == 0 && y[2 * i] == 0 && d[i] < best) {
best = d[i];
ba = i;
}
if (ba != -1) {
int a = ba;
printf("%d\n", d[a]);
while (a != n - 1) {
printf("%d ", a + 1);
a = nx[a];
}
printf("%d\n", n);
} else
puts("-1");
}
| 10 | CPP |
n = int(input())
string = input()
diff = n-11
no = diff//2
count = 0
j = 0
idx = -1
for i in string:
if i == '8':
if count < no:
count = count + 1
else:
idx = j
break
j=j+1
if idx == -1:
print("NO")
else:
temp = idx-no
te = diff - no
if temp <= te:
print("YES")
else:
print("NO")
| 8 | PYTHON3 |
from itertools import permutations
#from fractions import Fraction
from collections import defaultdict
from math import*
import os
import sys
from io import BytesIO, IOBase
from heapq import nlargest
from bisect import*
import copy
import itertools
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)
def input(): return sys.stdin.readline().rstrip("\r\n")
#-------------above part copied-----------------------
n=int(input())
arr=input()
brr=input()
i=0
ans=0
isdiffer=False
for i in range(n):
if arr[i]==brr[i]:
if isdiffer==True:
ans+=1
isdiffer=False
else:
if isdiffer:
if(arr[i]!=arr[i-1]):
ans+=1
isdiffer=False
else:
ans+=1
isdiffer=True
else:
isdiffer=True
if isdiffer:
ans+=1
print(ans)
| 9 | PYTHON3 |
s = input()
count = 0
for i in range(len(s)):
if s[i] == 'A':
a, b = 0, 0
for j in range(i-1, -1, -1):
if s[j] == 'Q':
a += 1
for j in range(i+1, len(s)):
if s[j] == 'Q':
b += 1
count += a * b
print(count)
| 7 | PYTHON3 |
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define rep(i, n)for((i) = 0;(i) < (n);++(i))
string solve(string s){
int i = 0, j;
string tmp;
rep(i, 100){
tmp += "=";
if(s == ">'" + tmp + "#" + tmp + "~")return "A";
}
tmp.clear();
rep(i, 100){
tmp += "Q=";
if(s == ">^" + tmp + "~~")return "B";
}
return "NA";
}
int main(void){
int i, j, n;
string s;
scanf("%d", &n);
for(;n--;){
cin >> s;
cout << solve(s) << endl;
}
return 0;
} | 0 | CPP |
n = int(input())
soldiers = list(map(int, (input()).split(' ')))
lowest = n - 1 - soldiers[::-1].index(min(soldiers))
highest = soldiers.index(max(soldiers))
steps = (n-1-lowest) + (highest)
if lowest < highest:
steps -= 1
print( steps )
| 7 | PYTHON3 |
#include <bits/stdc++.h>
class Input {
private:
char buf[1000000], *p1, *p2;
public:
inline char getc() {
if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin);
return p1 == p2 ? EOF : *(p1++);
}
template <typename tp>
inline Input &operator>>(tp &n) {
n = 0;
char c = getc();
while (!isdigit(c)) c = getc();
while (isdigit(c)) n = n * 10 + c - 48, c = getc();
return (*this);
}
} fin;
const int N = 3e5 + 5, LIM = 1e9;
using namespace std;
int n, w;
int ans[N], chs[N];
struct Level {
int a, b, id;
bool operator<(const Level &o) const { return b < o.b; }
} o[N];
struct node {
int id, val;
node(int a = 0, int b = 0) : id(a), val(b) {}
bool operator<(const node &o) const { return val > o.val; }
};
namespace SEG {
const int N = 12e6 + 233;
int tot = 1;
long long sum[N];
int lc[N], rc[N], cnt[N];
void modify(int &p, int l, int r, int pos, int v) {
if (!p) p = ++tot;
sum[p] += v * pos, cnt[p] += v;
if (l == r) return;
int mid = l + r >> 1;
if (mid >= pos)
modify(lc[p], l, mid, pos, v);
else
modify(rc[p], mid + 1, r, pos, v);
}
long long query(int p, int l, int r, int k) {
if (l == r) return 1ll * k * l;
int mid = l + r >> 1;
if (cnt[lc[p]] >= k) return query(lc[p], l, mid, k);
return sum[lc[p]] + query(rc[p], mid + 1, r, k - cnt[lc[p]]);
}
} // namespace SEG
int main() {
fin >> n >> w;
for (int i = 1; i <= n; ++i) fin >> o[i].a >> o[i].b, o[i].id = i;
sort(o + 1, o + n + 1);
int rt = 1;
for (int i = 1; i <= n; ++i) SEG::modify(rt, 1, LIM, o[i].a, 1);
int pos = -1;
long long s = 0, Ans = 1e18;
if (n >= w) pos = 0, Ans = SEG::query(1, 1, LIM, w);
for (int i = 1; i <= n and i <= w; ++i) {
SEG::modify(rt, 1, LIM, o[i].a, -1);
SEG::modify(rt, 1, LIM, o[i].b - o[i].a, 1);
s += o[i].a;
long long sum = s + SEG::query(1, 1, LIM, w - i);
if (Ans > sum) Ans = sum, pos = i;
}
cout << Ans << endl;
priority_queue<node> q;
for (int i = 1; i <= pos; ++i) q.push(node(i, o[i].b - o[i].a)), chs[i] = 1;
for (int i = pos + 1; i <= n; ++i) q.push(node(i, o[i].a));
int times = w - pos;
while (times--) ++chs[q.top().id], q.pop();
for (int i = 1; i <= n; ++i) ans[o[i].id] = chs[i];
for (int i = 1; i <= n; ++i) printf("%d", ans[i]);
puts("");
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
void io() { ios_base::sync_with_stdio(0), cin.tie(0); }
typedef long long ll;
typedef vector<int> vi;
void Case() {
ll a, b;
cin >> a >> b;
int ans = 2147483647;
for (int i = 0; i < 1000 && i < ans; i++) {
int cur = i;
ll x = b + i;
if (x == 1)
continue;
ll ax = a;
while (ax) {
ax /= x;
cur++;
}
ans = min(ans, cur);
}
cout << ans << "\n";
}
int main() {
io();
int T;
while (cin >> T)
while (T--)
Case();
return 0;
} | 7 | CPP |
#include <iostream>
int main(){int N;std::cin>>N;std::cout<<(2199-N)/200;}
| 0 | CPP |
#include <bits/stdc++.h>
using namespace std;
void solve() {
long long int l, r;
cin >> l >> r;
long long int mid;
if (r % 2 == 0)
mid = r / 2;
else
mid = (r + 1) / 2;
if (l > mid)
cout << r % l << endl;
else {
if (r % 2 == 0) r--;
cout << r % mid << endl;
}
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| 7 | CPP |
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e6 + 5;
const long long maxm = 1e3 + 5;
int ans2, ans, cys, dfsclock, n, m, t;
char ch;
int fir[maxn], dis[maxn], siz[maxn];
int cy[maxn], dfn[maxn], low[maxn], go[maxn];
bool mod[maxn], qaq[maxn], ins[maxn], col[maxn];
stack<int> s;
vector<int> Adj[maxn];
inline int cal(int x, int y) { return (x - 1) * m + y; }
void Tarjan(long long p) {
dfn[p] = low[p] = ++dfsclock;
s.push(p);
ins[p] = 1;
long long t = go[p];
if (!dfn[t]) {
Tarjan(t);
low[p] = min(low[p], low[t]);
} else {
if (ins[t]) {
low[p] = min(low[p], dfn[t]);
}
}
if (low[p] == dfn[p]) {
if (s.top() == p) {
ins[p] = 0;
s.pop();
return;
}
cys++;
fir[cys] = p;
while (s.top() != p) {
cy[s.top()] = cys;
ins[s.top()] = 0;
ans++;
siz[cys]++;
s.pop();
}
cy[p] = cys;
ins[p] = 0;
s.pop();
ans++;
siz[cys]++;
}
return;
}
int main() {
cin >> t;
while (t--) {
cin >> n >> m;
ans = ans2 = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> ch;
col[cal(i, j)] = ch - '0';
}
}
for (int i = 1; i <= n * m; i++) {
cy[i] = 0;
int len = Adj[i].size();
for (int j = 0; j < len; j++) {
Adj[i].pop_back();
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> ch;
if (ch == 'L') {
go[cal(i, j)] = cal(i, j - 1);
Adj[cal(i, j - 1)].push_back(cal(i, j));
} else if (ch == 'R') {
go[cal(i, j)] = cal(i, j + 1);
Adj[cal(i, j + 1)].push_back(cal(i, j));
} else if (ch == 'U') {
go[cal(i, j)] = cal(i - 1, j);
Adj[cal(i - 1, j)].push_back(cal(i, j));
} else if (ch == 'D') {
go[cal(i, j)] = cal(i + 1, j);
Adj[cal(i + 1, j)].push_back(cal(i, j));
}
}
}
cys = dfsclock = 0;
for (int i = 1; i <= n * m; i++) {
dfn[i] = 0;
siz[i] = 0;
}
for (int i = 1; i <= n * m; i++) {
if (!dfn[i]) {
Tarjan(i);
}
}
for (int i = 1; i <= cys; i++) {
long long CycleID = i;
for (int j = 0; j < siz[CycleID]; j++) {
mod[j] = 0;
}
int id = 0, op = fir[i];
for (int j = 0; j < siz[CycleID]; j++) {
queue<int> q;
q.push(op);
dis[op] = 0;
while (!q.empty()) {
int fr = q.front();
q.pop();
if (!col[fr]) {
mod[((id - dis[fr]) % siz[CycleID] + siz[CycleID]) % siz[CycleID]] =
1;
}
for (int k = 0; k < Adj[fr].size(); k++) {
int R = Adj[fr][k];
if (cy[R]) {
continue;
}
q.push(R);
dis[R] = dis[fr] + 1;
}
}
op = go[op];
id++;
}
for (int j = 0; j < siz[CycleID]; j++) {
if (mod[j]) {
ans2++;
}
}
}
cout << ans << " " << ans2 << endl;
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
int sum() { return 0; }
template <typename T, typename... Args>
T sum(T a, Args... args) {
return a + sum(args...);
}
vector<long long int> tree[200003];
vector<long long int> v[200003];
bool vis[200003];
void bfs(long long int n) {
vis[n] = true;
queue<long long int> q;
q.push(n);
while (!q.empty()) {
long long int p = q.front();
q.pop();
for (auto to : v[p]) {
if (vis[to] != true) {
tree[p].push_back(to);
vis[to] = true;
q.push(to);
}
}
}
}
void solve() {
long long int n, m;
cin >> n >> m;
while (m--) {
long long int a, b;
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
long long int ma = 1;
for (long long int i = 1; i <= n; i++) {
if ((long long int)v[i].size() > (long long int)v[ma].size()) ma = i;
}
bfs(ma);
for (long long int i = 1; i <= n; i++) {
for (auto j : tree[i]) cout << i << " " << j << "\n";
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long int t = 1;
while (t--) {
solve();
}
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
int num = 0;
while (n) {
num += n % 2;
n /= 2;
}
printf("%d\n", int(pow(2, num)));
}
return 0;
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
const long long int LINF = 1e18, mod = 1e9 + 7;
void Bl0ck_M0mb0();
signed main() {
Bl0ck_M0mb0();
long long int t = 1;
cin >> t;
while (t--) {
long long int n;
cin >> n;
long long int ip[n + 1];
for (long long int i = 1; i <= n; i++) cin >> ip[i];
sort(ip + 1, ip + n + 1);
long long int DP[n + 1][401];
memset(DP, -1, sizeof(DP));
;
for (long long int i = 0; i <= 2 * n; i++) DP[0][i] = 0;
for (long long int i = 1; i <= n; i++) {
for (long long int j = 1; j <= 2 * n; j++) {
long long int val = LINF;
for (long long int k = 0; k <= j - 1; k++) {
if (DP[i - 1][k] != -1) {
val = min(val, DP[i - 1][k]);
}
}
val += abs(ip[i] - j);
DP[i][j] = val;
}
}
long long int ans = LINF;
for (long long int i = 1; i <= 2 * n; i++) ans = min(DP[n][i], ans);
cout << ans << endl;
}
return 0;
}
void Bl0ck_M0mb0() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
| 9 | CPP |
#include <bits/stdc++.h>
using namespace std;
inline int getint() {
char ch = getchar();
int res = 0, sign = 1;
if (ch == '-') sign = -1;
while (ch < '0' || '9' < ch) {
ch = getchar();
if (ch == '-') sign = -1;
}
while ('0' <= ch && ch <= '9') {
res = res * 10 + ch - '0';
ch = getchar();
}
return res * sign;
}
int n, q;
struct tree {
int op, ed;
long long minn;
} tr[400007];
long long a[100007];
int l, r, v, p, x;
long long ans = 0;
void build(int v, int l, int r) {
tr[v].op = l;
tr[v].ed = r;
if (l == r) {
ans += abs(a[l]);
tr[v].minn = max(0ll, -a[l - 1]) + max(0ll, a[l]);
return;
}
int mid = (l + r) >> 1;
build((v << 1), l, mid);
build((v << 1 | 1), mid + 1, r);
tr[v].minn = min(tr[(v << 1)].minn, tr[(v << 1 | 1)].minn);
}
void update(int v, int pos, int x) {
if (tr[v].op == tr[v].ed) {
ans -= abs(a[tr[v].op]);
a[tr[v].op] += x;
ans += abs(a[tr[v].op]);
if (pos > 1)
tr[v].minn = max(0ll, -a[tr[v].op - 1]) + max(0ll, a[tr[v].ed]);
if (x && pos < n - 1) update(1, pos + 1, 0);
return;
}
int mid = (tr[v].op + tr[v].ed) >> 1;
if (mid >= pos)
update((v << 1), pos, x);
else
update((v << 1 | 1), pos, x);
tr[v].minn = min(tr[(v << 1)].minn, tr[(v << 1 | 1)].minn);
return;
}
long long query(int v, int l, int r) {
if (r < tr[v].op || l > tr[v].ed) return 0x7f7f7f7f7f7f7f7f;
if (l <= tr[v].op && tr[v].ed <= r) return tr[v].minn;
long long res = query((v << 1), l, r);
res = min(res, query((v << 1 | 1), l, r));
return res;
}
int main() {
n = getint();
for (int i = 1; i <= n; i++) a[i] = getint();
for (int i = 1; i <= n; i++) a[i] = a[i + 1] - a[i];
build(1, 1, n - 1);
q = getint();
while (q--) {
p = getint();
l = getint();
r = getint();
x = getint();
if (p == 1) {
if (l == r) {
if (l == 1) {
printf("%lld\n", ans - abs(a[1]) + abs(a[1] - x));
continue;
}
if (l == n) {
printf("%lld\n", ans - abs(a[n - 1]) + abs(a[n - 1] + x));
continue;
}
printf("%lld\n", ans - abs(a[l]) - abs(a[l - 1]) + abs(a[l - 1] + x) +
abs(a[l] - x));
} else {
long long del = 0;
del = max(del, 2 * x - 2 * query(1, max(l, 2), r));
if (l == 1) del = max(del, -abs(a[l]) + abs(a[l] - x));
if (r == n) del = max(del, -abs(a[r - 1]) + abs(a[r - 1] + x));
printf("%lld\n", ans + del);
}
} else {
if (l > 1) update(1, l - 1, x);
if (r < n) update(1, r, -x);
}
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
long long N, k = 1;
cin >> N;
while (N % k == 0) {
k *= 3;
}
cout << (N + k - 1) / k;
return 0;
}
| 7 | CPP |
import sys
def m(L,R):
global c
T=[];i=j=0
for _ in L[:-1]+R[:-1]:
if L[i]<R[j]:T+=[L[i]];i+=1
else:T+=[R[j]];j+=1
c+=1
return T
def d(A):s=len(A)//2;return m(d(A[:s])+[1e9],d(A[s:])+[1e9]) if len(A)>1 else A
c=0
input()
print(*d(list(map(int,sys.stdin.readline().split()))))
print(c)
| 0 | PYTHON3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.