input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that <image>... | import java.util.Scanner;
public class temp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] a = new int[n];
long sum = 0;
for (int i =0 ; i<n ; i++){
a[i] = s.nextInt();
sum = sum + a[i];
}
long sumt = sum/3;
if (sum%3!... |
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obvio... | #include <bits/stdc++.h>
using namespace std;
template <typename _T>
class vertix {
private:
int capacity = 0;
_T* arr = new _T[capacity];
public:
vertix() {
capacity = 000;
delete[] arr;
arr = new _T[capacity];
}
vertix(int S) {
capacity = S;
delete[] arr;
arr = new _T[capacity];
... |
You need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an... | #include <bits/stdc++.h>
using namespace std;
int n, c, nod;
set<int> gnext[1 << 20][2];
vector<int> ans;
void PANIC() {
cout << "IMPOSSIBLE\n";
exit(0);
}
void dfs(int r) {
int onod = nod++;
if (onod >= n) PANIC();
if (gnext[onod][0].empty())
ans.push_back(onod);
else {
if (!gnext[onod][1].empty() ... |
Help! A robot escaped our lab and we need help finding it.
The lab is at the point (0, 0) of the coordinate plane, at time 0 the robot was there. The robot's movements are defined by a program — a string of length l, consisting of characters U, L, D, R. Each second the robot executes the next command in his program: ... | #include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long x = 0, f = 1;
char c = getchar();
while ((c < '0' || c > '9') && (c != '-')) c = getchar();
if (c == '-') f = -1, c = getchar();
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void GG(... |
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
print(min(abs(a[i]-a[(i+1)%n]), abs(a[i]-a[i-1])), max(abs(a[i]-a[0]), abs(a[i]-a[-1]))) |
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimi... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
/* Your class sho... |
Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighbori... | #include <bits/stdc++.h>
using namespace std;
template <class T>
void debug(T a, T b) {
for (; a != b; a++) cerr << *a << ' ';
cerr << endl;
}
template <class T>
bool isprime(T x) {
long long till = (T)sqrt(x + .0);
if (x <= 1) return 0;
if (x == 2) return 1;
if (x / 2 * 2 == x) return 0;
for (long long i... |
IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from 2 to 10 every developer ... | n = int(raw_input())
temp = 8 * 9 * 5 * 7
print n / temp |
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m ... | #include <bits/stdc++.h>
template <class T>
T gcd(T a, T b) {
T r;
while (b != 0) {
r = a % b;
a = b;
b = r;
}
return a;
}
template <class T>
T lcm(T a, T b) {
return a / gcd(a, b) * b;
}
template <class T>
T sqr(T x) {
return x * x;
}
template <class T>
T cube(T x) {
return x * x * x;
}
using... |
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to b... | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> grafo[100100];
bool root[100100] = {false};
bool ferrou = false;
int wish[100100];
int cont = 0;
bool flag[100100] = {false};
int val = 0;
void DFP(int x) {
for (vector<int>::iterator it = grafo[x].begin(), fim = grafo[x].end();
it != fim; it+... |
Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:
<image>
Where <image> represents logical OR and <image> represents logical exclusive OR (XOR), and vi,... | #include <bits/stdc++.h>
using namespace std;
const int mo = 1000000007;
int x, k, X, Y, n, m, u[100005];
long long ans[2];
int f[2], g[2][2][2], G[2][2][2], vis[100005];
vector<int> a[100005], A[100005], e[100005], w[100005];
void dfs(int x) {
if (vis[x]) return;
vis[x] = 1;
memset(G, 0, sizeof G);
int j = a[x... |
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations:
* multiply the current number by 2 (that is, replace the number x by 2·x);
* append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1).
You need to help Vasil... | n, target = map(int, input().split())
def keep(target, ans):
#print(target)
while target % 2 == 0:
target = target // 2
ans = [target]+ans
if str(target).endswith("1") and target != 1:
return keep((target-1) // 10, [(target-1) // 10]+ans)
else:
return target, ans
next,... |
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
public class B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String patter = br... |
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that membe... | import java.io.*;
import java.util.*;
import java.math.*;
import java.util.stream.Collectors;
import java.util.stream.*;
public class Main {
static HashSet<Integer>[] grp;
static boolean[] vis;
static ArrayList<Integer> al;
public static void main(String[] args) throws java.lang.Exception {
... |
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.
<image>
The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: hou... | def main():
n, m, k = map(int, input().split())
m -= 1
a = list(map(int, input().split()))
min_dist = n
for i, ai in enumerate(a):
if ai != 0 and ai <= k:
min_dist = min(min_dist, abs(i - m))
print(min_dist * 10)
if __name__ == '__main__':
# import sys
# sys.stdin... |
To stay woke and attentive during classes, Karen needs some coffee!
<image>
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows n ... | ranges, maps, strs = range, map, str
fout = ""
count = 0
n, k, q = maps(int, input().split())
rangeArr = []
for i in ranges(200002):
rangeArr.append(0)
for recipe in ranges(n):
left, right = maps(int, input().split())
rangeArr[left] += 1
rangeArr[right + 1] -= 1
for recipe in ranges(1, len(rangeArr)):
rangeA... |
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts a... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int count = 0;
for (int i = 0; i < n; i++) {
int elements;
cin >> elements;
if (elements % 2 != 0) {
count++;
}
}
string res = (count == 0) ? "Second" : "First";
cout << res;
return 0;
}
|
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to f... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import jav... |
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ... | n = int(input())
arr = [int(x) for x in input().split()]
cnt = 0
for i in range(1,n-1):
if arr[i]< arr[i-1] and arr[i] < arr[i+1]:cnt += 1
else:
if arr[i]> arr[i-1] and arr[i] > arr[i+ 1]:
cnt += 1
print(cnt) |
Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side.
Determine a minimal number of wooden bars which are needed t... | n = int(input())
a = int(input())
b = int(input())
ans = 6
cnt = 0
cur = 2
cnt += 2 * ((n - b) // a)
while cnt < 4:
cur += 1
cnt += (n // a)
ans = min(ans, cur)
if b * 2 <= n:
cur, cnt = 0, 0
cur = 1
cnt += ((n - 2 * b) // a)
while cnt < 4:
cur += 1
cnt += (n // a)
ans = min(... |
You are given a node of the tree with index 1 and with weight 0. Let cnt be the number of nodes in the tree at any instant (initially, cnt is set to 1). Support Q queries of following two types:
* <image> Add a new node (index cnt + 1) with weight W and add edge between node R and this node.
* <image> Output the ... | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const int N = 5e5 + 7;
const int M = 22;
long long w[N], last;
long long sum[N][M];
int nx[N][M], cnt = 1;
void add(int u, int v) {
if (w[u] <= w[v])
nx[u][0] = v;
else {
for (int i = 20; i >=... |
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≤ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight <image> (where <image> is t... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
template <typename T>
void read(T &x) {
x = 0;
int f = 1;
char c = getchar();
for (; !isdigit(c); c = getchar())
if (c == '-') f = -1;
for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + c - '0';
x *= f;
}
long long n;
long lon... |
You are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). C... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1 << 22 + 1;
int pai[MAXN];
char ranki[MAXN];
char tmp[MAXN];
bool pd[MAXN];
bool inp[MAXN];
class ConjDisj {
public:
int n;
ConjDisj(int N) {
for (int i = 0, n = N; i < n; i++) {
pai[i] = i;
ranki[i] = 0;
}
}
int busca(int x) {... |
Akash is feeling lonely.So he decided to visit his friend's house.
His friend's house is located at the distance of K metres from his
house.Now,he can take a step of one metre ,two metres or three
metres at a time.Can you tell me number of ways of reaching
Akash's friend house.
As the answer can be large Print answ... | dist = range(1000000)
dist[0] = 1
dist[1] = 2
dist[2] = 4
for i in xrange(3 , 1000000):
dist[i] = (dist[i-1] + dist[i-2] + dist[i-3])%1000000007
t = int(raw_input())
for _ in xrange(0,t):
n = int(raw_input())
print dist[n-1] |
Brio wants to get a beautiful house constructed near the National Highway. As his in laws are very much fond of triangles, he decided to give his house a perfect Triangular Shape.
Now, here comes the problem that he faces. The plots in Hackers' Land are all circular in shape. You need to help Brio find the area of the ... | import math
t=input()
while t>0:
a,b,c=map(float, raw_input().split(" "))
r=(a*b*c)/(math.sqrt((a+b+c)*(b+c-a)*(c+a-b)*(a+b-c)))
print("%.4f" % (3.1415*r*r))
t-=1 |
Darshak (Dark) was playing with numbers and started learning various concepts of prime numbers, composite numbers...
One day he got bored solving problems of easy level so he started searching new concepts and end up reading about relative primes...
So he want you to help me design a program which takes two numbers '... | def gcd(m,n):
if n==0:
return m
else:
return gcd(n,m%n)
t=input()
while t>0:
t-=1
a,b=map(int,raw_input().split())
flag=gcd(a,b)
if(flag==1):
print "Is a Co-Prime"
else:
print "Not a Co-Prime" |
Joy and Rock decided to play a game. They have N cards numbered from 0 to N−1. Joy asks Rock to reverse the position of the cards, i.e., to change the order from say, 0,1,2,3 to 3,2,1,0. He further asks Rock to reverse the position of the cards N times, each time starting from one position further to the right, till he... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
t=input()
for _ in range(t):
b=[]
x=[]
y=[]
n,m=map(int,raw_input().split())
if((n-1)%2):
p=int(((n-1)/2)+1)
else :
p=(n-1)/2
for i in range(0,p):
b.append(n-i-1)
b.appen... |
King Kala the Fighter has an army of N soldiers. Each soldier is either a BanVeer or a TalwarBaaz. There are M soldiers in the army who are TalwarBaaz. The King forms a strategy. For each battle, he doesn’t have the resources to send his army in groups of more than K soldiers. Now, a group of at most K soldiers can win... | fact = [0]*200005
inv = [0]*200005
MOD = 1000000009
def invMod (n):
return pow(n, MOD-2, MOD)
def solve (n, r):
if r < 0 or r > n:
return 0
x = ( fact[n] * ( inv[r]%MOD * inv[n-r]%MOD)%MOD)%MOD
return x
def main():
fact[0] = 1
inv[0] = 1
for i in xrange(1,200003):
fact[i] = (fact[i-1]*i)%MOD
inv[i] = i... |
To defend her castle Count Mishti has invented a new challenge. In this challenge, the participant goes to a room that has n corridors and each corridor has n cells. Each cell has some coins of gold in it i.e. the jth cell of the ith corridor has a[i][j] gold coins ( 1 ≤ i ≤ n && 1 ≤ j ≤ n).
The participant starts at ... | noOfTestCases = int(raw_input())
def maxCoins(values, c):
i = 0
while(i<n):
j = 0
while(j<n):
values[i][j] = int(values[i][j])
j += 1
i += 1
i = 1
while(i<n):
values[i][0] += values[i-1][0]
i += 1
i = 1
while(i<n):
values[0][i] += values[0][i-1]
i += 1
i = 1
while(i<n):
j = 1
... |
Consider the palindromic prime numbers(Numbers which are palindrome as well as prime).Let p be the product of non zero digits of a nth palindromic prime number.Let product of digits of a palindromic prime is multiplied by a number m to generate number q(q=p*m).Your task is simple; you have to find number of divisors of... | l = [1, 2, 3, 5, 7, 1, 1, 3, 5, 8, 9, 9, 45, 63, 72, 98, 245, 392, 441, 81, 162, 3, 5, 6, 3, 4, 16, 28, 32, 27, 72, 81, 48, 112, 100, 125, 36, 108, 180, 216, 196, 441, 64, 256, 243, 648, 729, 9, 18, 36, 63, 72, 9, 45, 108, 144, 405, 720, 1152, 225, 225, 675, 1575, 648, 1620, 882, 2205, 576, 576, 4032, 1458, 98, 245, 29... |
One of the main tasks of an operating system is process scheduling, i.e., managing CPU sharing among a community of ready processes. Several algorithms exist for scheduling tasks to the CPU. Here we are considering Round Robin Scheduling(in a single CPU system) which is the most widely used of all the scheduling algori... | def prepare(C,N,P):
global waitTimes
global ranks
waitTimes = [0]
ranks = list(range(0,len(P)))
for i in range(1,len(P)):
waitTimes.append(waitTimes[i-1]+min(P[i-1],C))
pSorted = [(i,(N*((d-1)//C))+i) for (i,d) in enumerate(P)]
pSorted.sort(key = lambda p:p[1])
... |
Joy is a short and lazy guy, he uses elevator to reach his flat. But unfortunately elevator is not working today and he became sad. Suddenly God came and made the stairs magical, such that he can jump on it in a magical way. Initially he can take 1 or 2 steps. If he jumps x steps at a time then in the next step he can... | test = int(input())
while(test>0):
stairs = int(input())
steps = 0
size_of_step = 2
while(stairs > 0):
steps +=1
stairs = stairs - size_of_step
size_of_step+=1
test-=1
print(steps) |
Ben believes a lot in tarot cards. He believes that they are lucky for him. He even decides to wear clothes according to the color predicted by a draw of a card. This irritates his wife, because sometimes he wears the same color t-shirt continuously if his cards so predict.
Now, his wife wants to go on a vacation wit... | def solve(a):
l, r = 0, 0
d = {}
for ii in a:
d[ii] = 0
i = 0
n = len(a)
best = 0
bestl, bestr = 0, 0
dist = 0
while r<n:
d[a[r]]+=1
if d[a[r]]==2:
while d[a[r]]!=1:
d[a[l]]-=1
l+=1
if (r-l)>best:
... |
We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.
In how many ways can we choose three of the sticks with different lengths that can form a triangle?
That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:
... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner fs = new Scanner(System.in);
int n = fs.nextInt();
long[] inp = new long[n];
for(int i=0 ; i<n ; i++){
inp[i] = fs.nextLong();
}
int ans = 0 ;
for(int i=0 ; ... |
We have a string S of length N consisting of `R`, `G`, and `B`.
Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:
* S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.
* j - i \neq k - j.
Constraints
* 1 \leq N \leq 4000
* S is a string of length N consisting of... | from collections import *
N=int(input())
S=input()
c=Counter(S)
ans=c['R']*c['G']*c['B']
for i in range(1,N//2+1):
for j in range(i,N-i):
if S[j-i]!=S[j] and S[j]!=S[j+i] and S[j+i]!=S[j-i]:
ans-=1
print(ans)
|
AtCoder Mart sells 1000000 of each of the six items below:
* Riceballs, priced at 100 yen (the currency of Japan) each
* Sandwiches, priced at 101 yen each
* Cookies, priced at 102 yen each
* Cakes, priced at 103 yen each
* Candies, priced at 104 yen each
* Computers, priced at 105 yen each
Takahashi wants to buy s... | X = int(input())
q,mod = divmod(X,100)
if 5*q<mod:
print(0)
else:
print(1) |
We have a square grid with N rows and M columns. Takahashi will write an integer in each of the squares, as follows:
* First, write 0 in every square.
* For each i=1,2,...,N, choose an integer k_i (0\leq k_i\leq M), and add 1 to each of the leftmost k_i squares in the i-th row.
* For each j=1,2,...,M, choose an intege... | // Words are flowing out like endless rain into a paper cup
// They slither while they pass they slip away across the universe
// Pools of sorrow, waves of joy are drifting through my open mind
// Possessing and caressing me
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
namespace _buff {
const... |
There is an infinitely large triangular grid, as shown below. Each point with integer coordinates contains a lamp.
<image>
Initially, only the lamp at (X, 0) was on, and all other lamps were off. Then, Snuke performed the following operation zero or more times:
* Choose two integers x and y. Toggle (on to off, off t... | // #pragma GCC target("avx") // CPU 処理並列化
// #pragma GCC optimize("O3") // CPU 処理並列化
// #pragma GCC optimize("unroll-loops") // 条件処理の呼び出しを減らす
// #define BEGIN_STACK_EXTEND(size) void * stack_extend_memory_ = malloc(size);void * stack_extend_origin_memory_;char * stack_extend_dummy_memory_ = (char*)alloca((1+(int)(((... |
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and con... | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); ++i)
typedef long long ll;
int main(){
int h,w;
cin >> h >> w;
vector<vector<int>> mp(h,vector<int>(w));
int a;
rep(i,h){
rep(j,w){
cin >> a;
mp[i][j] = a%2;
}
}
vector<vector<int>> ans;
rep(i,h){
rep(j,w-1){
... |
Determine if there exists a sequence obtained by permuting 1,2,...,N that satisfies the following conditions:
* The length of its longest increasing subsequence is A.
* The length of its longest decreasing subsequence is B.
If it exists, construct one such sequence.
Constraints
* 1 \leq N,A,B \leq 3\times 10^5
* ... | #include <bits/stdc++.h>
using namespace std;
int n, a, b;
int main() {
cin >> n >> a >> b;
if (a+b > n+1 or a*(long long)b < n) {
cout << "-1";
return 0;
}
vector<int> v(a-1, 0);
for (int i=1; i<=n-b; i++) v[i%v.size()]++;
v.push_back(b);
int k = 1;
for (int i... |
Rng has a connected undirected graph with N vertices. Currently, there are M edges in the graph, and the i-th edge connects Vertices A_i and B_i.
Rng will add new edges to the graph by repeating the following operation:
* Operation: Choose u and v (u \neq v) such that Vertex v can be reached by traversing exactly thr... | #include<iostream>
#include<cstdio>
#include<cstring>
typedef long ll;
const int MAXN=1e5+5;
int N,M;
struct E{int next,to;} e[MAXN<<1];int ecnt,G[MAXN];
void addEdge(int u,int v){e[++ecnt]=(E){G[u],v};G[u]=ecnt;}
void addEdge2(int u,int v){addEdge(u,v);addEdge(v,u);}
int clr[MAXN];
bool dfs(int u)
{
for(int i=G[u]... |
There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.
You have two pieces, initially placed on square A and B, respectively. You will be asked to process Q queries of the following kind, in the order received:
* Given an integer x_i, move one of the two pieces of your choice to squar... | #pragma GCC optimize("O3")
#include<cstdio>
#include<cctype>
#include<cstdlib>
#include<algorithm>
typedef signed long long int int64;
inline unsigned getint() {
register char ch;
while(!isdigit(ch=getchar()));
register unsigned x=ch^'0';
while(isdigit(ch=getchar())) x=(((x<<2)+x)<<1)+(ch^'0');
return x;
}
inline ... |
There is a tree with N vertices, numbered 1 through N.
The i-th of the N-1 edges connects the vertices p_i and q_i.
Among the sequences of distinct vertices v_1, v_2, ..., v_M that satisfy the following condition, find the maximum value of M.
* For every 1 \leq i < M, the path connecting the vertices v_i and v_{i+1}... | #include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <cassert>
#... |
Write a program which solve a simultaneous equation:
ax + by = c
dx + ey = f
The program should print x and y for given a, b, c, d, e and f (-1,000 ≤ a, b, c, d, e, f ≤ 1,000). You can suppose that given equation has a unique solution.
Input
The input consists of several data sets, 1 line for each data set. In a ... | import sys
lines = sys.stdin.readlines()
for l in lines:
nums = list(map(int, l.split()))
A = [nums[0], nums[1], nums[3], nums[4]]
B = [nums[2], nums[5]]
detA = A[0]*A[3] - A[1]*A[2]
inA = [A[3], -A[1], -A[2], A[0]]
solutions = [n/detA+0.0 for n in [inA[0]*B[0] + inA[1]*B[1], inA[2]*B[0] + inA[... |
The height of the student was measured at the medical examination. Create a program that takes height data as input, creates a frequency distribution, and outputs it. The frequency distribution is divided into 6 classes in 5 cm increments, and the number of people is indicated by * (half-width asterisk). However, if th... | #include <iostream>
#include <vector>
using namespace std;
int main(){
double t;
int n,h;
vector<int> f(6,0);
cin>>n;
for(;n--;){
cin>>t;
if(t<165.0) h = 0;
else h = ((int)t-160)/5;
if(h>5)h=5;
f[h]++;
}
for(n=0;n<6;n++){
cout<<n+1<<":";
... |
Izua University Elementary School is famous as one of Japan's leading competition programmer training schools. The teachers at this school have a wide range of algorithmic knowledge and utilize it on a daily basis. As a teacher, you will be in charge of drawing and crafting classes this year. In this class, all childre... | // ???????????????
#include<vector>
#include<map>
#include<queue>
#include<tuple>
#include<functional>
// ?????????
const int NIL = -1;
const double INF = 1e9;
class MinimumCostFlow {
private:
struct Edge {
int from, to;
double weight, capacity;
Edge() {}
Edge(int f, int t, double w, double c) : f... |
problem
There are the following games.
N characters are lined up in a vertical row. The color of these characters is red, blue, or yellow, and in the initial state, four or more characters of the same color are not lined up in a row. The player can select a character at a certain position and change it to another col... | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
int n;
int search(int num, int a[20000]){
int ref = a[num];
int ans = 0;
for(int i = 1; i <= 3; i++){
a[num] = i;
int ind1 = num;
int ind2 = num;
int ind1_p = ind1;
int ind2_p = ind2;
whi... |
You are a student of University of Aizu. And you work part-time at a restaurant.
Staffs of the restaurant are well trained to be delighted to provide more delicious products faster.
The speed providing products particularly depends on skill of the staff. So, the manager of the restaurant want to know how long it take... | import java.util.*;
import java.math.*;
import java.awt.geom.*;
import java.io.*;
public class Main {
static int INF = 2 << 27;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
int n = sc.nextInt();
if(n == 0) break;
int[] count = new int[3];
int[]... |
If you are a computer user, you should have seen pictures drawn with ASCII characters. Such a picture may not look as good as GIF or Postscript pictures, but is much easier to handle. ASCII pictures can easily be drawn using text editors, and can convey graphical information using only text-based media. Program s extra... | #include <iostream>
#include <algorithm>
#include <vector>
#define WMAX 100
#define HMAX 1000
#define INF 9999999
using namespace std;
string M[HMAX];
int h;
int ha;
int hb;
int wa;
int wb;
bool visited[HMAX][WMAX];
int flag45_1, flag45_2;
class A {
public:
int S;
int N;
A(int S, int N) {
this->S = S;
... |
The first crossword puzzle was published on December 21, 1913 by Arthur Wynne. To celebrate the centennial of his great-great-grandfather's invention, John "Coward" Wynne1 was struggling to make crossword puzzles. He was such a coward that whenever he thought of a tricky clue for a word, he couldn’t stop worrying if pe... | // very kuso problem
#include <cassert>// c
#include <iostream>// io
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>// container
#include <map>
#include <set>
#include <queue>
#include <bitset>
#include <stack>
#include <algorithm>// other
#include <complex>
#include <numeric>
#include <func... |
Problem
A-chan, Rika-chan, and Hart-kun came to visit the condominium.
The three decided to sneak into a room where they could manage the electricity in all the rooms and play a trick.
This condominium has the shape of n cubes lined up in a row.
Each cube has one side length increasing by 1 from the west (1,2,3, ...,... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pa... |
The princess of the Fancy Kingdom has been loved by many people for her lovely face. However the witch of the Snow World has been jealous of the princess being loved. For her jealousy, the witch has shut the princess into the Ice Tower built by the witch’s extreme magical power.
As the Ice Tower is made of cubic ice b... | /*
00:42 - 01:17
*/
#include<iostream>
#include<algorithm>
#include<climits>
#include<cstdio>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define IINF (INT_MAX)
#define MAX 31
using namespace std;
int H,W;
bool used[MAX][MAX];
char G[MAX][MAX];
int sp,mincost;
int dx[] = {0,1,0,-1};
int dy[]... |
The story of yesterday evening. After finishing the lecture at the university as usual and feeding the cats on campus, which is a daily routine, when I got home, people in work clothes were working on replacing the door of my house. .. That's not a particularly headache for me, but the brown door with the familiar keys... | #include <iostream>
#include <algorithm>
using namespace std;
int n;
int t[10001],s[10001];
int main(void){
while(cin>>n,n){
for(int i=0;i<n;i++) cin>>t[i];
for(int i=0;i<n;i++) cin>>s[i];
sort(s,s+n);
reverse(s,s+n);
bool flg = true;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(t[j] > 0){
... |
Example
Input
3
NNN
NNN
NNN
Output
Taro | #include <algorithm>
#include <bitset>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
#define rep(i, n) for (int64_t i = 0; i < (int64_t)(n); i++)
#define irep(i, n) ... |
Problem Statement
You bought 3 ancient scrolls from a magician. These scrolls have a long string, and the lengths of the strings are the same. He said that these scrolls are copies of the key string to enter a dungeon with a secret treasure. However, he also said, they were copied so many times by hand, so the string ... | #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"
... |
Dice Stamp
Dice stamp
At a local fair, you found a game store you've never seen before. This is a game in which N 6-sided dice are dropped and rolled on the board. More precisely, N buttons are tied to N dice on a one-to-one basis, and pressing the button causes the corresponding dice to fall onto the board. It is a ... | #include <bits/stdc++.h>
using namespace std;
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) repl(i,0,n)
#define INF INT_MAX/3
#define fi first
#define se second
typedef long long ll;
typedef pair<int, int> P;
struct dice{
int a[6];
};
void rot(int &a,int &b,int &c,int &d){
int tmp=a; a... |
D: Indecision-Indecision-
problem
Ebi-chan has been addicted to gal games lately, and her goal now is to capture two heroines at the same time.
Ebi-chan can use several events to increase her liking from the heroine, but only one heroine can be selected for each event. However, Ebi-chan does not forget to follow the... | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
#define INF 1<<30
#define LINF 1LL<<60
#define MAX_C 105
#define Min 10010
ll dp[MAX_C][Min];
int main() {
cin.tie(0); ios::sync_with_stdio(false);
ll N, C; cin >> N >> C;
vector<ll> a(N), b(N), ... |
C: Shuttle Run
Story
University H has a unique physical fitness test program, aiming to grow the mindset of students. Among the items in the program, shuttle run is well-known as especially eccentric one. Surprisingly, there are yokans (sweet beans jellies) on a route of the shuttle run. Greedy Homura-chan would like... | #include <bits/stdc++.h>
#define vi vector<int>
#define int long long
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(x) (x).begin(), (x).end()
using namespace std;
signed main()
{
int n, m;
cin >> n >> m;
vector<pair<int, int>> data(n * 2);
rep(i, n) {
int l, r;
cin >> l >... |
Problem statement
Modulo is very good at drawing trees.
Over the years, Modulo has drawn a picture of a tree with $ N $ vertices. The vertices of this tree are numbered from $ 1 $ to $ N $, and the vertices $ a_i $ and $ b_i $$ (1 \ leq i \ leq N-1) $ are directly connected by edges. All vertices are not yet painted.... | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
... |
Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique I... | // GRL_5_D Range Query on a Tree (heavy-light)
#include <algorithm>
#include <cmath>
#include <iostream>
#include <stack>
#include <vector>
#define MAXN 101000
using namespace std;
struct {
int to, wt, next;
} par[MAXN], E[MAXN];
int LE[MAXN];
struct Seg {
vector<int> v;
Seg(vector<int> &in) : v(pow(2, 1 + ... |
Problem description
It is winter super sale and all the shops have various offers. Suraj selected N items to buy and he is standing in the billing queue. It was then he noticed the offer "Buy two, get two". That means for every two items you buy, they give you two items for free. However, items can be of varying price,... | T = int(raw_input())
for t in range(T):
N = int(raw_input())
A = map(int, raw_input().split())
A.sort()
A = A[::-1]
B = []
for i in range(len(A)):
if i%4==0 or i%4==1:
B.append(A[i])
print sum(B) |
Chef has N simple polygons (non self intersecting polygons) in which no two of them intersect with each other. For any two polygons P1, P2, either P1 lies inside P2 or vice versa.
Chef wants you to count number of polygons lying strictly inside each of the polygons.
Input
First line of the input contains an integer T... | class One:
def __init__(self,index,x):
self.index=index
self.x=x
t=int(input())
for i in range(0,t):
list=[]
n=int(input())
for j in range(0,n):
p=int(input())
e1=One(j,0)
arr=raw_input().split()
for k in range(0,p):
if(k==0):
e1.x=int(arr[2*k])
elif(int(arr[2*k]) > e1.x):
e1.x=int(arr[2*k... |
An equation is an equality containing one or more variables. Solving the equation consists of determining which values of the variables make the equality true. In this situation, variables are also known as unknowns and the values which satisfy the equality are known as solutions. An equation differs from an identity i... | t=input()
for i in range(t):
n=input()
l=map(int,raw_input().split())
s=sum(l)/(n-1)
for x in l:
if(x!=l[len(l)-1]):
print s-x,
else:
print s-x |
Chef develops his own computer program for playing chess. He is at the very beginning. At first he needs to write the module that will receive moves written by the players and analyze it. The module will receive a string and it should report at first whether this string represents the correct pair of cells on the chess... | from re import match
def process(M):
test1 = match(r'^([a-h])([1-8])\-([a-h])([1-8])$', M)
if not test1: return 'Error'
M = test1.groups()
M = ord(M[0])-96, int(M[1]), ord(M[2])-96, int(M[3])
D = abs(M[0]-M[2]), abs(M[1]-M[3])
if D==(1,2) or D==(2,1): return 'Yes'
return 'No'
def main():
... |
The Chef's latest idea is that some cooks might work better in pairs. So, he is going to experiment by pairing up some of his employees to see if the quality of the food prepared in his kitchen increases. However, only some pairs of employees are compatible. Two employees that are not compatible cannot be paired togeth... | for _ in range(int(raw_input())):
n, m = map(int, raw_input().split())
a = []
t = []
ans =[]
for __ in range(m):
a.append([map(int, raw_input().split())])
a.reverse()
for i in range(len(a)):
for p, q in a[i]:
if p not in t and q not in t:
t.append(... |
Mr. Sreeniketan the owner of Madras Super Kings is a very superstitious owner. He believes that certain gestures help the team to perform well. Whenever the team enters the field , they form a huddle to discuss strategies. Sreeni wishes that they always stay in the same cyclic order that he instructs them to. So, if th... | t=input()
for k in range(t):
order=raw_input()
obs=raw_input()
obser=obs+obs
flag=False
for i in range(len(order)):
if order[0]==obser[i]:
if obser[i:i+len(order)]==order:
print "YES"
flag=True
break
if not(flag):
print ... |
There is a rectangular grid of size n × m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints:
* You can move to the right or to the bottom onl... | #include <bits/stdc++.h>
const long double eps = 0.00000001;
const long long MOD = 1e9 + 7;
const double PI = 3.141592653589793238463;
using namespace std;
long long ans, k;
int n, m;
long long a[25][25];
map<pair<pair<int, int>, long long>, long long> cnt;
int half;
bool isOK(int x, int y) {
if (x >= 1 && x <= n && ... |
At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector А:
* Turn the vector by 90 degrees clockwise.
* Add to the vector a certain vector C.
Operations could be performed in any order any number of times.
... | #include <bits/stdc++.h>
using namespace std;
int p, q;
int x, y;
bool possible(int x, int y) {
long long bm = 1LL * p * p + 1LL * q * q;
if (bm == 0) {
if ((x || y))
return false;
else
return true;
} else if ((((-1LL * p * x - 1LL * q * y) % bm) ||
((-1LL * q * x + 1LL * p * y) ... |
Vasya owns three big integers — a, l, r. Let's define a partition of x such a sequence of strings s_1, s_2, ..., s_k that s_1 + s_2 + ... + s_k = x, where + is a concatanation of strings. s_i is the i-th element of the partition. For example, number 12345 has the following partitions: ["1", "2", "3", "4", "5"], ["123",... | #include <bits/stdc++.h>
using namespace std;
const int N = 1000005, M = 1000005;
const long long MOD = 1e9 + 7;
const double eps = 1e-9;
int n, len[2], dp[N], sum[N], mod = 998244353;
char a[N], l[N], r[N];
vector<int> z[2];
string s[2];
vector<int> ZAlgorithm(string &s) {
int n = s.size();
vector<int> z(n);
int... |
You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to t... | #include <bits/stdc++.h>
using namespace std;
const int sz = 2e5 + 10;
vector<int> sv[sz];
pair<int, int> dp[sz], ve[sz], be = {0, 0}, an1, an2;
void dfs(int v, int pr) {
dp[v] = {0, 1}, ve[v] = {v, -1};
vector<pair<int, int> > sp;
for (int a = 0; a < sv[v].size(); a++) {
int ne = sv[v][a];
if (ne != pr) ... |
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are... | #include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 5;
vector<vector<long long>> edges;
long long par[N];
long long find(long long x) { return x == par[x] ? x : par[x] = find(par[x]); }
void unite(long long x, long long y) {
x = find(x);
y = find(y);
if (x != y) par[x] = y;
}
int main() {
lo... |
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).
If there are many such subsegments find the longest one.
Input
The first line contains single integer... | n=int(input())
s=[int(x) for x in input().split()]
el=max(s)
pos1=-1
pos2=-1
c=0
ans=0
for i in range(0,len(s)):
if(s[i]==el):
c=c+1
else:
ans=max(ans,c)
c=0
ans=max(ans,c)
print(ans)
|
You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.
Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, maxi = 0;
cin >> n;
vector<int> store[n + 1];
map<int, int> s, s1;
int x, y;
for (int i = 0; i < n; ++i) {
cin >> x >> y;
if (x != -1) store[x].push_back(i + 1);
s1[i + 1] = y;
if (y == 1) s[x]++;
}
vector<int> ans;
for ... |
This problem is same as the next one, but has smaller constraints.
It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system cons... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.... |
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor.
Heidi figured out that Madame Kovarian uses a... | from math import sqrt
def get_int():
from sys import stdin
return int(stdin.readline().replace('\n', ''))
def is_even(n):
return n%2 == 0
def heidi_hash(r):
k = r-1
rt = int(sqrt(k))
for x in range(1, rt+2):
if k % x == 0:
temp = k/x -x -1
if temp > 0 and is_e... |
You are on the island which can be represented as a n × m table. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are k treasures on the island, the i-th of them is located at the position (r_i, c_i).
Initially you stand at the lower left corner of the island, at the position (1, 1). I... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
const int inf = 2000000000;
const long long infLL = 9000000000000000000;
template <typename first, typename second>
ostream& operator<<(ostream& os, const pair<first, second>& p) {
return os << "(" << p.first << ", " << p.second << ")";
}
template... |
Alice became interested in periods of integer numbers. We say positive X integer number is periodic with length L if there exists positive integer number P with L digits such that X can be written as PPPP…P. For example:
X = 123123123 is periodic number with length L = 3 and L = 9
X = 42424242 is periodic number with... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long N = 200005;
vector<long long> vis(N);
vector<vector<long long>> adj(N);
void dfs(long long v) {
vis[v] = 1;
for (auto i : adj[v]) {
if (!vis[i]) {
dfs(i);
}
}
return;
}
bool isPrime(long long n) {
if ... |
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.
The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
long long lcm(long long a, long long b) { return a * (b / gcd(a, b)); }
const int N = 100005;
void solve() {
long long n;
cin >> n;
long long ans = n;
for (long long i = 2; i * i <= n; i+... |
A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.
Polycarp has n (2 ≤ n ≤ 10) bank cards, the PIN code of the i-th card is p_i.
Polycarp has recently read a recommendation that it is bette... | import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class PINCodesB extends PrintWriter {
//this trick improves performances
PINCodesB() {
super(System.out);
}
public static void main(String[] $) {
PINCodesB o = new PINCodesB();
... |
Kiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle, which led Kiwon to think about the following puzzle.
In a 2-dimension plane, you have a set s = \{(x_1, y_1), (x_2, y_2), …, (x_n, y_n)\} consisting of n distinct points. In the set s, ... | #include <bits/stdc++.h>
char _;
using namespace std;
inline bool cmp(const pair<int, int>& a, const pair<int, int>& b) {
if ((b.second < 0) ^ (a.second < 0))
return 1LL * a.first * b.second > 1LL * b.first * a.second;
return 1LL * a.first * b.second < 1LL * b.first * a.second;
}
inline bool eq(const pair<int, ... |
We define the sum of prefix sums of an array [s_1, s_2, ..., s_k] as s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + ... + (s_1 + s_2 + ... + s_k).
You are given a tree consisting of n vertices. Each vertex i has an integer a_i written on it. We define the value of the simple path from vertex u to vertex v as follows: conside... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 100;
const long long is_query = -(1LL << 62);
struct Line {
long long m, b;
mutable function<const Line*()> succ;
bool operator<(const Line& rhs) const {
if (rhs.b != is_query) return m < rhs.m;
const Line* s = succ();
if (!s) return 0;... |
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test c... | import java.util.*;
public class codeforces2{
public static char lowToUp(char x){
if(x>='A'&&x<='Z'){
int t=(int)x+32;
return (char)t;
}
return x;
}
public static boolean lucky(int x){
while(x!=0){
if((x%10)!=4&&(x%10)!=7)return false;
x=x/10;
}
return true;
}
public static int abs(int x){
if(x<0)re... |
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even.
He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh... | t=eval(input())
for j in range(t):
n=eval(input())
if n==2 :
print(2)
else:
sum=2
for i in range(1,n//2):
sum=sum+2**(i+1)
print(sum)
|
This is an easier version of the problem H without modification queries.
Lester and Delbert work at an electronics company. They are currently working on a microchip component serving to connect two independent parts of a large supercomputer.
The component is built on top of a breadboard — a grid-like base for a micr... | #include <bits/stdc++.h>
using namespace std;
int n, m, f[100510][2];
char ch[4][100510];
int main() {
scanf("%d%d%*d", &n, &m);
scanf("%s%s%s%s", ch[0] + 1, ch[1] + 1, ch[2] + 1, ch[3] + 1);
for (int i = 1; i <= m; i++) {
if (ch[2][i] == 'R')
f[1][1]++;
else
f[1][0]++;
}
if (ch[0][1] == '... |
One day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story:
Everybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are n trees and m magic mushrooms in the woods: the i-th tree grows at a ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5, maxm = 1e4 + 5, maxe = maxn * 4 + maxm,
maxp = 4 * maxe;
int n, m, b[maxe], id[maxe], tot, cnt, d;
double p[maxp], ans;
int read() {
int ret = 0, f = 1;
char ch = getchar();
while (ch > '9' || ch < '0') {
if (ch == '-') f = -f;
... |
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is e... |
import java.util.Scanner;
public class ClassA {
public static void main(String[] arges) {
Scanner in=new Scanner(System.in);
int T=in.nextInt();
while(T!=0) {
T--;
int n=in.nextInt();
int[] dp=new int[n];
for(int i=0;i<n;i++) {
dp[i]=in.nextInt();
}
for(int i=n-1;i>=0;i--) {
if(i%2==1... |
Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111.
Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well... | #include<bits/stdc++.h>
#include<string>
using namespace std;
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)
int main()
{
fastio;
string s;
int t,n;
cin>>t;
while(t--)
{
cin>>s;
n=s.size();
cout<<n<<"\n";
}
return 0;
}
|
The only difference between the two versions is that this version asks the minimal possible answer.
Homer likes arrays a lot. Today he is painting an array a_1, a_2, ..., a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, ..., a_n is described by an array b_1, b_2, ..., b_n that b_i ind... | #include <bits/stdc++.h>
#pragma GCC optimize(3)
#define int long long
#define ri register
#define mk make_pair
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define is insert
#define es erase
using namespace std; const int N=200010;
inline int read()
{
int s=0, w=1; ri char ch=getcha... |
Polycarp found a rectangular table consisting of n rows and m columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns":
* cells are numbered starting from one;
* cells are numbered from left to right by columns, and inside each column from top to bottom;
... | import java.util.*;
public class strangetable
{
public static void main(String[] args)
{
long t,n,m,x,r,c;;
Scanner sc=new Scanner(System.in);
t=sc.nextInt();
while(t-->0)
{
n=sc.nextLong();
m=sc.nextLong();
x=sc.nextLong();
x--;
r=x%... |
A sequence (b_1, b_2, …, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 ≤ i<j ≤ k, we have |a_i-a_j|≥ MAX, where MAX is the largest element of the sequenc... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
... |
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th... | n = int(input())
t = map(int,list(str(raw_input())))
l = t[:n]; r = t[n:]
l.sort(); r.sort()
f1,f2 = 0,0
for i in range(n):
if l[i] >= r[i]:
f1 = 1; break
for i in range(n):
if l[i] <= r[i]:
f2 = 1; break
print("YES" if f1+f2 < 2 else "NO")
|
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number ... | #include <bits/stdc++.h>
using namespace std;
long long po(long long x, long long n, long long mo) {
long long s = 1, m = x;
while (n) {
if (n & (long long)1) s = (s * m) % mo;
m = (m * m) % mo;
n >>= 1;
}
return (mo + s) % mo;
}
long long ou(long long x) {
long long ans = 1;
for (long long i = ... |
You are playing a video game and you have just reached the bonus level, where the only possible goal is to score as many points as possible. Being a perfectionist, you've decided that you won't leave this level until you've gained the maximum possible number of points there.
The bonus level consists of n small platfor... | #include <bits/stdc++.h>
using namespace std;
long long l[100005][2];
long long r[100005][2];
int x[100005];
int n;
int main() {
scanf("%d", &n);
n--;
for (int i = 0; i < n; ++i) {
scanf("%d", x + i);
}
for (int i = n - 1; i >= 0; --i) {
r[i][1] = (x[i] == 1) ? 0 : r[i + 1][1] + x[i] & (~1);
if (x... |
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.
During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of... | #include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1e5 + 20;
long long n;
long long vec[MAXN];
long long p[MAXN];
long long ans[MAXN];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (long long i = 0; i < n; i++) cin >> vec[i];
sort(vec, vec + n, greater<long long>());
... |
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n.
A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct.
There is only one thing Petya likes more than permutations: playing with little Masha... | #include <bits/stdc++.h>
using namespace std;
int q[110], a[110];
int p1[110][110];
int p2[110][110];
int main() {
int n, k, v1, v2;
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++) {
scanf("%d", &q[i]);
}
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
for (int i = 1; i <= n; i++) {
p... |
The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). You need to f... | import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
void randomShuffle(long[] arr) {
Random rnd = new Random();
for (int i = arr.length - 1; i >= 0; i--) {
int pos = rnd.nextInt(i... |
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 ... | #include <bits/stdc++.h>
using namespace std;
long long p[10000005];
int idxp;
int main() {
long long n;
int i, j;
long long countt = 0;
scanf("%I64d", &n);
if (n % 3 != 0)
printf("0\n");
else {
n = n / 3;
long long r = (long long)sqrt(n);
for (i = 1; i <= r; i++) {
if (n % i == 0) p[i... |
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all:
* 'U': go up, (x, y) → (x, y+1);
* 'D': go down, (x, y) → (x, y-1);
* 'L': go left... | #include <bits/stdc++.h>
using namespace std;
struct node {
int x;
int y;
node(int a, int b) : x(a), y(b) {}
node() : x(0), y(0) {}
};
bool operator<(const node &a, const node &b) {
return a.x == b.x ? a.y < b.y : a.x < b.x;
}
int main() {
map<char, int> dir;
dir['U'] = 0;
dir['D'] = 1;
dir['L'] = 2;
... |
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.
More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The ... | import sys
inputs = sys.stdin.readline().split()
n = int(inputs[0])
inputs = sys.stdin.readline().split()
l = [int(i) for i in inputs]
l.sort()
print l[-1],
for i in xrange(1,n-1,1):
print l[i],
print l[0]
|
Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers.
During the game the host takes num... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<bitset<102> > cards;
vector<int> size;
for (int i = 0; i < n; i++) {
int m, x;
cin >> m;
size.push_back(m);
bitset<102> aux;
for (int j = 0; j < m; j++) {
cin >> x;
aux[x] = true;
}
cards... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.