input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Ivan is a novice painter. He has n dyes of different colors. He also knows exactly m pairs of colors which harmonize with each other.
Ivan also enjoy playing chess. He has 5000 rooks. He wants to take k rooks, paint each of them in one of n colors and then place this k rooks on a chessboard of size 10^{9} × 10^{9}.
L... | from sys import stdin, stdout
int_in = lambda: int(stdin.readline())
arr_in = lambda: [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for y in range(rows)]
str_in = lambda: stdin.readline().strip()
out = lambda o: stdout.write("{}\n".format(o))
arr_out = lambda o: out(" ".join(map(str, o)))
... |
A conglomerate consists of n companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left.
But anti-monopoly ... | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A_1090 implements Runnable{
static class Pair{
int a,b;
Pair(int aa,int bb){
a =aa;b=bb;
}
/**
* @return the a
*/
public int getA() {
ret... |
Egor likes math, and not so long ago he got the highest degree of recognition in the math community — Egor became a red mathematician. In this regard, Sasha decided to congratulate Egor and give him a math test as a present. This test contains an array a of integers of length n and exactly q queries. Queries were of th... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 1e5 + 15;
const int LOG = 18;
int n, mod;
vector<int> primeDivisors;
vector<vector<int> > powers;
int fiMOD;
int a[MaxN];
int goodPart[MaxN];
vector<int> f[MaxN];
int phi(int n) {
int res = n;
for (int i = 2; i * i <= n; ++i)
if (n % i == 0) {
... |
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.
You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ... |
n = int(input())
arr = list(map(int,raw_input().strip().split()))
ans = 0
for i in range(n-1,-1,-1):
ans+=arr[i]
if i!=0:
arr[i-1] = max(0,min(arr[i]-1,arr[i-1]))
#print(arr)
print(ans)
|
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).
You are given a sequence a consisting of n integers. All these integers are distinct, each value from 1 to n appears in the sequence exactly once.
You are making a sequen... | import java.util.*;
public class subsequenceeasy
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
char ans[] = new char[n];
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
int l=0,r=n-1;
int min=0;
int temp=0;
int count=0;
wh... |
Fedor runs for president of Byteland! In the debates, he will be asked how to solve Byteland's transport problem. It's a really hard problem because of Byteland's transport system is now a tree (connected graph without cycles). Fedor's team has found out in the ministry of transport of Byteland that there is money in t... | #include <bits/stdc++.h>
template <typename T>
void read(T &);
template <typename T>
void write(const T &);
const int iinf = 2147483647;
const long long llinf = 9223372036854775807ll;
const int N = 500005;
void dfs1(int u, int fa);
void dfs2(int u, int fa);
std::vector<int> G[N];
int siz[N];
long long ans[N];
int n;
in... |
Alice and Bob want to play a game. They have n colored paper strips; the i-th strip is divided into a_i cells numbered from 1 to a_i. Each cell can have one of 3 colors.
In the beginning of the game, Alice and Bob put n chips, the i-th chip is put in the a_i-th cell of the i-th strip. Then they take turns, Alice is fi... | #include <bits/stdc++.h>
using namespace std;
const int n = 64;
long long mod = 998244353;
struct Mat {
long long v[n][n];
void zero() { fill_n((long long*)v, n * n, 0); }
};
Mat operator*(Mat a, Mat b) {
Mat r;
r.zero();
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n;... |
Recently biologists came to a fascinating conclusion about how to find a chameleon mood. Consider chameleon body to be a rectangular table n × m, each cell of which may be green or blue and may change between these two colors. We will denote as (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m) the cell in row x and column y.
Let us defin... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2048, mod = 1e9 + 7, MAXN = 1e6 + 7;
const double eps = 1e-9;
const long long inf = 1e18;
mt19937 rnd(time(0));
const unsigned long long T = ((unsigned long long)1 << 64) - 1;
const int LEN = maxn / 64;
struct Bitset {
unsigned long long a[LEN];
void bu... |
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y?
Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime... | #import math
#def findPrimeFactor(difference):
# if difference % 2 == 0:
# print("YES")
# else:
# findOddPrimeFactor(int(difference))
num = int(input())
for i in range(num):
x, y = input().split(" ")
difference = int(x) - int(y)
if difference != int(1) and difference > (0):
print("YES")
else:
... |
You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
vector<int> a(n);
for (int j = 0; j < n; ++j) {
cin >> a[j];
--a[j];
}
int pos = 0;
while (pos < n) {
int nxt = min_element(a.begin() + pos, a.en... |
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with.
Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break th... | #include <bits/stdc++.h>
using namespace std;
int a[1001];
int main() {
int n;
cin >> n;
int b[n];
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a[x]++;
}
int cnt = 0;
for (int i = 1; i <= 100; i++) {
if (a[i] > 1) {
if (a[i] % 2 != 0) {
cnt += a[i] - 1;
} else {
... |
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage... | #include <bits/stdc++.h>
using namespace std;
int main() {
char O[3][3];
bool vv = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cin >> O[i][j];
}
}
if (O[0][0] == O[2][2]) {
if (O[1][0] == O[1][2]) {
if (O[2][0] == O[0][2]) {
if (O[0][1] == O[2][1]) {
... |
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task — she asked every student... | n=int(input())
s=input().strip()
c=0
v=0
o=0
cl=0
for j in range(n):
if s[j]=='(':
o=o+1
if cl>0:
v=v+1
else:
cl=cl+1
if o==0:
v=v+1
if o>0:
cl=cl-1
o=o-1
if cl>0:
v=v+1
if o==cl:
c=c+... |
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property.
Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=... | import sys
t=int(sys.stdin.readline())
for _ in range(t):
a=input()
a=a[::]
a=list(map(int, a))
i=0
if a.count(0)==0 or a.count(1)==0:
for j in range(len(a)):
print(a[j], end='')
print()
else:
while True:
if i==len(a)-1:
break
... |
Given a permutation p of length n, find its subsequence s_1, s_2, …, s_k of length at least 2 such that:
* |s_1-s_2|+|s_2-s_3|+…+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2.
* Among all such subsequences, choose the one whose length, k, is as small as possible.
If mul... | import math,sys,bisect
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(1000000)
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
#def list2d(a, b... |
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long t;
cin >> t;
while (t--) {
long long n, ind = 1;
string a, b;
cin >> n >> a >> b;
for (long long i = 0; i < n; i++)
if (a[i] > b[i]) {
cout << -1 << e... |
Let a_1, …, a_n be an array of n positive integers. In one operation, you can choose an index i such that a_i = i, and remove a_i from the array (after the removal, the remaining parts are concatenated).
The weight of a is defined as the maximum number of elements you can remove.
You must answer q independent queries... | #include <bits/stdc++.h>
using namespace std;
inline int re() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 3) + (x << 1) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
long long g... |
You are given an array of n integers a_1,a_2,...,a_n.
You have to create an array of n integers b_1,b_2,...,b_n such that:
* The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_... | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource
# sys.setrecursionlimit(10**6)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(... |
A string b is a subsequence of a string a if b can be obtained from a by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx".
You are given a string a. Your task is to reorder the characters of a so that "trygub" is not a subsequence of the result... | t = int(input())
for i in range(t):
n = int(input())
a = input()
check = []
trygub = "trygub"
k = 0
for j in range(len(trygub)):
for m in range(k,len(a)):
if(trygub[j] == a[m]):
check.append(a[m])
k = m+1
break
else:... |
Note that the memory limit is unusual.
You are given an integer n and two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n.
Let's call a set of integers S such that S ⊆ \{1, 2, 3, ..., n\} strange, if, for every element i of S, the following condition is met: for every j ∈ [1, i - 1], if a_j divides a_i, then j is... | #include "bits/stdc++.h"
using namespace std;
using ll = long long;
using pii = pair<int,int>;
struct Dinic {
// Edge u->v with capacity cap
struct FlowEdge {
int u,v;
ll cap, flow = 0;
FlowEdge(int u, int v, ll cap) : u(u),v(v),cap(cap) {}
};
const ll INF = 1e18;
vector<FlowEdge> edges;
vect... |
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water... | #149A
k=int(input())
a=list(map(int,input().split()))
a.sort(reverse=True)
k1,count=0,0
for i in range(len(a)):
if k<=k1:
break
else:
k1+=a[i]
count+=1
if k<=k1 :
print(count)
else:
print(-1) |
<image>
William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing n cells, with each cell either being alive or dead.
Evolution of the array in William's cellular automaton occurs ite... | import java.io.*;
import java.util.*;
public class deltix_round_a {
public static void main(String args[]){
FScanner in = new FScanner();
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
while(t-->0) {
int n=in.nextInt();
int m=in.nextInt();
char ch[]=in.ne... |
There is an infinite pond that can be represented with a number line. There are n rocks in the pond, numbered from 1 to n. The i-th rock is located at an integer coordinate a_i. The coordinates of the rocks are pairwise distinct. The rocks are numbered in the increasing order of the coordinate, so a_1 < a_2 < ... < a_n... | #pragma GCC optimize(3)
#pragma GCC optimize(2)
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef long long ll;
typedef pair<ll , ll> pll;
typedef pair<int , int> pii;
typedef long double ld;
const int maxx = 1e6 + 10;
const int maxn = 2e5 + 10;
const int inf32 = 1e9;
const ll inf64... |
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. ... | n = int(input())
i, s = 2, n
m = int(n ** 0.5) + 1
while n > 1 and i < m:
if n % i: i += 1
else:
n //= i
s += n
print(s + (n > 1)) |
Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high.
At the beginning of the first experiment there is a single bacterium in the test tub... | #include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
std::cerr << name << " : " << arg1 << '\n';
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
const char* comma = strchr(names + 1, ',');
std::cerr... |
The Little Elephant loves numbers.
He has a positive integer x. The Little Elephant wants to find the number of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations.
Help the Little Elephant to find the described number.
Input
... | #include <bits/stdc++.h>
using namespace std;
string toString(int x) {
string s;
while (x) {
s.push_back(x % 10 + '0');
x /= 10;
}
return s;
}
int main() {
int n;
cin >> n;
vector<int> divisors;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
int div = i;
divisors.push_back(... |
Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins.
Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2·x + 1 ≤ n) and... | #include <bits/stdc++.h>
using namespace std;
int vet[101];
int N, res;
int main(void) {
cin >> N;
for (int i = 0; i < N; i++) cin >> vet[i + 1];
for (int i = N; i >= 1; i--)
if (vet[i] != 0) {
if (i != 1 && (i / 2) * 2 + 1 <= N) {
int p = i / 2;
int h = vet[i];
vet[p] = max(0, v... |
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald... | 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.util.function.Function;
import java.io.InputStream;
/**
* Built us... |
Yaroslav, Andrey and Roman love playing cubes. Sometimes they get together and play cubes for hours and hours!
Today they got together again and they are playing cubes. Yaroslav took unit cubes and composed them into an a × a × a cube, Andrey made a b × b × b cube and Roman made a c × c × c cube. After that the game ... | import static java.util.Arrays.deepToString;
import java.io.*;
import java.math.*;
import java.util.*;
public class C {
static void solve() {
long n = nextLong();
if (n % 3 != 0) {
writer.println(0);
return;
}
long ans = solve(n / 3);
writer.println(ans);
}
static int solve(long n) {
ans = 0;
... |
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.
Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the number... |
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long a=sc.nextLong();
long b=sc.nextLong();
long m=sc.nextLong();
if(a>=m||b>=m) {
System.out.println(0);
}else if(a<=0&&b<=0){
System.out.println(-1);
}else{
long res=0;
... |
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents t... | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution... |
We'll call a set of positive integers a beautiful if the following condition fulfills: for any prime p, if <image>, then <image>. In other words, if one number from the set is divisible by prime p, then at least half of numbers from the set is divisible by p.
Your task is to find any beautiful set, where the number of... | #include <bits/stdc++.h>
template <typename T>
inline void checkMin(T &a, T b) {
if (b < a) a = b;
}
template <typename T>
inline void checkMax(T &a, T b) {
if (a < b) a = b;
}
using namespace std;
const int MAX_K = 5005;
const int MAX_KK = MAX_K * MAX_K * 2;
vector<int> prime;
void gen_prime(vector<int> &p, int MA... |
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output... | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public cla... |
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;
int a[100000 + 1];
int comb[100000 + 100 + 1][100 + 1], ans[100000 + 2][100 + 2];
template <typename T1, typename T2>
void madd(T1& x, const T2& y) {
(x += y) >= 1000000007 && (x -= 1000000007);
}
template <typename T1, typename T2, typename T3>
void madd(T1& x, const T2&... |
The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem.
<image>
One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters a... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.uti... |
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i... | import java.util.*;
import java.io.*;
import java.math.*;
public class test {
public static void main(String args[])
{
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
long n=in.nextInt(),i;
long max,count=0;
long b[]=new... |
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a stud... | R=lambda:map(int,raw_input().split())
def cmp(x,y):
if x[0]>y[0] or (x[0]==y[0] and x[1]>y[1]): return 1
return -1
ans=0
for x in sorted([R() for i in range(input())],cmp=cmp):
if ans<=x[1]: ans=x[1]
else: ans=x[0]
print ans |
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into s to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a... | #include <bits/stdc++.h>
using namespace std;
int main() {
string s, a;
cin >> s;
for (int i = 0; i <= s.length(); i++) {
for (int b = 'a'; b <= 'z'; b++) {
a = s.substr(0, i) + ((char)b) + s.substr(i, s.size());
if (a == string(a.rbegin(), a.rend())) {
cout << a << endl;
return 0;... |
Leonid works for a small and promising start-up that works on decoding the human genome. His duties include solving complex problems of finding certain patterns in long strings consisting of letters 'A', 'T', 'G' and 'C'.
Let's consider the following scenario. There is a fragment of a human DNA chain, recorded as a st... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
const int N = 800050;
void fft(complex<double> a[], int n, bool inv) {
for (int i = 1, j = 0; i < n; i++) {
int k = n;
do j ^= k >>= 1;
while (~j & k);
if (j > i) swap(a[i], a[j]);
}
for (int j = 2; j <= n; j <<= 1) {
do... |
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it ... | import java.io.*;
import java.util.*;
public class test{
public static void main(String aa[]){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
String cmp="";
int result=0,count=0;
String arr[]=new String[t];
for(int i=0;i<t;i++){
... |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | n,a=int(input()),list(map(int,input().split()))
mx=1
c=1
for i in range(n-1):
if(a[i+1]>=a[i]):
c+=1
if(c>mx):
mx=c
else:
c=1
print(mx) |
There's a famous museum in the city where Kleofáš lives. In the museum, n exhibits (numbered 1 through n) had been displayed for a long time; the i-th of those exhibits has value vi and mass wi.
Then, the museum was bought by a large financial group and started to vary the exhibits. At about the same time, Kleofáš...... | #include <bits/stdc++.h>
using namespace std;
const int N = 40005;
const int mod = 1e9 + 7;
const int bs = 1e7 + 19;
pair<int, int> a[N];
int n, st[N], ed[N], p[N], dp[1005];
int k, tot = n, q;
vector<int> t[N << 2];
bool vis[N];
void modify(int x, int l, int r, int L, int R, int id) {
if (L <= l && r <= R) {
t[x... |
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... | #include <bits/stdc++.h>
using namespace std;
int n, m, u, v, k, vis[505];
char ans[505];
char mp[] = {'a', 'c', 'b'};
set<int> nodes[3];
vector<int> edges[505];
int main() {
cin >> n >> m;
while (m--) {
scanf("%d %d", &u, &v);
edges[u].push_back(v);
edges[v].push_back(u);
}
bool same = true;
for ... |
After a drawn-out mooclear arms race, Farmer John and the Mischievous Mess Makers have finally agreed to establish peace. They plan to divide the territory of Bovinia with a line passing through at least two of the n outposts scattered throughout the land. These outposts, remnants of the conflict, are located at the po... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 200010;
const double eps = 1e-9;
const double pi = acos(-1);
int read() {
int tot = 0, fh = 1;
char c = getchar();
while ((c < '0') || (c > '9')) {
if (c == '-') fh = -1;
c = getchar();
}
while ((c >= '0') && (c <= '9')) {
tot = tot * ... |
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;
template <typename A>
inline std::istream& IN(A& a) {
return std::cin >> a;
}
template <typename A, typename... Args>
inline std::istream& IN(A& a, Args&... rest) {
std::cin >> a;
return IN(rest...);
}
inline std::ostream& OUT() { return std::cout << std::endl; }
temp... |
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and... | import java.util.*;
import java.io.*;
public class Vacations
{
public static void main(String[] s)
{
Scanner sc=new Scanner(System.in);
int dp=0,n,a[],i;
n=sc.nextInt();
a=new int[n];
for(i=0;i<n;i++)
a[i]=sc.nextInt();
for(i=0;i<n;i++)
{
if(i==0)
{
if(a[i]==0)
dp++;
}
else if(i==... |
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units... | #include <bits/stdc++.h>
using namespace std;
static int n;
static vector<int> ve;
int main() {
while (scanf("%d", &n) != EOF) {
ve.clear();
ve.resize(n);
for (int i = 0; i < n; i++) scanf("%d", &ve[i]);
if (n == 1 && ve[n - 1] != 15 && ve[n - 1] != 0) {
printf("-1\n");
} else {
if (ve... |
Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than x and not less than 2 items in his inventory. A new patch for the game appeared to view inv... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, x;
cin >> n >> x;
if (x == 2) {
cout << 0;
return 0;
}
int a[100000];
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] == 1) {
cout << 1;
return 0;
}
}
sort(a, a + n);
int next_prime = 2;
int prime[1... |
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
long long p, n;
bool ind;
long long a[N];
set<long long> num;
long long add(long long a, long long b) { return (a + b) % p; }
long long sub(long long a, long long b) { return (a - b + p) % p; }
long long mult(long long a, long long b) { return a * b %... |
ALT is a planet in a galaxy called "Encore". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy.
ALT has n cities numbered from 1 to n and n - 1 bidirectional road... | import java.util.*;
import java.io.*;
import java.math.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Main {
static class PR
{
public int x;
public int y;
public PR(int x_, int y_) {
x = x_;
y = y_;
}
};
static MaxFlow mf;
... |
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element be... | #include <bits/stdc++.h>
using namespace std;
int inf = 1e9;
const int N = 1e5 + 10;
int a[N], n;
multiset<int> suff, pref;
long long sumsuff, sumpref;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
suff.insert(a[i]);
sumsu... |
Vasya has a set of 4n strings of equal length, consisting of lowercase English letters "a", "b", "c", "d" and "e". Moreover, the set is split into n groups of 4 equal strings each. Vasya also has one special string a of the same length, consisting of letters "a" only.
Vasya wants to obtain from string a some fixed str... | #include <bits/stdc++.h>
using namespace std;
void read_file(bool outToFile = true) {}
const int MAXN = 500 + 99;
int n, m, nq;
char str[MAXN];
int A[MAXN][MAXN], B[MAXN];
int mod_inv[] = {0, 1, 3, 2, 4};
int num;
void swapp(int i, int j) {
for (int k = 0; k < m; k++) swap(A[i][k], A[j][k]);
}
inline void fix(int &x)... |
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.
First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares s... | #include <bits/stdc++.h>
using namespace std;
const long long N = 200005, logN = 21;
struct data {
long long ls, rs, val;
} tree[N * logN];
long long cur, rt[N], n, q, sortb[N], b[N];
inline void init() { cur = 0; }
inline void push_up(long long p) {
tree[p].val = tree[tree[p].ls].val + tree[tree[p].rs].val;
}
inli... |
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an... | #include <bits/stdc++.h>
using namespace std;
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
int a = 0, b = (1 << 10) - 1;
while (n--) {
string s;
int x;
cin >> s >> x;
if (s == "|")
a |= x, b |= x;
else if (s == "^")
a ^= x, b ^= x;
else
... |
You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n.
You have to answer q queries. Each query is described by a segment of vertices [l; r... | #include <bits/stdc++.h>
using namespace std;
int n, m, q, p[300005], dfn[300005], low[300005], Time = 0, sta[300005],
top = 0, tag[300005];
long long sum[300005];
bool insta[300005];
struct Edge {
int to, next;
};
struct Graph {
Edge edge[600005];
int first[30000... |
There are N cities in Bob's country connected by roads. Some pairs of cities are connected by public transport. There are two competing transport companies — Boblines operating buses and Bobrail running trains. When traveling from A to B, a passenger always first selects the mode of transport (either bus or train), and... | #include <bits/stdc++.h>
const int N = 1e5 + 5, M = 1e5;
using namespace std;
long long myrand() {
return ((long long)(rand() & 65535) << 32) + ((long long)rand() << 16) +
rand();
}
pair<int, pair<long long, int> > st1[N], st2[N];
int vis[N], dis[N], off, pre[N], n, deg[N], deg2[N], u, v, ret[N];
vector<int>... |
If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat.
<image>
However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat.
<image>
You have met a cat. Can you figure out w... | #include <bits/stdc++.h>
using namespace std;
string query(long long int i) {
string x;
cout << i << endl;
getline(cin, x);
return x;
}
void Solve() {
for (long long int i = 0; i <= 9; i++) {
string ans = query(i);
if (ans == "no") continue;
if (ans == "go die in a hole" || ans == "terrible" || an... |
Kuro is currently playing an educational game about numbers. The game focuses on the greatest common divisor (GCD), the XOR value, and the sum of two numbers. Kuro loves the game so much that he solves levels by levels day by day.
Sadly, he's going on a vacation for a day, and he isn't able to continue his solving str... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
struct node {
int vl, mnvl;
node *l, *r;
node() {
mnvl = MAXN;
vl = -1;
l = r = NULL;
}
};
vector<node*> dv(MAXN);
vector<bool> inarr(MAXN, false);
vector<vector<int>> diverse(MAXN);
deque<int> dbl(int a) {
deque<int> d;
whi... |
There are n cities and m roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.
What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?
New roads will also be one-way.
Input
The first line of input consists of three integers ... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOExceptio... |
View Russian Translation
One day Benny was walking and realized that her life was boring. Everything was grey, even roads in the best park were grey.
Therefore she decided to make roads a little bit brighter. She know that every road in the park is a segment laying on the X axis with coordinates Xl, Xr (Xl ≤ Xr). Roa... | t = input()
for i in range(t):
n,l=[int(x) for x in raw_input().split()]
l1=[]
for i in range(n):
l1.append([int(x) for x in raw_input().split()])
f=0
for i in range(n):
r=l1[i][0]+l
current=l1[i][1]
for j in range(n):
if l1[j][0] <=current and l1[j][0]>l1[i][0] and l1[j][1] <= r:
current=max(curren... |
You are given two strings, A and B. Find if there is a substring that appears in both A and B.
Input
The first line of the input will contain a single integer T, the number of test cases.
Then there will be T descriptions of the test cases. Each description contains two lines. The first line contains the string A an... | s="abcdefghijklmnopqrstuvwxyz"
t=input()
for k in range(0,t):
s1=raw_input()
s2=raw_input()
f=False
for i in range(0,26):
if((s[i] in s1) and (s[i] in s2)):
f=True
break
if f==False:
print "NO"
else:
print "YES" |
This is Fibonacci madness.
Given a number n. Print the first n Fibonacci numbers in reverse order.
Input:
First line is number T denoting number of test cases.
T lines follow. Each line has number N.
Output:
Print the first n Fibonacci numbers in reverse order for all test cases.
Constraints:
1 ≤ T ≤ 10
0 ≤ N ≤ ... | from sys import stdin
fib = [0,1]
for i in xrange(2,105):
fib.append(fib[i-1]+fib[i-2])
t = int(stdin.readline())
for _ in xrange(t):
n = int(stdin.readline())
for i in xrange(n):
print fib[n-i-1],
print "" |
Assume there is an Ideal Random Number Generator which generates any real number between 0 and given integer. Two numbers are generated from the above generator using integer A and B, let's assume the numbers generated are X1 and X2.
There is another integer C. What is the probability that summation of X1 and X2 is les... | def gcd(a,b):
if b == 0:
return a
else:
return gcd(b,a%b)
def lowest_form(a,b):
k = gcd(a,b)
aa = a/k
bb = b/k
return (aa,bb)
for i in xrange(1):
a,b,c = map(int,raw_input().split())
if a + b <= c :
print '1/1'
else:
k = min(a,b)
l =... |
Legends who were born in 90s remember Mario very well. As we all are aware of that fabulous video game our little Mario tackling with all the problems and barriers coming his way , he finally saves his Queen from the giant monster Dragon.
In this problem we let you play the game but with a little twist. The aim is sam... | import copy
def cal(l,l1,path,x,y,c,n):
#print(path)
path.append((x,y))
if(x-1>=0):
if(y-1>=0 and (x-1,y-1) not in path):
if(l[x-1][y-1]=='Q'):
if(c not in l1):
l1.append(c)
if(l[x-1][y-1]=='.'):
path1=copy.copy(path)
cal(l,l1,path1,x-1,y-1,c+1,n)
if((x-1,y) not in path):
if(l[x-1][y]==... |
Ranjit wants to design a algorithm such that, if he enters two numbers, all the numbers between these two numbers are listed(except the number divisible by 5 & 3).
BUT the number divisible by both 3 & 5 is also listed (example 30)
The Numbers should be separated by a "," sign
Example- if the two numbers added are- 25... | a, b = map(int, raw_input().split())
print ",".join(str(i) for i in range(a+1, b) if i % 3 and i % 5 or i % 15 == 0) |
Your mother sends you to market to buy some stuff which costs Rs. X, you simply need to find the minimum no. of currency denominations required to complete the transaction. Assume that the seller only takes exactly Rs. X, not more nor less than that.
Also assume standard denominations of 1, 2, 5, 10, 20, 50, 100, 500 ... | t = int(raw_input())
den=[1,2,5,10,20,50,100,500,1000]
den=sorted(den, reverse=True)
while (t!=0):
num=int(raw_input())
sorted(den, reverse=True)
coins=0
for d in den:
coins += num/d
num=num%d
print coins
t-=1 |
Shil has an array of N elements A1 , A2, ... ,AN . He also has an integer K. He wants to find out value of Square Sum for every i from 1 to N-K+1.
The value of Square Sum for certain i is defined as Σ1≤ j ≤ K (j^2 Ai+j-1).
Input:
First line of input consists of two integers N and K. Next line consists of N integers A... | [N, K] = map(int, raw_input().split())
A = map(int, raw_input().split())
modN = 10**9+7
S_1 = 0
S_2 = 0
S_3 = 0
for i in xrange(0, K):
S_3 = (S_3 + A[i]) % modN
S_2 = (S_2 + (i+1) * A[i]) % modN
S_1 = (S_1 + (i+1)**2 * A[i]) % modN
output = []
output.append(S_1)
for i in xrange(0, N-K):
S_1 = (S_1 + (K+1)**2*A[K... |
Monk is a multi-talented person, and prepares results for his college in his free time. (Yes, he is still in love with his old college!) He gets a list of students with their marks. The maximum marks which can be obtained in the exam is 100.
The Monk is supposed to arrange the list in such a manner that the list is s... | ary = sorted( [(name, int(marks)) for k in xrange(input()) for name, marks in [raw_input().split()]], key = lambda x: x[0] )
for i in sorted(ary, key = lambda x:x[1], reverse = True):
print i[0], i[1] |
There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M. Road i connects City A_i and City B_i.
Snuke can perform the following operation zero or more times:
* Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.
After he... | import java.util.*;
class DSU {
private int n;
private int[] parentOrSize;
public DSU(int n) {
this.n = n;
this.parentOrSize = new int[n];
java.util.Arrays.fill(parentOrSize, -1);
}
int merge(int a, int b) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("a=" + a);
if (!(0 <= b && b < ... |
Takahashi has an empty string S and a variable x whose initial value is 0.
Also, we have a string T consisting of `0` and `1`.
Now, Takahashi will do the operation with the following two steps |T| times.
* Insert a `0` or a `1` at any position of S of his choice.
* Then, increment x by the sum of the digits in the o... | #include<bits/stdc++.h>
using namespace std;
int n,s,i,j,p;
long long ans;
char c[200005];
int main()
{
scanf("%s",c+1);
for(i=1;c[i];++i)
if(c[i]=='0')
++s;
for(i=1;c[i];++i)
{
if(c[i]=='0')
break;
if(i&1)
ans+=s+1;
}
for(++i;c[i];++i)
{
++p;
int s0=0,s1=0;
for(j=i;c[j]=='1';++j)
{
if(... |
In a factory, there are N robots placed on a number line. Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.
We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect. Here, for each i (1 \leq i \leq N... | import java.util.*;
import java.io.*;
public class Main {
static boolean DEBUG;
public static void main(String[] args) {
DEBUG = args.length > 0 && args[0].equals("-DEBUG");
Solver solver = new Solver();
solver.solve();
solver.exit();
}
static class FastScanner {
private final InputStream in = System.in;... |
Find the number of sequences of N non-negative integers A_1, A_2, ..., A_N that satisfy the following conditions:
* L \leq A_1 + A_2 + ... + A_N \leq R
* When the N elements are sorted in non-increasing order, the M-th and (M+1)-th elements are equal.
Since the answer can be enormous, print it modulo 10^9+7.
Const... | #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;}
template<typename T,T MOD = 1000000007>
struct Mint{
static constexpr T mod = MOD;
T v;
... |
You are given a string S of length N consisting of lowercase English letters, and an integer K. Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`.
Constraints
* 1 \leq K \leq N\leq 10
* S is a string of length N consisting of lowercase English letters.
* N... | N=int(input())
S=input()
K=int(input())
print("".join(s if s==S[K-1] else "*" for s in S)) |
There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)
The master's favorite number is 753. The closer to this number, the better. What is the mini... | #include<iostream>
#include<cmath>
using namespace std;
int main(void)
{
long long s, n, mn = 1e9;
cin >> s;
for(;s>=100;s/=10)
{
n=s%1000;
mn = min(mn, (long long)abs(753-n));
}
cout << mn;
return 0;
}
|
There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:
* Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.
What is the largest possible sum of the integers written on the blackboard after... | #include <bits/stdc++.h>
using namespace std;
int main(){
int A,B,C,K;
cin>>A>>B>>C>>K;
int M=max({A,B,C});
cout<<pow(2,K)*M-M+A+B+C<<endl;
} |
Snuke has a sequence p, which is a permutation of (0,1,2, ...,N-1). The i-th element (0-indexed) in p is p_i.
He can perform N-1 kinds of operations labeled 1,2,...,N-1 any number of times in any order. When the operation labeled k is executed, the procedure represented by the following code will be performed:
for(i... | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<cstdlib>
#define cmax(a,b) (a<(b)?a=(b),1:0)
#define cmin(a,b) (a>(b)?a=(b),1:0)
#define dmin(a,b) ((a)<(b)?(a):(b))
#define dmax(a,b) ((a)>(b)?(a):(b))
#define regsiter register
#define CL fclose(stdin),fclose(stdout)
names... |
Snuke has N dogs and M monkeys. He wants them to line up in a row.
As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there a... | 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.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Bui... |
Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.
Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.
Here, both the x- and y-coordinates before and after each movement must ... | A, B, X, Y = map(int, input().split())
P = X-A
Q = Y-B
print("R"*P+"U"*Q+"L"*P+"D"*Q+"L"+"U"*(Q+1)+"R"*(P+1)+"D"+\
"R"+"D"*(Q+1)+"L"*(P+1)+"U") |
Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.
The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This li... | # -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permut... |
<image>
Arrange integers (0 or more and 99 or less) in a rhombus as illustrated in Fig. 1. Create a program that reads the data representing the rhombus and outputs the maximum value of the sum of the integers that pass when starting from the top and proceeding to the bottom according to the following rules.
* At ea... | #include<iostream>
#include<vector>
using namespace std;
// strをdelで区切る.いずれdelがstringでも大丈夫なように作り変える.
vector<string> split(string str, char del){
vector<string> ret;
string cutoff = "";
for(int i = 0; i < str.length(); i++){
if(str[i] == del){
if(cutoff != "") ret.push_back(cutoff);
... |
There is a game that uses numbers called "Fizz Buzz". In this game, multiple players count the numbers one by one, starting with 1, and each player says only one number after the previous player. At that time, you must say "Fizz" if it is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if it is divisible... | #include <iostream>
#include <algorithm>
#include <queue>
#include <string>
using namespace std;
bool check(int turn, string str, int player)
{
if(turn%3 == 0 && turn%5 == 0){
return str == "FizzBuzz";
} else if(turn%3 == 0){
return str == "Fizz";
} else if(turn%5 == 0){
return str == "Buzz";
}
... |
The university of A stages a programming contest this year as has been the case in the past. As a member of the team in charge of devising the problems, you have worked out a set of input data for a problem, which is an arrangement of points on a 2D plane in the coordinate system. The problem requires that any combinat... | #include<iostream>
#include<vector>
#include<utility>
#include<algorithm>
#include<map>
using namespace std;
int gcd(int a,int b) {
if(a<b)return gcd(b,a);
else if(b==0)return a;
else return gcd(b,a%b);
}
int main() {
int N,K;
cin >> N >> K;
vector<pair<short,short>> P(N);
int i,j;
for... |
It was long believed that a 2-dimensional place can not be filled with a finite set of polygons in aperiodic way. British mathematician, Sir Roger Penrose, developed an aperiodic tiling over the years and established a theory of what is known today as quasicrystals.
The classic Penrose tiles consist of two rhombi with... | #include <iostream>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const double EPS = 1e-5;
const double INF = 1e12;
const double PI = acos(-1);
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<double> P;
typedef vector<P> VP;
names... |
Chief Judge's log, stardate 48642.5. We have decided to make a problem from elementary number theory. The problem looks like finding all prime factors of a positive integer, but it is not.
A positive integer whose remainder divided by 7 is either 1 or 6 is called a 7N+{1,6} number. But as it is hard to pronounce, we s... | import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[85715];
int[] sosu = new int[35813];
... |
Do you know "sed," a tool provided with Unix? Its most popular use is to substitute every occurrence of a string contained in the input string (actually each input line) with another string β. More precisely, it proceeds as follows.
1. Within the input string, every non-overlapping (but possibly adjacent) occurrences... | #include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
using namespace std;
typedef long long int ll;
typed... |
Problem
Taro hides important books in the school locker, so he manages them more strictly than other people, and in addition to the keys provided by the school, he has installed the following button authentication type keys. ..
<image>
However, Taro, who easily forgets his password, has a habit of making it possible... | #include<iostream>
#include<string>
#include<cmath>
#include<map>
using namespace std;
typedef pair< int , int > Pi;
string mas[] = {"ABC","DEF","GHI"},s;
map< char , Pi > mp;
const int dy[] = { 1, 0, -1, 0}, dx[] = { 0, 1, 0 , -1};
bool rec(int now){
if( now == s.size()) return true;
for(int i = 0 ; i < 4 ; i++ )... |
Osaki
Osaki
English text is not available in this practice contest.
The Yamanote Line is a circular railway line laid in the 23 wards of Tokyo. The total route distance is 34.5km, and one lap takes about one hour. There are 29 stations in total. The line color is Uguisu color. The peak congestion rate exceeds 200%, ... | #include<iostream>
#include<string>
using namespace std;
int nowtrain[864000];
int main(){
int n;
string a;
int bef,aft;
while(true){
cin>>n;
if(n==0)
break;
for(int i=0;i<86400;i++)
nowtrain[i]=0;
for(int i=0;i<n;i++){
cin>>a;
bef=3600*((a[0]-'0')*10+a[1]-'0');
bef+=60*((a[3]-'0')*10+a[4]-'0');
bef... |
Open Binary and Object Group organizes a programming contest every year. Mr. Hex belongs to this group and joins the judge team of the contest. This year, he created a geometric problem with its solution for the contest. The problem required a set of points forming a line-symmetric polygon for the input. Preparing the ... | /*
テ」ツ?ャテ」ツ?」テ」ツ?ステ」ツ??
*/
#include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-4)
#define equals(a,b) (fabs((a)-(b))<EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
... |
The Quarkgo Empire Expeditionary Force is an evil organization that plans to invade the Earth. In keeping with the tradition of the invaders, they continued to send monsters at a pace of one every week, targeting the area around Tokyo in Japan. However, each time, five warriors calling themselves the Human Squadron Ear... | #include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n;
cin>>n;
int res=0;
int num[3];
while(n>1){
if(n<=3) n=3;
num[0]=n/3;
num[1]=(n-num[0])/2;
num[2]=n-num[1]-num[0];
n=max(num[0],num[2]);
res++;
}
cout << res<<endl;
return 0;
} |
Problem F: Magnum Tornado
We have a toy that consists of a small racing circuit and a tiny car. For simplicity you can regard the circuit as a 2-dimensional closed loop, made of line segments and circular arcs. The circuit has no branchings. All segments and arcs are connected smoothly, i.e. there are no sharp corners... | #include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <ctime>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <deque>
#include <complex>
#include <string>
#include <iomanip>... |
In 20XX AD, a school competition was held. The tournament has finally left only the final competition. You are one of the athletes in the competition.
The competition you participate in is to compete for the time it takes to destroy all the blue objects placed in the space. Athletes are allowed to bring in competition... | #include <bits/stdc++.h>
#define loop(n, i) for(int i=0;i<n;i++)
#define all(v) v.begin(),v.end()
#define HERE cout << "HERE: " << __LINE__ << endl;
#define INSP(v) cout << v << " at " << __LINE__ << endl;
using namespace std;
typedef long long ll;
typedef struct {
double x, y, z;
} P;
double dot(P a, P b)
{
... |
Problem statement
You and AOR Ika are preparing for a graph problem in competitive programming. Generating input cases is AOR Ika-chan's job. The input case for that problem is a directed graph of the $ N $ vertices. The vertices are numbered from $ 1 $ to $ N $. Edges may contain self-loops, but not multiple edges.
... | #include<bits/stdc++.h>
using namespace std;
void fail()
{
cout << "NO" << endl;
exit(0);
}
int main()
{
int N, A[51] = {}, B[51] = {};
bool graph[50][50] = {{}};
cin >> N;
for(int i = 0; i <= N; i++) cin >> A[i];
for(int i = 0; i <= N; i++) cin >> B[i];
if(accumulate(begin(A), end(A), 0) != N) fai... |
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and... | //include
//------------------------------------------
#include <bits/stdc++.h>
using namespace std;
//typedef
//------------------------------------------
typedef long long LL;
typedef vector<LL> VL;
typedef vector<VL> VVL;
typedef vector<string> VS;
typedef pair<LL, LL> PLL;
//container util
//---------------------... |
Story
A long time ago, in a galaxy far away.
In the midst of a storm of civil war, a vicious Galactic Empire army struck a secret rebel base.
Escaped from the dreaded pursuit of the Imperial Starfleet, the Freedom Warriors, led by Wook Starwalker, decide to build a new secret base on the outskirts of the galaxy.
As a ... | #include <bits/stdc++.h>
#define whlie while
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define rep(i,N) for(int i = 0; i < (N); i++)
#define repr(i,N) for(int i = (N) - 1; i >= 0; i--)
#define rep1(i,N) for(int i = 1; i <= (N) ; i++)
#define repr1(i,N) for(int i = (N) ; i > 0 ; i--... |
Write a program which prints the area of intersection between given circles $c1$ and $c2$.
Constraints
* $-10,000 \leq c1x, c1y, c2x, c2y \leq 10,000$
* $1 \leq c1r, c2r \leq 10,000$
Input
The input is given in the following format.
$c1x\; c1y\; c1r$
$c2x\; c2y\; c2r$
$c1x$, $c1y$ and $c1r$ represent the coordin... | #include <bits/stdc++.h>
#define For(i, a, b) for(int (i)=(int)(a); (i)<(int)(b); ++(i))
#define rFor(i, a, b) for(int (i)=(int)(a)-1; (i)>=(int)(b); --(i))
#define rep(i, n) For((i), 0, (n))
#define rrep(i, n) rFor((i), (n), 0)
#define fi first
#define se second
using namespace std;
typedef long long lint;
typedef uns... |
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $... | #include<bits/stdc++.h>
using namespace std;
int main()
{
map <string,int> m;
int q;
cin>>q;
while(q--)
{
int a;
cin>>a;
if(a==0)
{
string key;
long long x;
cin>>key>>x;
m[key]=x;
}
else if(a==1)
... |
Two cheeky thieves (Chef being one of them, the more talented one of course) have came across each other in the underground vault of the State Bank of Churuland. They are shocked! Indeed, neither expect to meet a colleague in such a place with the same intentions to carry away all the money collected during Churufest 2... | t=input()
for i in range(1,t+1):
m,p= raw_input().split(' ')
m=int(m)
p=float(p)
a=(10**9)*(1-(-p)**m)/(1+p)
b=(10**9)*(p+(-p)**m)/(1+p)
print a,b |
Given two binary strings, A (of length 10) and B (of length 5),
output 1 if B is a substring of A and 0 otherwise.
Input
The first line contains the number of test cases n. This is followed by n lines each consisting of pairs of binary strings A and B separated by a single space.
Output
output 1 if B is a sub... | def main():
test = int(raw_input())
i = 0
while i < test:
l = raw_input().split()
a = l[0]
b = l[1]
if b in a:
print(1)
else:
print(0)
i += 1
if __name__ == '__main__':
main() |
A certain grade of steel is graded according to the following conditions.
Hardness must be greater than 50.
Carbon content must be less than 0.7.
Tensile strength must be greater than 5600.
The grades are as follows:
Grade is 10 if all three conditions are met.
Grade is 9 if conditions (i) and (ii) are met.
Grade ... | t= int(raw_input())
for i in range(t):
h,c,t=map(float,raw_input().split())
if h>50 and c<0.7 and t>5600:
print "10"
elif h>50 and c<0.7:
print"9"
elif c<0.7 and t>5600:
print"8"
elif h>50 and t>5600:
print "7"
elif h>50 or c<0.7 or t>5600:
print "6"
e... |
Problem Statement
Levy's conjecture, named after Hyman Levy, states that all odd integers greater than 5 can be represented as the sum of an odd prime number and an even semiprime. To put it algebraically, 2n + 1 = p + 2q always has a solution in primes p and q (not necessary to be distinct) for n > 2. (Source: Wikiped... | from math import sqrt
def sieve(n):
L = [0 for i in range(n+1)]; s = int(sqrt(n)); P,S = {},[]; L[0],L[1] = 1,1
for i in range(2,s+1):
if L[i] is 0:
for j in range(i*i,n+1,i): L[j] = 1
for i in range(len(L)):
if L[i] is 0: P[i] = None; S.append(i)
return P,S
def precompute():
P,S = sieve(int(1e4)); l = len... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.