input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In... |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class SMSC {
static int n;
public static void main(String[] args){
FastScanner sc = new FastScanner();
n = sc.... |
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:
You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type:
1. For given numbers xi and vi assign value vi to element axi.... | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 200005;
const long long mod = 1000000000;
struct matrix {
long long r, c, m[2][2];
long long *operator[](long long b) { return m[b]; }
matrix operator*(matrix b) {
matrix ret;
ret.r = r, ret.c = b.c;
memset(ret.m, 0, sizeof ret.m);
... |
Berland is facing dark times again. The army of evil lord Van de Mart is going to conquer the whole kingdom. To the council of war called by the Berland's king Valery the Severe came n knights. After long discussions it became clear that the kingdom has exactly n control points (if the enemy conquers at least one of th... | #include <bits/stdc++.h>
using namespace std;
template <class T1>
void deb(T1 e1) {
cout << e1 << endl;
}
template <class T1, class T2>
void deb(T1 e1, T2 e2) {
cout << e1 << " " << e2 << endl;
}
template <class T1, class T2, class T3>
void deb(T1 e1, T2 e2, T3 e3) {
cout << e1 << " " << e2 << " " << e3 << endl;
... |
You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban β an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about ... | def answer(n):
if n==0:
print('O-|-OOOO')
while n!=0:
i=n%10
if i<5:
x=4-i
print("O-|",end="")
while i>0:
print("O", end="")
i=i-1
print("-", end="")
while x>0:
print("O",... |
You are playing the following game. There are n points on a plane. They are the vertices of a regular n-polygon. Points are labeled with integer numbers from 1 to n. Each pair of distinct points is connected by a diagonal, which is colored in one of 26 colors. Points are denoted by lowercase English letters. There are ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 200 + 10;
queue<pair<pair<int, int>, int> > q;
vector<int> nei[maxn][30];
bool mark[maxn][maxn][maxn];
pair<pair<int, int>, int> par[maxn][maxn][maxn];
vector<pair<int, int> > v;
char mat[maxn][maxn];
int n, s[3], p[3], ans[3], c[maxn], st[3];
void bfs() {
... |
You've got an array consisting of n integers: a[1], a[2], ..., a[n]. Moreover, there are m queries, each query can be described by three integers li, ri, ki. Query li, ri, ki means that we should add <image> to each element a[j], where li β€ j β€ ri.
Record <image> means the binomial coefficient, or the number of combin... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
template <class T>
inline T read() {
T x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 1) + (x << 3) + c - '0';
c = get... |
Nanami likes playing games, and is also really good at it. This day she was playing a new game which involved operating a power plant. Nanami's job is to control the generators in the plant and produce maximum output.
There are n generators in the plant. Each generator should be set to a generating level. Generating l... | #include <bits/stdc++.h>
using namespace std;
const int N = 52, M = 500005;
const long long INF = (long long)1ll << 50, INF2 = (long long)1ll << 30;
struct edge {
int v, nt;
long long w;
} e[M << 1];
void rd(int &x) {
char c = getchar();
x = 0;
while (!isdigit(c)) c = getchar();
while (isdigit(c)) x = x * 1... |
Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number <image>, in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a no... | #include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 10;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s, s1;
cin >> s >> s1;
reverse(s.begin(), s.end());
reverse(s1.begin(), s1.end());
s1.resize(N + 5, '0');
s.resize(N + 5, '0');
for (long long i = N ... |
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler!
However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measure... | import java.io.*;
import java.util.*;
import java.math.*;
public class Div2_274_D {
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(bis));
StringTokenizer st = new StringTokeniz... |
Let's define the sum of two permutations p and q of numbers 0, 1, ..., (n - 1) as permutation <image>, where Perm(x) is the x-th lexicographically permutation of numbers 0, 1, ..., (n - 1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.
For example, Perm(0) = (0, 1, ..., n... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 800005;
int a[maxn], b[maxn], c[maxn], v[maxn], n;
int read() {
int x = 0, f = 1, c = getchar();
for (; c > '9' || c < '0'; c = getchar()) f = c == '-' ? -1 : 1;
for (; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - 48;
return x * f;
}
struct... |
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the In... | #include <bits/stdc++.h>
using namespace std;
char s[200007], t[200007];
int arr[27][27], pos[27][27];
int main() {
int n, ham, i, coun, j, pos1, pos2, x, y;
pos1 = pos2 = -1;
cin >> n;
cin >> s;
cin >> t;
ham = 0;
for (i = 0; i < n; i++) {
if (s[i] != t[i]) ham++;
}
coun = 0;
for (i = 0; i < n;... |
Vanya is doing his maths homework. He has an expression of form <image>, where x1, x2, ..., xn are digits from 1 to 9, and sign <image> represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.
Inpu... | #include <bits/stdc++.h>
using namespace std;
long long P = 1e9 + 7;
double PI = 3.141592653589793;
const int sqr = 500;
const int arrn = 2e5 + 5;
const int arrn2 = 6e3 + 5;
void solve() {
string s;
cin >> s;
int n = (s.length() - 1) / 2;
vector<int> spos;
for (int i = 1; i < (int)s.length(); i += 2) {
if... |
You are given a sequence of n integers a1, a2, ..., an.
Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible.
The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.
The poor... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)2e5 + 10;
const int INF = (int)0x7f7f7f7f;
int n, a[MAXN];
double b[MAXN], s[MAXN];
double MCS() {
s[0] = 0;
for (int i = 1; i <= n; ++i) s[i] = s[i - 1] + b[i];
double m = 0;
double ans = -INF;
for (int i = 1; i <= n; ++i) {
ans = max(an... |
You are given two circles. Find the area of their intersection.
Input
The first line contains three integers x1, y1, r1 ( - 109 β€ x1, y1 β€ 109, 1 β€ r1 β€ 109) β the position of the center and the radius of the first circle.
The second line contains three integers x2, y2, r2 ( - 109 β€ x2, y2 β€ 109, 1 β€ r2 β€ 109) β the... | import math
from decimal import Decimal
from decimal import getcontext
from math import acos
pi = Decimal('3.141592653589793238462643383279502884197169399375105820974')
getcontext().prec=5000
eps = 2e-7
def _acos(x):
if 1 - eps > abs(x) > eps:
return Decimal(acos(x))
if x < 0:
return pi - ... |
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class C {
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static StringTokenizer tok;
public static int nextInt() throws IOException {
... |
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.
You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[... | import java.io.*;
import java.util.*;
public class C {
FastScanner in;
PrintWriter out;
class Host {
String hostName;
TreeSet<String> paths;
String concatenated;
public Host(String hostName) {
this.hostName = hostName;
paths = new TreeSet<>();
... |
Yasin has an array a containing n integers. Yasin is a 5 year old, so he loves ultimate weird things.
Yasin denotes weirdness of an array as maximum gcd(ai, aj) value among all 1 β€ i < j β€ n. For n β€ 1 weirdness is equal to 0, gcd(x, y) is the greatest common divisor of integers x and y.
He also defines the ultimate ... | #include <bits/stdc++.h>
using namespace std;
struct sgt {
int l, r, mn, mm, tag;
long long sum;
} c[200005 << 2];
int n;
long long ans;
int a[200005];
long long h[200005];
vector<int> x[200005];
void pd(int o) {
if (c[o].tag) {
c[o << 1].mm = c[o << 1].mn = c[o].tag;
c[o << 1 | 1].mm = c[o << 1 | 1].mn =... |
Barney has finally found the one, a beautiful young lady named Lyanna. The problem is, Lyanna and Barney are trapped in Lord Loss' castle. This castle has shape of a convex polygon of n points. Like most of castles in Demonata worlds, this castle has no ceiling.
<image>
Barney and Lyanna have an escape plan, but it r... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(double(-1));
const double INF = 1e10;
const double EPS = 1e-8;
inline double sqr(double x) { return x * x; }
struct PT {
double x, y;
PT() {}
PT(double x, double y) : x(x), y(y) {}
void in() { scanf("%lf%lf", &x, &y); }
};
bool operator<(const... |
You have recently fallen through a hole and, after several hours of unconsciousness, have realized you are in an underground city. On one of your regular, daily walks through the unknown, you have encountered two unusually looking skeletons called Sanz and Pβpairus, who decided to accompany you and give you some puzzle... | #include <bits/stdc++.h>
using namespace std;
int n, m;
char S[555], ch[555][555];
int X[555], V[555];
int Head[400010], Next[400010], Go[400010], Fl[400010], Cost[400010], H[400010],
Cnt = 1;
void addedge(int x, int y, int z, int w) {
Go[++Cnt] = y;
Next[Cnt] = Head[x];
Head[x] = Cnt;
Fl[Cnt] = z;
Cost[C... |
Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1 Γ 1 Γ 1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.
Sometimes Alyona chooses some segment towers, and put on the top of each tower several cub... | #include <bits/stdc++.h>
using namespace std;
const int N = 300005;
struct ban {
long long laz;
int e;
int maxs, maxl, maxr;
int nl, nr;
long long l, r;
void nor(long long x) {
laz = 0;
e = 1;
maxs = maxl = maxr = 1;
nl = nr = 1;
l = r = x;
}
void mer(const ban& ll, const ban& rr) {
... |
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!
The computers bought for the room were different. Some of them had only USB ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class ER17B
{
public static void main(String[] args) throws IOException
{
Scanner sc = new Scan... |
Anton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale:
"Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that ba... | #include <bits/stdc++.h>
using namespace std;
void display(vector<int> v1) {
for (long long int i = 0; i < v1.size(); i++) {
cout << v1[i] << " ";
}
cout << endl;
}
long long int dx[8] = {0, 1, 0, -1, 1, 1, -1, -1};
long long int dy[8] = {1, 0, -1, 0, 1, -1, 1, -1};
long long int m, r;
bool cool(long long int... |
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.
Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the s... | import sys
import math
def gcd(a, b, x, y):
if a == 0:
x[0], y[0] = 0, 1
return b
x1, y1 = [0], [0]
d = gcd(b % a, a, x1, y1)
x[0] = y1[0] - (b / a) * x1[0]
y[0] = x1[0]
return d
def check(a, b, p, q, k):
return a + p * k >= 0 and b + q * k >= 0
def ceil(a, b):
asse... |
There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.
You are to determine the mi... | #include <bits/stdc++.h>
using namespace std;
long long n, k, p;
int a[3000];
int b[3000];
int ch(long long mid) {
long long lastky = 0;
for (int i = 0; i < n; i++) {
int ok = 0;
while (lastky < k) {
long long minx = abs(a[i] - b[lastky]) + abs(b[lastky] - p);
minx = abs(a[i] - b[lastky]) + abs(... |
John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N.
John first has to select from which city he will start his journe... | #include <bits/stdc++.h>
constexpr int P = 1000000007;
using i64 = long long;
int norm(int x) {
if (x < 0) {
x += P;
}
if (x >= P) {
x -= P;
}
return x;
}
template <class T>
T power(T a, int b) {
T res = 1;
for (; b; b /= 2, a *= a) {
if (b % 2) {
res *= a;
}
}
return res;
}
stru... |
Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :)
Rick and Morty like to go to the ridge High Cry for crying loudly β there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this... | #include <bits/stdc++.h>
const int N = 200010;
const int M = 30;
int n;
int a[N], left[N], right[N], leftbit[N][M], rightbit[N][M];
std::stack<int> stack;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
a[0] = a[n + 1] = INT_MAX;
for (int i = 0; i <= n + 1; ++i) {
wh... |
You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis.
Input
The first line contains a single positive integer n (2 β€ n β€ 105).
The following n lines contain coordinates of the points. The i-t... | n = input()
l=[]
ac = 0
bc = 0
for i in range(n):
x,y = map(int ,raw_input().strip().split(' '))
l.append([x,y])
if x>0:
ac+=1
elif x<0:
bc+=1
if ac<=1 or bc<=1:
print "Yes"
else:
print "No"
|
Apart from plush toys, Imp is a huge fan of little yellow birds!
<image>
To summon birds, Imp needs strong magic. There are n trees in a row on an alley in a park, there is a nest on each of the trees. In the i-th nest there are ci birds; to summon one bird from this nest Imp needs to stay under this tree and it cost... | import java.util.Arrays;
import java.util.Scanner;
public class TaskE {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
long W = s.nextInt();
long B = s.nextInt();
long X = s.nextInt();
int[] c = new int[n];
int sumC = 0;
for (int i = 0; i < n; i++... |
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand.
The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactl... | l, r, a = map(int, input().split())
while a != 0:
if l < r:
l += 1
else:
r += 1
a -= 1
print(min(l, r)*2) |
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 β€ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are ... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.*;
public class AlmostArithematicProgression {
static class FastScanner {
BufferedReader br;
StringTokenizer st;
... |
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, β¦, a_j (1β€ iβ€ jβ€ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire strin... | n,x,y=map(int,input().split())
s=input()
c=0
for i in range(1,n):
if s[i]=='1' and s[i-1]=='0':
c+=1
if s[-1]=='0':
c+=1
if c==0:
print(0)
elif x>=y:
print(c*y)
else:
print((c-1)*x+y)
|
John loves prime numbers. One day he was playing a game "primcia" with his wife alicia. The game is as follows, John write a number N on a table.
The number is of the form:
N = (P1^A1) * (P2^A2) * .............. * (Px^Ax).
Where Pi are prime numbers and Ai are its corresponding powers.
Now, he asks Alicia to find ... | M = 10**9 + 7
for t in xrange(input()):
X = input()
P = map(int,raw_input().split())
A = map(int,raw_input().split())
res = 1
for i in xrange(len(A)):
res *= ((pow(P[i],A[i]+1,M)-P[i]+M)%M)*(pow(P[i]-1,M-2,M))
res %= M
print res |
On a rod of length a+b+c, lengths a, b, c are measured at random. Your task is to calculate the probability that no point of the measured lines will coincide.
INPUT:
First line contains the number of test cases T, followed by T lines, each line contains three space separated integers a, b, c.
OUTPUT:
For each test ... | ts=input()
for i in range(ts):
a,b,c=map(int,raw_input().split(" "))
print str(c*c)+" / "+str((a+c)*(b+c)) |
Statement: Sourav and his friends are in kolkata city and they are
planning for a city tour. So, they booked a TUBER cab
(Stop Giggling). Please help them to find the estimated fare
according to the fare evaluator system of TUBER cabs.
How to evaluate fare?
For first 2 Kilometers, Fare is 50 units (i.e., Base Charge ... | t=input()
for i in range(t):
flag=1
f=0
i,j=map(int,raw_input().split())
if i>60:
print "NA"
flag=0
elif i<=2:
f=50+j*2
else:
k=i-2
f+=(k*12)+(2*j)+50
if flag==1:
print f |
Humpty Dumpty lives on a two-dimensional plane. He likes to jump. Currently, he is located in the point (0, 0). He would like to reach the point (x, y). You are given the point x & y.
Humpty Dumpty wants to reach the desired destination in a specific way: using a series of jumps with pre-determined lengths. You are gi... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
import sys
import math
T = int(sys.stdin.readline())
for i in xrange(T):
N = int(sys.stdin.readline())
line = sys.stdin.readline().split()
x = int(line[0])
y = int(line[1])
dist =... |
Mahabir loves matrix and likes to rotate things a lot.
Today he is rotating an array in clock-wise direction. He gives you an array of size N X N and an positive integer Q.
Each Q number of integers contains an angle A (angle is always multiple of 90 or can be zero).
You have to rotate the array ( clock-wise only )... | r=raw_input
def ints():
return map(int,r().split())
n,q=ints()
M=[]
for i in range(n):
M.append(ints())
angle=0
m=n-1
for t in range(q):
angle=(input())%360
#print angle
if angle==0:
for i in range(n):
print " ".join(map(str,M[i]))
print
elif angle==90:
for i in range(n):
for j in range(n):
print... |
Aravind has a hexadecimal number H. he is willing to find number of ones and zeros in that number. He needs your help to solve his problem.
input
first line consists of t testcases
next t lines contains a string consists of hexadecimal numbers(Alphabets should be capital)
output
print ones followed by zeros
SAMPLE IN... | n = int(raw_input())
i = 0
while i < n:
'''
my_hexdata = raw_input()
scale = 16
num_of_bits = 8
print bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)
#print bin(int(my_hexdata, scale))[2:]
'''
s = ""
tc = raw_input().strip()
for x in tc:
s += str(bin(int(x,16))[2:].zfill(4))
#first test case is wro... |
Rohan bought new book Puzzleria in which he has to solve the puzzle.
So,now he need your help to solve one of the puzzle were he is given X consonant
and Y vowels to make a word from it whose length is equals to X + Y.
So now your are given the number of consonant and vowels and has to tell how many words can be formed... | import math
for _ in range(input()):
a,b = map(int,raw_input().split())
c= math.factorial(7)/(math.factorial(7-a)*math.factorial(a))
d= math.factorial(5)/(math.factorial(5-b)*math.factorial(b))
e = c*d*math.factorial(a+b)
print e |
Shil got an array of N integers as a present on his birthday. But he didn't liked it. Shil wants to make this array beautiful. Shil considers an array A1,A2,A3 . . . AN beautiful if A1 > AN. Inorder to make it beautiful Shil can swap any two numbers in the array. Also Shil can perform this operation any number of tim... | N=input()
s=raw_input().split(' ')
a=set()
for i in range(N):
a.add(int(s[i]))
l=len(a)
print (l*(l-1))/2 |
The Hound and his brother the Mountain are engaged in a fight against each other in King's Landing. At the end of the fight, one dies and the other wins. They both are given a decimal number each in the 8 bit binary representation A and B. These numbers will decide their fate in the following manner:
If A^B β€ B^A, then... | t = int(raw_input())
while t>0:
arr = [str(i) for i in raw_input().split()]
a = int(arr[0],2)
b = int(arr[1],2)
if pow(a,1.0/a) <= pow(b,1.0/b):
print 'The Hound'
else:
print 'The Mountain'
t-=1 |
Xsquare loves to play with strings a lot. Today, he has two strings S1 and S2 both consisting of lower case alphabets. Xsquare listed all subsequences of string S1 on a paper and all subsequences of string S2 on a separate paper. Xsquare wants to know whether there exists a string which is listed on both the papers.
X... | #!/usr/local/bin/python
import sys
from itertools import combinations
total_test_cases= int(sys.stdin.readline())
for _ in range(total_test_cases):
found = False
string_one = sys.stdin.readline().strip()
string_two = sys.stdin.readline().strip()
for i in string_two:
if i in string_one:
... |
Given is a positive integer N. Consider repeatedly applying the operation below on N:
* First, choose a positive integer z satisfying all of the conditions below:
* z can be represented as z=p^e, where p is a prime number and e is a positive integer;
* z divides N;
* z is different from all integers chosen in previous... | import java.util.*;
import java.util.function.*;
import java.lang.*;
import java.io.*;
class MathLib{
static long gcd(long a, long b){
if(a<0) a = -a;
if(b<0) b = -b;
if(a>b){
long t = a;
a = b;
b = t;
}
while(a>0){
long r = b%... |
Takahashi is participating in a programming contest, AXC001. He has just submitted his code to Problem A.
The problem has N test cases, all of which must be passed to get an AC verdict.
Takahashi's submission has passed M cases out of the N test cases.
Determine whether Takahashi's submission gets an AC.
Constraints
... | import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
if(m==n) System.out.println("Yes");
else System.out.println("No");
}
} |
N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.
The tournament is round-robin format, and there will be N(N-1)/2 matches in total. Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find t... | n=int(input());l=[list(map(int,input().split()))for i in[0]*n];a=[0]*n;d=1;k=n*(n-1)
while sum(a)<k and d<9999:
L=[0]*n;y=0;d+=1
for i in range(n):
if a[i]<n-1:
x=l[i][a[i]]-1
if l[x][a[x]]-1==i and L[x]+L[i]<1:
a[i]+=1;a[x]+=1;L[i]=L[x]=y=1
d*=y;print([k//2,d-1][d<9999]) |
There are N gems. The value of the i-th gem is V_i.
You will choose some of these gems, possibly all or none, and get them.
However, you need to pay a cost of C_i to get the i-th gem.
Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.
Find the maximum possible value of X-Y.
Co... | n = int(input())
Vi = map(int, input().split())
Ci = map(int, input().split())
print(sum([max(0, v-c) for (v, c) in zip(Vi, Ci)])) |
Takahashi's office has N rooms. Each room has an ID from 1 to N. There are also N-1 corridors, and the i-th corridor connects Room a_i and Room b_i. It is known that we can travel between any two rooms using only these corridors.
Takahashi has got lost in one of the rooms. Let this room be r. He decides to get back to... | #include<stdio.h>
#include<vector>
#define MaxN 200000+100
using namespace std;
int sum[MaxN];
vector<int>arr[MaxN];
int flag[MaxN];
int dfs2(int now,int limit_d,int limit_u)
{
if(now>limit_u || now<limit_d)
{
return 0;
}
// printf(" ----%d",now);
flag[now]=2;
int sum=1;
for(int i=0;i... |
Three people, A, B and C, are trying to communicate using transceivers. They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively. Two people can directly communicate when the distance between them is at most d meters. Determine if A and C can communicate, either ... | #include <bits/stdc++.h>
using namespace std;
int a, b, c, d;
int main() {
cin >> a >> b >> c >> d;
cout << (abs(c-a)<=d || (abs(a-b)<=d && abs(b-c)<=d) ? "Yes" : "No") << endl;
} |
You are given two strings s and t consisting of lowercase English letters and an integer L.
We will consider generating a string of length L by concatenating one or more copies of s and t. Here, it is allowed to use the same string more than once.
For example, when s = `at`, t = `code` and L = 6, the strings `atatat`... | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<functional>
#include<vector>
#include<queue>
using namespace std;
#define f(i,n) for(int i=0;i<(int)n;i++)
#define MOD 1000000009
int main(void){
char a[200001];
char b[200001];
f(i, 200001){
a[i] = 0;
b[i] = 0;
}... |
We will call a string that can be obtained by concatenating two equal strings an even string. For example, `xyzxyz` and `aaaaaa` are even, while `ababab` and `xyzxy` are not.
You are given an even string S consisting of lowercase English letters. Find the length of the longest even string that can be obtained by delet... | #include <bits/stdc++.h>
using namespace std;
char s[210];
int main()
{
scanf("%s", s);
int x = strlen(s);
for (int i = (x - 1) / 2 - 1; i >= 0; i--) {
if (!strncmp(s, s + i + 1, i + 1)) {
printf("%d\n", 2 * (i + 1));
break;
}
}
} |
You have an integer variable x. Initially, x=0.
Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=`I`, and decremented the value of x by 1 if S_i=`D`.
Find the maximum value taken by x duri... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String S = sc.next();
int max = 0;
int x = 0;
for(int i = 0 ; i < N ; i++) {
if(S.charAt(i) == 'I') {
x++;
max = Math.max(max, x);
} else if(S.ch... |
Mr. Takahashi has a string s consisting of lowercase English letters. He repeats the following operation on s exactly K times.
* Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of `z` is `a`.
For example, if you perform an operation for the second letter on `aa... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] input = sc.next().toCharArray();
int k = sc.nextInt();
int index = 0;
while(k > 0 && index < input.length){
int diff = input[index] ... |
<image>
You know the merry-go-round in the amusement park. Vehicles such as horses and carriages are fixed on a large disk, and it is a standard playset that the vehicle swings up and down at the same time as the disk rotates. A merry-go-round in an amusement park has two four-seater carriages, two two-seater cars, f... | #include <bits/stdc++.h>
using namespace std;
int main() {
int p[8];
int c[8] = {4, 1, 2, 1, 2, 1, 4, 1};
int temp[10];
int ans[10];
while(cin >> p[0] >> p[1] >> p[2] >> p[3] >> p[4] >> p[5] >> p[6] >> p[7]) {
memset(ans, 0, sizeof(ans));
ans[8] = -1;
for(int i = 0; i ... |
In Square Town, where many people who love squares live, a festival is held to color the town with illuminations that combine square lightning boards. This electric board emits light when electricity is applied, and the plate in contact with the light emitting plate also emits light. Therefore, no matter how many elect... | #include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
using namespace std;
const double EPS = 1e-10;
const double INF = 1e12;
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<double> P;
typedef vector<P>... |
A boy PCK had N straight iron bars, which were serially indexed. Unfortunately, the first M bars (0 β€ M β€ N) among them were bent during transportation. They all suffered a perpendicular bend at one point.
He is planning to make a cube using a set of bars selected using the following rules: X bars from bent ones, Y ba... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int a[6001][6001],b[6001];
int n,m,x,y,mn;
unordered_set<ll> st;
bool check(int A,int B,int C){
for(int i=0;i<=min(mn,a[A][B]);i++)
for(int j=0;i+j<=min(mn,a[B][C]+i);j++){
int k=x-i-j;
if(i+k>4||j+k>4||a[A][C]<k)continue;
if(A=... |
In the advanced algorithm class, n2 students sit in n rows and n columns. One day, a professor who teaches this subject comes into the class, asks the shortest student in each row to lift up his left hand, and the tallest student in each column to lift up his right hand. What is the height of the student whose both han... | #include<iostream>
#include<algorithm>
using namespace std;
int n;
int t[100][100];
int u[100],v[100];
void solve(){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(u[i]!=v[j])continue;
cout<<t[i][j]<<endl;
return;
}
}
cout<<0<<endl;
}
int main(){
while(cin>>n&&n){
for(int i=0;i<n... |
<image>
The International Clown and Pierrot Competition (ICPC), is one of the most distinguished and also the most popular events on earth in the show business.
One of the unique features of this contest is the great number of judges that sometimes counts up to one hundred. The number of judges may differ from one co... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
int n = sc.nextInt();
if(n==0)break;
int[] p = new int[n];
int sum = 0;
for(int i=0;i<n;i++){
p[i] = sc.nextInt();
sum += p[i];
}
Arrays.sort(p);
... |
A long time ago in a galaxy, far, far away, there were N spheres with various radii. Spheres were mirrors, that is, they had reflective surfaces . . . .
You are standing at the origin of the galaxy (0, 0, 0), and emit a laser ray to the direction (u,v, w). The ray travels in a straight line.
When the laser ray from I... | #include <bits/stdc++.h>
#define double long double
using namespace std;
const double EPS = 1e-8;
const double INF = 1e9;
struct p3{
double x,y,z,r;
p3(){x=y=z=r=0;}
p3(double x,double y,double z):x(x),y(y),z(z){};
p3(double x,double y,double z,double r):x(x),y(y),z(z),r(r){};
p3 operator + (const p3 a)const... |
Problem
I started a part-time job at the rental DVD shop "NEO". First of all, I decided to study the fee system of this store.
There are three types of rental DVDs, old, semi-new, and new, and the rental fee for one DVD is a yen, b yen, and c yen, respectively. The set rental shown below can be applied multiple times... | #include<iostream>
#include<algorithm>
#include<string>
using namespace std;
typedef basic_string<int> IS;
int main(){
for(int a,b,c,d,e,na,nb,nc;cin>>a>>b>>c>>d>>e>>na>>nb>>nc,a;){
IS is=IS(nc,c)+IS(nb,b)+IS(na,a);
int m,cs=a*na+b*nb+c*nc;
m=cs;
for(int i=0;i<is.size();i++){
cs-=is[i];
... |
Alice wants to send an email to Miku on her mobile phone.
The only buttons that can be used for input on mobile phones are number buttons. Therefore, in order to input characters, the number buttons are pressed several times to input characters. The following characters are assigned to the number buttons of the mobile... | ref = {"1":".,!? ",
"2":"abc",
"3":"def",
"4":"ghi",
"5":"jkl",
"6":"mno",
"7":"pqrs",
"8":"tuv",
"9":"wxyz"}
n = int(raw_input())
for _ in range(n):
ans = ""
inputs = map(str, raw_input().split('0'))
for i in inputs:
if len(i) > 0:
... |
You are a programmer on the development team for new recording media. This recording medium can be randomly accessed for reading and erasing data. On the other hand, when writing data, access is always performed in order from the beginning, and only the first free space found can be written.
You have begun to build a ... | #include<map>
#include<cstdio>
using namespace std;
int main(){for(int T;~scanf("%d",&T)&&T;puts("")){
map<pair<int,int>,int>m;
char C[2];
int n,k;
for(;T--;){
scanf("%s%d",C,&n);
if(*C=='D'){
for(auto it=m.begin();it!=m.end();)if(it->second==n)m.erase(it++);else ++it;
}else if(*C=='R'){
auto it=m.lower... |
Champernowne constant is an irrational number. Its decimal representation starts with "0.", followed by concatenation of all positive integers in the increasing order.
You will be given a sequence S which consists of decimal digits. Your task is to write a program which computes the position of the first occurrence of... | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <queue>
using namespace std;
#define MP(x,y) make_pair(x,y)
#define FI first
#define SE second
#define INF 1LL<<60
const int MAXN = 110;
int len;
char str[MAXN],st[MAXN];
long long ans,pos;
long long trans_stoi(int l,int r)
{
long ... |
The currency system in the Kingdom of Yoax-Musty is strange and fairly inefficient. Like other countries, the kingdom has its own currencty unit denoted by K $ (kingdom dollar). However, the Ministry of Finance issues bills for every value between 1 K $ and (231 - 1) K $ worth.
On the other hand, this system often ena... | #include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;++i)
typedef long long int ll;
int n;ll a[101000],s[101000];
int main(){
int co=0;
scanf("%d",&n);
rep(i,1,n){
cin>>a[i];
}
sort(a+1,a+n+1);
rep(i,1,n){
s[i]=s[i-1]+a[i];
if(a[i]>s[i-1]+1){cout<<s[i-1]+1<<endl;return 0;}
}
co... |
Sunuke cannot move in the initial state. The price of the i-th ticket is pi, which can be bought to move from (x, y) to (x + tai, y + tbi) for any (x, y) and any non-negative real number t. become able to. Find the minimum total amount of tickets that Sunuke must buy in order to be able to move between any two points o... | #include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
... |
Example
Input
8
-10 0
-10 5
-5 5
-5 0
10 0
10 -5
5 -5
5 0
Output
50 | /*
SUPTO
UNIVERSITY OF DHAKA
*/
#include <bits/stdc++.h>
using namespace std;
#define D(x) cerr<<#x " = "<<(x)<<endl
#define pb push_back
#define ff first
#define ss second
#define mem(a) memset(a,0,sizeof(a))
#define _set(a) memset(a,-1,sizeof(a))
typedef long long int ll;
typedef unsigned long long ul... |
I: Ravage
Santa Claus was caught in the illuminations of the city and broke it.
There are N light bulbs in the illumination, and the $ i $ th light bulb only comes on when the voltage is above $ A_i $ and below $ B_i $.
The voltage should be the same everywhere in the illumination.
Find out how many light bulbs can... | #include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#define lol(i,n) for(int i=0;i<n;i++)
#define mod 1000000007
typedef long long ll;
using namespace std;
#define N 100010
ll a[N],b[N],n;
int main(){
cin>>n;
lol(i,n)cin>>a[i]>>b[i];
sort(a,a+n); sort(b,b+n);
ll j=0,cnt=0,ans=0;
... |
Problem
How, you have been trapped in a cave!
Perhaps the wall had collapsed, and many rocks were in the way before we reached the only exit.
But I realized that there was a bomb vending machine right next to you.
In addition, it seems that some "blasters" have also fallen in the cave.
If you use these two tools, it ... | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
struct FastIO{
FastIO(){
cin.tie(0);
ios::sync_with_stdio(0);
}
}fastio_beet;
usin... |
Write a program which prints the central coordinate ($cx$,$cy$) and the radius $r$ of a incircle of a triangle which is constructed by three points ($x_1$, $y_1$), ($x_2$, $y_2$) and ($x_3$, $y_3$) on the plane surface.
Constraints
* $-10000 \leq x_i, y_i \leq 10000$
* The three points are not on the same straight li... | #include<bits/stdc++.h>
#define REP(i,first,last) for(int i=first;i<=last;++i)
#define DOW(i,first,last) for(int i=first;i>=last;--i)
using namespace std;
long long Random(long long a)
{
return (1ll*rand()*rand()+rand())%a;
}
long long Random(long long f,long long e)
{
return f+Random(e-f+1);
}
double Sqr(double a)
{... |
For a given sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, find the lower bound for a specific value $k$ given as a query.
* lower bound: the place pointing to the first element greater than or equal to a specific value, or $n$ if there is no such element.
Constraints
* $1 \leq n \le... | #include <bits/stdc++.h>
using namespace std;
int lower_bound(vector<int>& v, int istart, int iend, int value) {
int n = v.size();
int ng = -1;
int ok = v.size();
while (abs(ok - ng) > 1) {
int mid = (ok + ng) / 2;
if (v[mid] >= value) {
ok = mid;
} else {
ng = mid;
}
}
retur... |
Dhapu is a school girl who hacks and programs in free time. But right now she has to do her boring school homework. It's a few addition and subtraction problems. She has gotten bored with doing these repetitive questions. So, she wants to automate the entire process. Will you help her write a program to complete her ma... | q = int(raw_input())
while q>0:
q = q - 1
a, b = 0, 0
s = raw_input()
SA, SB = "", ""
OP = ""
for i in s:
if i=='+' or i=='-':
op = i
SB = SA
SA = ""
continue
else:
SA = SA + i
ans = 0
if op=='-':
ans = int (SB) - int (SA)
else:
ans = int (SB) + int (SA)
print ans |
Problem description
Clarissa Adele Fray (a.k.a Clary) has found out that she is a shadowhunter, a human with angelic qualities. She can create her own runes (magical spells). Last week, she created many powerful runes.
Right now, she is facing several underworld demons, help her find the number of ways, such that th... | MOD = 10**9+7
def fast_exp(base, exp):
res = 1
while (exp>=1):
if (exp%2==1):
res = (res*base)%MOD
base = (base*base)%MOD
exp/=2
return res
for testCase in range(int(raw_input())):
n = int(raw_input())
a = map(int,raw_input().split())
m = max(a)
c = a.count(m)
print fast_exp(2,c)-1 |
As we all know, F.C. Barcelona is the best soccer team of our era! Their entangling and mesmerizing game style usually translates into very high ball possession, consecutive counter-attack plays and goals. Lots of goals, thanks to the natural talent of their attacker and best player in history, Lionel Andres Messi.
How... | t=raw_input()
t=int(t)
while t!=0:
n, k=raw_input().split(' ')
n=int(n)
k=int(k)
count=0
i=1
while i<n:
count=pow(k, i)-count
i+=1
print (count%1000000007);
t-=1 |
The Little Elephant and his friends from the Zoo of Lviv were returning from the party. But suddenly they were stopped by the policeman Big Hippo, who wanted to make an alcohol test for elephants.
There were N elephants ordered from the left to the right in a row and numbered from 0 to N-1. Let R[i] to be the result of... | #!/usr/bin/python
from sys import stdin
T = int(stdin.readline())
global N,K,M,R
global minimal
def check(i,current):
global N,K,M,R
global minimal
#print current,minimal,i,R
if current >= minimal:
return
if i >= N:
if current < minimal:
minimal = current
return... |
After confronting Pinocchio, Lampwick decided to further analyse his diary about Pinocchio. (You can find the details about the diary in Part 1 of this problem)
Now he needs to find out the maximum number of days that passed by in which Pinocchio surely didn't lie. Can you help him out?
Β
Input
First line of input co... | # cook your code here
t = int(raw_input())
for i in xrange(t):
n = int(raw_input())
nums = map(int, raw_input().split())
d = {}
for num in nums:
d[num] = d.get(num, 0) + 1
m = max(d.values())
print m-1 |
Chef likes strings a lot but moreover he likes good strings. Chef calls a string str a good string if str starts and ends at different characters. For eg : strings such as abab , baccba , abc are all good strings whereas strings like aba, baab , baacaab are not good at all .
Today, Chef has a special string P consistin... | ch=str(raw_input())
length=len(ch)
arr=[]
cur=0
temp=[]
for k in range(length):
if(ch[k]=='c'):
cur+=1
temp.append(cur)
else:
temp.append(cur)
arr.append(temp)
cur=0
temp=[]
for k in range(length):
if(ch[k]=='e'):
cur+=1
temp.append(cur)
el... |
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.
The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance betwe... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ll n;
ll mod = 998244353;
cin >> n;
vector<ll> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
ll asum = 0ll;
ll total = 0ll;
vector<ll> two_powers(n + 2);
two_powers[0] = 1ll;
for (int i = 1; i <= n + 1; ++i) ... |
At many competitions that have a word Β«cupΒ» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.
The nameplate is to be rectangular an... | def print2d(a):
for i in range(len(a)):
print(''.join(list(map(str, a[i]))))
st = input()
for i in range(1, 5 + 1):
vst = len(st) // i
ost = len(st) % i
if vst + min(ost, 1) > 20:
continue
a = [0] * i
ind = 0
f = 0
for j in range(len(a)):
a[j] = []
for j i... |
You are given two arrays a_0, a_1, β¦, a_{n - 1} and b_0, b_1, β¦, b_{m-1}, and an integer c.
Compute the following sum:
$$$β_{i=0}^{n-1} β_{j=0}^{m-1} a_i b_j c^{i^2\,j^3}$$$
Since it's value can be really large, print it modulo 490019.
Input
First line contains three integers n, m and c (1 β€ n, m β€ 100 000, 1 β€ c ... | #include <bits/stdc++.h>
const int moder = 490019;
const int mod1 = 491;
const int mod2 = 499;
const int root = 7;
int powermod(int a, int exp, int moder) {
int ret = 1;
for (; exp > 0; exp >>= 1) {
if (exp & 1) {
ret = 1ll * ret * a % moder;
}
a = 1ll * a * a % moder;
}
return ret;
}
const do... |
A frog is currently at the point 0 on a coordinate axis Ox. It jumps by the following algorithm: the first jump is a units to the right, the second jump is b units to the left, the third jump is a units to the right, the fourth jump is b units to the left, and so on.
Formally:
* if the frog has jumped an even numb... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n, a, b, k;
cin >> n;
while (n--) {
cin >> a >> b >> k;
cout << (a * (k - (k / 2)) - b * (k / 2)) << endl;
}
}
|
A Thue-Morse-Radecki-Mateusz sequence (Thorse-Radewoosh sequence in short) is an infinite sequence constructed from a finite sequence gen of length d and an integer m, obtained in the following sequence of steps:
* In the beginning, we define the one-element sequence M_0=(0).
* In the k-th step, k β₯ 1, we define t... | #include <bits/stdc++.h>
using namespace std;
int d, m;
int gen[20];
vector<long long int> B;
long long int dp[100][60];
long long int shift(long long int b, int x) {
return (b >> x) | ((b & ((1LL << x) - 1)) << (m - x));
}
map<long long int, int> M;
int num = 0;
long long int ans[100][60];
int xx[100][60];
long long... |
Ilya lives in a beautiful city of Chordalsk.
There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring.
The ho... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t, n, x;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
if (v[0] != v[n - 1])
cout << n - 1;
else {
int temp1, temp2;
for (int i = 1; i < n - 1; i++)
if (v[i] != v[0]) {
temp1 = max(i, n ... |
In this problem you have to solve a simple classification task: given an image, determine whether it depicts a Fourier doodle.
You are given a set of 50 images with ids 1 through 50. You are also given a text file labels.txt containing the labels for images with ids 1 through 20, which comprise the learning data set.... | #include <bits/stdc++.h>
using namespace std;
int main() {
for (int i = 21; i <= 50; i++) {
cout << ((min(i, 25) + i) % (2 + i % 3) > 0) ? 1 : 0;
cout << endl;
}
return 0;
}
|
Given a positive integer m, we say that a sequence x_1, x_2, ..., x_n of positive integers is m-cute if for every index i such that 2 β€ i β€ n it holds that x_i = x_{i - 1} + x_{i - 2} + ... + x_1 + r_i for some positive integer r_i satisfying 1 β€ r_i β€ m.
You will be given q queries consisting of three positive intege... | for _ in range(int(input())):
a,b,m=map(int,input().split())
if a==b:
print(1,a)
continue
for k in range(2,51):
pw=1<<(k-2)
mn=pw*(a+1)
mx=pw*(a+m)
if mn<=b<=mx:
r=[0]*(k+1)
add=b-mn
r[1]=a
for i in range(2,k):
... |
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).
For example, as a result of typing the word "hello", the follo... | def f():
a=input()
i=0
p=a[i]
l=[]
while(i<len(a)):
temp=1
t=[p]
i+=1
while(i<len(a)):
if a[i]!=p:
p=a[i]
break
p=a[i]
t.append(p)
i+=1
if i==len(a):
temp=0
... |
The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version.
Polycarp is a very famous freelancer. His current rating is r units.
Some very rich customers asked him to complete some projects for their companies. To complete ... | n,r = map(int,(input().split()))
plus=[]
minn=[]
for i in range (0,n):
temp = list(map(int,input().split()))
if temp[1] <=0:
temp.append(temp[0]+temp[1])
minn.append(temp)
else:
plus.append(temp)
plus.sort()
minn.sort(reverse=True,key = lambda x: x[2])
flag = True
for i in plus:... |
Boy Dima gave Julian a birthday present β set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer n... | #include <bits/stdc++.h>
using ll = long long;
using namespace std;
const int N = 2e5 + 10, E = 65;
int n, cnt[E];
ll a[N];
int main() {
scanf("%d", &n);
for (auto i = 0, _end = n - 1; i <= _end; ++i) {
scanf("%lld", a + i);
cnt[__builtin_ctzll(a[i])]++;
}
int ans = max_element(cnt, cnt + E) - cnt;
pr... |
While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute 1 + 3 using the calculator, he gets 2 instead of 4. But when he tries computing 1 + 4, he gets the correct answer, 5. Puzzled by this mystery, he opened up his calculator... | #include <bits/stdc++.h>
using namespace std;
long long dp[40][2][2];
int digA[40], digB[40];
long long dfs(int pos, bool limA, bool limB) {
if (!pos) return 1;
long long &val = dp[pos][limA][limB];
if (val != -1) return val;
int mxA = limA ? digA[pos] : 1;
int mxB = limB ? digB[pos] : 1;
val = 0;
for (in... |
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, β¦, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 β€ i β€ n - 1.
Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequenc... | _count = list(map(int, input().split()))
num = '0 1 2 3'.split()
for pos in range(4):
count = _count[:]
ans = []
for i in range(sum(count)):
ans.append(num[pos])
count[pos] -= 1
if pos == 1:
if count[0] > 0:
pos = 0
else:
pos =... |
To defeat Lord Voldemort, Harry needs to destroy all horcruxes first. The last horcrux is an array a of n integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations:
1. choose an index i (1 β€ i β€ n), an... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 25;
const int maxs = 1 << 20;
template <typename T>
void chkmax(T &x, T y) {
x = max(x, y);
}
template <typename T>
void chkmin(T &x, T y) {
x = min(x, y);
}
template <typename T>
void read(T &x) {
x = 0;
int f = 1;
char c = getchar();
for (; !i... |
As a professional private tutor, Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.
The exam consists of n questions, and m students have taken the exam. Each question was worth 1 point. Question i was solved by at least l_i and at most r_... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class t, class u>
void chmax(t& first, u second) {
if (first < second) first = second;
}
template <class t, class u>
void chmin(t& first, u second) {
if (second < first) first = second;
}
template <class t>
using vc = vector<t>;
template ... |
Another feature of Shakespeare language is that the variables are named after characters of plays by Shakespeare, and all operations on them (value assignment, output etc.) look like a dialog with other characters. New values of variables are defined in a rather lengthy way, so a programmer should try to minimize their... | #include <bits/stdc++.h>
using namespace std;
const int MAXV = 600, MAXE = 70000, inf = 1000000000;
int N, Count;
int G[MAXV], Queue[MAXV], Dist[MAXV], Pre[MAXV], Last[MAXV];
int Data[MAXE], Weight[MAXE], Cost[MAXE], Next[MAXE];
bool Flag[MAXV];
int Calc(int X) {
if (!X) return 0;
return Calc(X / 2) + X % 2;
}
void... |
There are n players sitting at a round table. All of them have s cards of n colors in total. Besides, initially the first person had cards of only the first color, the second one had cards of only the second color and so on. They can swap the cards by the following rules:
* as the players swap, a player can give a ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 200001;
struct DIY {
int x, y;
};
DIY a[maxn], h[maxn], ans[maxn], t;
int n, s, m, len = 0;
void down(int x) {
int y;
while ((x * 2 <= m) && (h[x * 2].x > h[x].x) ||
(x * 2 + 1 <= m) && (h[x * 2 + 1].x > h[x].x)) {
y = x * 2;
if ((y +... |
Ashishgup and FastestFinger play a game.
They start with a number n and play in turns. In each turn, a player can make any one of the following moves:
* Divide n by any of its odd divisors greater than 1.
* Subtract 1 from n if n is greater than 1.
Divisors of a number include the number itself.
The player... | import java.util.Scanner;
public class NumberGame {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t > 0) {
int n = in.nextInt();
if (n == 2)
System.out.println("Ashishgup");
els... |
zscoder has a deck of n+m custom-made cards, which consists of n cards labelled from 1 to n and m jokers. Since zscoder is lonely, he wants to play a game with himself using those cards.
Initially, the deck is shuffled uniformly randomly and placed on the table. zscoder has a set S which is initially empty.
Every s... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper... |
You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times:
1. choose three integers i, j and x (1 β€ i, j β€ n; 0 β€ x β€ 10^9);
2. assign a_i := a_i - x β
i, a_j := a_j + x β
i.
After each operation, all elements of the array s... | # ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
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... |
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available... | #include <bits/stdc++.h>
using namespace std;
int n, x;
char s[100086];
int id[100086], tag[100086], cnt;
int sk[100086], top;
int main() {
scanf("%d", &n);
for (int i = 1; i <= 2 * n; i++) {
scanf("%s", s);
if (s[0] == '+') {
sk[++top] = ++cnt;
} else {
scanf("%d", &x);
if (!top || ta... |
A robot is standing at the origin of the infinite two-dimensional plane. Each second the robot moves exactly 1 meter in one of the four cardinal directions: north, south, west, and east. For the first step the robot can choose any of the four directions, but then at the end of every second it has to turn 90 degrees lef... | import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
public class Main7{
static public void main(String args[])throws IOException{
int tt=1;
StringBuilder sb=new StringBuilder();
for(int ttt=1;ttt<=tt;ttt++){
int n=i();
if(n%2==... |
Given a positive integer k, two arrays are called k-similar if:
* they are strictly increasing;
* they have the same length;
* all their elements are positive integers between 1 and k (inclusive);
* they differ in exactly one position.
You are given an integer k, a strictly increasing array a and q quer... | import javax.swing.event.ListDataEvent;
import javax.swing.plaf.FontUIResource;
import java.lang.reflect.Array;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef {
static class Pair {
int tokens;
int index;
Pair(int tokens, int index) {
this.tokens ... |
The student council is preparing for the relay race at the sports festival.
The council consists of n members. They will run one after the other in the race, the speed of member i is s_i. The discrepancy d_i of the i-th stage is the difference between the maximum and the minimum running speed among the first i members... | n = int(input())
s = list(map(int, input().split()))
s.sort()
dp = [0]*n
for i in range(1, n):
for j in range(n-i):
dp[j] = s[i+j] - s[j] + min(dp[j], dp[j+1])
print(dp[0]) |
2^k teams participate in a playoff tournament. The tournament consists of 2^k - 1 games. They are held as follows: first of all, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4 (exactly in this order), and so on (so, 2^{k-1} games are played in that phase). When a team loses a g... | # Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
def solve(z, dp, s):
n = len(dp)
while 1:
dp[z] = 0
if s[z] == '?':
if 2 * z + 1 < n:
dp[z] += dp[2 * z + 1]
else:
dp[z] += 1... |
And here goes another problem on arrays. You are given positive integer len and array a which consists of n integers a1, a2, ..., an. Let's introduce two characteristics for the given array.
* Let's consider an arbitrary interval of the array with length len, starting in position i. Value <image>, is the modular sum... | #include <bits/stdc++.h>
using namespace std;
long long int a[100005];
long long int n, len, k;
class data {
public:
set<pair<long long int, long long int> > mx, mn;
long long int sum1, ksum;
data() { ksum = 0, sum1 = 0; }
void ins(long long int v, long long int index) {
sum1 += v;
ksum += v;
mx.in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.