input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Mohan and his friends got bore so they decided to play something which help them to improve their Mental Math as exams are near by.So all of them frame their own questions for the game.
But when Mohan asked his question none his friends was able to answer it
so now they asked you for the help you have to tell the lar... | def _gcd(a, b):
if b==0:
return a
return _gcd(b, a%b)
t = input()
while t>0:
a, b, m, n = map(int, raw_input().split())
a = a-m
b = b-n
print _gcd(a,b)
t-=1 |
Ozo is making a project on mathematical equation given by his teacher, but he want to test the given equation,
whether this equation contain any positive integral root or not. Because if equation does not contain integral root his project will give abnormal results and he will not able to submit his project on time.
... | from sys import stdin;
import math
def dig(u):
total = 0
while u:
total+=u%10
u/=10
return total
def sol(u):
roo = int(math.sqrt(u))
roo+=1;
st = 1
if roo>100:
st = roo-100
# print "root is ",roo, " and we start from ",st
while st<=roo:
if u%st==0:
b = st + dig(st)
if b*st==u:
return st
st+=... |
Rasta calls a number like a Tavas if and only if 1 ≤ a ≤ n and the sum of all primes (like p) that p | a is exactly equal to k.
He asks you to find the number of Tavases.
Input format
The first and only line of input contains two integers, n and k (1 ≤ n, k ≤ 10^6).
Output format
Print a single integer, the number o... | n,k=map(int,raw_input().split())
s=[0]*(n+1)
for i in range(2,n+1):
if(s[i]==0):
for j in xrange(i,n+1,i):
s[j]=s[j]+i
count=0
for i in range(n+1):
if(s[i]==k):
count+=1;
print count |
1) Rama is late to college as usual. As he went on to pull a pair of socks , he found that the number of socks was odd. Though he had a pair of socks to put on he was curious on finding the socks whose pair was missing. The colours of socks are can take any integer value >0. Can you help him find out the colour of the... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
import math
ts=input()
for i in range(ts):
ts1=input()
dat=raw_input().split()
dat=map(int,dat)
z=max(dat)
v=min(dat)
for x in range(v,z+1):
if dat.count(x) is not 0 and dat.cou... |
Tic-Tac-Toe are three cousins. They are playing a game on Fibonacci numbers. The rule of the game is simple -
If the sum of Non-Fibonacci numbers upto N is prime, Tic wins.
If the sum of Non-Fibonacci numbers upto N is even, Tac wins.
If the sum of Non-Fibonacci numbers upto N is odd and not prime, Toe wins.
Fibonacci... | import math
def ips(n):
s=int(math.sqrt(n))
return (s*s==n)
def isfibo(n):
return ips(5*n*n+4) or ips(5*n*n-4)
def isprime(n):
if n==2 or n==3:
return True
if n<2 or n%2==0:
return False
if n<9:
return True
if n%3==0:
return False
r = int(n**(0.5))
f = 5
while f<=r:
if n%f==0:
return False
if n... |
In this problem, you should process T testcases.
For each testcase, you are given four integers N, M, A, B.
Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M).
Constraints
* 1 \leq T \leq 100,000
* 1 \leq N, M \leq 10^9
* 0 \leq A, B < M
Input
Input is given from Standard Input in the following format:
... | import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def floor_sum(n,m,a,b): # sum((A*i+B)//M for i in range(N))
res = 0
res += (a//m)*n*(n-1)//2 + (b//m)*n
a %= m
b %= m
y_max = (a*n+b)//m
if y_max == 0:
return ... |
You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.
There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.
According to an examina... | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int ulli;
int main() {
ulli n, ans = 0;
cin >> n;
map<int, int> m;
for (ulli i = 1; i <= n; i++) {
int temp;
cin >> temp;
ans += m[i-temp];
m[i+temp]++;
}
cout << ans;
} |
At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:
* The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)
* Each time the player wins a round, depending on which hand he/she use... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll ans;
int main() {
int n,k,R,P,S;
cin >> n >> k >> R >> S >> P;
string s;
cin >> s;
for(int i = 0;i<n;i++)
{
if(i >= k && s[i]==s[i-k]){
s[i] = ' ';
continue;
}
if(s[i] == 'r')
... |
We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.
For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate ... | #include<bits/stdc++.h>
using namespace std;
#define N 200005
long long n,O[N],X[N],Pow[N],mo=998244353,ans;
struct V {
long long x,y;
bool operator <(const V a)const {
return y<a.y;
}
} A[N];
long long _1[N],_2[N],_3[N],_4[N];
void ADD(int o) {
while(o<=n)O[o]++,o+=o&-o;
}
int SUM(int o) {
int sum=0;
while(o)s... |
You are given a permutation p = (p_1, \ldots, p_N) of \\{ 1, \ldots, N \\}. You can perform the following two kinds of operations repeatedly in any order:
* Pay a cost A. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the left by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, ... | #include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n,i,A,B,j,ans,f[5010][5010],a[5010];
int main(){
scanf("%lld%lld%lld",&n,&A,&B);
for(i=1;i<=n;i++)scanf("%lld",&a[i]);
memset(f,44,sizeof(f));
f[0][0]=0;
for(i=1;i<=n;i++){
for(j=0;j<=n;j++){
if(a[i]>j)f[i][a[i]]=min(f[i][a[i]],f[i-1][j]),f[... |
In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.
One day, there was an exam where a one-year-old child must write a program that prints `Hello World`, and a two-year-old child must write a program that receives integers A, B... | import sys
if input()=="1": print("Hello World"),sys.exit()
print(int(input())+int(input())) |
You are given sequences A and B consisting of non-negative integers. The lengths of both A and B are N, and the sums of the elements in A and B are equal. The i-th element in A is A_i, and the i-th element in B is B_i.
Tozan and Gezan repeats the following sequence of operations:
* If A and B are equal sequences, ter... | #include<cstdio>
#include<iostream>
using namespace std;
int q;long long sum,a,b,m=100000000000;bool flag;
int main()
{
cin>>q;
while(q--)
{
cin>>a>>b;
sum+=b;
if(m>b&&b<a)
m=b;
if(a!=b)
flag=1;
}
if(flag)
cout<<sum-m;
else cout<<0;... |
You are given a sequence a = \\{a_1, ..., a_N\\} with all zeros, and a sequence b = \\{b_1, ..., b_N\\} consisting of 0 and 1. The length of both is N.
You can perform Q kinds of operations. The i-th operation is as follows:
* Replace each of a_{l_i}, a_{l_i + 1}, ..., a_{r_i} with 1.
Minimize the hamming distance... | #include <bits/stdc++.h>
using namespace std;
struct SegTree{
vector<int> val;
void build(){
val.resize((1<<18)*2);
for(int i=0;i<(1<<18)*2;++i){
val[i]=INT_MIN;
}
}
void modify(int x,int v){
x+=(1<<18)-1;
val[x]=v;
while(x>0){
x=(x-1)/2;
val[x]=max(val[x*2+1],val[x*2+2]);
}
}
int query(int... |
Takahashi is an expert of Clone Jutsu, a secret art that creates copies of his body.
On a number line, there are N copies of Takahashi, numbered 1 through N. The i-th copy is located at position X_i and starts walking with velocity V_i in the positive direction at time 0.
Kenus is a master of Transformation Jutsu, an... | #include<bits/stdc++.h>
using namespace std;
const int N=200100,mod=1000000007;
inline void reduce(int&x){x+=x>>31&mod;}
int n,l[N],r[N],f[N],b[N];
pair<int,int>a[N];
int main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
for(int i=1;i<=n;++i)cin>>a[i].first>>a[i].second,b[i]=a[i].second;;
sort(a+1,a... |
There is a string s of length 3 or greater. No two neighboring characters in s are equal.
Takahashi and Aoki will play a game against each other. The two players alternately performs the following operation, Takahashi going first:
* Remove one of the characters in s, excluding both ends. However, a character cannot b... | #D
s = input()
if s[0] == s[-1]:
if len(s)%2==0:
print("First")
else:
print("Second")
else:
if len(s)%2==0:
print("Second")
else:
print("First") |
There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?
Constraints
* 1≦N≦100
Input
The input is given from Standard Inpu... | #include<bits/stdc++.h>
using namespace std;
int main(void){
int n;
cin>>n;
cout<<n*(1+n)/2<<endl;
} |
Mr. Suzuki has opened a new mobile sales shop for freshly squeezed milk in the Aizu area. It is assumed that all the customers who come to buy that day are already in the store with bottles to take home and will not increase any more. Customers only order once each. There is only one faucet in the tank, so you have to ... | #include <iostream>
#include <algorithm>
#include <cassert>
#include <cctype>
#include <complex>
#include <cstdio>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
ll n,w[10000];
int main(){
while(cin>>n){... |
The manager of the Japanese sweets shop Tomogurido in Aizuwakamatsu City is a very skillful craftsman, but he feels a little mood. The buns made by the manager are very delicious, but the size varies depending on the mood at that time.
The store manager's wife, who couldn't see it, came up with the idea of packing b... | #include <cstdio>
#include <map>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
typedef unsigned long long ull;
map<ull,int> memo;
int dfs2(ull, int, int);
int dfs1(ull s){
if(s <= 0xff){
return s / 10;
}
if(memo.count(s)){
return memo[s];
}
int k;
for(k = 8; !(s >> ((k ... |
Consider the following game. There are k pairs of n cards with numbers from 1 to n written one by one. Shuffle these kn cards well to make piles of k cards and arrange them in a horizontal row. The i-th (k-card) pile from the left of the n piles created in this way is called "mountain i".
<image>
The game starts at ... | #include <iostream>
#include <iomanip>
using namespace std;
int ans[11000];
int kansu( long long int a, long long int b ) {
for ( int i = 0; i < 11000; i++ ) {
ans[i] += a / b;
a = a % b * 10;
}
for ( int i = 11000 - 1; i > 0; i-- ) {
ans[ i-1 ] += ans[i] / 10;
ans[i] = ans[i] % 10;
}
... |
Nantendo Co., Ltd. has released a game software called Packet Monster. This game was intended to catch, raise, and fight monsters, and was a very popular game all over the world.
This game had features not found in traditional games. There are two versions of this game, Red and Green, and the monsters that can be caug... | #include<bits/stdc++.h>
using namespace std;
int main(){
int p;
string a[2],c,ans;
while(1){
cin>>a[0];
if(a[0]=="-")break;
cin>>a[1]>>c;
p=1;
while(c.size()){
if(c[0]==a[p][0]){
if(c.size())c=c.substr(1,c.size()-1);
if(a[p].size())a[p]=a[p].substr(1,a[p].size()-1);
p=0;
}else{... |
Amber Claes Maes, a patissier, opened her own shop last month. She decided to submit her work to the International Chocolate Patissier Competition to promote her shop, and she was pursuing a recipe of sweet chocolate bars. After thousands of trials, she finally reached the recipe. However, the recipe required high skil... | #include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <cassert>
using namespace std;
struct BipartiteMatching {
int V;
vector<vector<bool> > G;
vector<int> match;
vector<bool> used;
BipartiteMatching(int v) {
V = v;
G = v... |
After decades of fruitless efforts, one of the expedition teams of ITO (Intersolar Tourism Organization) finally found a planet that would surely provide one of the best tourist attractions within a ten light-year radius from our solar system. The most attractive feature of the planet, besides its comfortable gravity a... | #include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <utility>
const int drct[2][3][2] = {{{0, 1}, {-1, 0}, {1, 0}}, {{0, -1}, {1, 0}, {-1, 0}}};
int sd_x, sd_y, bottom;
struct State {
int x, y, bot, up, step;
State() {}
State(int x, int y, int bot, int up, int step):
x(x), y(y... |
Problem
At Abandoned University, N waste materials that give off a strong scent are lined up in a row. The waste materials are numbered from 1 to N in order, and the i-th waste material gives off a strong ai scent.
At work, Licht was asked to find the sum of the scents of all the waste wood. If the total scent is M o... | #include <bits/stdc++.h>
using namespace std;
const long long INIT = LLONG_MIN;
class segment_tree {
private:
int n;
vector<long long> dat;
static inline long long func(long long a, long long b) {
return max(a, b);
}
long long query(int a, int b, int k, int l, int r) const {
if(r <= a || b <= l) r... |
A space hunter, Ken Marineblue traveled the universe, looking for the space coconut crab. The space coconut crab was a crustacean known to be the largest in the universe. It was said that the space coconut crab had a body of more than 400 meters long and a leg span of no shorter than 1000 meters long. Although there we... | #include <stdio.h>
#include <iostream>
#include <vector>
#include <list>
#include <cmath>
#include <fstream>
#include <algorithm>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <complex>
#include <iterator>
#include <cstdlib>
using namespace std;
#define EPS (1e-10)
#define EQ(a,b) (abs((a)... |
Artistic Crystal Manufacture developed products named Crystal Jails. They are cool ornaments forming a rectangular solid. They consist of colorful crystal cubes. There are bright cores on the center of cubes, which are the origin of the name. The combination of various colored reflections shows fantastic dance of light... | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-12;
int w, d, h;
int n, m=3;
int[][][][] a;
... |
Problem statement
There is a rational number sequence $ X_0, X_1, X_2, ..., X_N $. Each term is defined as follows.
1. $ X_0 = 0 $
2. $ X_i = X_ {i-1} $ $ op_i $ $ Y_i $ ($ 1 \ leq i \ leq N $). However, $ op_i $ is $ + $, $ − $, $ × $, $ ÷ $ Either.
Find $ X_N $.
Constraint
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \... | #include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
long long module(long long x, long long m){
while(x >= m) x -= m;
return x;
}
long long mul(long long a, long long b, long long mod){
if(b == 0) return 0;
long long res = mul(module(a + a, mod), b / 2, mod);
... |
Problem Statement
Do you know the data structure called BDD (Binary Decision Diagram)? In recent years, ZDD, which has become a hot topic in the video related to Combinatorial Explosion Sister, is a data structure derived from BDD. This problem is a basic implementation of BDD.
BDD is a cycleless graph (DAG) that rep... | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
// B2D
// 2013/09/19
public class Main{
Scanner sc=new Scanner(System.in);
int n;
String s;
void run(){
n=sc.nextInt();
s=sc.n... |
Example
Input
3
aab
czc
baa
Output
aac | #include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<utility>
#include<cassert>
#in... |
B: Dansunau www --Dance Now!-
story
Last lab life! Daigakuin! !! Dosanko Snow has won 9th place in the event "Master Idol World", which can be said to be the outpost of the biggest competition "Lab Life" where master idols compete. The sharp dance is ridiculed as "9th place dance", and the whole body's deciding pose ... | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.NoSuchElementException;
public class Main {
int N;
int[] R;
int[][] spc;
private boolean ok(int x, int pos) {
spc[0][pos] += x;
int[][] points = ... |
D: Two Colors Sort
problem
During the walk, umg found a sequence of length N, P_1, P_2, ..., P_N, which can be made by rearranging 1,2, ..., N.
umg can use mysterious powers to exchange places by choosing two different numbers painted in the same color.
umg wanted to be able to sort the sequence in ascending order ... | #include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < n; i++)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pi;
typedef pair<pi, pi> pp;
typedef pair<ll, ll> pl;
const double EPS = 1e-9;
const ll MOD = 1000000007;
const int inf = 1 << 30;
const ll linf = 1LL <... |
Twins
square1001 and E869120 are twins.
Please output the one that was born first.
input
No input is given.
output
Output the correct character string on one line.
However, insert a line break at the end.
Output example 1
square1001
Example
Input
Output | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
//#include <boost/multiprecision/cpp_int.hpp>
//typedef boost::multiprecision::cpp_int ll;
typedef long double dd;
#define i_7 (ll)(1E9+7)
//#define i_7 998244353
#define i_5 i_7-2
ll mod(ll a){
ll c=a%i_7;
if(c>=0)return c;
return c+i_7;
}... |
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ ... | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <sstream>
#include <cmath>
#include <set>
#include <iomanip>
#include <deque>
#include <limits>
using namespace std;
typedef long long ll;
#define REP(i,n) for(int (i)=0;(i)<(int)(n);... |
Yesterday was Anish's birthday. The most interesting gift was definitely the chessboard. Anish quickly learned the rules of chess and started to beat all his peers.
That day night Anish was reading a Book on puzzles and Enigma. He opened the book somewhere in the middle and read the following problem: "How many kni... | while(1):
try:
x=input()
if((x==1) or (x==0)):
print x
else:
print 2*(x-1)
except:
break; |
A positive integer is called a palindrome if its representation in the
decimal system is the same when read from left to right and from right
to left. For a given positive integer K of not more than 5 digits,
write the value of the smallest palindrome larger than K to output.
Numbers are always displayed withou... | def palindrome(x):
n = str(x)
str1 = ''
for i in range(len(n)-1,-1,-1):
str1 += n[i]
if str1 == n:
return True
else:
return False
a = input()
for h in range(a):
num = input() + 1
while palindrome(num) != True:
num += 1
print num |
Write a program to check whether a triangle is valid or not, when the three angles of the triangle are the inputs. A triangle is valid if the sum of all the three angles is equal to 180 degress.
Input
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains three angl... | T = int(raw_input())
for i in range(T):
a = map(int, raw_input().split())
if (a[0]+a[1]+a[2]) == 180 and 0 not in a:
print 'YES'
else:
print 'NO' |
The Little Elephant likes permutations. This time he has a permutation A[1], A[2], ..., A[N] of numbers 1, 2, ..., N.
He calls a permutation A good, if the number of its inversions is equal to the number of its local inversions. The number of inversions is equal to the number of pairs of integers (i; j) such that 1 ≤... | for t in range(int(raw_input())):
n=int(raw_input())
a=[]
N=map(int,raw_input().split())
add=0
count=0
for i in range(n):
for j in range(i,n):
if N[i]>N[j]:
count+=1
for i in range(n-1):
if N[i]>N[i+1]:
add+=1
if add==count:
... |
Vicky has great love for gardening and prime numbers. He wants to create a rectangular garden such that the square of the diagonal of the rectangle is a prime number (the diagonal of course can be any real number) and its sides are positive integers. You have to help Vicky by telling whether he can create such a garde... | t=input("")
while t:
t=t-1
a=input("")
if(a==2):
print "YES"
elif(a%4==1):
print "YES"
else:
print "NO" |
India celebrates her Republic day on 26th January every year. It is celebrated in every colleges and schools.
While preparing for the celebration in BIT-Deoghar, Lemon Kumar, a student in-charge of the Republic day event, went to buy sweet packets.
In the shop n packets are kept in a tray, numbered from 1 to n and havi... | T=input()
for _ in xrange(T):
N,C=map(int,raw_input().split())
A=map(int,raw_input().split())
val,temp=0,0
for x in A:
x-=C
temp=max(0,temp+x)
val=max(temp,val)
print val |
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from ... | #include <bits/stdc++.h>
using namespace std;
double calc_fuel(double payload, double fuel, double ratio) {
double use = (payload + fuel) / (ratio);
return fuel - use;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cout << fixed << setprecision(15);
int N, M;
cin >> N >> M;
ve... |
Mr. F has n positive integers, a_1, a_2, …, a_n.
He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.
But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.
... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const int N = 3e5 + 5;
const int N2 = 1.5e7 + 5;
int n;
int cnt = 0;
int check[5005];
int a[N];
int num[N2];
int prime[N];
int gcd(int x, int y) { return y == 0 ? x : gcd(y, x % y); }
void _prime() {
int m = 5000;... |
Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of n problems and lasts for T minutes. Each of the problems is defined by two positive integers a_i and p_i — its difficulty and the score awarded by its solution.
Polycarp's experience suggests that... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
double C, T;
cin >> C >> T;
vector<pair<int, int>> ap(n);
long long max_points = 0;
for (auto& p : ap) {
cin >> p.first >> p.second;... |
As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC).
A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to differen... | import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
// int k(int l,int u){
// int ret=l;
// FOR(i,l+1,u+1){
// ret*=i;
// }
// return ret;
// }
//
static BigDecimal k(int l, int u) {
BigDecimal ret = ... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with... | import java.util.*;
public class MyClass {
public static void main(String args[]) {
int c=0,k,n,i;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
k=0;
//System.out.println(n);
if(n-18<0)
{
if(n==4)
System.out.print(n);
else if(n==7)
System.out.pr... |
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the tow... | #include <bits/stdc++.h>
using namespace std;
inline int rei() {
int x;
cin >> x;
return x;
}
inline long long rel() {
long long x;
cin >> x;
return x;
}
inline string res() {
string x;
cin >> x;
return x;
}
int A[500000];
int need[500001];
int needneed[500001];
void Calc() {
int N = rei();
int K ... |
Alice and Bob are playing a game with n piles of stones. It is guaranteed that n is an even number. The i-th pile has a_i stones.
Alice and Bob will play a game alternating turns with Alice going first.
On a player's turn, they must choose exactly n/2 nonempty piles and independently remove a positive number of stone... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) cin >> x;
const int m = *min_element(a.begin(), a.end());
const int c = count(a.begin(), a.end(), m);
cout << (c > n / 2 ? "Bob" : "Alice");
... |
Toad Ilya has a rooted binary tree with vertex 1 being the root. A tree is a connected graph without cycles. A tree is rooted if one vertex is selected and called the root. A vertex u is a child of a vertex v if u and v are connected by an edge and v is closer to the root than u. A leaf is a non-root vertex that has no... | #include <bits/stdc++.h>
const int maxn = 150005 + 7;
int L[maxn], sum[maxn], d[maxn], fa[maxn], link[maxn], f[maxn][27], g[maxn][27],
belong[maxn], bad[maxn], len, old[maxn][27];
int n, q, bad_cnt;
char c[maxn], s[maxn];
std::vector<int> ch[maxn], nxt[maxn], S[maxn][26];
int is_single(int x) {
if (x == 0 || x ==... |
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | for _ in range(int(input())):
n,s,t = map(int,input().split())
print(max(n-s+1,n-t+1)) |
Define the beauty of a permutation of numbers from 1 to n (p_1, p_2, ..., p_n) as number of pairs (L, R) such that 1 ≤ L ≤ R ≤ n and numbers p_L, p_{L+1}, ..., p_R are consecutive R-L+1 numbers in some order. For example, the beauty of the permutation (1, 2, 5, 3, 4) equals 9, and segments, corresponding to pairs, are ... | #include <bits/stdc++.h>
using namespace std;
const int mx = 100;
inline long long read() {
long long x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 1) + (x << 3) + c - '0';
c = getchar();
}
ret... |
You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!
You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of t... | t = int(input())
for case_num in range(t):
n = int(input())
p = list(map(int, input().split(' ')))
x, a = map(int, input().split(' '))
y, b = map(int, input().split(' '))
k = int(input())
p.sort()
p.reverse()
sum = [0]
for i in range(n):
sum.append(sum[-1] + p[i])
if x < ... |
In the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are n residents and n cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from 1 to n, where the i... | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e6 + 5;
int n, m;
vector<int> p, c;
struct Edge {
int to, nxt;
} e[MAX_N];
int cnt;
int head[MAX_N], tote;
void add_edge(int x, int y) {
e[++tote].to = y, e[tote].nxt = head[x];
head[x] = tote;
}
int dfn[MAX_N], low[MAX_N];
int idx;
int belong[MAX_N... |
Byteburg Senate elections are coming. Usually "United Byteland", the ruling Byteland party, takes all the seats in the Senate to ensure stability and sustainable development. But this year there is one opposition candidate in one of the constituencies. Even one opposition member can disturb the stability in the Senate,... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const long long INF = 1e9 + 7;
int main() {
long long n, m;
cin >> n >> m;
vector<vector<pair<long long, long long> > > v(
m, vector<pair<long long, long long> >(n));
for (long long i = 0; i < m; i++) {
for (long long j = 0; j < n; j... |
You are given a bipartite graph: the first part of this graph contains n_1 vertices, the second part contains n_2 vertices, and there are m edges. The graph can contain multiple edges.
Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs r coins) or p... | #include <bits/stdc++.h>
using namespace std;
template <class FLOWTYPE, class COSTTYPE>
struct Edge {
int rev, from, to, id;
FLOWTYPE cap, icap;
COSTTYPE cost;
Edge(int r, int f, int t, FLOWTYPE ca, COSTTYPE co, int id = -1)
: rev(r), from(f), to(t), cap(ca), icap(ca), cost(co), id(id) {}
friend ostream... |
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!
Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move:
* exactly a steps left: from (u,v) to (u-1,v);
* exactly b steps right: from (u,v) to (u+1,v); ... | import sys
I = lambda: int(input())
readline = lambda: sys.stdin.readline().strip('\n')
RM = readmap = lambda x=int: map(x,readline().split(' '))
#1332 630 div2
for _ in range(I()):
a,b,c,d,x,y,x1,y1,x2,y2 = *RM(),*RM()
flag1 = x2-x >= b-a and x-x1 >= a-b and y2-y >= d-c and y-y1 >= c-d
flag2 = ((b==0 an... |
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists o... | from sys import stdin, stdout
from collections import deque
def main():
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
ar = deque(map(int, stdin.readline().split()))
a = 0
b = 0
prev = ar.popleft()
a += prev
turn = 1
move ... |
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b.
Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc... | #include <bits/stdc++.h>
const long long iinf = 1e18;
const int inf = 1e9 + 10;
const int MOD = (1e6 + 3);
int dir4[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int knight[8][2] = {{2, 1}, {2, -1}, {-2, 1}, {-2, -1},
{1, 2}, {-1, 2}, {1, -2}, {-1, -2}};
using namespace std;
void solve() {
int n;
... |
Boboniu gives you
* r red balls,
* g green balls,
* b blue balls,
* w white balls.
He allows you to do the following operation as many times as you want:
* Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the b... | import java.awt.*;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class TaskC {
static class Edge implements Comparable<Edge> {
int v,cost;
public Edge( int x, int y) {
this.v = x;
this.cost = y;
}
public int compareTo(Edge o)... |
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ... | n = int(input())
a = sorted([int(i) for i in input().split()])
b = []
for i in range(n // 2):
b.append(a[-1-i])
b.append(a[i])
if n % 2 == 1:
b.append(a[n // 2])
print((n - 1) // 2)
print(' '.join([str(i) for i in b]))
|
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in whi... | #include <bits/stdc++.h>
using namespace std;
void solve() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) cin >> a[i];
vector<int> poss;
int count = 1;
for (int i = 2; i < n; i++) {
if (a[i] > a[i - 1]) {
count++;
} else {
... |
Polycarp has a string s[1 ... n] of length n consisting of decimal digits. Polycarp performs the following operation with the string s no more than once (i.e. he can perform operation 0 or 1 time):
* Polycarp selects two numbers i and j (1 ≤ i ≤ j ≤ n) and removes characters from the s string at the positions i, i+... | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in=new Scanner(System.in);
... |
A big football championship will occur soon! n teams will compete in it, and each pair of teams will play exactly one game against each other.
There are two possible outcomes of a game:
* the game may result in a tie, then both teams get 1 point;
* one team might win in a game, then the winning team gets 3 point... | import java.math.BigInteger;
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int p = 0; p < t; p++) {
int n = sc.nextInt();
StringBuilder res = new StringBuilder();
... |
The brave Knight came to the King and asked permission to marry the princess. The King knew that the Knight was brave, but he also wanted to know if he was smart enough. So he asked him to solve the following task.
There is a permutation p_i of numbers from 1 to 2n. You can make two types of operations.
1. Swap p_... | import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.System.arraycopy;
import static java.lang.System.exit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader... |
Polycarp came up with a new programming language. There are only two types of statements in it:
* "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a v... | def count(string):
c=0
for i in range(len(string)-3):
k=0
va=0
for j in "haha":
if string[i+k]==j:
va+=1
else:
break
k+=1
if va==4:
c+=1
return c
def values(string):
length=len(string)
occ... |
Polycarpus has many tasks. Each task is characterized by three integers li, ri and ti. Three integers (li, ri, ti) mean that to perform task i, one needs to choose an integer si (li ≤ si; si + ti - 1 ≤ ri), then the task will be carried out continuously for ti units of time, starting at time si and up to time si + ti -... | #include <bits/stdc++.h>
using namespace std;
int n, ans, si;
const int inf = 1e9 + 9;
struct pp {
int id, value;
bool operator<(const pp &temp) const { return id < temp.id; }
};
struct point {
int l, r, t;
};
point pt[110000];
struct segment_tree {
int l, r, value, min_value, max_value, delta;
int id_max, id... |
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Mish... | g1=list(input())
g2=list(input())
cntr=0
if sorted(g1)!=sorted(g2):
print('NO')
else:
for i in range(len(g1)):
if g1[i]!=g2[i]:
cntr=cntr+1
if cntr==2:
print('YES')
else:
print('NO') |
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem:
You've got some training set of documents. For each document you know its su... | #include <bits/stdc++.h>
using namespace std;
inline long long labs(long long a) { return a < 0 ? (-a) : a; }
template <typename T>
inline T sqr(T x) {
return x * x;
}
string ToStr3(int smpl) {
ostringstream oss;
oss << smpl;
string test = oss.str();
while (test.size() < 3) test = "0" + test;
return test;
}... |
John Doe has an n × m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n × n have exactly k points.
John Doe wondered, how many distinct ways to fill the table with points are there, provided that... | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStr... |
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ... | n=input()
c=0
res=''
for i in range(len(n)):
if(n[i]=='0' and c==0):
c+=1
elif(n[i]=='0' and c>0):
res+="0"
elif(n[i]=='1'):
res+="1"
else:
pass
l=len(res)
if c==0:
res=res[:l-1]
print(res)
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | n=list(input())
print(n[0].upper()+str(''.join(n[1:])))
|
Imagine a real contest or exam of n participants. Every participant will get a particular score. We can predict the standings board more or less, if we do some statistics on their previous performance.
<image>
Let's say the score of the participants will be uniformly distributed in interval [li, ri] (the score can be... | #include <bits/stdc++.h>
using namespace std;
const int N = 105;
int n, V, now;
int sl[N], sr[N], lens[N], h[N * 2];
double ans[N][N];
void add(int x, int l, int r, double y) {
ans[x][l] += y;
ans[x][r + 1] -= y;
}
void trans(int x, int c, double F[N][N]) {
double g0 = sr[x] > now + 1
? 1.0 * (h... |
You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows:
<image>
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain... | R, C = map(int, raw_input().split())
a = [raw_input() for i in xrange(R)]
print len([(i, j) for i in xrange(R) for j in xrange(C) if 'S' not in a[i] or 'S' not in map(list, zip(*a))[j]])
|
Cosider a sequence, consisting of n integers: a1, a2, ..., an. Jeff can perform the following operation on sequence a:
* take three integers v, t, k (1 ≤ v, t ≤ n; 0 ≤ k; v + tk ≤ n), such that av = av + t, av + t = av + 2t, ..., av + t(k - 1) = av + tk;
* remove elements av, av + t, ..., av + t·k from the sequen... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
const int MOD = 1000000007;
const int inf = (1 << 30) - 1;
const ll INF = (1LL << 60) - 1;
template <typename T>
bool chmax(T &x, const T &y) {
... |
You have a weighted tree, consisting of n vertices. Each vertex is either painted black or is painted red. A red and black tree is called beautiful, if for any its vertex we can find a black vertex at distance at most x.
The distance between two nodes is the shortest path between them.
You have a red and black tree. ... | #include <bits/stdc++.h>
using namespace std;
vector<vector<double> > m;
void change(int index, int a);
double simplex();
void solve(int n, int x, vector<bool>& c, vector<vector<long long> >& dis,
int count);
int main() {
int n, x;
int count = 0;
cin >> n >> x;
vector<bool> c(n);
bool b;
for (int... |
User ainta decided to paint a wall. The wall consists of n2 tiles, that are arranged in an n × n table. Some tiles are painted, and the others are not. As he wants to paint it beautifully, he will follow the rules below.
1. Firstly user ainta looks at the wall. If there is at least one painted cell on each row and a... | #include <bits/stdc++.h>
using namespace std;
const int N = 2222;
long double dp[N][N];
int n;
long double go(int r, int c) {
if (r < 0 || c < 0) return -1.0;
if (r == 0 && c == 0) return 0.0;
long double &ret = dp[r][c];
if (ret < 0) {
ret = 0;
ret += (go(r - 1, c - 1) + 1.0) * (long double)r * c;
... |
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!'
The head of the company d... | #include <bits/stdc++.h>
using namespace std;
int cnt[300010];
int freq[300010];
void inc(int k) {
cnt[k]++;
freq[cnt[k]]++;
}
void dec(int k) {
freq[cnt[k]]--;
cnt[k]--;
}
void clear(int k) {
while (cnt[k] >= 0) {
freq[cnt[k]]--;
--cnt[k];
}
}
pair<int, int> p[300010];
int main() {
int n, k;
sc... |
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d... | #include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> t(300, 0);
int p, n;
cin >> p >> n;
int col = -1;
for (int i = 0; i < n; ++i) {
int z;
cin >> z;
z %= p;
if (t[z] && col == -1) {
col = i + 1;
}
t[z] = 1;
}
cout << col;
return 0;
}
|
Little X and Little Z are good friends. They always chat online. But both of them have schedules.
Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the ti... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, l, r;
cin >> n >> m >> l >> r;
int p[n], q[n];
for (int c = 0; c < n; c++) cin >> p[c] >> q[c];
int b[m], d[m];
for (int c = 0; c < m; c++) cin >> b[c] >> d[c];
int ans = 0;
for (int c = l; c <= r; c++) {
bool posibil = 0;
for ... |
Hiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through.
It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the se... | #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int t = 1;
int f = 1;
for (int i = 0; i < a + b + 1; i++) {
if (i == a) {
cout << a + b + 1 << " ";
t = a + b;
f = -f;
continue;
}
cout << t << " ";
t += f;
}
}
|
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites <image>-th boy and... | import static java.lang.Math.abs;
import java.util.*;
public class Le {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
int b[]=new int[n];
int g[]=new int[m];
int bo=s.nextInt();
for(int i=0;i<... |
Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function <image>, that for any <image> the formula g(g(x)) = g(x) holds.
Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x), f(k)(x) = f(f(k - 1)(x))... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
if (a == 0) {
return b;
}
if (b == 0) {
return a;
}
if (a > b) {
return gcd(a % b, b);
} else {
return gcd(b % a, a);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin... |
Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.
A set ρ of pairs (a, b) of elements ... | // CodeForces Round #569 D
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class SimmTransitive {
int n;
long nret;
final long MOD=1000000007;
int [][]memCEN;
int [][]memCNK;
final static int MAXN=4001;
p... |
A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.
We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at poi... | import java.util.*;
public class D327 {
public static void main(String[] args) {
Scanner qwe = new Scanner(System.in);
double x1 = qwe.nextDouble();
double y1 = qwe.nextDouble();
double x2 = qwe.nextDouble();
double y2 = qwe.nextDouble();
double v = qwe.nextDouble();
double t = qwe.nextDou... |
You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.
For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".
Note it is allowed to split the string s to the strings only of length p or... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, p, q;
string s;
cin >> n >> p >> q >> s;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
if (n == i * p + j * q) {
int k = 0;
cout << i + j << endl;
while (i--) {
cout << s.substr(k, p) << end... |
Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.
She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and al... | n,k = map(int,input().split())
s = [input() for i in range(n)]
s = s[::-1]
x = 0
# print(s)
cost = 0
for i in s:
if i == "halfplus":
x = 2*x+1
cost += x/2*k
else:
x = 2*x
cost += x/2*k
print(int(cost)) |
You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.
Input
The first line of the input contains integer n (1 ≤ n ≤ 2000) — the number of points.
Each of the next n lines contains two integers... | #include <bits/stdc++.h>
using namespace std;
struct Center {
int x, y;
bool _x, _y;
bool operator==(const Center& a) const {
return (x == a.x && y == a.y && _x == a._x && _y == a.y);
}
bool operator<(const Center& a) const {
if (x != a.x) return x < a.x;
if (y != a.y) return y < a.y;
if (_x !... |
Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.
To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities nu... | import java.io.*;
import java.util.*;
import java.lang.*;
public class Rextester{
public static void shuffle(int[] array){
Random rand = new Random();
for(int i=0;i<array.length;i++){
int x = rand.nextInt(array.length-i)+i;
int temp = array[x];
array[x]=array[i];... |
There is a square box 6 × 6 in size. It contains 36 chips 1 × 1 in size. Those chips contain 36 different characters — "0"-"9" and "A"-"Z". There is exactly one chip with each character.
You are allowed to make the following operations: you may choose one of 6 rows or one of 6 columns and cyclically shift the chips th... | #include <bits/stdc++.h>
using namespace std;
int A[8][8];
vector<pair<char, int> > res;
int F(char c) {
if ('0' <= c && c <= '9') return c - '0';
return c - 'A' + 10;
}
void F(int x, int y, int z) {
int i;
if (z == 1) {
for (i = 0; i < 13; i++)
if (i & 1)
res.push_back(make_pair((i / 2) % 2 =... |
In the country of Never, there are n cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as <image> roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered ... | #include <bits/stdc++.h>
using namespace std;
const long long MN = 2e3 + 20, INF = 1e9 + 2000;
long long a[MN][MN], dist[MN];
set<pair<long long, long long>> myset;
bool fix[MN];
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, mn = INF;
cin >> n;
for (long long i = 0; i < n; ... |
Mike has a sequence A = [a1, a2, ..., an] of length n. He considers the sequence B = [b1, b2, ..., bn] beautiful if the gcd of all its elements is bigger than 1, i.e. <image>.
Mike wants to change his sequence in order to make it beautiful. In one move he can choose an index i (1 ≤ i < n), delete numbers ai, ai + 1 a... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
PrintWriter out =... |
Vova again tries to play some computer card game.
The rules of deck creation in this game are simple. Vova is given an existing deck of n cards and a magic number k. The order of the cards in the deck is fixed. Each card has a number written on it; number ai is written on the i-th card in the deck.
After receiving th... | #include <bits/stdc++.h>
const double eps = 1e-10;
const float epsf = 1e-6;
using namespace std;
inline long long int __gcd(long long int a, long long int b) {
if (a == 0 || b == 0) {
return max(a, b);
}
long long int tempa, tempb;
while (1) {
if (a % b == 0)
return b;
else {
tempa = a;
... |
Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.
String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
Input
First line of input con... | #include <bits/stdc++.h>
using namespace std;
int main() {
std::ios::sync_with_stdio(false);
string s;
cin >> s;
int n;
cin >> n;
map<char, int> m;
int c = 0;
for (int i = 0; i < 26; i++) {
m['a' + i] = 0;
}
for (int i = 0; i < s.length(); i++) {
if (m[s[i]] == 0) {
c++;
m[s[i]] ... |
Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.
Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers fr... | def solve(printing):
n = int(input())
nums = [int(st)-1 for st in input().split(" ")]
numdupe = [0] * n
dupeindex = []
dupeindexindv = {}
missing = []
if printing:
print("nums"); print(nums)
for i in range(n):
numdupe[nums[i]] += 1
for i in range(n):
if nu... |
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time,... | #include <bits/stdc++.h>
using namespace std;
int INF = std::numeric_limits<int>::max();
long long LLINF = std::numeric_limits<long long>::max();
int NINF = std::numeric_limits<int>::min();
int MOD = 1000000007;
int col[] = {1, 0, -1, 0, 1, 1, -1, -1};
int row[] = {0, 1, 0, -1, 1, -1, 1, -1};
int cc[] = {1, 2, 2, 1, -1... |
The following problem is well-known: given integers n and m, calculate
<image>,
where 2n = 2·2·...·2 (n factors), and <image> denotes the remainder of division of x by y.
You are asked to solve the "reverse" problem. Given integers n and m, calculate
<image>.
Input
The first line contains a single integer n (1 ... | n,m=int(input()),int(input())
n=min(n,31)
print(m%(2**n))
|
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ... | n = int(input())
count = 1
for i in range(2,(n//2)+1):
if (n-i)%i ==0:
count+=1
print(count)
|
Santa has an infinite number of candies for each of m flavours. You are given a rooted tree with n vertices. The root of the tree is the vertex 1. Each vertex contains exactly one candy. The i-th vertex has a candy of flavour f_i.
Sometimes Santa fears that candies of flavour k have melted. He chooses any vertex x ran... | #include <bits/stdc++.h>
using namespace std;
struct segtree {
segtree *left = nullptr, *right = nullptr;
int lazy = 0, sum1 = 0;
long long sum2 = 0;
void apply(int x, int l, int r) {
sum2 += (long long)x * (2 * sum1 + (r - l + 1) * x);
sum1 += (r - l + 1) * x;
lazy += x;
}
void pull() {
sum... |
You are given an integer n from 1 to 10^{18} without leading zeroes.
In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes.
What is the minimum ... | #include <bits/stdc++.h>
using namespace std;
string buf, tmp;
int len, ans[4], ans1 = 10000000;
void swap(char& a, char& b) {
char t = a;
a = b;
b = t;
}
void ww(int i, char fir, char sec) {
tmp = buf;
ans[i] = -1;
if (tmp.rfind(sec) != -1) {
int pos1 = tmp.rfind(sec);
tmp.erase(pos1, 1);
if (t... |
Akshara is a Maths teacher at Dynamic Public School.One day she decided to take an unusual test of all her students.She took all her students to a fair.There she took them to a candy room.The room had 2 doors and behind each door was unlimited supply of candies.The excitement of the students could not be measured.Each ... | '''
# 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!'
'''
def maxsum(c, i, w):
if (i <= 0 or w <= 0):
return 0
if (c[i-1] > w):
return maxsum(c, i-1, w)
if (d[i-1][w] != -1):
return d... |
It is Jawa's birthday today. His each friend tells him the least number of toffees he wants. Later, his friends together decided that if he is able to satisfy the condition of atleast one of his friends than they will buy him a $1000 gift.
You have to help Jawa to decide the minimum number of toffees he need to buy to ... | T = int (raw_input ())
for t in xrange (T):
N = int (raw_input ())
l = [int (i) for i in raw_input ().split ()]
print sum (l) - N + 1 |
Vardhaman college of engg. is conducting a coding challenge. The registrations are opened. Many people from different colleges are being registered for this event. Some of them are trying to make some errors in the registrations. They have registered there names more than one time by creating different e-mail ids. This... | '''
# 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!'
t=input()
l=[]
p=[]
while t>0:
t-=1
s=raw_input()
if s in l:
if s not in p:
p.append(s)
else:
l.append(s)
print len(p)
p.sort()
for i in p:
print i |
Gandhijee is interested in building human tree. He defined a human node as follows :
Person_Id = English alphabet {a...z} .
Person_Chain_Definition = Person_Id ( Person_Chain_Definition Person_Chain_Definition )
For example :
a( b(..) c( d( . e(..) ) f( . . ) ) ) refers to a human tree having a as the roo... | #!/usr/bin/python
#gandhi tree problem
import copy
def convert(key, mystr):
global column,temp,Fcolumn
L = list(mystr)
#check if binary or single
open = 0
close = 0
LFindex = 0
LLindex = 0
RFindex = 0
RLindex = 0
#stores the a of a()
column[key] = L.pop(0)
#removes '(' and ')'
L.pop(0)
L.pop(len(L)-1)
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.