input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
In a far away kingdom is the famous Lio Shan monastery. Gods constructed three diamond pillars on the monastery's lawn long ago. Gods also placed on one pillar n golden disks of different diameters (in the order of the diameters' decreasing from the bottom to the top). Besides, gods commanded to carry all the disks fro... | #include <bits/stdc++.h>
using namespace std;
const int fin = 0, maxn = 30;
int n, m;
int a[maxn];
vector<pair<int, int> > V;
void U(int p, int A, int B, int C) {
if (p > n) return;
U(p + 1, A, C, B);
for (int i = 0; i < a[p]; ++i) V.push_back(pair<int, int>(A, B));
U(p + 1, C, B, A);
}
void F(int p, int A, int... |
Aniruddha loves to code on HackerEarth. There are some type of problems which he likes the most.
Problems are tagged with non empty strings containing only 'H' or 'E' or both. But he likes the problems tagged with strings containing no consecutive E's. Given an integer N, find maximum number of problems Aniruddha may l... | arr=[]
sarr=[]
t=0
n=int(raw_input())
if(n>=1 and n<=1000000):
for i in range(n):
t=int(raw_input())
arr.append(t)
sarr.append(t)
sarr.sort()
d ={}
a =2
b=3
ans = a+b
j=0
for i in range(1,sarr[n-1]+1):
if(i>=1 and i<=1000000):
if(i==1):
while(j<n and sarr[j]==i):
d[1]=2
j=j+1
if(i==2... |
Its time for the Potions class. Harry absolutely HATES potions because he has to face mockery by the potions teacher Snape everytime he has a potions class. Snape never leaves any chance of insulting him in front of everyone.
Snape is not in a good mood today, which is not good for Harry. Snape challenges Harry to an... | import sys
t=int(sys.stdin.readline())
while t:
n,q=map(int,sys.stdin.readline().split())
s=raw_input().split()
cum=[]
cum2=[]
for i in range(0,n+1):
cum.append(0)
cum2.append(0)
for i in range(1,n+1):
cum[i]=cum[i-1] + int(s[i-1])
cum2[i]=cum2[i-1]+i*(int(s[i-1]))
for i in range(0,q):
w,x,y,z=map(int,... |
Yesterday while Omar was trying to learn English, he saw that there are letters repeated many times in words while some other letters repeated only few times or not repeated at all!
Of course anyone can memorize the letters (repeated many times) better than the letters repeated few times, so Omar will concatenate al... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
import string
n=int(raw_input())
for i in range(n):
d=dict(zip(string.ascii_lowercase, [0]*26))
s=raw_input()
for key in d.keys():
d[key]=s.count(key)
for z in sorted(d.items(),... |
Katoch, a notorious boy, is always keen about getting number 1. Given a number, he squares every digit of the number and adds to the result. He repeats the process until he gets a 1 digit number. Suppose he is given a number 82, he squares 8 & 2 individually and then add the result to make it 68. Then he continues with... | SQUARE = dict([(c, int(c)**2) for c in "0123456789"])
def is_happy(n):
s = set()
while (n > 1) and (n not in s):
s.add(n)
n = sum(SQUARE[d] for d in str(n))
return n == 1
T=int(raw_input())
case=1
while(T>0):
num=int(raw_input())
if is_happy(num)==1:
print 'Case #%d:YES'%case
else:
print 'C... |
While Omar was studying for Math lectures, he found the following problem.
Given 3 Integers N_1, N_2, N_3, count the number of common divisors which divide all of them.
Can you please help Omar in solving this problem, because he usually sleeps in lectures.
Input:
Given an integer T, which indicates the number o... | def factors(n):
return list(set(reduce(list.__add__,
([i, n//i] for i in range(1, long(n**0.5) + 1) if n % i == 0))))
for t in range(input()):
num=sorted(map(long,raw_input().split()))
fact=sorted(factors(num[0]),reverse=True)
flag=False
for d in fact:
flag=True
... |
Monk visits a magical place, Makizam. He is greeted by his old friend, Wiz. Wiz happy to see his old friend, gives him a puzzle.
He takes him to a room with N keys placed on the floor, the i'th key is of type Xi. The keys are followed by M chests of treasures, the i'th chest is of type Ci.
These chests give out gems ... | from fractions import gcd
def func(z,k,y2,ele):
gs=sum([n1 for m,n1 in zip(k,v) if gcd(ele,m)!=1])
z=[i for i in z if i!=ele]
k=[i if gcd(i,ele)==1 else 1 for i in k]
while y2-1:
max=0
lar=0
for i in z:
tot=sum([n1 for m,n1 in zip(k,v) if gcd(i,m)!=1])
... |
In the town of Pirates, Captain Jack is the best pirate. Captain Smith is jealous of Jack's popularity. So he challenged Jack to solve the following puzzle:
Given an array A, find the length of the largest contiguous sub-array such that the difference between any two consecutive elements in the sub-array is 1. Captain ... | n = input()
max = 1
c = 1
l = map(int,raw_input().strip().split())
for i in range(1,n):
if abs(l[i] - l[i-1]) == 1:
c+=1
if c > max:
max = c
else:
c = 0
print max+1 |
Its Diwali time and Little Roy's family is having a lot of guests. Guests come in families. Each guest family has M members. Roy's task is to serve sweets to them. Roy has N different sweets and each sweet has some specific sweetness level S and quantity Q.
Each guest family will give R rupees (as a token of gratitude... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
n= long(raw_input());
s=[long(0)]*1000001;
for i in range(0,n):
b,c=raw_input().split();
s[long(b)] = long(c);
m=long(raw_input());
r=long(0);
for i in range(9... |
Given a set S. Generate T, a set that contains all subsets of S minus the null set and calculate A, XOR sum of the set T.
S={1,2,3}
T={{1},{2},{3},{1,2},{1,3},{2,3} ,{1,2,3}}
A=XORiana of T .
XORiana of a set is defined as XOR of all the elements it contains.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
0 ≤ Array[i] ≤ 200
... | t=int(input());
for i in range(0,t):
n=int(input());
d=raw_input("");
d=d.split(" ");
Y=0;
if(len(d)==1):
Y=int(d[0]);
print Y |
Today, Vasya has decided to study about Numbers and Number Theory. One of her good friends Kolya is very good at the subject. To help her, he kept the following task in front of Vasya:
Given an array A of size N, Vasya needs to find the size of the Largest Good Subset. A Subset is considered to be good, if for any pa... | def size_good_subset(arr,n):
c= [1 for i in range(n)]
for i in range(n):
j = n - 1 -i
maxCount = 1
for k in range(j+1,n):
if (arr[k] % arr[j] == 0) and (maxCount <= c[k]):
maxCount = c[k] + 1
c[j] = maxCount
print max(c) if max(c)!=1 else -1
#Array size
n = input()
array = map(int,raw_input().split... |
We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i.
How many squares i satisfy both of the following conditions?
* The assigned number, i, is odd.
* The written integer is odd.
Constraints
* All values in input are integers.
* ... | #include<iostream>
using namespace std;
int main(){
long long n,sum=0;
cin>>n;
long long arr[n+1];
for(long long i=1;i<=n;i++){
cin>>arr[i];
if(i%2!=0&&arr[i]%2!=0){
sum++;
}
}
cout<<sum;
} |
Given is a positive integer N. Find the number of permutations (P_1,P_2,\cdots,P_{3N}) of (1,2,\cdots,3N) that can be generated through the procedure below. This number can be enormous, so print it modulo a prime number M.
* Make N sequences A_1,A_2,\cdots,A_N of length 3 each, using each of the integers 1 through 3N ... | #include <bits/stdc++.h>
using namespace std;
const int maxN = 6005;
int n, mod;
int fac[maxN + 1], inv[maxN + 1];
int f[maxN + 1][maxN * 2 + 1];
inline int ADD(int x, int y) { return x + y >= mod ? x + y - mod : x + y; }
inline int mpow(int a, int x)
{
int ans = 1;
while(x)
{
if(x & 1) ans = 1ll * ans * a % m... |
Given is a string S of length N-1. Each character in S is `<` or `>`.
A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1):
* If S_i= `<`: a_i<a_{i+1}
* If S_i= `>`: a_i>a_{i+1}
Find the minimum possible sum of the ele... | #include <iostream>
#include <vector>
using namespace std;
using ll=long long;
int main() {
string S; cin>>S;
int N=S.size();
vector<int> A(N+1);
for(int i=0; i<N; i++){
if(S.at(i)=='<') A.at(i+1)=A.at(i)+1;
}
for (int i=N-1; i>=0; i--){
if(S.at(i)=='>' && A.at(i)<=A.at(i+1)) A.at(i)=A.at(i+1)+1;
... |
There are N integers, A_1, A_2, ..., A_N, written on a blackboard.
We will repeat the following operation N-1 times so that we have only one integer on the blackboard.
* Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.
Find the maximum possible value of the... | #include <iostream>
#include <utility>
#include <algorithm>
#include <vector>
using namespace std;
int n, a[100010], p, q;
vector<pair<int,int>> op;
int main(){
cin >> n;
p = 0;
for (int i = 0; i < n; ++i){
cin >> a[i];
if (a[i] >= 0) p++;
}
q = n - p;
if (p == 0){p++; q--;}
if (q == 0){p--; q++;}
sort(a,... |
In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0. You are given a sequence h=\\{h_1,h_2,h_3,......\\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:
* Specify integers... | n = int(input())
h = list(map(int,input().split()))
ans = h[0]
for i in range(1,n):
if h[i-1] < h[i]:
ans += h[i]-h[i-1]
print(ans) |
The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:
* 1 ≤ i < j < k ≤ |T| (|T| is the length of T.)
* T_i = `A` (T_i is the i-th character of T from the beginning.)
* T_j = `B`
* T_k = `C`
For example, when T = `ABCBC`, there are three triples of... | s=input()
n=len(s)
dp=[4*[0]for i in range(n+1)]
dp[0][0]=1
for i in range(1,n+1):
for j in range(4):
dp[i][j]+=dp[i-1][j]*((s[i-1]=="?")*2+1)
if s[i-1] in "A?":dp[i][1]+=dp[i-1][0]
if s[i-1] in "B?":dp[i][2]+=dp[i-1][1]
if s[i-1] in "C?":dp[i][3]+=dp[i-1][2]
for j in range(4):dp[i][j]%=10**9+7
#for i in ... |
You went shopping to buy cakes and donuts with X yen (the currency of Japan).
First, you bought one cake for A yen at a cake shop. Then, you bought as many donuts as possible for B yen each, at a donut shop.
How much do you have left after shopping?
Constraints
* 1 \leq A, B \leq 1 000
* A + B \leq X \leq 10 000
* ... | import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println((x-a)%b);
}
}
|
You are playing the following game with Joisino.
* Initially, you have a blank sheet of paper.
* Joisino announces a number. If that number is written on the sheet, erase the number from the sheet; if not, write the number on the sheet. This process is repeated N times.
* Then, you are asked a question: How many numbe... | N = input()
S = set()
for i in xrange(N):
a = int(raw_input())
if a in S:
S.discard(a)
else:
S.add(a)
print len(S)
|
Squid loves painting vertices in graphs.
There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1.
Squid performed Q operations on th... | import java.io.*;
import java.util.*;
import java.math.*;
// import java.awt.Point;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
static int mod = 1_000_000_007;
// int mod = 998244353;
long inf = Long.MAX_VALUE/2;
ArrayList<Integer>[] edge;
int n, m;
i... |
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including t... | import java.util.Scanner;
public class Main {
static String map[][];
static boolean used[][];
static int h, w;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
h = sc.nextInt();
w = sc.nextInt();
map = new String[h][];
used = new boolean[h][w];
for(int i = 0;i < h;i++){
... |
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separate... | word_list = input().split(' ')
word_dict = {}
longest_word_len = 0
longest_word = ''
high_freq_word_num = 0
for word in word_list:
if longest_word_len < len(word):
longest_word_len = len(word)
longest_word = word
if word not in word_dict:
word_dict[word] = 1
else :
word_... |
The courier charges for a courier company are set according to size and weight as shown in the table below.
A size | B size | C size | D size | E size | F size
--- | --- | --- | --- | --- | --- | ---
Size | 60 cm or less | 80 cm or less | 100 cm or less | 120 cm or less | 140 cm or less | 160 cm or less
Weight | 2kg o... | #include <iostream>
#define A 600
#define B 800
#define C 1000
#define D 1200
#define E 1400
#define F 1600
#define Z 0
using namespace std;
int rmn_max( int x, int y ){
return x > y ? x : y;
}
int main(){
int n;
while( 1 ){
cin >> n;
if( !n ){ return 0; }
int cost = 0;
for( int i = 0; i <... |
Countless lithographs have been found in the ruins of the ancient nation Iwashiro. Researchers have found that each lithograph has one word engraved on it. However, due to many years of weathering, some lithographs are difficult to decipher for the following reasons.
* Only one letter of a word written on a lithograph... | #include <cstdio>
#include <cstdint>
#include <vector>
#include <algorithm>
#include <string>
struct cmp {
size_t k;
cmp(size_t k): k(k) {}
bool operator ()(std::string const& s, std::string const& t) const {
return s.compare(0, k, t, 0, k) < 0;
}
};
int main() {
size_t n, m;
scanf("%zu %zu", &n, &m)... |
Do you know Just Odd Inventions? The business of this company is to "just odd inventions". Here, it is abbreviated as JOI.
JOI is conducting research to confine many microorganisms in one petri dish alive. There are N microorganisms to be investigated, and they are numbered 1, 2, ..., N. When each microorganism is tra... | #include<bits/stdc++.h>
#define x first
#define y second
using namespace std;
pair<int,int> a[300010],c;
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > Q;
int main(){int n,r=0;cin>>n;for(int i=0;i<n;i++)cin>>a[i].x>>a[i].y;sort(a,a+n);long long s=0;for(int i=0;i<n;i++){s+=a[i].x,c.x=a[i].... |
Spring is the time for school trips. The University of Aizu Elementary School (Aizu University and Small) also had a plan for a school trip next year. It is a tradition to travel by train on school trips. This is because there are few opportunities to use the train in Aizuwakamatsu city.
However, the teachers were tro... | #include <stdio.h>
#include <algorithm>
#include <utility>
#include <functional>
#include <cstring>
#include <queue>
#include <stack>
#include <cmath>
#include <iterator>
#include <vector>
#include <string>
#include <set>
#include <iostream>
#include <random>
#include <map>
#include <iomanip>
#include <stdlib.h>
#inclu... |
You have just been put in charge of developing a new shredder for the Shredding Company. Although a ``normal'' shredder would just shred sheets of paper into little pieces so that the contents would become unreadable, this new shredder needs to have the following unusual basic characteristics.
* The shredder takes as ... | #include<bits/stdc++.h>
#define range(i,a,b) for(int i = (a); i < (b); i++)
#define rep(i,b) for(int i = 0; i < (b); i++)
#define all(a) (a).begin(), (a).end()
#define debug(x) cout << "debug " << x << endl;
const int INF = 100000000;
using namespace std;
string s, ans_str;
int n, ans_num;
bool f[8];
map<int, int> m;
... |
Example
Input
0 3 1 7 5 9 8 6 4 2
7 0 9 2 1 5 4 8 6 3
4 2 0 6 8 7 1 3 5 9
1 7 5 0 9 8 3 4 2 6
6 1 2 3 0 4 5 9 7 8
3 6 7 4 2 0 9 5 8 1
5 8 6 9 7 2 0 1 3 4
8 9 4 5 3 6 2 0 1 7
9 4 3 8 6 1 7 2 0 5
2 5 8 1 4 3 6 7 9 0
Output
0 | #include <cmath>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int number[10];
int table[15][15];
bool check(int x)
{
for (int i = 4; i >= 1; --i)
number[i] = x % 10, x /= 10;
number[5] = 0; // check number
for (int i = ... |
Problem
A graph is given in which N vertices, each numbered from 1 to N, are connected by N-1 undirected edges. For each vertex, output the shortest number of steps to start from that vertex and visit all vertices.
However, one step is to follow one side from one vertex and move to another vertex.
Constraints
* 2 ≤... | #include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)... |
You are playing a puzzle game named petoris. It is played with a board divided into square grids and square tiles each of which fits to a single grid.
In each step of the game, you have a board partially filled with tiles. You also have a block consisting of several tiles. You are to place this block somewhere on the ... | import java.util.LinkedList;
import java.util.Scanner;
//Petoris
public class Main{
class R{
int h, w;
LinkedList<LinkedList<Character>> p;
public R(char[][] m) {
p = new LinkedList<LinkedList<Character>>();
for(int i=0;i<m.length;i++){
LinkedList<Character> l = new LinkedList<Character>();
for(i... |
I'm traveling to a country with a rabbit. There are n cities in this country numbered from 1 to n, and the rabbit is now in city 1. City i is a point on the coordinate plane (xi, yi) ).
Rabbits travel to meet the following conditions.
* The travel path is a polygonal line, each part of which must be a line segment co... | #include <iostream>
#include <vector>
#include <cmath>
#define EPS 1.0e-9
#define inf 1000000000
using namespace std;
struct edge{
int toi, toj;
double cost;
edge(int a, int b, double c){
toi = a, toj = b, cost = c;
}
};
int n;
double r, th;
int x[25], y[25];
vector<edge> G[25][25];
double dp[10005][25][25];
d... |
Second Problem B War
2D enthusiasts (2D Respecters) from R University will participate in a programming training camp held at Atsu University. In this training camp, participants bring their own programming problems and use them for practice. This year, the 2D Respecters ran for the questioner of question B, who can e... | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cst... |
B --Doctor Course Is Recommended / D How about going forward?
Story
Since the person D decided to advance to D, he decided to take the entrance examination for the doctoral program. The written test was in mark sheet format. Since all the questions were in his area of expertise, D was able to quickly come up with a... | /*
* 2576.cc: Doctor Course Is Recommended
*/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#i... |
Example
Input
3 2
R1
Output
3 1 2
4 5 6
7 8 9 | #include<iostream>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<functional>
#include<stack>
#include<queue>
#include <iomanip>
#include<map>
#include<limits>
#include<cmath>
#include<algorithm>
#include<bitset>
#include<utility>
#include<complex>
#include<cstdlib>
#include<set>
#include... |
A: Many Kinds of Apples
Problem Statement
Apple Farmer Mon has two kinds of tasks: "harvest apples" and "ship apples".
There are N different species of apples, and N distinguishable boxes. Apples are labeled by the species, and boxes are also labeled, from 1 to N. The i-th species of apples are stored in the i-th bo... | #include<bits/stdc++.h>
using namespace std;
int a[1005];
int c[1005];
int main(){
int n;
cin >> n;
for(int i = 1; i <= n;i++){
cin >> c[i];
}
int q;
cin >> q;
while(q--){
int t,x,d;
cin >> t >> x >> d;
if(t == 1){
a[x] += d;
if(a[x] > ... |
Problem
There is a grid of $ N \ times N $ cells. Initially all cells are white. Follow the steps below to increase the number of black squares.
Select one white cell from the cells that are even-numbered from the top and even-numbered from the left. The selected square turns black. Further, the adjacent white square... | #include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <cstdlib>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Sum2D {
vector<vector<ll>> b;
Sum2D() {};
Sum2D(const vector<vector<ll>>& a) {
int H = a.size(), W = a[0].size();... |
We want to encode a given string $S$ to a binary string. Each alphabet character in $S$ should be mapped to a different variable-length code and the code must not be a prefix of others.
Huffman coding is known as one of ways to obtain a code table for such encoding.
For example, we consider that appearance frequencyc... | #include <bits/stdc++.h>
//typedef
//-------------------------#include <bits/stdc++.h>
const double pi = 3.141592653589793238462643383279;
using namespace std;
//conversion
//------------------------------------------
inline int toInt(string s)
{
int v;
istringstream sin(s);
sin >> v;
return v;
}
template <c... |
Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.
Constraints
* $0 < n \leq 10000$
* $-1000000 \leq a_i \leq 1000000$
Input
In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in... | #include<iostream>
#define MAX 1000000;
using namespace std;
int main()
{
int t;
long min=MAX;
long max=-MAX;
long sum=0;
int n;
cin>>n;
for(int i=0;i<n;i++){
std::cin>>t;
if(min > t) min = t;
if(max < t) max = t;
sum = sum + t;
}
cout<<min<<" "<<max<<" "<<sum<<endl;
return 0;
} |
Yesterday Chef had a great party and doesn't remember the way he celebreated it. But he found a strange paper in his kitchen containing n digits (lets give them indices from 1 to n and name them a1, a2 ... aN).
Chef remembers that he played such game:
On each step he choose an index x from 1 to n.
For all indices ... | [n, m] = [int(x) for x in raw_input().split(" ")]
a = raw_input().rstrip()
digits = [int(x) for x in a]
L = len(a)
# construct
p = [[0]*L for _ in range(10)]
for i, x in enumerate(digits):
p[x][i] = 1
for i in range(1, L):
for j in range(10):
p[j][i] += p[j][i-1]
for _ in range(m):
t = int(raw_inp... |
One day, Chef prepared D brand new dishes. He named the i-th dish by a string Si. After the cooking, he decided to categorize each of these D dishes as special or not.
A dish Si is called special if it's name (i.e. the string Si) can be represented in the form of a double string by removing at most one (possibly zero... | def is_subseq(x, y):
i = 0
for c in x:
while i < len(y) and y[i] != c: i += 1
if i == len(y): return False
i += 1
return True
for cas in xrange(input()):
a = raw_input()
n = len(a)
print 'YES' if n > 1 and (is_subseq(a[:n/2], a[n/2:]) or is_subseq(a[(n+1)/2:], a[:(n+1)/2... |
When
displaying a collection of rectangular windows, a critical step is determining
whether two windows overlap, and, if so, where on the screen the overlapping
region lies. Write a program to perform this function. Your program will accept
as input the coordinates of two rectangular... | print "80 20 100 60"
print "No Overlap" |
XOXO likes to play with numbers.So,given a number N help XOXO to find whether it is a fibonacci number or not.It won't be hard!
Input
First line contains T denoting the number of test case.
The next T line contains an integer N
Output
For every test case print(without quotes) "Yes" if N is a fibonacci number else o... | list=[]
list.append(0)
list.append(1)
for i in range (2,5000):
list.append(list[i-1]+list[i-2])
t=int(raw_input())
while(t):
n=int(raw_input())
if n in list:
print "Yes"
else:
print "No"
t-=1 |
Majin wants to label his N (1 ≤ N ≤ 1,000,000) towers. He has lost the labels with the digit L (0 ≤ L ≤ 9) written on them. Assume he has sufficient labels to complete the task.
If the towers are labeled with the smallest set of N positive integers that don't have the digit L, what is the largest number that Majin wil... | def calc2(n):
tp=n
s=''
while tp>0:
k=tp%9
if(k==0):
k=9
s=str(k)+s
tp=(tp-k)/9
return int(s)
def calc1(n,d):
di=dict()
for i in range(0,9):
if i<d:
... |
Chef has decided to arrange the free shuttle service for his employees. City of Bhiwani has a strange layout - all of its N shuttle boarding points are arranged in a circle, numbered from 1 to N in clockwise direction. Chef's restaurant is at boarding point number 1. There is a single ring road that runs over the circu... | def init_primes(n):
primes = []
is_prime = [True] * n
is_prime[0] = False
is_prime[1] = False
for i in xrange(2, n):
if not is_prime[i]:
continue
for j in xrange(i * i, n, i):
is_prime[j] = False
primes = [i for i in xrange(n) if is_prime[i]]
return p... |
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ... | #include <bits/stdc++.h>
using namespace std;
long long n, d, c;
long a[105];
int main() {
cin >> n >> d;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 1; i < n; i++) {
if (a[i] - a[i - 1] == 2 * d)
c++;
else if (a[i] - a[i - 1] > 2 * d)
c += 2;
}
return cout << c + 2, 0;... |
Consider a table of size n × m, initially fully white. Rows are numbered 1 through n from top to bottom, columns 1 through m from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 115) — th... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const double EPS = (1e-9);
void carrotiq() {}
void fast() {
std::ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
}
int main(int argc, char const *argv[]) {
fast();
carrotiq();
int n, m;
cin >> n >> m;
vector<pair<in... |
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a num... | #include <bits/stdc++.h>
using namespace std;
int a[210000], len, b[410000], p[410000];
int as[210000], aslen;
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
len = 0, b[++len] = -2;
for (int i = 1; i < n; i++) b[++len] = a[i + 1] - a[i], b[++len] = -1;
b[len] ... |
Elections in Berland are coming. There are only two candidates — Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
... | #include <bits/stdc++.h>
using namespace std;
bool compare(const long long& a, const long long& b) { return a > b; }
int main() {
int n;
cin >> n;
vector<long long> A;
vector<long long> B;
vector<long long> AB;
vector<long long> NN;
;
string str;
long long pt;
for (int i = 0; i < n; ++i) {
cin >... |
There are n students in a university. The number of students is even. The i-th student has programming skill equal to a_i.
The coach wants to form n/2 teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equa... | #include <bits/stdc++.h>
template <typename T>
void swap(T &l, T &r) {
T tmp = l;
l = r;
r = tmp;
}
template <typename T>
void bubble_sort(std::vector<T> &vct) {
for (int i = 0; i != vct.size(); ++i) {
for (int j = 0; j != vct.size() - 1; ++j) {
if (vct[j] > vct[j + 1]) {
swap(vct[j], vct[j + ... |
You are given two integers l and r.
Let's call an integer x modest, if l ≤ x ≤ r.
Find a string of length n, consisting of digits, which has the largest possible number of substrings, which make a modest integer. Substring having leading zeros are not counted. If there are many answers, find lexicographically smalles... | #include <bits/stdc++.h>
using namespace std;
const int sigma = 10;
int main() {
do {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
} while (false);
string L, R;
cin >> L >> R;
int n, m = 0;
cin >> n;
reverse(L.begin(), L.end());
L.resize(R.size(), '0');
reverse(L.begin... |
Let's denote that some array b is bad if it contains a subarray b_l, b_{l+1}, ..., b_{r} of odd length more than 1 (l < r and r - l + 1 is odd) such that ∀ i ∈ \{0, 1, ..., r - l\} b_{l + i} = b_{r - i}.
If an array is not bad, it is good.
Now you are given an array a_1, a_2, ..., a_n. Some elements are replaced by -... | #include <bits/stdc++.h>
using namespace std;
long long mpow(long long x, long long y, long long m) {
long long res = 1;
while (y > 0) {
if (y & 1) res = res * x % m;
y = y >> 1;
x = x * x % m;
}
return res;
}
void solve() {
long long n, k;
cin >> n >> k;
long long a[n], dp[n + 1][2];
for (l... |
n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i an... | #include <bits/stdc++.h>
const int maxn = 3e5 + 7;
const int inf = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
using namespace std;
long long a[maxn], b[maxn];
int main() {
long long n, m, sum = 0;
scanf("%lld%lld", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%lld", a + i);
sum += a[i] * m;
}
for (in... |
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in n ⋅ m colored pieces that form a rectangle with n rows and m columns.
The colored pieces attracted Innokenty's attention so he immediately came up with the ... | #include <bits/stdc++.h>
using namespace std;
const int mn = 1005;
const int mod = 1e9 + 7;
int n, m;
int ans;
char s[mn][mn];
int up[mn][mn];
int down[mn][mn];
bool vis[mn][mn];
void draw(int x0, int x1, int y0, int y1) {
for (int i = x0; i <= x1; i++)
for (int j = y0; j <= y1; j++) vis[i][j] = 1;
}
inline int d... |
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...
To prepare for the exam, one has to study proofs of n theorems... | #include <bits/stdc++.h>
using namespace std;
int n, k, q;
int a[111];
bool checked[111];
double curMin = 999.99;
double curMax = -99.99;
int infoCount = 0;
void evaluate() {
int lim = n / k;
int tmp[111];
for (int i = 0; i < lim; i++) scanf("%d", &tmp[i]);
if (checked[tmp[0]]) return;
infoCount++;
double c... |
You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n.
You have to connect all n rooms to the Internet.
You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins.
Some rooms a... | import java.io.*;
import java.util.*;
//import javafx.util.*;
import java.math.*;
//import java.lang.*;
public class Main
{
// static int n;static ArrayList<Integer> arr[];
// static int m;
// static boolean v[];
// int ans[];
static final long oo=(long)1e18;
static int mod=1000000007;
... |
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.
A square (x; y) is cons... | import java.io.*;
import java.util.*;
public class e {
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int a = input.nextInt(), b = input.nextInt();
int x1 = input.nextInt(), y1 = input.nextInt();
int x2 =input.nextInt(), y2 = input.... |
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensu... | #include <bits/stdc++.h>
using namespace std;
int N, ans, tot;
int ar[1002][1002];
int main() {
cin >> N;
while (tot <= N) {
ans++;
tot += ans;
}
cout << ans << endl;
tot -= ans;
ans--;
int temp = 0;
for (int i = 0; i < ans; i++)
for (int j = i; j < ans; j++) {
ar[i][j] = temp + 1;
... |
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign ea... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
if (a > b) swap(a, b);
if (a == 0) return b;
return gcd(b % a, a);
}
long long powerMod(long long x, long long y) {
long long res = 1;
x %= 1000000007;
while (y > 0) {
if (y & 1) res = (res * x) % 1000000007;
y =... |
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.
The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored w... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual soluti... |
You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.
A sequence a is a subsequence of an array b if a can be obtained from b by deletion o... | #include <bits/stdc++.h>
using namespace std;
const int rlen = 1 << 20 | 5;
char buf[rlen], *ib = buf, *ob = buf;
inline int read() {
static int ans, f;
static char ch;
for (ch = (((ib == ob) && (ob = (ib = buf) + fread(buf, 1, rlen, stdin))),
ib == ob ? -1 : *ib++),
f = 1;
!isdigit(ch);... |
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)
You have completed many programming projects. In fact, there are exactly n types of programming projects, and you ha... | 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.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.... |
You are given n integers a_1, a_2, ..., a_n.
For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair.
Input
The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the ar... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Input... |
You are given an undirected graph where each edge has one of two colors: black or red.
Your task is to assign a real number to each node so that:
* for each black edge the sum of values at its endpoints is 1;
* for each red edge the sum of values at its endpoints is 2;
* the sum of the absolute values of all... | #include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int> > > graph;
vector<pair<int, int> > val;
vector<int> visited;
int ov2 = 1e9;
vector<int> component;
void dfs(int cur) {
component.push_back(cur);
visited[cur] = true;
for (auto a : graph[cur]) {
int newSign = -val[cur].first;
int ne... |
There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m).
In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should ... | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
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.uti... |
This is the easy version of the problem. The only difference is that in this version q=1. You can make hacks only if all versions of the problem are solved.
Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i.
Strangely, she... | #include <bits/stdc++.h>
using namespace std;
std::mt19937 rnd(
(int)std::chrono::steady_clock::now().time_since_epoch().count());
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
const int NDIG = 6;
const int MAXQ = 100000;
const int MAXSUM = 999999;
int nvals;
int gain[NDIG];
int nq;... |
You are asked to watch your nephew who likes to play with toy blocks in a strange way.
He has n boxes and the i-th box has a_i blocks. His game consists of two steps:
1. he chooses an arbitrary box i;
2. he tries to move all blocks from the i-th box to other boxes.
If he can make the same number of blocks in ... | #include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
typedef long long ll;
const int N = 2e5+10;
int a[N];
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
scanf("%d",&n);
ll sum=0;
int maxx=0;
for(int i=0;i<n;i++) {
scanf("%d",&a[i]);
sum+=a[i];
maxx=max(maxx,a[i]);
}... |
Polycarp found on the street an array a of n elements.
Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i ≠ j:
* a_i is divisible by a_j;
* or a_j is divisible by a_i.
For exam... | #include<bits/stdc++.h>
using namespace std;
const int N=2e5+7;
int dp[N];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> v(n);
map<int,int> mp;
for(int i=0;i<n;i++){
... |
Vanya invented an interesting trick with a set of integers.
Let an illusionist have a set of positive integers S. He names a positive integer x. Then an audience volunteer must choose some subset (possibly, empty) of S without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen... | #include <bits/stdc++.h>
const int N = 1000010;
using ll = long long;
using pii = std::pair <ll, ll>;
template <typename T>
void read(T &n){
char ch;
while (!isdigit(ch = getchar()))
;
n = ch - '0';
while (isdigit(ch = getchar())){
n = n * 10 + ch - '0';
}
}
struct Treap{
#define ... |
You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours.
More formally, find an array b, such that:
* b is a permutation of a.
* For every i from 1 to 2n, b_i ≠ \frac{b_{i-1}+b_{i+1}}... | #include <bits/stdc++.h>
using namespace std;
#define lli long long int
#define li long int
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
lli t;
cin>>t;
while(t--){
lli n;
cin>>n;
vector<lli>a;
for(int i=0;i<n*2;i++){
... |
As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answe... | #include <bits/stdc++.h>
using namespace std;
int acc[100005];
int nacc[100005];
int nc;
int a[100005];
int lied[100005];
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] > 0) {
acc[a[i]]++;
} else if (a[i] < 0) {
nacc[-1 * a[i]]++;
nc++;
... |
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.
The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different citie... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
const int M = N;
const int inf = 1e9 + 9;
const long long base = 1e18;
const double pi = acos(-1);
const double ep = 1e-9;
int low[N], num[N], pa[N];
int n, m, cnt;
vector<int> adj[N];
bool check[N];
void DFS(int u) {
low[u] = num[u] = ++cnt;
for ... |
Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of the... | #include <bits/stdc++.h>
using namespace std;
struct edge {
int nxt, t, id;
} e[10010 << 1];
int head[10010], edge_cnt;
void add_edge(int x, int y, int z) {
e[edge_cnt] = (edge){head[x], y, z};
head[x] = edge_cnt++;
}
int Cnt, Rec, dep[10010], sum[10010], ID[10010];
vector<int> Ans;
bool vis[10010];
void dfs(int ... |
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
Input
The first and the single line contains three space-separated integers — the areas of the parallelepi... | a,b,c=map(int,input().split())
print(int(4*pow(a*c/b,0.5)+4*pow(a*b/c,0.5)+4*pow(b*c/a,0.5)))
|
For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!"
Dr. Suess, How The Grinch Stole Christmas
Christmas celebrations are coming to Whoville. Cindy Lou Who and her paren... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, t;
cin >> n >> t;
string s;
cin >> s;
vector<int> house, shop;
for (int i = 0; i < n; ++i) {
if (s[i] == 'H')
house.push_back(i);
else if (s[i] == 'S')
shop.push_back(i);
}
if (house.back() >= t) {
cout << -1 << en... |
Dima came to the horse land. There are n horses living in the land. Each horse in the horse land has several enemies (enmity is a symmetric relationship). The horse land isn't very hostile, so the number of enemies of each horse is at most 3.
Right now the horse land is going through an election campaign. So the horse... | #include <bits/stdc++.h>
using namespace std;
priority_queue<pair<int, int> > q;
vector<int> G[300010];
int deg[300010], ans[300010];
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
G[a].push_back(b);
G[b].push_back(a);
deg[a]++;
... |
Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≤ i, j ≤ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w.
A string's template is a string... | #!/usr/bin/python3
def build(n, s, t):
ans = 1
for i in range(n):
if s[i] == '?' and t[i] == '?':
ans = (55 * ans) % (10 ** 9 + 7)
elif s[i] == '?':
ans = ((ord(t[i]) - ord('0') + 1) * ans) % (10 ** 9 + 7)
elif t[i] == '?':
ans = ((ord('9') - ord(s[i]... |
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so ... | #include <bits/stdc++.h>
using namespace std;
const int NMax = 101000;
struct node {
vector<int> s;
} T[NMax * 8];
int N, nn, L;
pair<int, int> B[NMax];
vector<long long> LSH;
map<long long, int> ID;
vector<pair<int, pair<long long, long long> > > Q;
void insert(int a, int b, int c, int first, int second, int p) {
... |
Mad scientist Mike has applied for a job. His task is to manage a system of water pumping stations.
The system consists of n pumping stations, which are numbered by integers from 1 to n. Some pairs of stations are connected by bidirectional pipes through which water can flow in either direction (but only in one at a t... | #include <bits/stdc++.h>
class _int {
public:
static int t;
int o, l, v;
_int(int _v) : o(_v), l(t), v(_v) {}
_int() : o(0), l(t), v(0) {}
_int& operator=(int _v) {
v = _v, l = t;
return *this;
}
operator int() {
if (l != t) v = o, l = t;
return v;
}
_int& operator+=(int _v) { return ... |
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 100;
int n, m, p, number[maxn];
vector<int> ans;
map<int, int> result;
void compute(int start);
int main() {
int num;
scanf("%d%d%d", &n, &m, &p);
for (int i = 1; i <= n; i++) scanf("%d", &number[i]);
for (int i = 1; i <= m; i++) {
scanf("... |
Once Petya and Vasya invented a new game and called it "Smart Boy". They located a certain set of words — the dictionary — for the game. It is admissible for the dictionary to contain similar words.
The rules of the game are as follows: first the first player chooses any letter (a word as long as 1) from any word fro... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 29;
const int xam = 100010;
int n, m;
string str[xam];
map<string, int> M;
vector<int> graf[xam];
pair<int, pair<int, int> > prize[xam];
vector<int> lisc;
vector<int> sorts[40];
string dane[40];
bool num[xam][40];
void set_ans() {
bool bol = 0;
for ... |
As it has been found out recently, all the Berland's current economical state can be described using a simple table n × m in size. n — the number of days in each Berland month, m — the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, wh... | # Codeforces Beta Round #39
# Problem E -- Number Table
n, m = map(int, raw_input().split())
if (n + m) % 2 == 1:
print 0
else:
k = input()
f = [map(int, raw_input().split()) for i in xrange(k)]
if n < m:
n, m = m, n
for i in xrange(k):
f[i][0], f[i][1] = f[i][1], f[i][0]
p = input()
cnt, pro = [m] * n, [1... |
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.
Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array a[1], a[2], ..., a[n]. Then he... | import java.io.*;
import java.util.*;
public class Main extends PrintWriter {
private void solve() {
n = sc.nextInt();
int m = sc.nextInt();
a = new long[n];
for(int i = 0; i < n; i++) a[i] = sc.nextLong();
sum = new long[4*n];
max = new long[4*n];
... |
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve... | n, m = map(int, input().split() )
r = 0
t = 1
while n:
n -= 1
if t % m == 0:
n += 1
t += 1
print(t-1)
|
You play the game with your friend. The description of this game is listed below.
Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals <image>. You... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:100000000000000")
using namespace std;
int n, vis[(1 << 21) + 1], col = 1, m, tw[22], cnt[(1 << 21) + 1];
long long dp[(1 << 21) + 1];
string st[55];
long long rep[(1 << 21) + 1];
int count_bit(long long x) {
int ret = 0;
while (x) {
ret++;
x ^= x & (... |
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.
Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of... | from collections import deque
def bfs(n, v, s, t):
dis = [n] * n
load = [n] * n
path = [None] * n
q = deque([s])
dis[s] = 0
load[s] = 0
while (q):
node = q.popleft()
for i in range(len(v[node])):
nb = v[node][i][0]
status = v[node][i][1]
t... |
Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there.
At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one... | import java.util.*;
public class _557A_Ilya_and_Diplomas {
public static void main(String[] args) {
Scanner input=new Scanner (System.in);
int n=input.nextInt();
int min1=input.nextInt(),max1=input.nextInt();
int min2=input.nextInt(),max2=input.nextInt();
int min3=input.nextI... |
For a given prime integer p and integers α, A calculate the number of pairs of integers (n, k), such that 0 ≤ k ≤ n ≤ A and <image> is divisible by pα.
As the answer can be rather large, print the remainder of the answer moduly 109 + 7.
Let us remind you that <image> is the number of ways k objects can be chosen fro... | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class cf582d
{
public static final int INF = 1000000007;
public static final int MAXN = 3333;
public static int add(int a, int b)
{
a += b; if (a >= INF) a -= INF;
return a;
}
public static int... |
As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where... | #include <bits/stdc++.h>
using namespace std;
long long po(long long x, long long y, int mod) {
if (y == 0) return 1;
if (y == 1) return x % mod;
long long half = po(x, y / 2, mod);
if (y % 2)
return ((half) * ((half * x) % mod)) % mod;
else
return (half * half) % mod;
}
long long find(long long k, lo... |
Johnny is at a carnival which has n raffles. Raffle i has a prize with value pi. Each participant can put tickets in whichever raffles they choose (they may have more than one ticket in a single raffle). At the end of the carnival, one ticket is selected at random from each raffle, and the owner of the ticket wins the ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 6;
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;... |
My name is James diGriz, I'm the most clever robber and treasure hunter in the whole galaxy. There are books written about my adventures and songs about my operations, though you were able to catch me up in a pretty awkward moment.
I was able to hide from cameras, outsmart all the guards and pass numerous traps, but w... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.io.IOException;
import java.util.HashSet;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import ja... |
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than k characters of the original string. W... | import java.util.*;
public class CF354
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
int c = 0;
int posa[] = new int[n];
int posb[] = new int[n];
for(int i=0;i<n;i++)
{
p... |
In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle... | #include <bits/stdc++.h>
const int N = 100010;
const int inf = 0x3f3f3f3f;
using namespace std;
int k, n, m, q;
map<string, int> mp;
map<int, string> pm;
struct data {
vector<int> a, b;
} da[N];
map<int, int> p[N];
int main() {
scanf("%d%d%d%d", &k, &n, &m, &q);
for (int i = 0; i < n; i++) {
string str;
c... |
Misha has an array of integers of length n. He wants to choose k different continuous subarrays, so that each element of the array belongs to at least one of the chosen subarrays.
Misha wants to choose the subarrays in such a way that if he calculated the sum of elements for each subarray, and then add up all these su... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
struct group {
ll x, c, l, r;
group() {}
group(ll x, ll c, ll l, ll r) : x(x), c(c), l(l), r(r) {}
};
struct fenwick {
ll C[131313], M[131313], V[131313];
ll sz = 1 << 17;
void init() {
fill(C, C + 131313, 0);
... |
As you have noticed, there are lovely girls in Arpa’s land.
People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi.
<image>
Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are a... | #include <bits/stdc++.h>
using namespace std;
long long crush[110];
bool vis[110];
long long gaba, src;
void dfs(long long n, long long cn = 0) {
if (crush[n] == src) {
gaba = cn + 1;
return;
}
vis[n] = 1;
if (vis[crush[n]] == 0) {
dfs(crush[n], cn + 1);
}
}
long long gcd(long long a, long long b)... |
If you have gone that far, you'll probably skip unnecessary legends anyway...
You are given a binary string <image> and an integer <image>. Find the number of integers k, 0 ≤ k < N, such that for all i = 0, 1, ..., m - 1
<image> Print the answer modulo 109 + 7.
Input
In the first line of input there is a string s c... | #include <bits/stdc++.h>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")... |
Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia.
It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending... | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<vector<int> > adj;
int sameEdge = 0;
vector<int> diffEdge;
vector<int> visited;
void preprocess(void) { return; }
void dfs(int v) {
visited[v] = 1;
for (int i = 0; i < (int)adj[v].size(); i++) {
int u = adj[v][i];
if (!visited[u]) {
dfs(u)... |
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one.
In school, where Noora is studying, teachers are putting down marks to the online class register, wh... | n,k=tuple(int(i) for i in input().strip().split(" "))
a=input().strip().split(" ")
sum=0
o=0
for i in a:
sum+=int(i)
if sum/n>=k-0.5:
print(0)
exit(0)
while sum/n<k-0.5:
sum+=k
n+=1
o+=1
print(o) |
Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.
A string is 1-palindrome if and only if it reads the same backward as forward.
A string is k-palindrome (k > 1) if and only if:
1. Its ... | #include <bits/stdc++.h>
template <class T, class U>
inline bool smin(T &x, const U &y) {
return y < x ? x = y, 1 : 0;
}
template <class T, class U>
inline bool smax(T &x, const U &y) {
return x < y ? x = y, 1 : 0;
}
using LL = long long;
using PII = std::pair<int, int>;
constexpr int N(5005);
std::array<int, 26> c... |
After destroying all of Voldemort's Horcruxes, Harry and Voldemort are up for the final battle. They each cast spells from their wands and the spells collide.
The battle scene is Hogwarts, which can be represented in the form of a tree. There are, in total, n places in Hogwarts joined using n - 1 undirected roads.
Ro... | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to;
int next;
} e[200005];
int n, tot = 0, sz[100005], dep[100005], fa[100005], last[100005], s[100005],
f[100005];
long long ans = 0, val[100005];
int ff(int x) {
if (f[x] == x) {
return x;
} else {
return f[x] = ff(f[x]);
}
}
voi... |
A long time ago somewhere in the depths of America existed a powerful tribe governed by the great leader Pinnie-the-Wooh. Once the tribe conquered three Maya cities. Pinnie-the-Wooh grew concerned: there had to be some control over the conquered territories. That's why he appealed to the priests of the supreme god Mogo... | #include <bits/stdc++.h>
using namespace std;
struct point {
long long x, y;
point(long long x, long long y) { this->x = x, this->y = y; }
point() { this->x = 0, this->y = 0; }
point operator-(point b) { return {this->x - b.x, this->y - b.y}; }
point operator+(point b) { return {this->x + b.x, this->y + b.y};... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.