input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Xsquare loves to play with arrays a lot. Today, he has two arrays named as A and B. Each array consists of N positive integers.
Xsquare has decided to fulfill following types of queries over his array A and array B.
1 L R : Print the value of AL + BL+1 + AL+2 + BL+3 + ... upto R^th term.
2 L R : Print the value of... | n,q=map(int,raw_input().split())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
for i in range(2,n):
a[i]+=a[i-2]
b[i]+=b[i-2]
a.insert(0,0)
b.insert(0,0)
while(q>0):
t,l,r=map(int,raw_input().split())
al=0
ar=0
bl=0
br=0
if(t==1):
if(l%2==r%2):
if(l-2>=0):
al=l-2
ar=r
br=r-1
... |
Compute A \times B, truncate its fractional part, and print the result as an integer.
Constraints
* 0 \leq A \leq 10^{15}
* 0 \leq B < 10
* A is an integer.
* B is a number with two digits after the decimal point.
Input
Input is given from Standard Input in the following format:
A B
Output
Print the answer as ... | #include<bits/stdc++.h>
using namespace std;
int main() {
int64_t a,c;
double b;
cin>>a>>b;
c=(b+0.001)*100;
c=c*a/100;
cout<<c<<endl;
} |
Silver Fox is fighting with N monsters.
The monsters are standing in a row, and we can assume them to be standing on a number line. The i-th monster, standing at the coordinate X_i, has the health of H_i.
Silver Fox can use bombs to attack the monsters. Using a bomb at the coordinate x decreases the healths of all mo... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,n) for(int i=0;i<(n);i++)
int main(int argc, char const *argv[])
{
int n, d, a; cin >> n >> d >> a;
vector<pair<int, int>> v(n);
rep(i, n) {
int x, h; cin >> x >> h;
v[i] = make_pair(x, h);
}
sort(v.begin(), v.end());
ll ans =... |
For an integer N, we will choose a permutation \\{P_1, P_2, ..., P_N\\} of \\{1, 2, ..., N\\}.
Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.
Find the maximum possible value of M_1 + M_2 + \cdots + M_N.
Constraints
* N is an integer satisfying 1 \leq N \leq 10^9.
Input
Input is giv... | import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
long N = scan.nextInt();
long ans = 0;
for (int i = 1; i < N; i++) {
ans += i;
}
System.out.println(ans);
}
} |
A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.
Find the total number of biscuits produced within T + 0.5 seconds after activation.
Constraints
* All values in input are integers.
* 1 \leq A, B, T \le... | //台湾旅行中(Day 1)
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int B = sc.nextInt();
int T = sc.nextInt();
System.out.println( ((int)(T+0.5)/A) * B);
}
}
|
Takahashi and Aoki will play a game using a grid with H rows and W columns of square cells. There are N obstacles on this grid; the i-th obstacle is at (X_i,Y_i). Here, we represent the cell at the i-th row and j-th column (1 \leq i \leq H, 1 \leq j \leq W) by (i,j). There is no obstacle at (1,1), and there is a piece ... | #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ff first
#define ss second
vector<pair<int,int>> v;
signed main(){
int h, n, x = 0;
cin >> h >> n >> n;
v.resize(n);
for(auto& i: v)
cin >> i.ss >> i.ff;
sort(v.begin(),v.end());
for(auto p: v){
... |
You are given a set S of strings consisting of `0` and `1`, and an integer K.
Find the longest string that is a subsequence of K or more different strings in S. If there are multiple strings that satisfy this condition, find the lexicographically smallest such string.
Here, S is given in the format below:
* The data... | #include <iostream>
#include <cstdio>
using namespace std;
int ch[2][1 << 22], id[22][1 << 22], cnt, a[22][1 << 22], siz[22], c[22][1 << 22], num[22][1 << 22], ans[22], n, k;
char s[1 << 22];
inline int read()
{
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}... |
In a long narrow forest stretching east-west, there are N beasts. Below, we will call the point that is p meters from the west end Point p. The i-th beast from the west (1 ≤ i ≤ N) is at Point x_i, and can be sold for s_i yen (the currency of Japan) if captured.
You will choose two integers L and R (L ≤ R), and throw ... | #include <iostream>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <algorithm>
#include <complex>
#include <array>
using namespace std;
#define REP(i,n) for(int i=0; i... |
Snuke is buying a bicycle. The bicycle of his choice does not come with a bell, so he has to buy one separately.
He has very high awareness of safety, and decides to buy two bells, one for each hand.
The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively. Find the m... | print(sum(sorted([int(tok) for tok in input().split()])[:2])) |
There are two rectangles. The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B. The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.
Print the area of the r... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a=Integer.parseInt(scan.next());
int b=Integer.parseInt(scan.next());
int c=Integer.parseInt(scan.next());
int d=Integer.parseInt(scan.next(... |
There are N rabbits, numbered 1 through N.
The i-th (1≤i≤N) rabbit likes rabbit a_i. Note that no rabbit can like itself, that is, a_i≠i.
For a pair of rabbits i and j (i<j), we call the pair (i,j) a friendly pair if the following condition is met.
* Rabbit i likes rabbit j and rabbit j likes rabbit i.
Calculate ... | import java.util.Scanner;
public class Main {
static final int INF=Integer.MAX_VALUE; // 2147483647
static final long LINF=Long.MAX_VALUE; // 9223372036854775807
public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int as[] = new i... |
Read a set of coordinates of three different points P1 (x1, y1), P2 (x2, y2), Q (xq, yq) on the plane, and line symmetry with point Q with the straight line passing through point P1 point P2 as the axis of symmetry. Create a program that outputs the point R (x, y) at the position of. Note that the point Q is not on its... | #define _USE_MATH_DEFINES
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
using namespace std;
typedef long long ll;
int main(){
double x1,y1,x2,y2,xq... |
Housing maker Yamada House has launched a new featured product, a land for sale in a green home town with a rich environment such as schools and hospitals. This lot is divided into multiple lots and you can buy as many as you like, but the shape of the land with the lots you buy must be rectangular (including squares).... | //58
#include<iostream>
#include<algorithm>
using namespace std;
int x,y,n;
int a[16];
int g[10][10];
int dfs(int (*c)[10],bool (*u)[10]){
/*
for(int i=0;i<y;i++){
for(int j=0;j<x;j++){
cout<<c[i][j];
}
cout<<endl;
}
cout<<"---"<<endl;
*/
int s=0;
for(int i=0;i<y;i++){
for(int j... |
Hideyo has come by two aerial photos of the same scale and orientation. You can see various types of buildings, but some areas are hidden by clouds. Apparently, they are of the same area, and the area covered by the second photograph falls entirely within the first. However, because they were taken at different time po... | #include <bits/stdc++.h>
#define int long long
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
int w1, w2, h1, h2, sum;
int hash_a[800][800][13], hash_b[800][13];
int cumo_a[800][800][13], cumo_b[800][13];
char s[800][800],t[800][700];
void make_table(){
rep(i,h1) rep(j,w1-w2+1) {
rep(k,w2){
re... |
We arrange the numbers between 1 and N (1 <= N <= 10000) in increasing order and decreasing order like this:
1 2 3 4 5 6 7 8 9 . . . N
N . . . 9 8 7 6 5 4 3 2 1
Two numbers faced each other form a pair. Your task is to compute the number of pairs P such that both numbers in the pairs are prime.
Input
Input cont... | #include <iostream>
#include <vector>
using namespace std;
const int SIZE = 10000;
int main (int argc, char *argv[]) {
// make sieve
vector<bool> sieve(SIZE,true);
sieve[0] = false; sieve[1] = false;
for(int i = 2; i < SIZE; ++i) {
if (sieve[i]) {
for(int j = i+i; j < SIZE; j+=i) {
sieve[j] = false;
}
... |
Long long ago, there were several identical columns (or cylinders) built vertically in a big open space near Yokohama (Fig. F-1). In the daytime, the shadows of the columns were moving on the ground as the sun moves in the sky. Each column was very tall so that its shadow was very long. The top view of the shadows is s... | #include<cmath>
#include<cstdio>
#include<vector>
#include<algorithm>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
const double EPS=1e-11;
const double INF=1e77;
const double PI=acos(-1);
struct point{
double x,y;
point():x(0),y(0){}
point(double x,double y):x(x),y(y){}
point operator+(const poi... |
Taro attempts to tell digits to Hanako by putting straight bars on the floor. Taro wants to express each digit by making one of the forms shown in Figure 1.
Since Taro may not have bars of desired lengths, Taro cannot always make forms exactly as shown in Figure 1. Fortunately, Hanako can recognize a form as a digit i... | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int,... |
Given n numbers a0, a1, ..., an-1 and q.
I want you to perform appropriate processing for q queries.
The query has the following three types of operations.
* Shift the value
Given a pair of l and r. (l <r) Circular shift the value from al to ar.
0 1 2 3 4 5 6 7 8 9
Is given the query l = 2, r = 5.
The shifted numb... | #include <cstdlib>
#include <cassert>
#include <utility>
#include <tuple>
#include <ctime>
#include <cstdio>
#include <vector>
#define loop(i,a,b) for(int i=(a);i<int(b);i++)
#define rep(i,n) loop(i,0,n)
using namespace std;
#define np nullptr
struct Node {
int val;
Node * ch[2];
int pri, cnt, sum;
in... |
In 21XX, humanity finally began a plan to relocate to Mars. Selected as the first group of immigrants to Mars, you are assigned to the Administrative Center of Mars to deal with various problems that occur on Mars. The biggest problem at the moment of the Central Bureau is securing an independent supply and demand cycl... | #include<iostream>
#include<algorithm>
using namespace std;
const int MAX=101;
const int INF=(1<<21);
int main(){
int n,m;
int s,g1,g2;
int pipe[MAX][MAX];
while(1){
cin >> n >> m >> s >> g1 >> g2;
if(n==0 && m==0 && s==0 && g1==0 && g2==0) break;
for( int i=0;i<=n;i++ ) {
for( int j=0;j<=n;j++... |
A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who is trying to kill the princess is releasing a thug on the way to his wife.
You have already decided on a safe route to safely deliver the princess to the other country, but with the wish of the pr... | #include "bits/stdc++.h"
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2151&lang=jp
using namespace std;
typedef long long ll;
#define INF 1<<30
#define LINF 1LL<<62
struct edge {
int from, to;
int dist, cost;
edge() {}
edge(int from, int to, int dist, int cost) :from(from), to(to), dist(dist), cost(... |
Taro, a junior high school student, is working on his homework. Today's homework is to read Chinese classic texts.
As you know, Japanese language shares the (mostly) same Chinese characters but the order of words is a bit different. Therefore the notation called "returning marks" was invented in order to read Chinese ... | #include <iostream>
#include <fstream>
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <iomanip>
#include <map>
#include <numeric>
#include <queue>
#include ... |
You are the owner of a restaurant, and you are serving for N customers seating in a round table.
You will distribute M menus to them. Each customer receiving a menu will make the order of plates, and then pass the menu to the customer on the right unless he or she has not make the order. The customer i takes Li unit t... | #include <cstdio>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int n, m;
vector<int> sum;
int check(int x, int mid){
int t = x;
int mindif = INT_MAX;
int minindex = -1;
for(int k = 0; k < m; ++k){
int u = upper_bound(sum.begin(), sum.end(), sum[t] + mid)
- sum.begin() - ... |
Let w be a positive integer and p be a character string with a length of 22w + 1. (w, p) -A cellular automaton is as follows.
* An infinite number of cells that can take the state of 0 or 1 are lined up in one dimension.
* At time 0, Sunuke can choose any finite number of squares and set the state to 1. The remaining ... | #define _USE_MATH_DEFINES
#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <cfloat>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <time.h>
#i... |
Example
Input
3 9
6 3
5 2
3 1
2
2
2
Output
2 | import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, L = map(int, readline().split())
P = [list(map(int, readline().split())) for i in range(N)]
C = [int(readline()) for i in range(N)]
P.sort(key = lambda x: (x[0] - x[1]), reverse=1)
INF = 10**18
S = [0]*(N+1)
... |
H: Mercy
Santa Claus found a group doing programming even though it was Christmas.
Santa Claus felt sorry for them, so he decided to give them a cake.
There are $ N $ types of cream, and the taste is $ A_1, A_2, A_3, \ dots, A_N $.
There are $ M $ types of sponges, and the taste is $ B_1, B_2, B_3, \ dots, B_M $.
... | #include<bits/stdc++.h>
using namespace std;
int main(){
int n,m;cin>>n>>m;
long long s=0;
for(int i=0;i<n;i++){int x;cin>>x;s+=x;}
long long t=0;
for(int j=0;j<m;j++){int x;cin>>x;t+=x;}
cout<<(s*t)<<endl;
}
|
Problem
Satake doesn't like being bent.
For example, I don't like pencils, chopsticks, and bent-shaped houses, and I don't like taking actions such as turning right or left.
By the way, Satake who lives on the XY plane is $ N $ shops $ (X_ {1}, Y_ {1}), (X_ {2}, Y_ {2}), \ ldots, (X_ {N} , Y_ {N}) I was asked to shop... | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <utility>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
#define PI acos(-1.0)
int main() {
int n; cin >> n;
vector<pair<... |
For given two circles $c1$ and $c2$, print
4
if they do not cross (there are 4 common tangent lines),
3
if they are circumscribed (there are 3 common tangent lines),
2
if they intersect (there are 2 common tangent lines),
1
if a circle is inscribed in another (there are 1 common tangent line),
0
if ... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define F first
#define S second
#define pii pair<int, int>
#define eb emplace_back
#define all(v) v.begin(), v.end()
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep3(i, l, n) for (int i = l; i < (n); ++i)
#define chmax(a, b) a = (a >= b ? a... |
For given two sequneces $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$, determine whether all elements of $B$ are included in $A$. Note that, elements of $A$ and $B$ are sorted by ascending order respectively.
Constraints
* $1 \leq n, m \leq 200,000$
* $-1,000,000,000 \leq a_0 < a_1 < ... <... | #include <algorithm>
#include <iostream>
int main(int argc, char *argv[]) {
int n, m;
std::cin >> n;
long a[200001], b[200001];
for (int i = 0; i < n; ++i)
std::cin >> a[i];
std::cin >> m;
for (int i = 0; i < m; ++i)
std::cin >> b[i];
std::cout << std::includes(a, a + n, b, b + m) << std::endl;... |
Problem description.
Shyam has his computer science exam next week . He is solving one problem but he is not able to write the program
that for that . As a good programmer you thought that you will help so help him by writing a program that solves that problem .
The problem is that you have N boxes numbered from ... | from math import *
n = int(raw_input())
print factorial(2*n-1)/(factorial(n)*factorial(n-1)) |
Nikhil learnt two new commands pwd and cd on the first day of Operating Systems lab.
pwd - command displays the current working directory and,cd - changes the location of working directory.
If the cd parameter contains ".."(without quotes), that means to step one directory back.
The absolute path of directory is separa... | import re
#t test cases
t = int(raw_input())
for i in range(0,t):
#n command lines
n = int(raw_input())
path = "/"
for j in range(0,n):
com = raw_input()
#print "New command"
if com == "pwd":
#print current working d... |
The most important part of a GSM network is so called Base Transceiver Station (BTS). These transceivers form the areas called cells (this term gave the name to the cellular phone) and every phone connects to the BTS with the strongest signal (in a little simplified view). Of course, BTSes need some attention and techn... | noOfInputs = int(raw_input())
for x in range(noOfInputs):
varInput = int(raw_input())
flag = 0
while varInput:
varInput /= 5
flag += varInput
print flag |
The Little Elephant from the Zoo of Lviv is going to the Birthday Party of the Big Hippo tomorrow. Now he wants to prepare a gift for the Big Hippo.
He has N balloons, numbered from 1 to N. The i-th balloon has the color Ci and it costs Pi dollars. The gift for the Big Hippo will be any subset (chosen randomly, possi... | def fn():
n,m = map(int, raw_input().split())
tnum,tcost = [0 for i in range(41)], [0 for i in range(41)]
for i in range(n):
a,b = map(int, raw_input().split())
tnum[a]+=1
tcost[a]+=b
num, cost = [], []
for i in range(41):
if tnum[i]:
num.append(tnum[i])
... |
Who's interested in football?
Rayne Wooney has been one of the top players for his football club for the last few years. But unfortunately, he got injured during a game a few months back and has been out of play ever since.
He's got proper treatment and is eager to go out and play for his team again. Before doing that,... | t=input()
while t:
t-=1
n=input()
num=map(int,raw_input().split())
mini=1000001
max_diff=0
for i in num:
if i<mini:
mini=i
elif i>mini and i-mini>max_diff:
max_diff=i-mini
if max_diff==0:
print 'UNFIT'
else:
print max_diff |
You are given a string S of length N consisting only of 0s and 1s. You are also given an integer K.
You have to answer Q queries. In the i^th query, two integers Li and Ri are given. Then you should print the number of substrings of S[L, R] which contain at most K 0s and at most K 1s where S[L, R] denotes the substring... | def sumv(fr, to):
num = to - fr + 1
return (to + fr) * num / 2
t = int(raw_input())
for i in xrange(t):
n, k, q = map(int, raw_input().split())
s = raw_input().rstrip()
cnt = 0
c1 = 0
c0 = 0
far = [0 for x in xrange(n)]
for j in xrange(n):
while (c0 == k and s[j] == '0') or (... |
You are given a rooted undirected tree consisting of n vertices. Vertex 1 is the root.
Let's denote a depth array of vertex x as an infinite sequence [d_{x, 0}, d_{x, 1}, d_{x, 2}, ...], where d_{x, i} is the number of vertices y such that both conditions hold:
* x is an ancestor of y;
* the simple path from x t... | import java.io.*;
import java.util.*;
//http://codeforces.com/problemset/problem/1009/F
public class DominantIndicies {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
... |
Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence a_1, a_2, …, a_n of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.
Paul is very clever and knows that the essential thing is... | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main {
FastScanner in;
PrintWriter out;
private void solve() throws IOException {
int n = in.nextInt();
int[] a = new int[n];
... |
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.
In the city in which Alice and Bob live, the first metro line is being built. This metro line contains n stations numbered from 1 to n. Bob lives near the station with number 1, while Alice ... | import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(),s=sc.nextInt();
int[] arr = new int[n];
int[] brr = new int[n];
for(int i=0;i<n;i++){arr[i]=sc.nextInt();}
for(int i=0;i<n;i++){b... |
There is a house with n flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of n integer numbers a_1, a_2, ..., a_n, where a_i = 1 if in the i-th flat the light is on and a_i = 0 otherwise.
Vova thinks that people in the i-th flats are distur... | n = int(input())
A = [int(i) for i in input().split()]
V = []
for i in range(n-2):
if (A[i]==1 and A[i+1]==0 and A[i+2]==1):
V.append(i+1)
V.append(1000)
k = 0
l = 0
n = len(V)
for i in range(n):
if (V[i]-V[l] != 2):
d = i-l
k += (d+1)//2
l = i
print(k)
|
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vert... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
vector<int> graph[N];
int a[N];
int s[N];
void DFS(int u, int p) {
if (s[u] == -1) {
int best = INT_MAX;
for (int v : graph[u]) {
if (v != p) {
best = min(best, s[v]);
}
}
if (best == INT_MAX) {
best = s[p];
... |
Alyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
long long int h;
cin >> n >> h;
long long int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int sum = 0;
int count = 0;
for (int i = 0; i < n; i += 1) {
long long int sum = 0;
sort(a, a + i + 1);
for (int j = i; j >... |
Input
The input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive.
Output
Output "YES" or "NO".
Examples
Input
NEAT
Output
YES
Input
WORD
Output
NO
Input
CODER
Output
NO
Input
APRILFOOL
Output
NO
Input
AI
O... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<long long, long long>;
using pcc = pair<char, char>;
using pdd = pair<double, double>;
using pci = pair<char, int>;
using si = set<int>;
using s = string;
using seti = set<int>;
using useti = unordered_set<i... |
Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?
There are n stores numbered from 1 to n in Nlogonia. The i-th of these stores offers a positive integer a_i.
Each day among the last m days Dora bought a single integer from s... | #include <bits/stdc++.h>
using namespace std;
long long nMod = 1e9 + 7;
inline long long GCD(long long a, long long b) {
while (b != 0) {
long long c = a % b;
a = b;
b = c;
}
return a;
};
inline long long LCM(long long a, long long b) { return (a / GCD(a, b)) * b; };
int m, n, k;
vector<set<int>> st(5... |
The only difference between easy and hard versions is constraints.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
*... | #include <bits/stdc++.h>
const int SIZE = 200005;
struct BIT {
long long A[SIZE];
long long sum(int i) {
i++;
long long sum = 0;
while (i > 0) sum += A[i], i -= ((i) & -(i));
return sum;
}
void add(int i, long long k) {
i++;
while (i < SIZE) A[i] += k, i += ((i) & -(i));
}
};
int n, m;... |
The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version.
Polycarp is a very famous freelancer. His current rating is r units.
Some very rich customers asked him to complete some projects for their companies. To complete ... | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class F {
public static int r;
public static int m;
public static int[][] b;
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
... |
Alex decided to go on a touristic trip over the country.
For simplicity let's assume that the country has n cities and m bidirectional roads connecting them. Alex lives in city s and initially located in it. To compare different cities Alex assigned each city a score w_i which is as high as interesting city seems to A... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
template <class T>
bool set_max(T &a, const T &b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
bool set_min(T &a, const T &b) {
... |
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer.
For example,... | #include <bits/stdc++.h>
const long long INF = 2000000005;
const long long BIG_INF = 2000000000000000005;
const long long mod = 1000000007;
const long long P = 31;
const long double PI = 3.141592653589793238462643;
const double eps = 1e-9;
using namespace std;
vector<pair<long long, long long> > dir = {{-1, 0}, {0, 1},... |
Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n.
Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there ... | import java.io.*;
import java.util.*;
public class P604E {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] line = br.readLine().split(" ");
int[] p =... |
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry... | n=int(input())
for i in range(n):
m=int(input())
l=list(input())
p=[]
c=0
r=len(l)
for i in range(r):
if l[i]=="P":
c+=1
if i==r-1:
p.append(c)
if l[i]=="A":
p.append(c)
c=0
if len(p)!=1:
if p[0]==0:
print(max(p))
else:
p.pop(0)
print(max(p))
else:
print(0) |
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales.
However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a... | t = int (input ())
ans = []
for i in range (t):
day = 0
p = list (map (int, input ().split ()))
n, d = p #
flag = False
num = list (map (int, input ().split ()))
for k in range (1, n) :
while (num[k] > 0 and day + k <= d) :
num[0] += 1
num[k] -= 1
... |
Dreamoon is a big fan of the Codeforces contests.
One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing!
Based on this, you come up with the following problem:
There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi... | cycles = int(input())
def find_v(x, places):
places = set(places)
v = 0
i = 1
while True:
if i in places:
v = i
elif x > 0:
v = i
x -= 1
else:
break
i += 1
return v
results = []
for cycle in range(cycles):
n, x ... |
Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b.
For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1.
For example, f(7)=7,f(10)=2,f(35)=5.
... | t = int(input())
for _ in range(t):
n, k = map(int, input().split())
ans = n
for i in range(2, n + 1):
if n % i == 0:
ans += i
break
ans += 2 * (k - 1)
print(ans) |
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements... | import sys
import math
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def MI():
return map(int, sys.stdin.readline().split())
def SI():
return sys.stdin.readline().strip()
n,k = MI()
a = LI()
def check(mid,isEven):
ans = 0
for i in range(n):
if isEven... |
As Kevin is in BigMan's house, suddenly a trap sends him onto a grid with n rows and m columns.
BigMan's trap is configured by two arrays: an array a_1,a_2,…,a_n and an array b_1,b_2,…,b_m.
In the i-th row there is a heater which heats the row by a_i degrees, and in the j-th column there is a heater which heats the c... | #include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1e-11;
template <class T>
inline void ckmin(T& a, T b) {
a = min(a, b);
}
template <class T>
inline void ckmax(T& a, T b) {
a = max(a, b);
}
template <class T>
inline T sqr(T x) {
return x * x;
}
using uint = unsigned i... |
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion i... | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<string> data(n);
for (int i = 0; i <= 29; i++) {
long long tes = pow(2, i);
for (int j = 0; j < n; j++) {
if ((tes & a[j]) == tes) {
... |
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the ... | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
long long a, b, c, d;
cin >> a >> b >> c >> d;
if (a > b * c) {
cout << -1 << '\n';
... |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Pety... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.StringTokenizer;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.Math.floor;
import static java.lang.Math.c... |
A pair of positive integers (a,b) is called special if ⌊ a/b ⌋ = a mod b. Here, ⌊ a/b ⌋ is the result of the integer division between a and b, while a mod b is its remainder.
You are given two integers x and y. Find the number of special pairs (a,b) such that 1≤ a ≤ x and 1 ≤ b ≤ y.
Input
The first line contains a s... | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
while(t-->0) {
long x = in.nextInt(), y = in.nextInt();
long cnt ... |
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circl... | import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Abc {
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
long q=sc.nextLong();
ArrayList<Long> arr=prim... |
You are given a rooted tree. Each vertex contains a_i tons of gold, which costs c_i per one ton. Initially, the tree consists only a root numbered 0 with a_0 tons of gold and price c_0 per ton.
There are q queries. Each query has one of two types:
1. Add vertex i (where i is an index of query) as a son to some ver... | // Cutiepie is a hoe!
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize ("Ofast")
#pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
#include <bits/stdc++.h>
using namespace std;
#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void _... |
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string ... | #include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if (a < b) swap(a, b);
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int main() {
int a, b, c;
string s1, s2, s3, s4;
cin >> s1 >> s2;
a = ((int)s1.size()), b = ((int)s2.size());
c = gcd(a, b);
bool f = 1;
s3 = s1.sub... |
The Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.
To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scie... | #include <bits/stdc++.h>
using namespace std;
int n;
priority_queue<pair<int, int> > q;
vector<int> a[200020];
int cnt[200020];
vector<pair<int, int> > vt;
int main() {
scanf("%d", &n);
int ans = 0;
int sum = 0;
for (int i = 1; i <= n; ++i) {
int k, a1, x, y, m;
scanf("%d%d%d%d%d", &k, &a1, &x, &y, &m);... |
To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third mem... | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
int[] v;
boolean[] was;
int end;
void dfs(int v) {
while (true) {
was[v] = true;
if (this.v[v] == -1) {
... |
Mr. Bender has a digital table of size n × n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.
We'll consider the table rows numbered from top to bottom from 1 to n, and the columns — numbered from left to right f... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:100000000000")
bool ascending(int i, int j) { return (i < j); }
bool descending(int i, int j) { return (i > j); }
using namespace std;
int dp[5000][5000];
int A[5000];
int n, x, y, c;
bool f(unsigned long long level) {
unsigned long long ret = 0;
ret = (level... |
You've got a positive integer sequence a1, a2, ..., an. All numbers in the sequence are distinct. Let's fix the set of variables b1, b2, ..., bm. Initially each variable bi (1 ≤ i ≤ m) contains the value of zero. Consider the following sequence, consisting of n operations.
The first operation is assigning the value of... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 23;
int n;
int a[MaxN], b[MaxN];
vector<pair<int, int> > v[MaxN];
int u[1 << MaxN];
int main() {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
b[i] = 1 << i;
}
for (int k = 1; k < n; ++k) {
for (int i = 0; i < k; ++i)
for (i... |
Yaroslav likes algorithms. We'll describe one of his favorite algorithms.
1. The algorithm receives a string as the input. We denote this input string as a.
2. The algorithm consists of some number of command. Сommand number i looks either as si >> wi, or as si <> wi, where si and wi are some possibly empty strin... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1001001001;
const long long INFLL = 1001001001001001001LL;
template <typename T>
void pv(T a, T b) {
for (T i = a; i != b; ++i) cout << *i << " ";
cout << endl;
}
template <typename T>
void chmin(T& a, T b) {
if (a > b) a = b;
}
template <typename T>
v... |
Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.
Arithmetic progression is a sequence a1, a1 + d, a1 + 2d, ..., a1 + (n - 1)d, where a1 and d are any numbers.
Ge... | #include <bits/stdc++.h>
using namespace std;
int main() {
int a1[4];
for (int i = 0; i < 4; i++) cin >> a1[i];
bool a = 1, g = 1;
for (int i = 2; i < 4; i++) {
if (a1[i] - a1[i - 1] != a1[i - 1] - a1[i - 2]) a = 0;
if (a1[i] * 1.0 / a1[i - 1] != a1[i - 1] * 1.0 / a1[i - 2]) g = 0;
}
if (!a && !g)
... |
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ... | n, m = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
ans = 0
for i in range(len(a)):
if a[i] < 0:
ans += a[i]
m -= 1
if m == 0:
break
print(-1 * ans) |
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.
Each kangaroo can hold at most one kangaroo, and the kangaroo who is ... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, i, j, a[500005] = {0}, low, high, ans = 0;
cin >> n;
for (i = 1; i <= n; i++) cin >> a[i];
sort(a + 1, a + n + 1);
low = 1, high = (n / 2) + 1;
for (i = 1; i <= n / 2; i++) {
while (a[high] < 2 * a[i] && high < n) high++;
if (a[... |
The Minister for education is coming! Naturally, nobody wants to perform poorly in front of such a honored guest. However, two hours before the arrival it turned out that one of the classes has a malfunctioning lightbulb — for some reason it doesn't get enough energy. The solution was found quickly: all we've got to do... | #include <bits/stdc++.h>
using namespace std;
const int MAXM = 100005;
const long double eps = 1e-9;
int n, m, c = 0;
long double ax[MAXM], ay[MAXM], gx[MAXM], gy[MAXM], sx = 0, sy = 0;
bool check(long double a, long double b, long double c, long double d) {
if (b * d > 0) return 0;
return a + b * (c - a) / (b - d)... |
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member — Pavel. But since he was the wi... | import java.io.*;
public class main{
public static void main(String args[])throws IOException{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out));
String s[]=in.readLine().trim().split(" ");
i... |
DZY loves strings, and he enjoys collecting them.
In China, many people like to use strings containing their names' initials, for example: xyz, jcvb, dzy, dyh.
Once DZY found a lucky string s. A lot of pairs of good friends came to DZY when they heard about the news. The first member of the i-th pair has name ai, the... | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the ... |
There are n employees working in company "X" (let's number them from 1 to n for convenience). Initially the employees didn't have any relationships among each other. On each of m next days one of the following events took place:
* either employee y became the boss of employee x (at that, employee x didn't have a bos... | #include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m, numpackets;
vector<pair<int, int> > queries[N];
int ans[N];
vector<int> children[N];
vector<int> toremove[N];
vector<int> toadd[N];
set<int> nums[N];
bool done[N];
struct DSU {
int p[N];
DSU() {
for (int i = 0; i < N; ++i) p[i] = i;
... |
Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer.
So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α li... | #include <bits/stdc++.h>
using namespace std;
int n, a[1005];
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
double mx = (a[0] + 1) * 10.0, mi = a[0] * 10.0;
for (int i = 1; i < n; i++) {
mx = min(mx, (a[i] + 1) * 10.0 / (i + 1));
mi = max(mi, (a[i]) * 10.0 / (i + 1));
}... |
You are given an array of length n and a number k. Let's pick k non-overlapping non-empty subarrays of the initial array. Let si be the sum of the i-th subarray in order from left to right. Compute the maximum value of the following expression:
|s1 - s2| + |s2 - s3| + ... + |sk - 1 - sk|
Here subarray is a contiguou... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void chkmax(T &x, T y) {
x = x > y ? x : y;
}
template <typename T>
void chkmin(T &x, T y) {
x = x > y ? y : x;
}
const int INF = (1ll << 30) - 1;
template <typename T>
void read(T &x) {
x = 0;
bool f = 1;
char ch;
do {
ch = getchar();
... |
Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list co... | import java.util.PriorityQueue;
import java.util.Scanner;
public class Autocomplete {
public static void main (String args []) {
Scanner in = new Scanner(System.in);
String intr = in.next();
int nDic = in.nextInt();
PriorityQueue<String> dic = new PriorityQueue<String>();
f... |
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.
He wants to know how many subsequences of length three can be selected from a, so that they form a geometric p... | from collections import defaultdict
def geometric(k, lst):
d = defaultdict(int)
total = 0
for i, num in enumerate(lst):
if num % k == 0:
total += d[num // k, 2]
d[num, 2] += d[num // k, 1]
d[num, 1] += 1
return total
_, k = map(int, raw_input().spli... |
Recently Duff has been a soldier in the army. Malek is her commander.
Their country, Andarz Gu has n cities (numbered from 1 to n) and n - 1 bidirectional roads. Each road connects two different cities. There exist a unique path between any two cities.
There are also m people living in Andarz Gu (numbered from 1 to m... | #include <bits/stdc++.h>
using namespace std;
int N, i, j, T, level, subtree[100111], centroid[100111][20], nc, M, Q, ans[20];
vector<vector<int>> G;
vector<int> persons[100111];
set<int> ps, plist[100111][20];
bool vis[100111];
void dfs(int v, int p);
int find_centroid(int v, int sz);
void dfs2(int v, int p);
int main... |
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.
Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will ... | import java.util.*;
import java.io.*;
public class task610B {
FastScanner in;
PrintWriter out;
void solve(){
int n = in.nextInt();
int min=2000000001;
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i]=in.nextInt();
min = Math.min(min, a[i... |
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.
A young hacker Vasya disassembled the program and foun... | #Nearly Lucky
'''
a=list(map(str,input()))
l=0
for i in range(len(a)):
if(a[i]=='4' or a[i]=='7'):
l+=1
if(l==4 or l==7 or l==44 or l==47 or l==74 or l==77):
print("YES")
else:
print("NO")'''
#IQ Test
'''
a=int(input())
b=list(map(int,input().strip().split()))
e,o=[],[]
for i in range(len(b)):
i... |
Maria participates in a bicycle race.
The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.
Let's introduce a system of coordinates, directing the Ox axis from west to east, and th... | #include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
const int maxn = 1e3;
const int INF = 0x7fffffff;
const int mod = 1e9 + 7;
const double eps = 1e-7;
const double Pi = acos(-1.0);
inline int read_int() {
char c;
int ret = 0, sgn = 1;
do {
c = getchar();
} while ((c < '0' || c > '9') && c... |
After finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integers — the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column ... | m,n = map(int,raw_input().split())
ma = [0 for i in range(10)]
mb = [0 for i in range(10)]
for i in range(1,m+1):
ma[i%10]+=1
for i in range(1,n+1):
mb[i%10]+=1
res = ma[0]*(mb[0]+mb[5])
res+= ma[1]*(mb[9]+mb[4])
res+= ma[2]*(mb[3]+mb[8])
res+= ma[3]*(mb[2]+mb[7])
res+= ma[4]*(mb[1]+mb[6])
res+= ma[5]*(mb[0]+mb[... |
Tony Stark is playing a game with his suits (they have auto-pilot now). He lives in Malibu. Malibu has n junctions numbered from 1 to n, connected with n - 1 roads. One can get from a junction to any other junction using these roads (graph of Malibu forms a tree).
Tony has m suits. There's a special plan for each suit... | #include <bits/stdc++.h>
using db = double;
const int N = 100007;
const db eps = 1e-10, inf = 1e10;
int n, m, fa[N], dep[N], size[N], son[N], top[N], vis[N];
db ans = inf, t, c[N], ed[N];
struct line {
int x, id, o;
db t, c;
} b[N];
db cal(const line& x) { return dep[x.x] + (t - x.t) * c[x.id]; }
int operator<(cons... |
This is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in Pascal — flush(output).
In this problem you should guess an array a which is unknown for you. The only information you have initia... | #include <bits/stdc++.h>
const int N = 2e5 + 100, M = 1e6 + 100, second = 1e2 + 100;
const long long mod = 1e9 + 7, MOD = 1e9 + 9, Mod = 1e8;
const long long INF = 1e9, inf = 1e18;
const long double Pi = (22 * 1.0) / (7 * 1.0);
using namespace std;
long long n, a[N];
long long ask(int l, int r) {
long long x;
cout ... |
Santa Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string si having the same length n. We denote the beauty of the i-th string by ai. It can happen that ai is negative — that means that Santa doesn't find this s... | #include <bits/stdc++.h>
using namespace std;
void showpq(priority_queue<long long> pq) {
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
cout << "\n";
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
map<string, pair<priority_queue<long long>, priority_queue<long long>>> mp;
... |
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.
Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.
Limak recently learned how to jump. He can jump from a vertex to any verte... | #include <bits/stdc++.h>
const uint32_t MAX_K = 5;
int32_t k;
int64_t mod(int64_t a) {
a = a % k;
if (a < 0) {
a += k;
}
return a;
}
struct Vertex {
std::vector<Vertex *> edges;
Vertex *par;
uint64_t upCnt[MAX_K];
uint64_t upDist;
uint64_t downCnt[MAX_K];
uint64_t downDist;
Vertex() : par(null... |
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks.
<image>
There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the ... | #include <bits/stdc++.h>
using namespace std;
const int N = 300010;
int n, cnt;
int head[N], nex[N << 1], to[N << 1];
int val[N];
int ans = -0x3f3f3f3f, fans;
map<int, int> siz;
void addedge(int a, int b) {
nex[++cnt] = head[a];
head[a] = cnt;
to[cnt] = b;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= ... |
Karen has just arrived at school, and she has a math test today!
<image>
The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.
Th... | n = int(input())
p = list(map(int,input().split()))
MOD = 10**9+7
mode = 0
if n%4 == 3:
n-= 1
new = []
for i in range(n):
if mode == 0: new.append(p[i]+p[i+1])
else: new.append(p[i]-p[i+1])
mode = 1-mode
p = new
def calc0(p):
res = 0
ncr = 1
n = len(p)//2-1
for ... |
Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say... | #include <bits/stdc++.h>
using namespace std;
vector<int> a[300010], b[300010], v;
int d[300010];
bool vis[300010];
int dfs(int x) {
vis[x] = 1;
int nxt, tmp, i_have = 0;
for (int i = 0; i < a[x].size(); ++i) {
nxt = a[x][i];
if (!vis[nxt]) {
tmp = dfs(nxt);
if (tmp == 1) {
v.push_back... |
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≤ j ≤ m - n. Suppose, ci = ai - bi + j. Then f(j) = |c1 - c2 + c3 - c4... cn|. More formally, <image>.
Dr. Evil wants Ma... | #include <bits/stdc++.h>
using namespace std;
vector<long long> cand;
long long solve(long long goal) {
int indx = 0;
int minim = 0, maxim = ((int)(cand).size()) - 1;
while (minim <= maxim) {
int mid = (minim + maxim) / 2;
if (cand[mid] <= goal) {
minim = mid + 1;
indx = max(indx, mid);
} ... |
You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.
You have to find minimum k such that there exists at least one k-dominant character.
Input
The first line contains string s consisting of lowercas... | word = input()
n = len(word)
d,e = {},{}
for i in range(n):
if word[i] in d:
d[word[i]].append(i+1)
else:
e[word[i]] = 0
d[word[i]] = [i+1]
# print(d,e)
for i in d:
temp = d[i]
if len(temp)==1:
cnt = temp[0]
cnt = max(n-temp[0]+1,cnt)
e[i] = cnt
else:
... |
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n ... | from sys import maxsize
n = int(input())
arr = list(map(int,input().split()))
m = maxsize
res= maxsize
ind = []
for i in range(len(arr)):
if arr[i] < m:
m = arr[i]
ind = [i]
res=maxsize
elif arr[i] == m:
ind.append(i)
if ind[-1]-ind[-2] < res and len(ind) > 1:
... |
You are given a tree with n nodes (numbered from 1 to n) rooted at node 1. Also, each node has two values associated with it. The values for i-th node are ai and bi.
You can jump from a node to any node in its subtree. The cost of one jump from node x to node y is the product of ax and by. The total cost of a path for... | #include <bits/stdc++.h>
using namespace std;
void debug_out() { cerr << endl; }
template <typename H, typename... T>
void debug_out(H h, T... t) {
cerr << " " << (h);
debug_out(t...);
}
void read() {}
template <typename H, typename... T>
void read(H &h, T &...t) {
cin >> h;
read(t...);
}
template <typename H, ... |
Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin ... | #include <bits/stdc++.h>
using namespace std;
vector<string> v;
string s;
int used[105];
int main() {
memset(used, 0, sizeof(used));
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> s;
for (int i = 0; i < s.size(); i++) {
if (s[i] >= 'a') s[i] = s[i] - 32;
}
v.push_back(s);
}
cin... |
Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervi... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const int M = 1e7 + 10;
const int Mod = 1e9 + 7;
const int P = 1e7 + 10;
map<int, int> mp;
int cntmp = 0, maxv = 0, pri = 0;
int prime[P], minp[P];
bool vis[P];
void get_prime() {
minp[1] = 1;
for (int i = 2; i < P; i++) {
if (!vis[i]) {
... |
Akash singh is a student of Mathematics at Geekland University. These days he is busy with his girlfriend Jassi. On the other hand, Jassi don't like mathematics that much. One day, Jassi decided to find all the strings of length N (comprising only of characters from '0' to '9') having odd number of 0's.
For Example: 10... | modulo=(10**9)+9
t=input()
for i in range(t):
a=input()
print((pow(10,a,modulo)-pow(8,a,modulo))*pow(2,modulo-2,modulo))%modulo |
It has been truly said that love is not meant for everyone.
Let me introduce you to a very sad story of my friend Broken Amit. Yes several times he has been left heartbroken. Looking at his poor condition even God is pity on him. God has given Amit a very nice opportunity to Kiss as many girls as he likes .
There ar... | n=input()
love=map(int,raw_input().split())
decr=map(int,raw_input().split())
for i in range(len(decr)): decr[i]*=i
decr.sort()
decr.reverse()
tDecr=[0]*n
for i in range(len(decr)):
cDecr=0
tDec=0
for j in range(i):
tDec+=cDecr
cDecr+=decr[i]
tDecr[i]=tDec+(n-i)*cDecr
su=sum(love)*n-sum(tDecr)
print su |
Darshit is planning to celebrate the birthday of his friend, Diksha. There are two types of gifts that Diksha wants from Darshit: one is black and the other is white. To make her happy, Darshit has to buy B number of black gifts and W number of white gifts.
The cost of each black gift is X units.
The cost of every wh... | for tc in xrange(input()):
b,w=tuple(map(int,raw_input().split()))
x,y,z=tuple(map(int,raw_input().split()))
cost=0
if x<y+z:
cost+=b*x
else:
cost+=b*(y+z)
if y<x+z:
cost+=w*y
else:
cost+=w*(x+z)
print(cost)# your code goes here |
Alice and Bob are playing a game of coins. N coins are placed on the table in a row.
The game begins with Alice and afterwards they alternate the moves.
A valid move is defined as follows:
You pick one coin or two adjacent coins and remove them.
The game is over if anyone is not able to make any valid move, and th... | t = int(raw_input())
for i in range(0,t):
coins = int(raw_input())
print "Alice" |
Karan's mathematics professor has given him a lots of homework. Since he is busy preparing for September Easy Challenge, he needs your help.
Given two numbers, find the sum of prime numbers between them, both inclusive.
Input:
The first line contains the number of test cases T. Each test case contains two space sep... | import math
def is_prime(n):
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
n = 0
break
return n
t = int(raw_input())
for i in range(0, t):
s = raw_input()
s = s.split()
sum = 0
if int(s[1]) < 2:
sum = 0
if int(s[0]) < 2:
s[0] = "2"
... |
An infinite army of ants is marching on an infinite 2-D plane. Since ants are disciplined, here's how they march: each ant chooses exactly one x coordinate and moves along it in positive y direction, starting from (x, 0). There exists exactly one ant for each x coordinate on that plane and hence there are infinite ants... | n = int(raw_input())
l = []
for _ in range(n):
x,y,d = map(int,raw_input().split())
l.append((x,d))
l.sort(key=lambda x: x[0])
start,d = l.pop(0)
sum = d+1
last = start + d
for start,d in l:
if start > last:
sum += d+1
last = start + d
elif start <= last and start+d > last:
sum += start + d - last
last = st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.