input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Chandan is back with his array to blow your mind. As usual Chandan has an array consisting of N integers .He allows you to perform 2 kinds of operation on his array.
Type 1 : Increment any integer of the array by 1.
Type 2 : Decrement any integer of the array by 1.
You can perform these operation as many times as yo... | t=int(raw_input())
n=[]
l=[]
for k in range(t):
n.append(raw_input())
l.append(raw_input())
def getmin(l):
mn=-1
# print l
for i in l:
cost=0
for j in l:
temp=i-j
#print temp
if(temp<0):
temp=abs(temp)*5
else:
temp=abs(temp)*3
cost+=temp
#print cost
if mn==-1 or mn>cost:
mn=cost
... |
On the divine friendship day, "A" tied "B" a friendship band. But alas! Frequent quarrels started between them and "B" decided to remove and break off the band! The band isnt a huge one and consists of red, blue and white beads in random positioning. Here are two examples for number of beads = 29:
1 2 ... | n=int(raw_input())
a=raw_input()
ans=0
for i in range(0,n):
j=i+1
temp=a[i]
count=1
flag=0
while (j%n != i):
if(a[j%n]=='w' and temp=='w'):
count+=1
elif (a[j%n]=='w'):
count+=1
elif(a[j%n]!='w' and temp=='w'):
count+=1
temp=a[j... |
Daisy, being a good hacker as we all know, recently came across a file of the evil organization-Hydra which requires a password to open, and you have been assigned the task to help her in it.
She knows that the password of Hydra files are usually made from a list of words that Daisy already has.
The password is made ... | def process(base, s):
s = list(s)
for i in base:
for j in range(2):
if i not in s:
return "Impossible"
del s[s.index(i)]
if len(s) == 0:
return "Possible"
return "Impossible"
T = input()
for i in xrange(T):
base, s = raw_input().strip(" \n").split(" ")
print process(base, s) |
Would you want to fight against bears riding horses?
Me neither.
Limak is a grizzly bear.
He is a general of the dreadful army of Bearland.
The most important part of an army is the cavalry of course.
The cavalry of Bearland consists of N warriors and N horses, both numbered 1 through N.
Limak knows the strength of e... | import fileinput
def solve(w, h):
h.sort()
bb = w.pop(0)*h.pop()
w.sort()
while len(w) > 0:
if w.pop(0)*h.pop() >= bb:
return "NO"
return "YES"
first = True
getn = False
getw = False
geth = False
for line in fileinput.input():
if first:
first = False
t = in... |
Atish is very talkative. He just doesn't stop speaking. Unfortunately for those around him, he's also a maths wiz, and befuddles anyone who dares speak to him. Annoyed with this, Souradeep asked him to shut up, to which Atish replied,
Take a number, x, find its factorial, remove the zeroes, and find the last digit. C... | n=input()
raw_input()
for _ in xrange(n):
m=input()
i=1
f=1
while i<=m:
f=f*i
while f%10==0:
f=f/10
f%=10000
i+=1
print f%10 |
You are given a string of characters, or numbers. Find the minimum number of characters to be inserted into the string in order to obtain a palindrome.
A palindrome is a word, phrase, number, or other sequence of symbols or elements that reads the same forward or reversed.
For example, the string abcbd can be transf... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def min_insert(s):
if len(s) == 1 or len(s) == 0:
return 0
return min_insert(s[1:-1]) if s[0] == s[-1] else 1 + min(min_insert(s[:-1]), min_insert(s[1:]))
T = input()
for t in xran... |
One day Viru and Gauty after playing cricket decided to play an indoor game. In this Viru will give a string of even length to Gauty. The each character of string will be either ‘a’ ,’b’ or ‘/’. Gauty’s task is to replace each ‘/’ such that final string becomes palindrome.
Here twist is that Viru will also give him t... | def costPalindrome():
myString = raw_input()
aCost = int(raw_input())
bCost = int(raw_input())
stringLength = len(myString)
cost = 0
for i in range(stringLength/2):
if myString[i] == 'a':
if myString[stringLength-1-i] == 'b':
return -1
elif myString[stringLength-1-i] == '/':
cost += aCost
elif m... |
Madhav went to Riya's Birthday Party. He was a geek so he had no idea regarding which gift she'l like.
So he took an array of integers with him. The array followed a particular order.
First element of array is 1.
Second element of array is 6.
Other elements of the array are two less than the mean of the number precedin... | for _ in xrange(int(raw_input())):
n=int(raw_input())
print 1+( ( 4 * ((n*(n-1))/2))%1000000007 + (n-1)%1000000007) %1000000007 |
Your friend gives you an equation A≡X2(modM) and asks you to find an integer solution for X.
However, you know your friend's mischievous nature and suspect that there is no solution to such an equation. Thus, you first want to find out whether there is a solution to it.
You may find this link helpful: http://en.wikip... | for _ in range(input()):
a, m = map(int, raw_input().split())
if a == 0 or m == 2:
print "YES"
elif pow(a, (m - 1)/2, m) == 1:
print "YES"
else:
print "NO" |
Little Pandey is someone who is lazy, and when he's around his best friend GJ, he becomes super lazy. Pandey thinks that he is a Math-wizard, so he picks up a number S and asks GJ to throw him a challenge around that number.
GJ explains Little Pandey a property called nothingness and decides to ask him Q queries bas... | def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
s, q = map(int, raw_input().strip().split())
already_seen = set()
for _ in xrange(q):
a = input()
m = gcd(s, a)
if m in already_seen:
print -1
else:
already_seen.add(m)
print m |
We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).
Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where th... | #include <bits/stdc++.h>
using namespace std;
int p1,p2,a[300005],b[300005];
set<pair<int,int> > st;
vector<int> v1,v2;
int main()
{
int h,w,m;
cin>>h>>w>>m;
while(m--)
{
int x,y;
cin>>x>>y;
st.insert(make_pair(x,y));
a[x]++;
b[y]++;
if(a[x]>p1) v1.clear(),p1=a[x];
if(a[x]==p1) v1.push_back(x);... |
Given is a three-digit integer N. Does N contain the digit 7?
If so, print `Yes`; otherwise, print `No`.
Constraints
* 100 \leq N \leq 999
Input
Input is given from Standard Input in the following format:
N
Output
If N contains the digit 7, print `Yes`; otherwise, print `No`.
Examples
Input
117
Output
Y... | #include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
if(n%10==7 || n/10%10==7 || n/100==7) cout<<"Yes"; else cout<<"No";
}
|
We have an integer sequence A of length N, where A_1 = X, A_{i+1} = A_i + D (1 \leq i < N ) holds.
Takahashi will take some (possibly all or none) of the elements in this sequence, and Aoki will take all of the others.
Let S and T be the sum of the numbers taken by Takahashi and Aoki, respectively. How many possible ... | N,X,D=map(int,input().split())
from collections import defaultdict
A=defaultdict(list)
A[0].append([0,0])
MIN=0
MAX=0
if D==0:
w=1
else:
w=D
for i in range(N):
MIN+=X+D*i
MAX+=X+D*(N-1-i)
A[MIN%w].append(sorted([MIN,MAX]))
D=abs(D)
if D==0:
if X==0:
D=1
else:
D=X
ANS=... |
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, th... |
"""
https://atcoder.jp/contests/agc035/tasks/agc035_c
全ての対の頂点に関して、パス上の重みのxorが自分に等しい
1から順に求めていくことを考える
A,Bの関係を考える
木なので、片方のパス上にあればいい→片方にのみ含ませることも、両方に含ませることも可能
1をいい感じに使って構築できないか?
101-100-1-101-100
みたいに、1の位だけ違う数字をまとめて処理すればいい感じになる
もう一つの1は、どっかの葉につけておけばおk
これで、Nが奇数かつ1でない場合は全て構築可能!!
偶数の時は? 2,4みたいな場合は自明にダメ
6は?
001 010 011 ... |
Count the number of strings S that satisfy the following constraints, modulo 10^9 + 7.
* The length of S is exactly N.
* S consists of digits (`0`...`9`).
* You are given Q intervals. For each i (1 \leq i \leq Q), the integer represented by S[l_i \ldots r_i] (the substring of S between the l_i-th (1-based) character a... | #include<bits/stdc++.h>
using namespace std;
typedef long long lint;
typedef long double louble;
template<typename T1,typename T2> inline T1 max(T1 a,T2 b){return a<b?b:a;}
template<typename T1,typename T2> inline T1 min(T1 a,T2 b){return a<b?a:b;}
const char lf = '\n';
namespace ae86
{
const int bufl = 1<<15;
c... |
You are given integers A and B, each between 1 and 3 (inclusive).
Determine if there is an integer C between 1 and 3 (inclusive) such that A \times B \times C is an odd number.
Constraints
* All values in input are integers.
* 1 \leq A, B \leq 3
Input
Input is given from Standard Input in the following format:
A... | print("Yes" if all(int(i) % 2 != 0 for i in input().split()) else "No") |
Find the number of palindromic numbers among the integers between A and B (inclusive). Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.
Constraints
* 10000 \leq A \leq B \leq 99999
* All input values are integers.
Inp... | #include <bits/stdc++.h>
using namespace std;
int main() {
int A,B;
cin >> A >> B;
int N=0;
for(int i=A/100;i<=B/100;i++){
int tmp=i*100+(i%100/10)*10+(i/100);
if(A<=tmp&&tmp<=B)N++;
}
cout<<N<<endl;
} |
We have N points in a two-dimensional plane.
The coordinates of the i-th point (1 \leq i \leq N) are (x_i,y_i).
Let us consider a rectangle whose sides are parallel to the coordinate axes that contains K or more of the N points in its interior.
Here, points on the sides of the rectangle are considered to be in the inte... | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
try (Scanner in = new Scanner(System.in)) {
int N = in.nextInt();
int K = in.nextInt();
long[] x = new long[N];
long[] y = new long[N];
... |
In a public bath, there is a shower which emits water for T seconds when the switch is pushed.
If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds. Note that it does not mean that the shower emits water for T additional seconds.
N people will pus... | #include <iostream>
using namespace std;
int main(void) {
long long N, T, t1, t2, sum = 0;
cin >> N >> T >> t2;
for (int i = 0; i < N; ++i) {
t1 = t2;
cin >> t2;
if (t2 - t1 >= T) sum += T;
else sum += t2 - t1;
}
sum += T;
cout << sum << endl;
return 0;
} |
Takahashi recorded his daily life for the last few days as a integer sequence of length 2N, as follows:
* a_1, b_1, a_2, b_2, ... , a_N, b_N
This means that, starting from a certain time T, he was:
* sleeping for exactly a_1 seconds
* then awake for exactly b_1 seconds
* then sleeping for exactly a_2 seconds
* :
*... | #include <iostream>
#include <algorithm>
#define DAY_LENGTH 86400
#define FOUR_TO_SEVEN 10800
using namespace std;
bool check(int k, int ts[], int n) {
for (int i = 0; i <= 2 * n - k; i++) {
if (ts[k - 1 + i] - ts[i] <= FOUR_TO_SEVEN)
return true;
}
return false;
}
int main() {
int... |
There is a data which provides heights (in meter) of mountains. The data is only for ten mountains.
Write a program which prints heights of the top three mountains in descending order.
Constraints
0 ≤ height of mountain (integer) ≤ 10,000
Input
Height of mountain 1
Height of mountain 2
Height of mountain 3
.
.
He... | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int a[10];
for(int i=0;i<10;i++)cin >> a[i];
sort(a,a+10);
for(int i=9;i>6;i--)cout << a[i] << endl;
} |
Create a program that rotates the pattern of 8 characters x 8 lines clockwise by 90 degrees, 180 degrees, and 270 degrees and outputs it.
Input
A pattern consisting of 8 characters x 8 lines is given. Characters consist of alphanumeric characters, half-width pound'#', and asterisk'*'.
Output
Output the rotated pa... | # AOJ 0133 Rotation of a Pattern
# Python3 2018.6.19 bal4u
a = [[[0 for c in range(8)] for r in range(8)] for k in range(4)]
title = ["0", "90", "180", "270"]
for r in range(8):
a[0][r] = list(input())
for k in range(1, 4):
print(title[k])
for r in range(8):
for c in range(8):
a[k][c][7-r] = a[k-1][r][c]
for... |
You have obtained the Izua Japanese dictionary, which is the official language of Izua, and the Izua alphabet (list of letters). There are N types of letters in the Izua alphabet. The order of the words that appear in the Izua Japanese dictionary is in the alphabetical order of Izua.
Looking at the dictionary, I found... | #include<bits/stdc++.h>
#define MOD 1000000007
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
int a[100000];
ll fact[100000];
ll bit[100001];
int n;
void add(int i, int x) {
while (i <= n) {
bit[i] += x;
i += i&-i;
}
}
int sum(int i) {
int s = 0;
while (i > 0) {
s += bit[i];... |
problem
In one river, there is a slightly dangerous game of jumping from one shore to the other on a stone.
<image>
Now, as shown in Figure 4-1 we consider the stone to be above the squares. The number of rows is n. In Figure 4-1 we have n = 5.
In this game, you start with one shore and make a normal jump or a on... | #include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
using namespace std;
#define int long long
#define inf 3000000000000
typedef pair<int, int>P;
int dp[160][10][80];
vector<P>s[160];//P(??????,???????????????)
void init(int m) {
for (int i = 0; i < 160; i++) {
s[i].clear();
for... |
The best night ever in the world has come! It's 8 p.m. of December 24th, yes, the night of Cristmas Eve. Santa Clause comes to a silent city with ringing bells. Overtaking north wind, from a sleigh a reindeer pulls she shoot presents to soxes hanged near windows for children.
The sleigh she is on departs from a big ch... | #include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstdio>
using namespace std;
struct NODE{
int to,cost;
NODE(int to,int cost) : to(to) , cost(cost) {}
NODE(){}
};
bool operator < (const NODE &a,const NODE &b){
return a.cost > b.cost;
}
int done[110] = {};
double dp[110] = {} , ... |
Rational numbers are numbers represented by ratios of two integers. For a prime number p, one of the elementary theorems in the number theory is that there is no rational number equal to √p. Such numbers are called irrational numbers. It is also known that there are rational numbers arbitrarily close to √p
Now, given ... | #include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
struct DATA{
int x, y;
double r;
DATA(){}
DATA(int x_, int y_){ x=x_; y=y_; r=(double)x/(double)y; }
void set(int x_, int y_){ x=x_; y=y_; r=(double)x/(double)y; }
};
int main(){
int n;
double p, k;
DATA a, b;
while(1)... |
Let us compare two triples a = (xa, ya, za) and b = (xb, yb, zb) by a partial order ∠ defined as follows.
a ∠ b ⇔ xa < xb and ya < yb and za < zb
Your mission is to find, in the given set of triples, the longest ascending series a1 ∠ a2 ∠ ... ∠ ak.
Input
The input is a sequence of datasets, each specifying a set... | #include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <cstring>
#include <functional>
#include <cmath>
#include <complex>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);++i)
#define rep1(i,n) for(in... |
Problem
There are numbers from 0 to N-1. I would like to select the lucky number for M + 1 days by the following methods. Randomly decide the lucky number on the first day. If the lucky number after i days is A and the lucky number after (i + 1) days is B,
B = (A + j)% N
(However, j is all integers where 0 ≤ j <N an... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 100000... |
Hide-and-seek is a children’s game. Players hide here and there, and one player called it tries to find all the other players.
Now you played it and found all the players, so it’s turn to hide from it. Since you have got tired of running around for finding players, you don’t want to play it again. So you are going to ... | #include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-8)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
#define equals(a,b) (fabs((a)-(b)) < EPS)
using namespace std;
class Point{
public:
dou... |
You have successfully completed your studies and are preparing to move from near Komaba to near Hongo. As I was organizing my house, I found a lot of lottery tickets I bought last year. After confirming the exchange deadline, I have to cash in by tomorrow, but it is troublesome to go to the lottery counter for a small ... | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
typedef long long ll;
ll n, m;
int main() {
while (cin>>n>>m) {
if (!n) break;
string key[n];
ll score[n];
for (int i=0; i<n; i++) {
string str; cin>>str>>score[i];
key[i]=str;
... |
Example
Input
4
5
8
58
85
Output
2970.000000000 | from itertools import permutations
from math import acos, sin, cos, pi
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
R = [int(readline()) for i in range(N)]
R.sort(reverse=1)
ans = 0
for l in range(3, N+1):
for rs in permutations(R[:l]):
... |
Problem Statement
One day in a forest, Alice found an old monolith.
<image>
She investigated the monolith, and found this was a sentence written in an old language. A sentence consists of glyphs and rectangles which surrounds them. For the above example, there are following glyphs.
<image>
<image>
Notice that... | #include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)
#define all(c) c.begin(),c.end()
#define pb push_back
#define fs first
#define sc second
#define show(x) cout << #x << " = " << x << endl
#define chmin(x,y) x=min(x,y)
#define chmax(x,y) x=max(x,y)
using... |
Airport Codes
Airport code
In the Kingdom of JAG, airport codes are assigned to each domestic airport for identification.
Airport codes are assigned according to the following rules based on the name of the airport in lowercase English alphabet:
1. Extract the first letter of the name and the letter immediately aft... | #include<bits/stdc++.h>
using namespace std;
using ll=long long;
#define REP(i,n) for(ll i=0;i<ll(n);i++)
#define ALL(v) v.begin(),v.end()
bool f(char c){
return c=='a'||c=='i'||c=='u'||c=='e'||c=='o';
}
int main() {
int n;
while(cin>>n,n){
vector<string> v(n);
REP(i,n)cin>>v[i];
for(int k=1;k<=50;++k){
... |
A: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's... | #include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <iomanip>
using namespace std;
int main() {
int d = 0;
string S;
cin >> S;
if (S[0] == 'A') { d++; }
for (int i = 1; i < S.size(); i++) {
if (S[i] <= S[i - 1]) {
d++;
}
}
cout << d << endl;
return 0;
} |
Problem Statement
JAG land is a country, which is represented as an $M \times M$ grid. Its top-left cell is $(1, 1)$ and its bottom-right cell is $(M, M)$.
Suddenly, a bomber invaded JAG land and dropped bombs to the country. Its bombing pattern is always fixed and represented by an $N \times N$ grid. Each symbol in ... | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <complex>
#include <string>
#include <algorithm>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <functi... |
Problem statement
The spellbook you have contains $ N $ of spells.
Magic is numbered from $ 1 $ to $ N $, and the cost of magic $ i (1 \ le i \ le N) $ is initially an integer $ A_i $.
Your goal is to cast all the spells in the spellbook $ 1 $ each.
You can eat $ K $ of cookies before you start casting magic. It do... | #include <bits/stdc++.h>
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<typename T> using gpp_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T, typename L> using gpp_map = tre... |
Diameter of a Tree
Given a tree T with non-negative weight, find the diameter of the tree.
The diameter of a tree is the maximum distance between two nodes in a tree.
Constraints
* 1 ≤ n ≤ 100,000
* 0 ≤ wi ≤ 1,000
Input
n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1
The first line consists of an integer n which repre... | #include <bits/stdc++.h>
#define INF 999999999
using namespace std;
typedef pair<int,int>P;
const int MAX_N = 100000;
vector<P> G[MAX_N];
int d[MAX_N];
bool visited[MAX_N];
void dfs(int v)
{
visited[v] = true;
for(int i=0; i<G[v].size(); i++){
if(!visited[G[v][i].first]){
d[G[v][i].... |
Let's consider a rooted binary tree with the following properties:
The number of nodes and edges in the tree is infinite
The tree root is labeled by 1
A node labeled by v has two children: 2 × v (the left son of v) and 2 × v + 1 (the right son of v)
Here is an image of the first several tree layers of such a tree:
L... | for q in xrange(int(raw_input())):
n, a, b = map(int, raw_input().split())
na, nb = n, n
while (a!=b):
#print a, b, na, nb, "to",
if (a>b):
if (a%2==0):
na/=2
else:
na-=1
na/=2
a/=2
else:
if (b%2==0):
nb/=2
else:
nb-=1
nb/=2
b/=2
#print a, b, na, nb
print min(na, nb... |
Wet Shark once had 2 sequences:
{a_n}= {a_1, a_2, a_3, ... , a_(10^9)}
{b_n} = {b_1, b_2, b_3, ... , b_(10^9)}
However, he only kept one element from each sequence. Luckily, both the elements that Wet Shark kept have the same index in Wet Shark's sequences: that is, he took a_i and b_i for some 1 ≤ i ≤ 10^9.
Righ... | # 5th question in long challenge. 5 line code :D
i,k,s=map(int, raw_input().split())
a,b=map(int, raw_input().split())
k-=i
if k%2:print 2 ** (2*(k-1)-s+1)*(2**0.5*a+6**0.5*b)
else:print 2**(2*k-s)*(a+b); |
In olden days finding square roots seemed to be difficult but nowadays it can be easily done using in-built functions available across many languages
.
Assume that you happen to hear the above words and you want to give a try in finding the square root of any given integer using in-built functions. So here's your cha... | t = int(raw_input())
for i in range(t):
k = int(raw_input())
root_k= k**(1/2.0)
int_root_k = int(root_k)
print int_root_k |
Chef Palin, as his name suggests, is always very interested in palindromic strings. Recently, he made a pretty interesting discovery on palindromes and that made him feel really Lucky. He came across something known as Lucky Palindromes. He defines a string as being a lucky palindrome if it is a palindrome containing t... | import copy
t=int(raw_input().rstrip())
while t:
s = raw_input().rstrip()
if len(s)<=8:
print "unlucky"
else:
length = len(s)
initialCount = 0
palindrome = ''
for i in range(length):
if s[i]>s[length-1-i]:
initialCount+=1
palind... |
Chef, Artem and Eugene are the best of friends and teammates. Recently, they won a lot of money at the Are You Feeling Lucky Cup. Having put their fortune to test and emerging victorious, they are now busy enjoying their wealth. Eugene wanted to drink it all away. Chef and Artem had better plans.
Chef and Artem decide... | t=int(raw_input())
for _ in range(0,t):
t1,t2,t3,t4=map(float,raw_input().split())
print t1/(t1+t2) |
Consider a sequence of non- negative integers b(1), b(2) … , b(n) of length n. The given sequence is called a winning sequence if and only if there exists integers p and q between 1 and n (both inclusive) such that a(p) xor a(p+1) xor a(p+2) …. xor a(q) = 0. The xor operation is the bitwise xor operation between two in... | mod = 1000000009
n,k = map(int,raw_input().split())
p = pow(2,k,mod)
ans = 1
for i in range(n):
p-=1
ans*=p
ans%= mod
print ans |
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.
There are... | from functools import reduce
from math import gcd
n, k = map(int, input().split())
A = list(map(int, input().split()))
G = gcd(k, reduce(lambda x,y:gcd(x,y),A))
print(k // G)
print(*list(range(0, k, G))) |
Consider some positive integer x. Its prime factorization will be of form x = 2^{k_1} ⋅ 3^{k_2} ⋅ 5^{k_3} ⋅ ...
Let's call x elegant if the greatest common divisor of the sequence k_1, k_2, ... is equal to 1. For example, numbers 5 = 5^1, 12 = 2^2 ⋅ 3, 72 = 2^3 ⋅ 3^2 are elegant and numbers 8 = 2^3 (GCD = 3), 2500 = 2... | #include <bits/stdc++.h>
using namespace std;
int mu[66];
void init() {
mu[1] = 1;
for (int i = 1; i <= 59; i++)
for (int j = i * 2; j <= 59; j += i) mu[j] -= mu[i];
}
void solve() {
long long n, ans;
scanf("%lld", &n);
ans = n - 1;
for (int i = 2; i <= 59; i++) {
if (!mu[i]) continue;
long long... |
You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belo... | #include <bits/stdc++.h>
using namespace std;
const long long MAXN = 100005;
const long long LOG = 20;
long long n, l, s;
long long a[MAXN];
vector<long long> g[MAXN];
long long depth[MAXN], sum[MAXN], up[MAXN][LOG];
long long dp[MAXN];
long long ans = 0;
void calc(long long v) {
for (long long i = 1; i < LOG; i++) {... |
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.
He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operatio... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 100;
int ans[20002];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
if (n == 2) {
cout << 2 << '\n';
} else {
cout << 1 << '\n';
}
return 0;
}
|
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this... | import java.util.Scanner;
public class Question {
public static void main(String[] args) {
int n,k;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
int arr[] = new int[n];
int b = n/k;
int globalcount1 = 0,globalcount2 = 0;
... |
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.
A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this o... | #include <bits/stdc++.h>
const int N = 1e5 + 5;
int n;
long long ans, dlt[N], s[N];
char t[N], p[N];
int main() {
scanf("%d%s%s", &n, p + 1, t + 1);
for (int i = 1; i <= n; ++i) s[i] = p[i];
for (int i = 1; i < n; ++i)
dlt[i] = t[i] - s[i], s[i + 1] += dlt[i], ans += abs(dlt[i]);
if (s[n] != t[n]) return pu... |
Consider an undirected graph G with n vertices. There is a value a_i in each vertex.
Two vertices i and j are connected with an edge if and only if gcd(a_i, a_j) > 1, where gcd(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y.
Consider a set ... | #include <bits/stdc++.h>
template <class T>
inline void read(T &x) {
x = 0;
register char c = getchar();
register bool f = 0;
while (!isdigit(c)) f ^= c == '-', c = getchar();
while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
if (f) x = -x;
}
template <class T>
inline void print(T x) {
if (x < 0) pu... |
You have a garden consisting entirely of grass and weeds. Your garden is described by an n × m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either gras... | #include <bits/stdc++.h>
using namespace std;
template <class T, class IT>
inline void PRINT(IT i1, IT i2) {
cout << '[';
copy(i1, i2, ostream_iterator<T>(cout, ", "));
cout << "]\n";
}
char field[155][155];
int l[155];
int r[155];
int total_weed;
int main() {
int n, m;
cin >> n >> m;
total_weed = 0;
for ... |
Let's call beauty of an array b_1, b_2, …, b_n (n > 1) — min_{1 ≤ i < j ≤ n} |b_i - b_j|.
You're given an array a_1, a_2, … a_n and a number k. Calculate the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.
A sequence a is a subsequenc... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
const int N = 1005;
long long dp[N][N], tot[N][N], ans = 0, ret[N * N];
int n, a[N], k;
void solve(int x) {
dp[0][0] = 1;
tot[0][0] = 1;
int now = 0;
for (int i = 1; i <= n; ++i) {
while ((a[i] - a[now]) >= x) ++now;
for (int... |
You are given a sequence of n pairs of integers: (a_1, b_1), (a_2, b_2), ... , (a_n, b_n). This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences:
... | #include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
const int inf = 1 << 30;
const int maxn = 300000 + 5;
inline int add(int x, int y) {
x += y;
return x >= mod ? x -= mod : x;
}
inline int sub(int x, int y) {
x -= y;
return x < 0 ? x += mod : x;
}
inline int mul(int x, int y) { return 1ll ... |
You are at the top left cell (1, 1) of an n × m labyrinth. Your goal is to get to the bottom right cell (n, m). You can only move right or down, one cell per step. Moving right from a cell (x, y) takes you to the cell (x, y + 1), while moving down takes you to the cell (x + 1, y).
Some cells of the labyrinth contain r... | #include <bits/stdc++.h>
using namespace std;
struct fast_ios {
fast_ios() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << fixed << setprecision(20);
};
} fast_ios_;
template <typename T>
istream &operator>>(istream &is, vector<T> &v) {
for (auto &x : v) is >> x;
return is;
}
template <typename T... |
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy.
Input
The only line contains three integers n, a and ... | x,y,z=map(int,input().split())
if y+z>=x:
print(x-y)
else:
print(z+1) |
You are given a tournament — complete directed graph.
In one operation you can pick any vertex v and change the direction of all edges with v on one of the ends (i.e all edges u → v change their orientation to v → u and vice versa).
You want to make the tournament strongly connected with the smallest possible number ... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast", "unroll-loops", "omit-frame-pointer", "inline")
#pragma GCC option("arch=native", "tune=native", "no-zero-upper")
#pragma GCC target("avx2")
#pragma GCC optimize("03")
#pragma GCC target("sse4")
using namespace std;
int n;
bool is_scc(vector<int> degrees) {
int s... |
Ildar is the algorithm teacher of William and Harris. Today, Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.
A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows:
1. If the sequence is em... | #include <bits/stdc++.h>
using namespace std;
int a[200010], p[200010];
long long ans[200010];
set<int> S;
struct LCT {
int ch[200010][2], fa[200010];
int val[200010], sz[200010], ss[200010], sss[200010];
long long sum[200010], ssum[200010];
LCT() {
memset(ch, 0, sizeof(ch)), memset(fa, 0, sizeof(fa)),
... |
In modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows:
Let's fix a [finite field](https://en.wikipedia.org/wiki/Finite_field) and two it's elements a and b. One need to fun such x that a^x = b or... | #include <bits/stdc++.h>
#pragma GCC optimize(3)
#pragma GCC target("avx")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC opt... |
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring... | #include <bits/stdc++.h>
int main() {
int n, k;
std::cin >> n >> k;
std::vector<bool> look_right(n, false);
for (size_t i = 0; i < n; i++) {
char t;
std::cin >> t;
if (t == 'R') look_right.at(i) = true;
}
int min_moves = 0;
std::vector<std::vector<int>> moves;
for (;;) {
moves.emplace_ba... |
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed.
Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes.
Every time Polycarp wakes up, he decides if he wants to sleep... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
for (int lap = 1; lap <= t; lap++) {
long long int a, b, c, d, ans = 0;
cin >> a >> b >> c >> d;
a -= b;
long long int e = c - d;
if (a <= 0)
cout << b... |
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a co... | 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 integer k and a tree T with n nodes (n is even).
Let dist(u, v) be the number of edges on the shortest path from node u to node v in T.
Let us define a undirected weighted complete graph G = (V, E) as following:
* V = \\{x ∣ 1 ≤ x ≤ n \} i.e. the set of integers from 1 to n
* E = \{(u, v, w) ∣ ... | #include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 20;
long long n, k;
vector<long long> g[N];
long long sz[N], h[N];
long long cen;
set<pair<long long, long long> > second, st[N];
set<long long> child[N];
long long par[N];
long long match[N];
void pre_dfs1(long long v, long long par = -1) {
sz[v... |
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long int n, i, j, k = 0, l;
cin >> n;
vector<long long int> numbers(n), freq(32, 0);
for (i = 0; i < n; i++) {
cin >> numbers.at(i);
for (j = 1; j < 32; j++) {
if (pow(2, j) > numbers... |
This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operat... | #include <bits/stdc++.h>
using namespace std;
const int MX = 105;
string str[MX];
vector<pair<int, int> > ans;
void process(int x, int y) {
ans.push_back({x, y});
if (str[x][y] == '0')
str[x][y] = '1';
else if (str[x][y] == '1')
str[x][y] = '0';
}
int main() {
int i, j, k;
int t;
cin >> t;
while (... |
You are given a tree. We will consider simple paths on it. Let's denote path between vertices a and b as (a, b). Let d-neighborhood of a path be a set of vertices of the tree located at a distance ≤ d from at least one vertex of the path (for example, 0-neighborhood of a path is a path itself). Let P be a multiset of t... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define pii pair<int,int>
#define fi first
#define se second
#define mp make_pair
#define poly vector<ll>
#define For(i,l,r) for(int i=(int)(l);i<=(int)(r);i++)
#define Rep(i,r,l) for(int i=(int)(r);i>=(int)(l);i--)
#defi... |
Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any i (1 ≤ i ≤ n-1), this condition must be satisfied: $$$(max(a[i], a[i+1]))/(min(a[i], a[i+1])) ≤ 2$$$
For example, the arrays [1, 2, 3, 4, 3], [1, 1, 1] and [5, 10] are dense.... | import java.util.*;
import java.io.*;
public class Main {
static final int M = 1000000007;
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new ... |
You are given a number n and an array b_1, b_2, …, b_{n+2}, obtained according to the following algorithm:
* some array a_1, a_2, …, a_n was guessed;
* array a was written to array b, i.e. b_i = a_i (1 ≤ i ≤ n);
* The (n+1)-th element of the array b is the sum of the numbers in the array a, i.e. b_{n+1} = a_1... | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
/*
HashMap<> map=new HashMap<>();
TreeMap<> map=new TreeMap<>();
map.put(p,map.getOrDefault(p,0)+1);
for(Map.Entry<> mx:map.entrySet()){
int v=mx.getValue(),k=mx.getKey();
}for (int i = 1; i <= 1000; i++)
... |
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. T... | import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author codeKNIGHT
*/
public class Main {
public static void main(String[] args) {
InputStream i... |
Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After ... | #include <bits/stdc++.h>
using namespace std;
long long a[55], b[55], visited[55];
int main() {
cin.sync_with_stdio(false);
cout.sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < 5; i++) cin >> b[i];
long long choco = 0;
for (int i = 0; i < n; i++) {
... |
Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed k hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light... | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package javaapplication1;
//import java.util.Scanner;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.i... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di... | n=int(input())
q=list(map(int,input().split()))
eve,eve_indx,neg,neg_indx=0,0,0,0
for i in range(n):
x=q[i]%2
if x==0:
eve +=1
eve_indx=i
else:
neg +=1
neg_indx=i
if eve==1:
print(eve_indx+1)
else:
print(neg_indx+1) |
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following:
1. Add the integer xi to the first ai elements of the sequence.
2. Append an integer ki to the end of the sequenc... | #include <bits/stdc++.h>
using namespace std;
inline int min(const int &x, const int &y) { return x < y ? x : y; }
inline long long min(const long long &x, const long long &y) {
return x < y ? x : y;
}
inline double min(const double &x, const double &y) { return x < y ? x : y; }
inline int max(const int &x, const int... |
Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses.
Before the game began, the string is written on a piece of paper, one letter per cell.
<image> An example of the initial situation at s = "abacaba"
A player's ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 5005;
char s[maxn];
bool g[maxn];
int sg[maxn];
int ans;
int dfs2(int x) {
if (x <= 0) return 0;
if (x == 1) return 1;
if (sg[x] != -1) return sg[x];
int i, temp;
bool judge[101];
memset(judge, false, sizeof(judge));
for (i = 1; i <= x; i++) {... |
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open ... | #include <bits/stdc++.h>
using namespace std;
map<pair<long long, long long>, pair<long long, long long> > mp;
long long n;
pair<long long, long long> solve(pair<long long, long long> a) {
if (a.second < 10)
return make_pair(a.first || a.second, a.second - max(a.first, a.second));
if (mp[a].first) return mp[a];... |
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.
Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning... | #include <bits/stdc++.h>
using namespace std;
int main() {
string S;
cin >> S;
long long ans = 0, ml = 0;
for (int i = 0; i < S.size(); i += 1) {
if (S[i] == 'M')
ml++;
else
ans = max(ans + (ml > 0), ml);
}
cout << ans << endl;
return 0;
}
|
Kostya is playing the computer game Cookie Clicker. The goal of this game is to gather cookies. You can get cookies using different buildings: you can just click a special field on the screen and get the cookies for the clicks, you can buy a cookie factory, an alchemy lab, a time machine and it all will bring lots and ... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 200000;
template <class T>
inline void tension(T &a, const T &b) {
if (b < a) a = b;
}
template <class T>
inline void relax(T &a, const T &b) {
if (b > a) a = b;
}
int main() {
int n;
long long s;
pair<int, int> a[MaxN];
cin >> n >> s;
for (in... |
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 — to a2 billion, ..., and in the current (2000 + n)-th... | #include <bits/stdc++.h>
using namespace std;
int n, a[1000], b[1000], dem;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
if (a[i] == dem + 1) {
dem++;
b[dem] = i;
}
}
if (dem == 0) {
cout << 0;
ret... |
People in the Tomskaya region like magic formulas very much. You can see some of them below.
Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas:
<image><image>
Here, "mod" means the operation of taking the residue after dividing.
The expression <image> ... | #include <bits/stdc++.h>
using namespace std;
inline void debug() {}
template <typename _type, typename... type>
inline void debug(_type arg, const type&... next) {}
const int MaxN = 1000 * 1000 + 5;
int n, p[MaxN];
int res;
int sum[MaxN], full;
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> p[i], res ^... |
Jzzhu has a big rectangular chocolate bar that consists of n × m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements:
* each cut should be straight (horizontal or vertical);
* each cut should go along edges of unit squares (it is prohibited to divide any unit choc... | n,m,k=map(int,raw_input().split())
if k>n+m-2:
print -1
else:
print max((n*(m/(k+1))),(m*(n/(k+1))),(n/max(1,k-m+2)),(m/max(1,k-n+2)))
|
It happened at the times of the Great Berland Empire. Once the Emperor dreamt that the Messenger from the gods ordered to build a temple whose base would be a convex polygon with n angles. Next morning the Emperor gave the command to build a temple whose base was a regular polygon with n angles. The temple was built bu... | #include <bits/stdc++.h>
using namespace std;
struct ver {
int x, y;
ver operator+(ver p) { return (ver){x + p.x, y + p.y}; }
} v[160005];
long long dis(ver p) { return 1ll * p.x * p.x + 1ll * p.y * p.y; }
bool cmp(ver x, ver y) { return dis(x) < dis(y); }
bool inr(int p) {
if (v[p].y == 0) return v[p].x > 0;
r... |
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger tha... | #include <bits/stdc++.h>
using namespace std;
long long n, m, ans1, ans2, ass = -9999999999;
long long a[200100];
long long b[200100];
long long ab[400100];
int main() {
ios::sync_with_stdio(false);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
ab[i] = a[i];
}
cin >> m;
for (int i = 0; i < m;... |
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The... | #include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
cin >> a >> b;
int flag = 0;
int mp1[130] = {0};
int mp2[130] = {0};
for (int i = 0; a[i]; i++) mp1[a[i]]++;
for (int i = 0; b[i]; i++) mp2[b[i]]++;
int cnt1 = 0, cnt2 = 0;
for (int i = 0; i < 130; i++) {
int temp = min(mp1[i]... |
A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each ... | n,k=input().split()
n,k=int(n),int(k)
if k>(n*n+1)//2:
print("NO")
exit()
print("YES")
for i in range(0,n):
for j in range(0,n):
if((i+j)%2==0 and k>0):
print('L',end='')
k-=1
else:
print('S',end='')
print()
# Made By Mostafa_Kh... |
Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the i... | #include <bits/stdc++.h>
using namespace std;
#pragma warning(disable : 4996)
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int N = 500005;
const double EPS = 1e-9;
int n, m, arr[N], u, v;
char c;
vector<int> adj[N];
vector<pair<int, int> > pre[N];
int s[N], d[N];
int ndfn;
void godfs(int cur = 0, int depth... |
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TheMonsterAndTheSquirrel {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
long n = Integer.parseI... |
Oleg Petrov loves crossword puzzles and every Thursday he buys his favorite magazine with crosswords and other word puzzles. In the last magazine Oleg found a curious puzzle, and the magazine promised a valuable prize for it's solution. We give a formal description of the problem below.
The puzzle field consists of tw... | #include <bits/stdc++.h>
using namespace std;
inline void add(int &x, int y) {
((x += y) >= 1000000007) ? x -= 1000000007 : 0;
}
char s1[2005], s2[2005], s3[2005];
int lcp[2005][2005][2][2];
void pre(int n, int m) {
for (int i = n; i > 0; i--) {
for (int j = 1; j <= m; j++) {
lcp[i][j][0][0] = ((s1[i] == ... |
An e-commerce startup pitches to the investors to get funding. They have been functional for n weeks now and also have a website!
For each week they know the number of unique visitors during this week vi and the revenue ci. To evaluate the potential of the startup at some range of weeks from l to r inclusive investors... | #include <bits/stdc++.h>
using namespace std;
long long mod = 1000000007LL;
const double pi = acos(-1.0);
vector<vector<int> > sv, sc;
int n, k;
int queryv(int l, int r) {
while (r >= n) {
r--;
}
int p = 0;
while ((1 << (p + 1)) <= (r - l + 1)) {
p++;
}
return max(sv[l][p], sv[r - (1 << p) + 1][p]);... |
Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches.
First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hour... |
import java.util.Scanner;
/**
* Created on 23.06.2016.
*/
public class task3 {
private static String from10to7(long number) {
long value = number;
String result = "";
while ( value > 0 ) {
long p = value / 7;
long q = value % 7;
result = q + result;
... |
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by pallavi on 24/8/16.
*/
public class B709 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.... |
Polycarp is playing a game called "Running Over The Bridges". In this game he has to run over n bridges from the left to the right. Bridges are arranged one after the other, so the i-th bridge begins where the (i - 1)-th bridge ends.
You have the following data about bridges: li and ti — the length of the i-th bridge ... | #include <bits/stdc++.h>
using namespace std;
const int oo = 0x3f3f3f3f;
const double eps = 1e-9;
const int maxn = 200000 + 10;
const long long MAX = 100000;
int n;
long long r;
long long L[maxn], T[maxn];
long long ANS[maxn], pnt = 0;
long long add(long long a, long long b, long long r, long long &ans) {
long long t... |
This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For exa... | #include <bits/stdc++.h>
using namespace std;
const long double EPS = 1e-10;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;
const long double PI = 3.1415926535897932384626433832795028841;
map<string, int> ssol;
void checkAdd(string vs) {
if (ssol.find(vs) != ssol.end()) {
return;
}
ssol[vs] = 1;
}... |
Stepan had a favorite string s which consisted of the lowercase letters of the Latin alphabet.
After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers c1, c2, ..., cn, where n equals t... | #include <bits/stdc++.h>
using namespace std;
int sayi_s;
vector<int> sayilar;
int string_s;
int toplam;
int a_mi_b_mi;
int main() {
scanf("%d", &sayi_s);
for (int i = 0; i < sayi_s; i++) {
sayilar.push_back(0);
scanf(" %d", &sayilar[i]);
}
for (int i = sayi_s - 1; i >= 0; i--) {
toplam += string_s;... |
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus.
* Initially, there is a pile that contains x 100-yen coins and y 10-yen coi... | //Abra at 22.06.11 21:36
import java.io.*;
import java.math.*;
import java.util.*;
public class Abra {
void solve() throws IOException {
int x = nextInt(), y = nextInt();
boolean f = true;
while (true) {
if ((x >= 2 && y < 2) || (x == 1 && y < 12) || (x == 0 && y < 22)) break;
... |
After the educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received n marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark.
Now it'... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 100002;
bool flag;
struct Node {
int x;
int p;
bool operator<(const Node& o) const {
if (x != o.x) {
return x < o.x;
} else if (flag) {
return p < o.p;
} else {
return p > o.p;
}
}
} node[MaxN];
int ans[MaxN];
int n... |
Polycarp owns a shop in the capital of Berland. Recently the criminal activity in the capital increased, so Polycarp is thinking about establishing some better security in the storehouse of his shop.
The storehouse can be represented as a matrix with n rows and m columns. Each element of the matrix is either . (an emp... | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100001;
const long long MOD = 1000000007;
const long long INF = 1e18;
long long add(long long a, long long b) { return (a + b) % MOD; }
long long sub(long long a, long long b) { return (a - b + MOD) % MOD; }
long long mul(long long a, long long b) { return... |
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | print((lambda s: 'YES' if s[1][0] == 'S' and s[1][-1] == 'F' else 'NO')((input(), input().strip()))) |
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
What is the minimum number of ope... | import math
n=int(input())
a=list(map(int,input().split()))
x=[1 for x in a if x==1]
x=len(x)
if(x>=1):
print(n-x)
quit()
ans=n
for i in range(n):
g=a[i]
for j in range(i,n):
g=math.gcd(g,a[j])
if(g==1): ans=min(ans,j-i)
if(ans==n): print(-1)
else: print(ans+n-1)
|
The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and reduce it to the number of bits set to 1 in the binary representation of x. For example for number 13 it's true that 1310 = 11... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static String s=null;
static int length=-1;
static int INF= 10000000;
static ... |
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j, sum = 0;
vector<int> a;
cin >> n;
for (i = 0; i < n; i++) {
int x;
cin >> x;
a.push_back(x);
if (x == 0) sum++;
}
sort(a.begin(), a.end());
for (i = 0; i < n - 1; i++) {
if (a[i] == a[i + 1] && a[i] != 0) sum++;
... |
You are given a positive integer n, written without leading zeroes (for example, the number 04 is incorrect).
In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.
Determine the minimum number of operations that you need to consistently ap... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args){
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.