input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
The Smart Beaver from ABBYY has come up with a new developing game for children. The Beaver thinks that this game will help children to understand programming better.
The main object of the game is finite rooted trees, each of their edges contains some lowercase English letter. Vertices on any tree are always numbered... | #include <bits/stdc++.h>
using namespace std;
void RI() {}
template <typename... T>
void RI(int& head, T&... tail) {
scanf("%d", &head);
RI(tail...);
}
mt19937 rng(0x5EED);
int randint(int lb, int ub) {
return uniform_int_distribution<int>(lb, ub)(rng);
}
const int LOG = 18;
const int MXN = 200005;
struct Operati... |
A piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array.
However, before looking for such number, you are allowed to perform not more than k following operations — choose an arbitrary element from the array and add 1 to it. I... | #include <bits/stdc++.h>
using namespace std;
long long a[200000];
int n, i, ans, j, x;
long long sum, k, num;
int main() {
cin >> n >> k;
for (i = 0; i < n; i++) {
scanf("%d", &x);
a[i] = x;
}
sort(a, a + n);
sum = 0;
ans = 0;
j = 0;
for (i = 0; i < n; i++) {
if (i > 0) sum = sum + (a[i] - ... |
Petya and Vasya decided to play a little. They found n red cubes and m blue cubes. The game goes like that: the players take turns to choose a cube of some color (red or blue) and put it in a line from left to right (overall the line will have n + m cubes). Petya moves first. Petya's task is to get as many pairs of nei... | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUF... |
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: <image>.
The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is t... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 9;
int a[MAX], n, ans;
vector<int> l;
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) {
while (l.size() && a[i] >= l.back()) l.pop_back();
if (l.size()) ans = max(ans, l.back() ^ a[i]);
l.pu... |
Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not.
A permutation triple of permutations of length n (a, b, c) is called a... | #include <bits/stdc++.h>
using namespace std;
long long int a[100010], b[100010], c[100010];
int main() {
long long int n;
cin >> n;
if (n % 2 == 0)
cout << "-1" << endl;
else {
for (long long int i = 0; i < n; i++) {
a[i] = i % n;
b[i] = i % n;
c[i] = (a[i] + b[i]) % n;
}
for ... |
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a nu... | import sys
line = sys.stdin.readline()
print line.replace('--', '2').replace('-.', '1').replace('.', '0') |
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, contai... | import static java.lang.System.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
imp... |
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.
Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resultin... | #include <bits/stdc++.h>
using namespace std;
const long long INF = 0x7fffffff;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int maxn = 1000000 + 10;
int num[10];
bool judge(int hh, string now) {
for (int i = 0; i < now.size(); i++) {
hh *= 10;
hh += (now[i] - '0');
hh %= 7;
}
if (hh == ... |
You are given an integer m as a product of integers a1, a2, ... an <image>. Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers.
Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, ... |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Stack;
import java.util.regex.Pattern;
public class ROUGH {
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is ... |
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having c... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse4")
#pragma GCC optimize("unroll-loops")
using namespace std;
pair<int, char> dp[105][105][15];
string A[105];
int main() {
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int i, j, k, n, m, K, maxi = INT_MIN, maxp = -1;
... |
As we know, DZY loves playing games. One day DZY decided to play with a n × m matrix. To be more precise, he decided to modify the matrix with exactly k operations.
Each modification is one of the following:
1. Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the v... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.PriorityQueue;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.I... |
Little X has met the following problem recently.
Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234) = 1 + 2 + 3 + 4). You are to calculate <image>
Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the foll... | #include <bits/stdc++.h>
using namespace std;
int bit[25];
pair<long long, long long> dp[25];
bool vis[25];
pair<long long, long long> dfs(int pos, int lim) {
if (!pos) return make_pair(0, 1);
if (!lim && vis[pos]) return dp[pos];
int num = lim ? bit[pos] : 9;
pair<long long, long long> ret = make_pair(0, 0);
... |
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.
Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long inte... | #include <bits/stdc++.h>
using namespace std;
int64_t fast(int64_t x, int64_t y, int64_t p) {
x %= p;
int64_t res = 1;
while (y) {
if (y & 1) {
res = (res * x) % p;
}
y >>= 1;
x = (x * x) % p;
}
return res;
}
int main() {
string s;
cin >> s;
int64_t n = s.length();
int64_t a, b;
... |
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mech... | from sys import stdin
from functools import reduce
from collections import defaultdict
_data = iter(stdin.read().split('\n'))
def input():
while True:
return next(_data)
n, m = [int(x) for x in input().split()]
B = 10007
MOD = 1000000000000000003
h = lambda s: reduce(lambda s, c: (B * s + ord(c)) % MOD, s... |
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper... | #include <bits/stdc++.h>
using namespace std;
const int N = 101;
double a[N][N][N];
double b[N][N][N];
double c[N][N][N];
bool v[N][N][N];
int ca, cb, cc;
void input() { cin >> ca >> cc >> cb; }
void calc(int i, int j, int k) {
if (v[i][j][k]) {
return;
}
if (i && !j && !k) {
a[i][j][k] = 1;
b[i][j][k... |
Note that the memory limit in this problem is less than usual.
Let's consider an array consisting of positive integers, some positions of which contain gaps.
We have a collection of numbers that can be used to fill the gaps. Each number from the given collection can be used at most once.
Your task is to determine su... | #include <bits/stdc++.h>
using namespace std;
int n, m, r, v;
const int N = 200000;
int ai[N], bi[N], gc[N], pc[N], pd[N];
int ls[N], id[N], pr[N], va[N], wa[N];
int flag[N];
int main() {
ios::sync_with_stdio(0);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> ai[i];
n++;
ai[n] = 1e9 + 5;
cin >> m;
for (int... |
On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 ≤ i ≤ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should... | if __name__ == '__main__':
n = int(raw_input().rstrip())
heights = [int(x) for x in raw_input().rstrip().split()]
dic = {}
for i in range(0, n):
heights[i] -= min(i, n - 1 - i)
key = heights[i]
if key == 0:
continue
if key not in dic:
dic[key]... |
Do you know the story about the three musketeers? Anyway, you must help them now.
Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength a, Borthos strength b, and Caramis has strength c.
The year 2015 is almost over and there are stil... | #include <bits/stdc++.h>
using namespace std;
const int INF = INT_MAX;
const long long INFL = LLONG_MAX;
const long double pi = acos(-1);
int N;
int mus[3];
int T[200100];
int main() {
ios_base::sync_with_stdio(0);
cout.precision(15);
cout << fixed;
cout.tie(0);
cin.tie(0);
cin >> N;
for (int(i) = 0; (i) ... |
Kris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the pr... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
int table[5007][5007], n, m, k;
bool frq[5007][2];
struct q {
int t, x, c;
} mem[N], a;
int main() {
cin >> n >> m >> k;
for (int i = 0; i < k; i++) scanf("%d%d%d", &mem[i].t, &mem[i].x, &mem[i].c);
for (int i = k - 1; i >= 0; i--) {
a = m... |
Harry Potter lost his Invisibility Cloak, running from the school caretaker Filch. Finding an invisible object is not an easy task. Fortunately, Harry has friends who are willing to help. Hermione Granger had read "The Invisibility Cloaks, and Everything about Them", as well as six volumes of "The Encyclopedia of Quick... | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;
import ja... |
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only ope... | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1000000000000000;
const int maxn = 1e5 + 100;
long long dp[maxn][2], c[maxn];
string reverse(string s) {
string t = "";
for (int i = s.size() - 1; i >= 0; i--) t += s[i];
return t;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < ... |
There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior.
There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate ... | #include <bits/stdc++.h>
using namespace std;
const int MXN = 1e6 + 30;
const int MAXN = 1e3 + 2;
const long long INF = 1e9 + 7;
const long long BINF = 1e15;
const int MOD = 1e9 + 7;
const long double EPS = 1e-15;
long long n, m;
long long a[MXN];
long long used[MXN];
multiset<long long> st;
multiset<long long>::iterat... |
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.
In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five proble... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SRM68_1 {
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//String []s =... |
This is an interactive problem.
The judge has a hidden rooted full binary tree with n leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2n - 1 nodes in the tree. The leaves of t... | #include <bits/stdc++.h>
using namespace std;
struct edge {
int v, nxt;
} e[500005];
int n, pt, a[100005], h[100005], t, rt, qrt, ls[100005], rs[100005], f[100005],
q;
int sz[100005], vis[100005];
void add(int u, int v) {
e[++t].v = v;
e[t].nxt = h[u];
h[u] = t;
}
void dfs(int u) {
if (!ls[u] && !rs[u]) {... |
a is an array of n positive integers, all of which are not greater than n.
You have to process q queries to this array. Each query is represented by two numbers p and k. Several operations are performed in each query; each operation changes p to p + ap + k. There operations are applied until p becomes greater than n. ... | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
/... |
There are n students who have taken part in an olympiad. Now it's time to award the students.
Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and ce... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k, a;
cin >> n >> k;
a = (n / 2) / (k + 1);
cout << a << " " << a * k << " " << n - (k + 1) * a;
}
|
This is an interactive problem.
You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x.
More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the int... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual soluti... |
Recently Ivan bought a new computer. Excited, he unpacked it and installed his favourite game. With his old computer Ivan had to choose the worst possible graphic settings (because otherwise the framerate would be really low), but now he wants to check, maybe his new computer can perform well even with the best possibl... | #include <bits/stdc++.h>
using namespace std;
int M, R, C, S, T, a[8], b[8], id[8];
vector<vector<vector<int> > > ver;
void createVer(int prod, int cur) {
if (cur == M) return;
for (int i = 1; i <= (int)(a[0]); ++i)
for (int j = 1; j <= (int)(prod); ++j) {
ver[i][j][cur] = 1;
}
for (int k = 2; k <= ... |
You are given a set of n points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines.
Multiset is a set where equal elements are allowed.
Multiset is called symmetric, if there is a point P on t... | #include <bits/stdc++.h>
using ll = long long;
using ld = long double;
using namespace std;
const int MAXN = 20001;
int n;
ll x[MAXN], y[MAXN];
void rm(int id) {
for (int i = id; i + 1 < n; ++i) {
x[i] = x[i + 1];
y[i] = y[i + 1];
}
--n;
}
ll vals[MAXN];
int ans = 0;
const int BTS = 20;
const ll MSK = (1 ... |
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol' bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness.
The choice of candies has a direc... | #include <bits/stdc++.h>
using namespace std;
using lli = long long int;
using llu = long long unsigned;
using ld = long double;
using pii = pair<lli, lli>;
using vi = vector<lli>;
using vii = vector<pii>;
using vvi = vector<vi>;
using vvii = vector<vii>;
template <typename T>
istream& read_collection(istream& in, T& a... |
Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.
Big Banban is hesitating over the amount ... | #include <bits/stdc++.h>
using namespace std;
int a[] = {1, 4, 8}, k;
int main() {
cin >> k;
if (k > 36)
cout << -1 << endl;
else if (k % 2 == 1) {
for (int i = 0; i < k / 2; i++) cout << a[2];
cout << a[1];
for (int i = k / 2 + 1; i < 18; i++) cout << a[0];
cout << endl;
} else {
for (i... |
You have a full binary tree having infinite levels.
Each node has an initial value. If a node has value x, then its left child has value 2·x and its right child has value 2·x + 1.
The value of the root is 1.
You need to answer Q queries.
There are 3 types of queries:
1. Cyclically shift the values of all nod... | #include <bits/stdc++.h>
namespace loquat {
namespace bitmanip {
template <typename T>
inline auto ctz(T x) noexcept -> T {
return __builtin_ctzll(x);
}
template <typename T>
inline auto clz(T x) noexcept -> T {
return __builtin_clzll(x);
}
template <typename T>
inline T flp2(T x) noexcept {
if (x == 0u) {
re... |
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 ≤ k ≤ n) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri... | n, k = map(int, input().split())
a = list(map(int, input().split()))
d = {}
for i in range(n):
d[a[i]] = i + 1
if len(d) < k:
print('NO')
else:
print('YES')
values = list(d.values())
for i in range(k):
print(values[i], end=' ') |
A student is assigned a problem, to get a alphanumeric string from the user and to calculate the sum of digits in the given string.after this he has to delete the digits(0-9) from the string and to display the each word of the string in dictionary order followed by the sum of digits continuously decreasing by the size... | n=int(raw_input())
for i in range(n):
ss=''
tot=0
s=raw_input()
for j in range(len(s)):
if s[j] in ['0','1','2','3','4','5','6','7','8','9']:
tot+=int(s[j])
else:
ss=ss+s[j]
j+=1
ss=ss.split()
ss.sort()
for k in range(len(ss)):
tot-=(len(ss[k]))
print ss[k],
if tot<0:
print str(tot*-1),
el... |
Given A and B, compute the sum of lcm(a, b) over all pairs of positive integers a and b such that:
(1) a ≤ A and b ≤ B.
(2) There is no integer n>1 such that n^2 divides both a and b.
Give your answer modulo 2^30.
INPUT
The first line contains the number of test cases, t (about 200). Each of the next t lines conta... | def lcm(x, y):
p=x*y
if x>y:
x,y=y,x
while(y):
x, y = y, x % y
gcd=x
lcm = p/gcd
return lcm
import math
def check(a,b):
m=min(a,b)
for n in range(2, int(math.sqrt(m)+1)):
s=n**2
if a%s==0 and b%s==0:
return False
return True
for i in range(int... |
See Russian Translation
The end semester exams are now approaching. Ritu is the Computer Science Teacher of Coder Public School. He has been assigned the task of preparing good algorithmic problems for the students by the Dean of the school.
Ritu like every other teacher has his own favorite topics. Ritu likes matri... | __author__ = 'siddharth'
D = None
N = 0
MOD = 1000000007
def vfoo():
for i in sorted(D.iteritems(), key=lambda v: v[1]):
yield i
def indices(i):
u, v = i/N, i%N
I = list()
if u > 0:
I.append((u-1)*N + v)
if u < N-1:
I.append((u+1)*N + v)
if v > 0:
I.append(u*N ... |
Puchi and Ghissi are playing a game with strings. As Ghissi is a champion at strings, Puchi decides to challenge her. He gives Ghissi a string S and an integer K . The objective for Ghissi is to find a substring of S such that:
- The substring occurs at the start of the string S.
- The substring occurs at the ... | output = []
for x in range(int(raw_input())):
out = ''
s, k = map(lambda x:x, raw_input().split())
k = int(k)
s_l = len(s)
stri = ''
l,j=0,0
for p in s[1:k]:
if p == s[j]:
stri += p
j+=1
if(l<j and p==s[-1]):
if(stri==s[-j:]):
out = stri
l=j
else:
stri = ''
j=0
if out == '':
o... |
Shizuka, the daughter of Code King, is the most beautiful girl of Candyland. Every other Prince wants to marry her.The Code King invites all the other Prince in the town for a RACE and the winner of the race gets a chance to marry her.
Obviously , the RACE will be full of hurdles. Given the number of Princes N, each w... | tc = int(raw_input())
for t in range(tc):
n, k = [int(c) for c in raw_input().rstrip().split(" ")]
n_arr = [int(c) for c in raw_input().rstrip().split(" ")]
k_arr = [int(c) for c in raw_input().rstrip().split(" ")]
n_max = max(n_arr)
k_max = max(k_arr)
if k_max>n_max:
for k_val in k_arr:... |
Monk's favourite game is Football and his favourite club is "Manchester United". Manchester United has qualified for the Champions League Final which is to be held at the Wembley Stadium in London. So, he decided to go there and watch his favourite team play. After reaching the stadium, he saw that many people have lin... | import heapq
def solve(n, xs):
xs = [-x for x in xs]
heapq.heapify(xs)
tot = 0
for _ in range(n):
price = xs[0]
tot += price
heapq.heapreplace(xs, price + 1)
return -tot
if __name__ == '__main__':
_, n = map(int, raw_input().split())
xs = map(int, raw_input().split(... |
Pankaj is a very intelligent student studying in one of the best colleges of this country. He's good enough to challenge the smartest minds in the country, but even the smart ones make mistakes and so did Pankaj - he fell in love, ah. He was so deeply in love that he decided to propose the love of his life. What he did... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n=input()
m=map(int,raw_input().split())
l=[]
for i in xrange(n):
l.append(1)
for i in xrange(n):
for j in xrange(i):
if m[i]>m[j] and l[i]<l[j]+1:
... |
Roy is working on HackerEarth Profile. Right now he is working on User Statistics.
One of the statistics data (Code Streak) is as follows:
Given the User Activity Data, find the maximum number of continuous correct solutions submitted by any user.
Seems easy eh? Here's the catch! In order to maximize this number a use... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
t=int(raw_input())
for i in range(t):
n=int(raw_input())
maxi=0
count=0
presid=set()
for j in range(n):
q=raw_input().split()
sid,result=int(q[0]),int(q[1... |
Rahul is a young chap who loves strings but simply hates mathematics. While his friend Ramesh is in love with mathematics but hates strings. So their teacher decided to take a test which combined both these topics so that neither of them gets a better hand over the other.
Their teacher gave both of them a single strin... | T=int(raw_input())
for _ in xrange(T):
K,Z=(int(e) for e in raw_input().split())
s=raw_input()
if K>len(s):
print -1
else:
lis=[[-1 for e in xrange(len(s))] for f in xrange(len(s))]
for e in xrange(len(s)):
for i in xrange(e,len(s)):
if int(s[e:i+1])<=Z:
lis[e][i]=int(s[e:i+1])
dp=[[-1 for e in ... |
Utkarsh's mother recently received N piles of books as a gift from someone. The i^th pile contains Bi books.
She neither wants to keep the voluminous books with herself nor she wants to throw them away. So, she decided to distribute them to students of the nearby school. She decided to call K students to her home and... | T=int(raw_input())
B=[]
A=[]
for i in range(0,T):
N=int(raw_input())
S=raw_input()
B=S.split()
for i in range(0,N):
a=int(B[i])
A.append(a)
m=min(A)
U=m-1
s=sum(A)-2*(N)
K=s+N
print U,K
A=[]
B=[] |
You are given positions (X_i, Y_i) of N enemy rooks on an infinite chessboard. No two rooks attack each other (at most one rook per row or column).
You're going to replace one rook with a king and then move the king repeatedly to beat as many rooks as possible.
You can't enter a cell that is being attacked by a rook.... | #include<bits/stdc++.h>
using namespace std;
const int maxn=200009;
int n;
struct Point{
int x,y,id;
bool operator < (const Point &rhs) const{
return x<rhs.x;
}
}r[maxn];
int sy[maxn];
long long ans[maxn];
long long f[maxn][2];
vector<pair<int,int>>section;
int dist(int i,int j){
return abs(r[i].x-r[j].x)+abs... |
Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)
Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?
(We as... | import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
long x = (a/500)*1000;
x+=((a%500)/5)*5;
System.out.println(x);
}
} |
Chokudai made a rectangular cake for contestants in DDCC 2020 Finals.
The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them.
The positions of the strawberries are given to you as H \times W ch... | import bisect
H,W,K=map(int,input().split())
s=[""]*H
ans=[[0]*W for _ in range(H)]
St=[0]*H#i行目にイチゴがあるか?
St2=[]
for i in range(H):
s[i]=input()
if "#" in s[i]:
St[i]=1
St2.append(i)
a=1
#i行目,aからスタートして埋める
for i in range(H):
if St[i]==1:
flag=0
for j in r... |
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does th... | import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.ne... |
Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions:
* He never visits a point with coordinate less than 0, or a point with coordinate greater than L.
* He starts walking at a point with integer coordinate, and also finishes walking at a point with ... | #include "bits/stdc++.h"
using namespace std;
signed main(){
int n;
cin >> n;
long long x, sv = 0, sp = 0, sz = 0, min1 = 0, min2 = 0, min3 = 0, min4 = 0;
for(int i = 1; i <= n; i++){
cin >> x;
sv+=x; sp+=x%2; sz+=!x;
min4 = min(min4,
(min3 = min(min3,
... |
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of ... | #include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
#define int long long
#define MN 100005
using namespace std;
inline int in(){
int x=0;bool f=0;char c;
for (;(c=getchar())<'0'||c>'9';f=c=='-');
for (x=c-'0';(c=getchar())>='0'&&c<='9';x=(x<<3)+(x<<1)+c-'0');
return f?-x:x;
}
in... |
We have an N \times M grid. The square at the i-th row and j-th column will be denoted as (i,j). Particularly, the top-left square will be denoted as (1,1), and the bottom-right square will be denoted as (N,M). Takahashi painted some of the squares (possibly zero) black, and painted the other squares white.
We will de... | import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
ModuloCombinatorics mc = new ModuloCombinatorics(10000, P);
static final int P = 998244353;
static int nextPowerOf2(int x) {
return x == 1 ? 1 : Integer.highestOneBit(x - 1) << 1;
}
static class CompV {
double[] re, im;
void ... |
Ringo is giving a present to Snuke.
Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with `YAKI` in Japanese, and does not like other things.
You are given a string S representing the Japanese name of ... | #include <bits/stdc++.h>
using namespace std;
int main () {
string s;
cin >> s;
if (s.find("YAKI") == 0) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
} |
Joisino has a lot of red and blue bricks and a large box. She will build a tower of these bricks in the following manner.
First, she will pick a total of N bricks and put them into the box. Here, there may be any number of bricks of each color in the box, as long as there are N bricks in total. Particularly, there may... | #include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<fstream>
using namespace std;
const int mod=1000000007;
int n,m;
int f[3003][3003][2];
int dp(int tur,int num,int sta){
int &ret=f[tur][num][sta];
if(ret!=-1){
return ret;
}
if(tur==m){
if(sta==1){
return re... |
The problem set at CODE FESTIVAL 20XX Finals consists of N problems.
The score allocated to the i-th (1≦i≦N) problem is i points.
Takahashi, a contestant, is trying to score exactly N points. For that, he is deciding which problems to solve.
As problems with higher scores are harder, he wants to minimize the highest... | N = int(input())
for n in range(1, N+1):
if n*(n+1)//2 >= N:
break
d = n*(n+1)//2-N
s = set(range(1, n+1))
s.discard(d)
for i in s:
print(i)
#print(sum(s))
|
Write a program which computes the area of a shape represented by the following three lines:
$y = x^2$
$y = 0$
$x = 600$
It is clear that the area is $72000000$, if you use an integral you learn in high school. On the other hand, we can obtain an approximative area of the shape by adding up areas of many rectangles... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int d = sc.nextInt();
long sum=0;
for(int i=d; i<=600-d; i+=d) sum += d*i*i;
System.out.println(sum);
}
}
} |
The phantom thief "Lupin IV" is told by the beautiful "Fujiko Mine", a descendant of the Aizu clan, that the military funds left by the Aizu clan are sleeping in Aizuwakamatsu city. According to a report by Lupine's longtime companion, "Ishikawa Koshiemon," military funds are stored in several warehouses in a Senryobak... | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class KuraInfo{
public:
int num;
int dist;
int weight;
};
typedef pair<double,vector<int> > P;
P dp[(1<<15)][15];
int dp2[(1<<15)];
int n;
KuraInfo kuras[15];
const int INF=100000000;
P dfs(const int s,const int d,const double sumW... |
Let's write a program related to an unsolved math problem called "Happy End Problem". Create a program to find the smallest convex polygon formed by connecting exactly k points from the N points given on the plane. However, after being given the coordinates of N points, the question is given the number k of the angles ... | def cross(z1, z2):
return z1.real * z2.imag - z1.imag * z2.real
def ccw(p1, p2, p3):
return cross(p2 - p1, p3 - p1) > 0
def triangle_area(p1, p2, p3):
# returns signed trangle area
return cross(p2 - p1, p3 - p1) / 2
from sys import stdin
file_input = stdin
N = int(file_input.readline())
P = []
M = {... |
Sugoroku
problem
JOI is playing sugoroku alone. There are N squares in a straight line in this sugoroku, and each has a movement instruction written on it. The starting point is the 1st square and the goal is the Nth square. JOI repeats the following until he reaches the goal.
Roll the dice and proceed from the curr... |
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
private void run() throws IOException {
Scanner scanner = new Scanner(System.in);
while (true) {
int n = scanner.nextInt();
int m = scanner.nextIn... |
You are the planning manager of an animation production company. What animation production companies produce these days is not limited to animation itself. Related products, such as figures of characters and character song CDs, are also important sources of revenue. How much this profit can be increased depends solely ... | #include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
char s[20];
int main() {
int n;
while (scanf("%d", &n), n) {
vector<string>v[31];
map<string, int>mp;
rep(i, n) {
int m; scanf("%s%d", s, &m);
string t = s;
mp[t] = 0;
rep(j, m) {
int d; scanf("%d", &d);
v[d].... |
Dr. Extreme experimentally made an extremely precise telescope to investigate extremely curi- ous phenomena at an extremely distant place. In order to make the telescope so precise as to investigate phenomena at such an extremely distant place, even quite a small distortion is not allowed. However, he forgot the influe... | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int n,m;
double x[40],y[40],dp[42][42][42];
double calArea(int a,int b,int c){
int t[3];
int i,p1,p2;
double res = 0;
t[0] = a;
t[1] = b;
t[2] = c;
for(i=0;i<3;i++){
p1 = t[i];
p2 = t[(i+1)%3];
res += x[p... |
Example
Input
6 5 1 2 3
5 5 5
1 5 5
2 5 4
3 5 3
4 5 2
5 5 1
Output
0.631579 | #include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
typedef double Real;
typedef vector<int> Vector;
const Real inf=1e12;
const Real eps=1e-9;
template<class T> bool eq(T a, T b){
return abs(a-b)<eps;
}
template<class T> int sgn(T a){
if(eq(a,0.0)) return 0;
if(a>0) return... |
Problem
In a certain universe, there are n stars on a two-dimensional lattice point, and aliens use the Reflection Warp Machine to move between the stars.
This device can draw a straight line at any position and angle.
With this straight line as the axis of symmetry, it is possible to move from the current coordinates... | #include<bits/stdc++.h>
using namespace std;
#define int long long
typedef long long ll;
typedef pair<int,int>pint;
typedef vector<int>vint;
typedef vector<pint>vpint;
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for(int i=0;i<(n);i... |
Year 20XX — a nuclear explosion has burned the world. Half the people on the planet have died. Fearful.
One city, fortunately, was not directly damaged by the explosion. This city consists of N domes (numbered 1 through N inclusive) and M bidirectional transportation pipelines connecting the domes. In dome i, Pi citiz... | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
namespace Dinic {
const int mxn=5000, mxm=500000;
int S, T;
int head[mxn];
int next[mxm], to[mxm], flow[mxm];
inline void addedge(int idx, int a, int b, int f)
{
next[idx]=head[a]; head[a]=idx;
to[idx]=b; flow[idx... |
Description
THE BY DOLM @ STER is a training simulation game scheduled to be released on EXIDNA by 1rem on April 1, 2010. For the time being, it probably has nothing to do with an arcade game where the network connection service stopped earlier this month.
This game is a game in which members of the unit (formation) t... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
typedef long long int ll;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000001
using namespace std;
struct Info{
int cost,vocal,dance,looks;
};
int main(){
int N,M,dp[301... |
Example
Input
1 1 1 1 1
Output
0.000000000000 | #include <vector>
#include <iostream>
#include <map>
#include <algorithm>
#include <random>
#include <complex>
#include <unordered_map>
#include <cmath>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <bitset>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
ll gcd(ll a, ll b) {
... |
H - Rings
Problem Statement
There are two circles with radius 1 in 3D space. Please check two circles are connected as chained rings.
Input
The input is formatted as follows.
{c_x}_1 {c_y}_1 {c_z}_1
{v_x}_{1,1} {v_y}_{1,1} {v_z}_{1,1} {v_x}_{1,2} {v_y}_{1,2} {v_z}_{1,2}
{c_x}_2 {c_y}_2 {c_z}_2
{v_x}_{2,1} {v_y}_{... | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-8;
const double INF = 1e+8;
struct P3{
double x, y, z;
P3(double x=0, double y=0, double z=0):x(x),y(y),z(z){}
P3 operator + (const P3 &a) const{ return P3(x+a.x, y+a.y, z+a.z); }
P3 operator - (const P3 &a) const{ return P3(x-a.x, y-a.y, z-a... |
H --Bit Operation Game
Given a rooted tree with N vertices. The vertices are numbered from 0 to N − 1, and the 0th vertex represents the root. `T = 0` for the root, but for the other vertices
* `T = T & X;`
* `T = T & Y;`
* `T = T | X`
* `T = T | Y`
* `T = T ^ X`
* `T = T ^ Y`
One of the operations is written. Her... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define fi first
#define se second
typedef pair<ll,ll> P;
using VP = vector<P>; using VVP = vector<VP>;
using VI = vector<int>; using VVI = vector<VI>; using VVVI = vector<VVI>;
const int inf=1e9+7;
const ll INF=1LL<<60;
const ll mo... |
You received a card at a banquet. On the card, a matrix of $N$ rows and $M$ columns and two integers $K$ and $S$ are written. All the elements in the matrix are integers, and an integer at the $i$-th row from the top and the $j$-th column from the left is denoted by $A_{i,j}$.
You can select up to $K$ elements from th... | #include<bits/stdc++.h>
using namespace std;
signed main(){
int n,m,k,s;
cin>>n>>m>>k>>s;
int a[11][11];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>a[i][j];
/*//
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cout<<a[i][j]<<" \n"[j==m-1]<<flush;
//*/
auto row=[&](int i){
int x... |
Problem
Mr. ukuku1333 is a little sloppy, so when I expanded the product of the linear expressions of x, I couldn't figure out the original linear expression.
Given the nth degree polynomial of x, factor it into the product of the original linear expressions of x.
The nth degree polynomial of x is given by the follow... | import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
char[] arr = sc.next().toCharArray();
int num = 0;
boolean plus = true;
boolean si = false;
boolean xs = false;
long[] keis = new long[6];
for (char c : arr) {
if (c == '+') {
... |
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving ... | #include <bits/stdc++.h>
#define rep(i,a,b) for(int i=int(a);i<int(b);++i)
#define SIZE 200005
#define INF 1000000005LL
//#define INF 1e18
#define MOD 1000000007
using namespace std;
typedef long long int ll;
typedef pair <int,int> P;
int c;
vector<int> E[SIZE];
int d[SIZE],f[SIZE]; //init:0
void dfs(int v){
c++;
... |
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was rolled in the same way as Dice I. Write a program to print an integer on the right side face.
<image>
Constraints
* $0 \leq $ the integer assigned to a face $ ... | import java.util.Scanner;
public class Main {
private static Scanner sc=new Scanner(System.in);
private static int[] a=new int[6];
private static int questionLength;
public static void main(String[] args){
for(int i=0;i<a.length;i++){
a[i]=sc.nextInt();
}
questionLength=sc.nextInt();
for(int i=0;i<quest... |
Chef is judging a game called "Broken telephone". There are total N players taking part in the game. They are all sitting in a line. In the start of the game, first player is given a secret message written on a sheet of paper. Then they keep sending the message by whispering it to the player sitting immediate right to ... | T = input()
for i in xrange(T):
N = input()
A = map(int,raw_input().split())
visited = [0 for k in xrange(N)]
count = 0;
for j in xrange(N-1):
if(A[j] != A[j+1]):
if(visited[j] == 0):
visited[j] = 1
count += 1
if(visited[j+1] == 0):
visited[j+1] = 1
count += 1
print count |
The Chef commutes to work every day using the city's underground metro. The schedule for the trains has recently been changed and he wants to know how long it will take to travel from the station nearest to his house and the station nearest to his restaurant.
The Chef doesn't want to change the route he took before, ... | def train():
tcases = int(raw_input())
for i in range(tcases):
n = int(raw_input())
time = 0
for j in range(n):
path = raw_input()
path = path.split()
path = map(int, path)
if time <= path[0]:
time = path[0]
elif... |
You are given an array A of integers of size N. You will be given Q queries where each query is represented by two integers L, R. You have to find the gcd(Greatest Common Divisor) of the array after excluding the part from range L to R inclusive (1 Based indexing). You are guaranteed that after excluding the part of th... | def gcd(x, y):
while y > 0:
x, y = y, x % y
return x
for _ in range(input()):
n, q = map(int, raw_input().split())
a = map(int, raw_input().split())
lg, rg = [0], [0]
for v in a:
lg.append(gcd(v, lg[-1]))
for v in reversed(a):
rg.append(gcd(v, rg[-1]))
rg.reverse... |
A Little Elephant from the Zoo of Lviv likes lucky strings, i.e., the strings that consist only of the lucky digits 4 and 7.
The Little Elephant has K favorite lucky strings A1, A2, ..., AK. He thinks that the lucky string S is good if either |S| ≥ 47 or for some j from 1 to K we have that Aj is a substring of S.
The ... | def isLuckyString(b, A):
if len(b)>=47:
print "Good"
return
for a in A:
if a in b:
print "Good"
return
print "Bad"
K, N = map(int, raw_input().split())
A=[]
for _ in range(K):
A.append(raw_input())
for _ in range(N):
isLuckyString(raw_input(), A) |
Naturally, the magical girl is very good at performing magic. She recently met her master wizard Devu, who gifted her R potions of red liquid,
B potions of blue liquid, and G potions of green liquid.
The red liquid potions have liquid amounts given by r[1], ..., r[R] liters.
The green liquid potions have liquid am... | t =input()
for i in range(t):
r,g,b,m =map(int,raw_input().split())
rlist =map(int,raw_input().split())
listg = map(int,raw_input().split())
listb = map(int,raw_input().split())
rmax = max(rlist)
gmax = max(listg)
bmax = max(listb)
ls=[rmax,gmax,bmax]
for j in xrange(m):
ls[ls.index(max(ls))]/=2
print max(... |
Guru S has turned miserly after the rise in petrol prices and wants to save as much petrol. For this he decides to calculate the total distance he has to travel to go to a place from a given distance T between each city. He also wants to see what distances he will travel in the reverse journey.
For N distances given b... | while(1):
try:
t=raw_input()
a=[]
while(len(a)==0):
a=raw_input().split()
sum=0
a.reverse()
x=""
k=len(a)
for j in range(k):
a[j]=int(a[j])
sum=sum+a[j]
x=x+str(a[j])
if(j!=k-1):
x=x+" "
print x
print sum
except EOFError: br... |
Gleb is a famous competitive programming teacher from Innopolis. He is planning a trip to N programming camps in the nearest future. Each camp will be held in a different country. For each of them, Gleb needs to apply for a visa.
For each of these trips Gleb knows three integers: the number of the first day of the tr... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void read(T &t) {
t = 0;
char ch = getchar();
int f = 1;
while ('0' > ch || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
do {
(t *= 10) += ch - '0';
ch = getchar();
} while ('0' <= ch && ch <= '9');
t *= f;
}
con... |
Given an array a of n integers and an integer k (2 ≤ k ≤ n), where each element of the array is denoted by a_i (0 ≤ i < n). Perform the operation z given below on a and print the value of z(a,k) modulo 10^{9}+7.
function z(array a, integer k):
if length(a) < k:
return 0
... | #include <bits/stdc++.h>
using namespace std;
using li = long long;
using ld = long double;
void solve(bool);
signed main() {
cin.sync_with_stdio(false);
cin.tie(nullptr);
solve(true);
return 0;
}
vector<vector<li>> ed;
vector<vector<li>> e;
vector<li> depth;
vector<li> parent;
void dfs(li v, li p = -1) {
for... |
You are given a positive integer n.
Let S(x) be sum of digits in base 10 representation of x, for example, S(123) = 1 + 2 + 3 = 6, S(0) = 0.
Your task is to find two integers a, b, such that 0 ≤ a, b ≤ n, a + b = n and S(a) + S(b) is the largest possible among all such pairs.
Input
The only line of input contains a... | n=[k for k in raw_input().split(" ")][0]
def sd(n):
res=0
while n:
res+=n%10
n/=10
return res
fn=int(n[0])-1
res=str(fn)+"9"*(len(n)-1)
res=int(res)
n=int(n)
print sd(res)+sd(n-res)
|
After learning some fancy algorithms about palindromes, Chouti found palindromes very interesting, so he wants to challenge you with this problem.
Chouti has got two strings A and B. Since he likes [palindromes](https://en.wikipedia.org/wiki/Palindrome), he would like to pick a as some non-empty palindromic substring ... | #include <bits/stdc++.h>
using namespace std;
const int N = 234567;
const int LOG = 18;
const int ALPHA = 26;
const int base = 2333;
const int md0 = 1e9 + 7;
const int md1 = 1e9 + 9;
struct hash_t {
int hash0, hash1;
hash_t(int hash0 = 0, int hash1 = 0) : hash0(hash0), hash1(hash1) {}
hash_t operator+(const int &... |
An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code 091), a colon (ASCII code 058), some (possibly zero) vertical line characters (ASCII code 124), another colon, and a ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
s = input()
ans = -1
left = 0
right = len(s) - 1
lok = 1
while left < len(s):
if s[left] == '[':
lok = 2
left += 1
elif s[left] == ':' and lok == 2:
break
else:
left += 1
rok = 1
while right >= 0:
if s[right] == ']':
... |
This is an interactive problem.
A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster.
To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains n vertices, enumerated from 1 through n. She al... | #include <bits/stdc++.h>
int n;
int sz[505], s[505];
std::pair<int, int> a[505];
std::vector<int> ver;
inline int fnd(int u) {
int L = 0, R = ver.size() - 1, res = L - 1;
while (L <= R) {
int mid = (L + R) >> 1;
printf("1\n1\n%d\n", mid + 1);
for (int i = 0; i <= mid; i++) printf("%d ", ver[i]);
pri... |
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million... | #include <bits/stdc++.h>
using namespace std;
int main() {
int K, L;
while (scanf("%d", &K) == 1) {
scanf("%d", &L);
if (L < K)
puts("NO");
else if (L == K)
printf("YES\n0\n");
else {
int ret = -1;
long long hitung = K;
for (int i = 1;; i++) {
hitung *= K;
... |
Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v... | #include <bits/stdc++.h>
const int N = 1e3 + 5;
int n, rt, fa[N];
std::vector<int> vec[N];
std::vector<std::pair<int, int>> e[N];
std::vector<std::tuple<int, int, int>> ans;
void addEdge(int u, int v, int w) { e[u].emplace_back(std::make_pair(v, w)); }
void modifyPath(int u, int x) {
if (vec[u].size() == 1u) {
an... |
You are given n arrays that can have different sizes. You also have a table with w columns and n rows. The i-th array is placed horizontally in the i-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.
You need to find the maximum sum o... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
const int N = 100010;
const int MX = 123456;
const int mod = (int)1e9 + 7;
const int base = 1023456789;
const unsigned long long BS1 = 10000019ULL;
const int INF = (1 << 29);
template <class T>
inline void fastScan(T &x) {
register char c = getc... |
This is the harder version of the problem. In this version, 1 ≤ n, m ≤ 2⋅10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more e... | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> t;
int q(int v, int l, int r, int L, int R, int k) {
if (l > R || r < L || L > R) return 0;
if (l <= L && R <= r)
return lower_bound(t[v].begin(), t[v].end(), k) - t[v].begin();
return q(v * 2, l, r, L, (L + R) / 2, k) +
q(v * 2 + 1, l... |
Bob is about to take a hot bath.
There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can ... | #include <bits/stdc++.h>
using namespace std;
int cmp(unsigned long long z1, unsigned long long k1, unsigned long long z2,
unsigned long long k2) {
unsigned long long r1 = z1 * k2;
unsigned long long r2 = z2 * k1;
if (r1 < r2) return -1;
if (r1 > r2) return 1;
return 0;
}
int cmp(unsigned long long t1... |
This is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.
This is an interactive problem.
You're considering moving to another city, where one of your friends already lives. There are n cafés ... | #include <bits/stdc++.h>
using namespace std;
const int mac = 2e3 + 10;
int a[mac], vis[mac];
int ask(int pos) {
printf("? %d\n", pos + 1);
fflush(stdout);
char s[5];
scanf("%s", s);
if (s[0] == 'Y') return 1;
return 0;
}
int main(int argc, char const *argv[]) {
int n, m;
scanf("%d%d", &n, &m);
int bl... |
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).
<image> Examples of convex regular polygons
Your task is to say if it is poss... | for i in range(int(input())):
a,b=input().split()
if int(b)<=2:
print("NO")
elif int(a)%int(b)==0:
print("YES")
else:
print("NO") |
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge i... | #include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18;
const long double pi = 3.141592653589793238;
const long long MOD = 998244353;
const long long N = 1e2 + 10;
long long n, fact[N], ifact[N];
long long power(long long a, long long b) {
if (b == 0) return 1;
long long temp = power(a, b / 2);
... |
This is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages.
There are n gift boxes in a row, numbered from 1 to n from left to right. It's known that exactly k of them contain valuable gifts — other... | import java.io.*;
import java.util.*;
public class Main implements Runnable {
boolean judge = false;
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int t = scn.nextInt();
while (t-- > 0) {
int n = scn.nextInt(), k = scn.nextInt();
if (n < 5) {
int stone = 1;
for (int loop =... |
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.
Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read exactly m books before all entertainments. Alice and Bob will read ... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7, mz = 1e9 + 7;
vector<pair<int, int> > ap[4];
int n, m, k;
int ans = 1e18;
vector<int> ans_list;
int F(int v) {
if (k > v && (k - v > m - k || k - v > min(ap[1].size(), ap[2].size())))
return 1e18;
int fans = 0;
vector<int> fans_list;
for (... |
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.
For example, if the... | for i in range(int(input())):
s = list(filter(lambda x:x !='',input().split('0')))
s.sort(reverse=True)
pr = ''
for i in range(0,len(s),2):
pr +=s[i]
print(len(pr))
|
Ringo found a string s of length n in his [yellow submarine](https://www.youtube.com/watch?v=m2uTFF_3MaA). The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string s into a palindrome by applying two types of operations to the stri... | import java.util.*;
import java.io.*;
public class Main {
static final int M = 1000000007;
static FastReader in = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
// static Scanner in = new Scanner(System.in);
// File file = new File("input.txt");
// Scanner in = new Scanner(... |
For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operatio... | import java.io.*;
import java.util.*;
public class Main {
private static void solve() throws Exception {
String s = in.readLine();
boolean neg = false;
if (s.startsWith("-")) {
neg = true;
s = s.substring(1);
}
if (neg) out.print("(");
out.print("$");
String st, nd;
if (s.indexOf('.') != -1) ... |
Whoso in ignorance draws near to them and hears the Sirens' voice, he nevermore returns.
Homer, Odyssey
In the times of Jason and the Argonauts, it was well known that sirens use the sound of their songs to lure sailors into their demise. Yet only a few knew that every time sirens call a sailor by his name, his will ... | #include<bits/stdc++.h>
using namespace std;
#define P 1000000007
#define N 100005
#define M 2000005
char a[N],b[N],c[M],d[M];
int p[M],cf[N],qh[N][26],inv[N];
int pw(int x,int p){
int ans=1;
while(p){
if(p&1)ans=1ll*ans*x%P;
x=1ll*x*x%P;p>>=1;
}return ans;
}
int main(){
cf[0]=1;inv[0]=1;
for(int i=1;i<N;++i)c... |
You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds:
* 1 x : Assign to a_x the value 1 - a_x.
* 2 k : Print the k-th largest value of the array.
As a reminder, k-th largest value of the array b is defined as following:
... | n, q = map(int,input().split())
a = list(map(int,input().split()))
zero = a.count(0)
one = n - zero
for _ in range(q):
t, x = map(int,input().split())
if t == 1:
if a[x-1] == 1:
zero += 1
one -= 1
a[x-1] = 0
else:
zero -= 1
one += 1
... |
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_... |
class UnionFind:
def __init__(self, n):
self.Id = list(range(n+1))
self.sz = [1]*(n+1)
def find(self, node):
root = node
while root != self.Id[root]:
root = self.Id[root]
while node != root:
nxt = self.Id[node]
self.Id[node] = root
... |
This is the hard version of the problem. The only difference is that in this version 1 ≤ q ≤ 10^5. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each... | #include <bits/stdc++.h>
using namespace std;
#define u_map unordered_map
#define u_set unordered_set
#define u_multiset unordered_multiset
using ll = long long;
using vvi = vector<vector<int>>;
using vi = vector<int>;
using vvll = vector<vector<long long>>;
using vll = vector<long long>;
using vd = vector<double>;
... |
Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.
Each spell consists of several lines. The line, whose first non-space chara... | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 500;
const long long mod = 1e9 + 7;
const long long INF = 1LL << 57;
const int M = 1e6 + 500;
string x = "";
bool flag = 0;
bool ok(string s) {
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') continue;
if (s[i] == '#') return true;
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.