input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Today at the lesson Vitya learned a very interesting function β mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.
Vitya quickly understood all tasks of the teacher, but can you do the sa... | #include <bits/stdc++.h>
using namespace std;
const int N = (1 << 19) - 1;
const int MAXN = 600010;
int cnt[MAXN << 2];
int dig[20];
void update(int x, int l, int r, int rt) {
if (l == r) {
cnt[rt] = 1;
return;
}
int mid = (l + r) >> 1;
if (x <= mid)
update(x, l, mid, rt << 1);
else
update(x, ... |
You are given an array a of size n, and q queries to it. There are queries of two types:
* 1 li ri β perform a cyclic shift of the segment [li, ri] to the right. That is, for every x such that li β€ x < ri new value of ax + 1 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari;
... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct node {
node *ch[2] = {0}, *p = 0;
int cnt = 1, val;
bool flip = 0;
node(int val, node* l = 0, node* r = 0) : ch{l, r}, val(val) {}
};
node* update(node* x);
void prop(node* x);
int cnt(node* x) { return x ? x->cnt : 0; }
int dir(node* p,... |
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t = 1;
while (t--) {
long long n, i;
cin >> n;
map<long long, long long> mp;
long long s = 0;
for (i = 1; i <= n; i++) {
long long x;
cin >> x;
... |
You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps:
1. choose two leaves;
2. add the length of the simple path between them to the answer;
3. remove one of the chosen leaves from the tree.
Initial an... | #include <bits/stdc++.h>
using namespace std;
namespace Acc {
const long long N = 2e5 + 10;
basic_string<long long> G[N];
long long n, st, bg, l, ed, f[N], dis[N], ans, pos, tag[N], stk[2][N], cnt;
void dfs(long long u, long long fa, long long d) {
if (dis[u] = st ? d : 0, f[u] = fa, d > l) l = d, pos = u;
for (aut... |
Everything red frightens Nian the monster. So do red paper and... you, red on Codeforces, potential or real.
Big Banban has got a piece of paper with endless lattice points, where lattice points form squares with the same area. His most favorite closed shape is the circle because of its beauty and simplicity. Once he ... | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int mod = 1e9 + 7, N = 1e6 + 1;
const int rev2 = 500000004, rev3 = 333333336, rev6 = 1ll * rev2 * rev3 % mod;
int s2[N], s4[N], s6[N];
LL q2(LL i) {
i %= mod;
return i * i % mod;
}
LL q4(LL i) {
i %= mod;
return i * i % mod * i % mod * i ... |
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.
B now gi... | import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution {
public static void main(String[] args) throws Exception {
new Solution().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Solution() throws IOExceptio... |
Some company is going to hold a fair in Byteland. There are n towns in Byteland and m two-way roads between towns. Of course, you can reach any town from any other town using roads.
There are k types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least s differ... | /**
* Created by Baelish on 5/29/2018.
*/
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Stream;
import static java.lang.Math.*;
public class D {
public static void main(String[] args) throws Exception {
FastReader in = new FastReader(System.in);
P... |
Bob has just learned bit manipulation and is very excited about it. He goes to his friend Alice to show off his skills who is new to programming, and thus Bob challenges Alice to solve the following problem. Given two positive integers L and R, find L ^ (L+1) ^ (L+2) ^ ....... ^ (R-1) ^ R.
Alice needs to answer k such... | def f(a):
res=[]
res.append(a)
res.append(1)
res.append(a+1)
res.append(0)
return res[a%4]
if __name__=='__main__':
T = int(raw_input())
for i in range(T):
M,N=map(int,raw_input().split())
print f(N)^f(M-1) |
In Byteland,people don't use standard e-mail services like gmail,yahoo-mail etc.Instead they have their own e-mail service know as Bytemail.In Bytemail, encryption of e-mails is done using a special algorithm known as Bytecryption algorithm.It works as follows:
1)All the text is converted into lower-case alphabets onl... | #Sudhanshu Patel
if __name__=='__main__':
t=int(raw_input())
for i in range(t):
st=raw_input()
st=st.lower()
r=''
while(st!=''):
l=len(st)
if l%2!=0:
r=r+st[l/2]
st=st[0:l/2]+st[(l/2)+1:]
else:
x... |
You'll be given an array A of N integers as input. For each element of the array A[i], print A[i]-1.
Input:
There will be N+1 iines of input each consisting of a single integer.
Integer in first line denotes N
For the following N lines the integer in i^{th} line denotes the integer A[i-1]
Output:
For each element of... | totalCases = int(raw_input())
for i in xrange(totalCases):
print int(raw_input()) -1 |
There is a special game played in remote part of Rajasthan, where all people assemble with their all wealth and try to earn more wealth on the account of their current wealth.
Suppose you are also a part of this game.
The game is like, there are N people playing the game where everyone has its wealth. You are given w... | for i in range(input()):
s=raw_input().split(" ")
t=raw_input().split(" ")
l=[];
for k in t:
z=str(k)+".0"
l.append(int(float(z)))
l.sort()
l.reverse()
c=l.index(int(t[0]))
l2=[]
l2.append(int(t[0]))
cd=c
while True:
cd=cd-int(s[1])
if cd<0:
... |
Pradeep Khicchar , a very influential ,dominating ,smart and definitely an intelligent guy, is very eager to get his patent on his first project which he is about to complete. Only assistance that he needs from his friend Amit Chahal from IT department is the only thing that his friend know (:p :P) i.e. coding .
But ... | def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
for _ in xrange(input()):
l=[]
for i in xrange(5):
l.append(int(raw_input()))
print gcd(l[0],gcd(l[1],gcd(l[2],gcd(l[3],l[4])))) |
As we all know that power sets of any set are formed by taking i elements (where i is from 1 to n) and then random shuffling them like this power set of {1,2,3} are {EMPTY SET},{1},{2},{3},{1,2}{1,3}{2,3}{1,2,3} .
Now we have a MODIfied POWER SET which contains only those subsets which have consecutive elements from s... | from collections import OrderedDict
t=input()
while t:
t-=1
s=raw_input()
l= list(OrderedDict.fromkeys(s))
l=len(l)
print (l*(l+1))/2 |
Panda had recently learnt about Bit manipulation and logic gates,now he is very excited about it.One day he came across a very interesting question: Given two numbers,xor them and then in resulting number find the number of set bits.If number of set bits are even then print "YES" otherwise "NO".As he is unable to solve... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
T=long(raw_input(''))
while(T>0):
[A,B]=map(long,raw_input().split(' '))
C=A^B
count=0
while C>0:
C-=C&(-1*C)
count+=1
if(count&1):
print "NO"
else:
print "YES"
T-=1 |
To round an integer a, it is customary to round to some multiple of a power of 10, and you will round it accordingly. This time, rules have changed. Given an int n and an int b, round n to the nearest value which is a multiple of b.
If n is exactly halfway between two multiples of b, print the larger value.
INPUT
Fi... | T = int(raw_input())
for i in range(T):
n,b = (raw_input()).split()
n,b = int(n), int(b)
div_a = (n//b)*b
div_b = div_a + b
if(n - div_a == div_b - n) :
print div_b
elif(n - div_a < div_b - n) :
print div_a
else :
print div_b |
Dark completed with studying Strings last night and trying to solve the problem of primes numbers from last three months but did not succeed every time he preferred to ask your help and same goes this time.
He likes to play a game with PRIMES AND STRINGS and he named the game as "PRIME ASCII CHARACTERS".
The rules ar... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def isPrime(n):
for i in range(2,n):
if n% i == 0:
return 1
return 0
n = int(raw_input())
i=0
str = []
out = []
while i < n:
str.append(raw_input())
... |
Admin is provided with infinite supply of Unusual blocks and now he has being assigned the task to fill the rectangular floor(completely) of Area A with one of these Unusual blocks.
The Property of Unusual Blocks being :-
Property 1 :- Both of it's dimensions are integers
Property 2 :- When both of it's dimension... | def s(n):
x=[]
c=0
for i in xrange(1,int(n**.5)+1):
if n%i==0:
if i%2==0 and (n/i)%2==0:
if i==n/i:
c+=1
else:
c+=1
return c
for _ in xrange(input()):
n=input()
print s(n) |
Letβs take a prime P = 200\,003. You are given N integers A_1, A_2, \ldots, A_N. Find the sum of ((A_i \cdot A_j) \bmod P) over all N \cdot (N-1) / 2 unordered pairs of elements (i < j).
Please note that the sum isn't computed modulo P.
Constraints
* 2 \leq N \leq 200\,000
* 0 \leq A_i < P = 200\,003
* All values in... | #include<bits/stdc++.h>
#define LL long long
using namespace std;
const int mod=200003,G=5,N=8e5+50;
const double pi=acos(-1);
int n,id[N],r[N],lim=1,val[N];LL ans;
struct node{
double x,y;
node friend operator +(node a,node b){return node{a.x+b.x,a.y+b.y};}
node friend operator -(node a,node b){return node... |
Takahashi has decided to work on K days of his choice from the N days starting with tomorrow.
You are given an integer C and a string S. Takahashi will choose his workdays as follows:
* After working for a day, he will refrain from working on the subsequent C days.
* If the i-th character of S is `x`, he will not wor... | n,k,c=map(int, input().split())
s = input()
leftmost = []
cursor = 0
for _ in range(k):
while s[cursor] == 'x':
cursor += 1
leftmost.append(cursor)
cursor += c+1
rightmost = []
cursor = n-1
for _ in range(k):
while s[cursor] == 'x':
cursor -= 1
rightmost.append(cursor)
cursor -= ... |
Given are a sequence of N positive integers A_1, A_2, \ldots, A_N, and a positive integer K.
Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from... | from collections import defaultdict
def gets():
return list(map(int, input().split()))
N, K = gets()
A = gets()
S = [0] * (N + 1)
for i in range(N):
S[i + 1] = (S[i] + A[i] - 1) % K
cnt = defaultdict(int)
ans = 0
cnt[0] += 1
for i in range(1, N+1):
if i - K >= 0:
cnt[S[i - K]] -= 1
ans += cnt[S[i]]
cn... |
We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.
Print the number of elements p_i (1 < i < n) that satisfy the following condition:
* p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.
Constraints
* All values in input are integers.
* 3 \leq n \leq 20
* p... | N = int(input())
p = list(map(int,input().split()))
s = 0
for i in range(1,N-1):
s += p[i-1] < p[i] < p[i+1] or p[i-1] > p[i] > p[i+1]
print(s) |
Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.
Constraints
* 1\leq N,K\leq 100
* N and K are integers.
Input
Input is given from Standard Input in the following format:
N K
Output
If we can choose K integers as above, print `YES`; otherwise, prin... | N, K = list(map(int, input().split(" ")))
print("YES") if 2*K-1 <= N else print("NO")
|
There is an N-car train.
You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."
Constraints
* 1 \leq N \leq 100
* 1 \leq i \leq N
Input
Input is given from Standard Input in the following format:
N i
O... | n,i = map(int,input().split())
ans = n+1-i
print(ans) |
Takahashi has an N \times M grid, with N horizontal rows and M vertical columns. Determine if we can place A 1 \times 2 tiles (1 vertical, 2 horizontal) and B 2 \times 1 tiles (2 vertical, 1 horizontal) satisfying the following conditions, and construct one arrangement of the tiles if it is possible:
* All the tiles m... | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef complex<double> point;
#define xx real()
#define yy imag()
#define REP(i, a, b) for(int i = (a); i < (int)(b); i++)
#define REPN(i, a, b) for(int i ... |
Snuke prepared 6 problems for a upcoming programming contest. For each of those problems, Rng judged whether it can be used in the contest or not.
You are given a string S of length 6. If the i-th character of s is `1`, it means that the i-th problem prepared by Snuke is accepted to be used; `0` means that the problem... | #include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
cout<<count(s.begin(),s.end(),'1');
} |
You are given an array A of length N. Your task is to divide it into several contiguous subarrays. Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order. At least how many subarrays do you need to divide A into?
Constraints
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* Each A_i ... | N = int(input())
A = list(map(int, input().split()))
sgn = 0
answer = 1
for i in range(N-1):
cur = A[i+1] - A[i]
if cur * sgn < 0:
answer += 1
sgn = 0
continue
if cur != 0:
sgn = cur
print(answer) |
There is an undirected connected graph with N vertices numbered 1 through N. The lengths of all edges in this graph are 1. It is known that for each i (1β¦iβ¦N), the distance between vertex 1 and vertex i is A_i, and the distance between vertex 2 and vertex i is B_i. Determine whether there exists such a graph. If it exi... | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <cassert>
#include <functional>
#include <numeric>
#include ... |
Let's play Amidakuji.
In the following example, there are five vertical lines and four horizontal lines. The horizontal lines can intersect (jump across) the vertical lines.
<image>
In the starting points (top of the figure), numbers are assigned to vertical lines in ascending order from left to right. At the first... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int w = sc.nextInt();
int n = sc.nextInt();
int[] values = new int[w];
for (int i = 0; i < values.length; i++) {
values[i] = i + 1;
}
for (int i = 0; i < n; i++) {
String str = sc.nex... |
ZhinΓΌ was a child of the Emperor, but he was weaving the machine even if he opened it at the request of his father.
It was a pleasure of the Emperor to wear clothes made of a splendid cloth called Unnishiki woven by ZhinΓΌ. Unnishiki has a short lifespan and deteriorates quickly, but there was no problem because the ha... | #include<bits/stdc++.h>
#define EPS (1e-10)
#define equals(a,b)(fabs((a)-(b))<EPS)
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
struct Point {
double x, y;
Point(double x = 0, double y = 0) :x(x), y(y) {}
Point operator*(double a) { return Point(a*x, a*y); }
Point operator-(Point p) { return Point(x -... |
At Akabe High School, which is a programmer training school, the roles of competition programmers in team battles are divided into the following three types.
C: | Coder | I am familiar with the language and code.
--- | --- | ---
A: | Algorithm | I am good at logical thinking and think about algorithms.
N: | Navigator |... | #include<bits/stdc++.h>
using namespace std;
signed main(){
cin.tie(NULL);
ios::sync_with_stdio(false);
long long Q,team=0,C,A,N;
cin>>Q;
for(int i=0;i<Q;i++){
cin>>C>>A>>N;
while(true){
if(C>0 && A>0 && N>0){
team++;
C--;
A--;
N--;
continue;
}
else if(C>=2 && A>=1){
team++;
C... |
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the ... | #include <iostream>
using namespace std;
int DP[1001][1001];
int pt[1001][1001];
int main() {
while(true){
int H,W,N;
int lastX=1,lastY=1;
cin >> H >> W >> N;
if(H==0)
break;
for(int i=1;i<=H;i++)
for(int j=1;j<=W;j++)
cin >> pt[j][i];
DP[1][1]=N-1;
for(int i=1;i<=H;i++)
for(int j=1;j<=W;j++)
if(i!... |
Problem H: Squid Multiplication
Squid Eiko loves mathematics. Especially she loves to think about integer. One day, Eiko found a math problem from a website.
"A sequence b ={ai + aj | i < j } is generated from a sequence a ={a0 , ... , an | ai is even if i is 0, otherwise ai is odd}. Given the sequence b , find the s... | #include<cstdio>
#include<algorithm>
#include<vector>
#include<cmath>
#define MAXX 65555
unsigned long long gcd(const unsigned long long &a,const unsigned long long &b)
{
return b?gcd(b,a%b):a;
}
unsigned long long n,i,j,k,m;
unsigned long long num[MAXX],g;
std::vector<unsigned long long>ev,od;
int main()
{
... |
Bill is a boss of security guards. He has pride in that his men put on wearable computers on their duty. At the same time, it is his headache that capacities of commercially available batteries are far too small to support those computers all day long. His men come back to the office to charge up their batteries and sp... | #include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
using namespace std;
typedef pair<int,int> ii;
struct Data{
int id,stamp;
bool operator < ( const Data& data ) const {
if( stamp != data.stamp ) return stamp > data.stamp;
return id > data.id;
}
};
vector<ii> ... |
Example
Input
6 3
((()))
4
3
1
Output
2
2
1 | import java.util.*;
class Main{
int n, m, sz;
char[] kakko;
int[] a, bkt, add;
void solve(){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
kakko = sc.next().toCharArray();
sz = Math.max(1, (int)Math.sqrt(n) - 1);
a = new int... |
Problem
You've come to an n x n x n cubic Rubik's Cube dungeon.
You are currently in the room (x1, y1, z1).
The target treasure is in the room (x2, y2, z2).
You can move to adjacent rooms in front, back, left, right, up and down in unit time.
<image>
Each room has 6 buttons, and by pressing each button, you can per... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n,x1,y1,z1,x2,y2,z2;
cin >> n >> x1 >> y1 >> z1 >> x2 >> y2 >> z2;
int ans=1<<29;
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
for(int k=0; k<4; k++) {
int a[3]={0,1,2};
do {
int x=x1,y=y1,z=z1,d=0;
... |
Mr. Hoge is in trouble. He just bought a new mansion, but itβs haunted by a phantom. He asked a famous conjurer Dr. Huga to get rid of the phantom. Dr. Huga went to see the mansion, and found that the phantom is scared by its own mirror images. Dr. Huga set two flat mirrors in order to get rid of the phantom.
As you m... | #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-7)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
class Point{
public:
dou... |
Description
KMC sells CDs every year at a coterie spot sale called Comic Market. F was supposed to sell CDs at the comic market, but due to the popularity of F, the KMC sales floor was flooded with people, and the calculation of change could not keep up. So F decided to write a program that would output the change as ... | #include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<set>
using namespace std;
int main() {
int a, b;
while(cin>>a>>b&&a!=0&&b!=0){
int h = 0, g = 0, s = 0,o=b-a;
while (o >= 1000) {
s++;
o -= 1000;
}
while (o >= 500) {
g++;
o -= 500;
}
while (o >= 100) {
h++;
... |
Example
Input
6 3 1.0
1 2 3
4 5 6
0 0
1 0
2 0
0 1
1 1
2 1
Output
3 | #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 reps(i,s,n) for(int i=s;i<n+s;i++)
#define ireps(i,s,n) for(int i=s+n-1;i>=s;i--)
#define all(c) c.begin(),c.end()
#define pb push_back
#define fs first
#define sc second
#define show(x) cout << ... |
E - Minimum Spanning Tree
Problem Statement
You are given an undirected weighted graph G with n nodes and m edges. Each edge is numbered from 1 to m.
Let G_i be an graph that is made by erasing i-th edge from G. Your task is to compute the cost of minimum spanning tree in G_i for each i.
Input
The dataset is forma... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100005 , maxm = 400005;
const long long inf = 41351356514454ll;
typedef pair<int , long long> pii;
#define x first
#define y second
struct edge{
int u , v , p;
long long w;
edge(){}
void read(int i){scanf("%d%d%lld" , &u , &v , &w);p=i;}
friend bool op... |
Tunnel formula
One day while exploring an abandoned mine, you found a long formula S written in the mine. If you like large numbers, you decide to take out the choke and add `(` or `)` so that the result of the formula calculation is as large as possible. If it has to be a mathematical formula even after adding it, ho... | #include <bits/stdc++.h>
using namespace std;
int dp[201][201][2];
int main() {
string s;
cin >> s;
int n=s.size();
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)dp[i][j][0]=1<<29,dp[i][j][1]=-(1<<29);
if(isdigit(s[i]))dp[i][i][0]=dp[i][i][1]=s[i]-'0';
}
for(int i=0; i<n; i++){
for(int j=0;j<n-i;j++... |
You are supposed to play the rock-paper-scissors game. There are $N$ players including you.
This game consists of multiple rounds. While the rounds go, the number of remaining players decreases. In each round, each remaining player will select an arbitrary shape independently. People who show rocks win if all of the o... | #include<bits/stdc++.h>
using namespace std;
signed main(){
int n,x;
cin>>n>>x;
n--;
int a[n];
double r[n],p[n],s[n];
for(int i=0;i<n;i++) cin>>a[i]>>r[i]>>p[i]>>s[i];
for(int i=0;i<n;i++){
r[i]/=100;p[i]/=100;s[i]/=100;
}
double dp[1<<n];
for(int i=0;i<(1<<n);i++)
dp[i]=-1;
function<doubl... |
J: Horizontal-Vertical Permutation
Problem Statement
You are given a positive integer N. Your task is to determine if there exists a square matrix A whose dimension is N that satisfies the following conditions and provide an example of such matrices if it exists. A_{i, j} denotes the element of matrix A at the i-th r... | #include <bits/stdc++.h>
using namespace std;
const int N = 505;
int c[N][N],n;
int main() {
scanf("%d",&n);
if(n==1) printf("Yes\n1\n");
else {
if(n&1) printf("No\n");
else {
printf("Yes\n");
for(int i=1;i<n;i++) c[i][1]=c[n-1][i+1]=i;
for(int i=n-2;i>=2;i--) {
for(int j=2;j<=i;j++) c[i][j]=c[i+1][... |
For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \\{a,b,c,b,d,a,b\\}$ and $Y = \\{b,d,c,a,b,a\\}$, the sequence $\\{b,c,a\\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\\{b,c,a... | def lcs(x,y):
L=[]
for chk in y:
bg_i=0
for i,chr_i in enumerate(L):
cur_i=x.find(chk,bg_i)+1
if not cur_i:
break
L[i]=min(cur_i,chr_i)
bg_i=chr_i
else:
cur_i=x.find(chk,bg_i)+1
if cur_i:
... |
You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.
The variance Ξ±2 is defined by
Ξ±2 = (βni=1(si - m)2)/n
where m is an average of si. The standard deviation of the scores is the square root of their variance.
Constraints
* n β€ 1000
* 0 β€ si β€ 100
Inpu... | import math
n = int(input())
while not n == 0:
ss = [float(i) for i in input().split(' ')]
m = sum(ss)/n
a2 = sum([(i-m)**2 for i in ss]) / n
print(math.sqrt(a2))
n = int(input())
|
Bhallaladeva was an evil king who ruled the kingdom of Maahishmati. He wanted to erect a 100ft golden statue of himself and he looted gold from several places for this. He even looted his own people, by using the following unfair strategy:
There are N houses in Maahishmati, and the i^th house has Ai gold plates. Each g... | import sys
n = input()
lists = map(int,sys.stdin.readline().split())
lists.sort()
pref = [0]*(n+1)
pref[0] = lists[0]
for i in range(1,n) :
pref[i] = pref[i-1]
pref[i] += lists[i]
for __ in range(input()) :
k = input()
print pref[n/(k+1)] if n%(k+1) else pref[(n/(k+1)-1)] |
Chef likes cooking. But more than that, he likes to give gifts. And now he wants to give his girlfriend an unforgettable gift. But unfortunately he forgot the password to the safe where the money he saved for the gift is kept.
But he knows how to hack the safe. To do this, you need to correctly answer questions asked ... | import sys
def readtestcase():
n = int(sys.stdin.readline())
num = map(int, sys.stdin.readline().split())
mini = num[0]
maxi = num[0]
for i in range(1,len(num)):
omini = mini
mini = min([ mini-num[i], mini+num[i], mini*num[i], maxi-num[i], maxi+num[i], maxi*num[i]])
maxi = m... |
Arunava has learnt to find the sum of first N natural numbers using the expression N(N+1)/2.But now Kartik Sir has asked him to find the sum of floor(N/2) for first N natural numbers where floor(X) is the greatest integer less than or equal to a given real number X.Arunava has not memorized any formula for this. So can... | import sys
def main():
answers = [0]*10000
val = 0
for i in xrange(1,5000):
d = i*2
val += d
answers[d] = val-i
answers[d+1] = val
t = int(raw_input())
inp = map(int, sys.stdin.read().split())
out = ""
for _ in inp:
out+=str(answers[_])+"\n"
print... |
Chef wants you to write a calculator program for carrying out some simple mathematical operations. Chef calls the program Calculator Plus Plus.
Input
First line contains an operation in the form : a operator b
Output
Output in a single line the result of the mathematical operation. Print "Invalid Operator" if inp... | A=raw_input().split(); op_1=int(A[0]); op_2=int(A[2]);
if A[1]=='+':
print op_1+op_2;
elif A[1]=='-':
print op_1-op_2;
elif A[1]=='*':
print op_1*op_2;
elif A[1]=='/':
print op_1/op_2;
else:
print 'Invalid Operator'; |
Raavan abducted sita in the past, at that time when Ram went to save her wife , he was posed a question by Raavan in binomial theorem :
given N Ram has to find the number of odd coefficients in the expansion of (1+x)^n . As the number given by Raavan was huge, Ram was unable to calculate at that time , so he was force... | print 2**(bin(int(raw_input())).count('1')) |
Chef recently saw the movie Matrix. He loved the movie overall but he didn't agree with some things in it. Particularly he didn't agree with the bald boy when he declared - There is no spoon. Being a chef, he understands the importance of the spoon and realizes that the universe can't survive without it. Furthermore, h... | tc = int(raw_input()) #number of test cases
for t in range(tc):
r, c = map(int,raw_input().split())
L = []
for r1 in range(r):
L.append(raw_input().strip().lower())
findCase = False
for e in L:
if 'spoon' in e:
findCase = True
break
nL = ['']*c
for e i... |
Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | if __name__ == "__main__":
_ = int(input())
arr = [int(num) for num in input().split()]
for i in arr:
if i % 2 == 0:
print(i - 1, end=" ")
else:
print(i, end=" ")
|
There is an infinite board of square tiles. Initially all tiles are white.
Vova has a red marker and a blue marker. Red marker can color a tiles. Blue marker can color b tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be e... | #include <bits/stdc++.h>
using namespace std;
const long long N = 1e14;
const long long oo = (1ll << 63) - 1;
long long a, b, ab;
vector<long long> A, B, AB;
int tknp(const long long& a, const long long& b) {
int l = lower_bound(AB.begin(), AB.end(), a) - AB.begin(), r = AB.size() - 1;
while (l < r) {
int m = l... |
As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space.
Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and ... | #include <bits/stdc++.h>
using namespace std;
struct reqest {
long long a, b, ind;
};
bool comp(reqest a, reqest b) {
if (a.b == b.b) return a.a < b.a;
return a.b < b.b;
}
int main() {
long long n;
scanf("%lld", &n);
vector<long long> w(n);
for (int i = 0; i < n; ++i) scanf("%lld", &w[i]);
long long m;
... |
You are given a string s, consisting of n lowercase Latin letters.
A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not.
The length of the substring is the number of letters in it.
Let's call some string of length n diverse if and o... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
string s;
cin >> n >> s;
for (int i = 1; i < n; ++i) {
if (s[i] != s[i - 1]) {
cout << "YES" << endl;
cout << s.substr(i - 1, 2);
return 0;
}
}
cout << "NO" << endl;
re... |
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 β€ m β€ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | try:
t = int(input())
s = input()
_ = 1
i = 0
l = []
while((i)<=(len(s)-1)):
#print(i)
l.append(s[i])
_+=1
i = i+_
s = "".join(l)
print(s)
except:
pass
|
An array b is called to be a subarray of a if it forms a continuous subsequence of a, that is, if it is equal to a_l, a_{l + 1}, β¦, a_r for some l, r.
Suppose m is some known constant. For any array, having m or more elements, let's define it's beauty as the sum of m largest elements of that array. For example:
* ... | from operator import itemgetter
from itertools import accumulate
from sys import stdin, stdout
n, m, k = [int(x) for x in stdin.readline().split()]
a = [int(x) for x in stdin.readline().split()]
id = [x for x in range(n)]
b = list(zip(a, id))
a.sort(reverse = True)
b.sort(reverse = True)
c = [p[1] for p in b[:m*k]]
c.s... |
Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one.
Vasya drew several distinct points with integer coordinates on a plane and then drew an... | #include <bits/stdc++.h>
using namespace std;
long long mod = (1000000007LL);
inline long long Mod(long long a, long long b) { return (a % b); }
inline long long poww(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1) res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return... |
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;
const int maxn = 100;
int a[maxn];
int n;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
sort(a + 1, a + n + 1);
for (int i = 2; i <= n / 2 + 1; i++) {
if (a[i] != a[i - 1]) {
cout << "Alice" << endl;
return 0;
... |
This problem is actually a subproblem of problem G from the same contest.
There are n candies in a candy box. The type of the i-th candy is a_i (1 β€ a_i β€ n).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di... | for _ in range(int(raw_input())):
n=int(raw_input())
l=[int(i) for i in raw_input().split()]
from collections import Counter
c=Counter(l)
# print(c)
l=[c[i] for i in c]
l.sort(reverse=1)
from collections import defaultdict
d=defaultdict(int)
for i in l:
if not d[i]:
... |
Amugae has a sentence consisting of n words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "sa... | /*loltyleronedotcomdiscountcodealpha*/
import java.io.*;
import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
StringBuilder sb = new StringBuilder();
for(int i=0;i<n;i++) {
String s = s... |
Three planets X, Y and Z within the Alpha planetary system are inhabited with an advanced civilization. The spaceports of these planets are connected by interplanetary space shuttles. The flight scheduler should decide between 1, 2 and 3 return flights for every existing space shuttle connection. Since the residents of... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
int N, M;
int x[MAXN], y[MAXN];
vector<pair<int, int> > adj[MAXN], ch[MAXN];
char part[MAXN];
int label[MAXN];
int clr[MAXN];
int ans[MAXN];
void load() {
scanf("%d%d%s", &N, &M, part);
for (int i = 0; i < M; i++) {
scanf("%d%d", x + i, y +... |
Ujan needs some rest from cleaning, so he started playing with infinite sequences. He has two integers n and k. He creates an infinite sequence s by repeating the following steps.
1. Find k smallest distinct positive integers that are not in s. Let's call them u_{1}, u_{2}, β¦, u_{k} from the smallest to the largest.... | #include <bits/stdc++.h>
using namespace std;
const long long M = 1e7 + 19;
long long h[M], g[M];
vector<int> buc;
int gethash(long long a) {
int x = a % M;
while (h[x] && h[x] != a) x = (x + 1) % M;
return x;
}
long long n, k, T;
long long lim = 1000000;
long long f(long long n) {
if (n < k * (k + 1) / 2) retu... |
Your program fails again. This time it gets "Wrong answer on test 233"
.
This is the easier version of the problem. In this version 1 β€ n β€ 2000. You can hack this problem only if you solve and lock both problems.
The problem is about a test containing n one-choice-questions. Each of the questions contains k options... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int MAXN = 2001;
int add(int a, int b) {
if (a + b < 0) return a + b + MOD;
if (a + b >= MOD) return a + b - MOD;
return a + b;
}
int mul(int a, int b) { return (long long)a * b % MOD; }
bool bio[MAXN][2 * MAXN];
int n, k;
int a[MAXN],... |
Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.
Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of n lam... | #include <bits/stdc++.h>
using namespace std;
vector<bool> vis;
vector<vector<long long>> adj;
void dfs(long long node) {
vis[node] = true;
for (long long child : adj[node]) {
if (vis[child]) continue;
dfs(child);
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long ... |
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are ... | from __future__ import division,print_function
#from sortedcontainers import SortedList
import sys
#sys.__stdout__.flush()
le=sys.__stdin__.read().split("\n")
le.pop()
le=le[::-1]
for k in range(int(le.pop())):
n,b,g=list(map(int,le.pop().split()))
h=(n+1)//2
q=(h-1)//b
r=(h-1)%b+1
#print(r,q)
p... |
Petya has a rectangular Board of size n Γ m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column.
In one action, Petya can move all the chips to the left, right, down or up by 1 cell.
If the chip was in the (x, y) cell, then after the oper... | n,m,k=map(int, input().split())
for i in range(2*k):
map(int, input().split())
ans = (m-1)*'L' + (n-1)*'U'
for i in range(n):
if i%2==0:
ans += 'R'*(m-1)
else:
ans += 'L'*(m-1)
if i < n-1:
ans+='D'
print(len(ans))
print(ans) |
Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.
To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the follo... | import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
print((n+1)*3+1)
for i in range(n+1):
print(i,i)
print(1+i,i)
print(i,1+i)
print(n+1,n+1)
#for i in range(mint()):
solve()
|
Berland year consists of m months with d days each. Months are numbered from 1 to m. Berland week consists of w days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than w days.
A pair (x, y) such that x < y is ambiguous if day x of month y is the same... | #include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int m, d, w;
cin >> m >> d >> w;
long long mod = w / gcd(d - 1, w);
long long... |
As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's ... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
const int maxn = 100005;
int r[305][305];
int ans[305];
int main() {
int n;
scanf("%d", &n);
int d;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &d);
r[i][d] = j;
}
}
for (int i = 1; i <= ... |
Recently you've discovered a new shooter. They say it has realistic game mechanics.
Your character has a gun with magazine size equal to k and should exterminate n waves of monsters. The i-th wave consists of a_i monsters and happens from the l_i-th moment of time up to the r_i-th moments of time. All a_i monsters spa... | #include <bits/stdc++.h>
using namespace std;
long long const MAXN = 2005;
long long l[MAXN], r[MAXN], a[MAXN];
long long C[MAXN][MAXN];
long long R[MAXN][MAXN];
long long f[MAXN];
signed main() {
long long n, k;
cin >> n >> k;
for (register long long i = 1; i <= n; ++i) cin >> l[i] >> r[i] >> a[i];
l[n + 1] = ... |
There is a game called "Unique Bid Auction". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem).
Let's simplify this game a bit. Formally, there are n participants, the i-th participant chose the number a_i. The winner of the game is... | #include <bits/stdc++.h>
#include<string.h>
#include<utility>
#define ll long long int
#include<fstream>
#define pb push_back
#include<vector>
#include<stack>
#define INF INT_MAX
#include <deque>
#define modulo 1000000007
using namespace std;
//Fuck ratings
//Get charasi...Have some ganja
ll checkpalindrome(ll c)
{ ... |
Nezzar buys his favorite snack β n chocolate bars with lengths l_1,l_2,β¦,l_n. However, chocolate bars might be too long to store them properly!
In order to solve this problem, Nezzar designs an interesting process to divide them into small pieces. Firstly, Nezzar puts all his chocolate bars into a black box. Then, he... | #include<bits/stdc++.h>
#define fo(i,a,b)for(int i=a,_e=b;i<=_e;++i)
#define fd(i,a,b)for(int i=b,_e=a;i>=_e;--i)
using namespace std;
#define fastio ios_base::sync_with_stdio(0);cin.tie(0)
#define FOR(i,m,n) for(int i = (m); i < (n); i++)
#define pb push_back
#define mp make_pair
#define fst first
#define snd second
#... |
Many people are aware of DMCA β Digital Millennium Copyright Act. But another recently proposed DMCA β Digital Millennium Calculation Act β is much less known.
In this problem you need to find a root of a number according to this new DMCA law.
Input
The input contains a single integer a (1 β€ a β€ 1000000).
Output
O... | n = int(input())
sumo = n
while n>=10:
sumo = 0
while n!=0:
sumo+=n%10
n//=10
n = sumo
print(sumo) |
Soroush and Keshi each have a labeled and rooted tree on n vertices. Both of their trees are rooted from vertex 1.
Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph o... | #pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
#define FOR(i,a,b) for(int i=a;i<=b;++i)
#define PII pair<int,int>
#define ll long long
#define pb push_back
#define sz(x) (int)(x.size())
#define rd (rand()<<16^rand())
#define db double
#define gc (_p1==_p2&&(_p2=(_p1=_buf)+fread(_buf,1,100000,stdin),_p1==_p2)?EOF... |
Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n Γ m cells and a robotic arm. Each cell of the field is a 1 Γ 1 square. The robotic arm has two lasers po... | #include <bits/stdc++.h>
using namespace std;
long long t, n, m;
int main() {
long long x1, x2, y1, y2, dx, dy;
long long top1, bot1, lef1, rig1, top2, bot2, lef2, rig2, top3, bot3, lef3,
rig3, s1, s2, s3;
cin >> t;
while (t--) {
cin >> n >> m >> x1 >> y1 >> x2 >> y2;
dx = x2 - x1;
dy = y2 - y... |
The Smart Beaver from ABBYY has a long history of cooperating with the "Institute of Cytology and Genetics". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows.
There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercas... | #include <bits/stdc++.h>
const double eps = 1e-9;
const int oo = 1000000000;
const double E = 2.7182818284590452353602874713527;
const double pi = 3.1415926535897932384626433832795;
using namespace std;
struct case1 {
int son[26];
int v, f;
} p[50002];
int f[50002][101];
string a[101];
int n, k;
void dfs(int now, i... |
Once n people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of n people made an appointment on one of the... | #include <bits/stdc++.h>
using namespace std;
int jud(long long N, long long M, long long K) {
int i;
if (K < 40 && (1ll << K) < N) return 0;
long long cnt = 0, sum = 0, x = 1;
for (i = 0;; i++) {
long long tmp = min(N - cnt, x);
cnt += tmp;
sum += tmp * i;
if (cnt == N) break;
x = x * (K - ... |
Harry Potter has a difficult homework. Given a rectangular table, consisting of n Γ m cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second β in the selected column. Harry's task is to make non-negative the ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
int n, m;
cin >> n >> m;
vector<vector<int> > a(n, vector<int>(m));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) cin >> a[i][j];
vector<int> czyR(n, 0), czyK(m, 0);
vector<int> sR(n, 0), sK(m, 0);
for... |
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons β 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef".... | #include <bits/stdc++.h>
using namespace std;
int N;
char s[1000];
int chartoint(char c) {
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return c - '0';
}
int stringtoint(char *s) {
int len = strlen(s);
int sum = 0;
for (int i = 0; i < len; i++) sum = sum * 16 + chartoint(s[i]);
return sum;
}
vector<int> s... |
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = xΒ·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-mu... | def solve():
n,k=map(int,input().split())
a=sorted([int(i) for i in input().split()])
b=set(a)
if k!=1:
for i in a:
if i in b:
b.discard(i*k)
print(len(b))
solve() |
Polar bears like unique arrays β that is, arrays without repeated elements.
You have got a unique array s with length n containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays a and b that are also of length n, w... | #include <bits/stdc++.h>
using namespace std;
template <class T>
void debug(T a, T b) {
for (; a != b; a++) cerr << *a << ' ';
cerr << endl;
}
template <class T>
bool isprime(T x) {
int till = (T)sqrt(x + .0);
if (x <= 1) return 0;
if (x == 2) return 1;
if (x % 2 == 0) return 0;
for (int i = 3; i <= till;... |
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has n cities connected by n - 1 undirected roads, and for any two cities there always exists a path between them.
Fox Ciel needs to assign an officer to each city. Each officer has a rank β a letter from 'A' to 'Z'. So there will be 26 diffe... | #include <bits/stdc++.h>
using namespace std;
const int N = 100100;
vector<int> e[N];
char a[N];
int n, ans, id, order;
int dfs(int r, int last, int n) {
int tmp = 0, sum = 1, res = 0;
for (int i = e[r].size() - 1; i >= 0; i--) {
if (e[r][i] == last || a[e[r][i]] != -1) continue;
tmp = dfs(e[r][i], r, n);
... |
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two di... | import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
import java.math.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public ... |
Valera loves segments. He has recently come up with one interesting problem.
The Ox axis of coordinates has n segments, the i-th segment starts in position li and ends in position ri (we will mark it as [li, ri]). Your task is to process m queries, each consists of number cnti and a set of cnti coordinates of points l... | #include <bits/stdc++.h>
using namespace std;
long long pw(long long base, long long e) {
return e ? pw(base * base, e / 2) * (e % 2 ? base : 1) : 1;
}
const int maxn = 3e5 + 10, mod = 1e9 + 7, maxlg = 21;
const long long INF = 1e9;
long long seg[maxlg][maxn];
int n;
pair<int, int> a[maxn];
int get(int lx, int rx, in... |
This problem consists of two subproblems: for solving subproblem D1 you will receive 3 points, and for solving subproblem D2 you will receive 16 points.
Manao is the chief architect involved in planning a new supercollider. He has to identify a plot of land where the largest possible supercollider can be built. The su... | #include <bits/stdc++.h>
int vx[50007], vy[50007], vl[50007];
int hx[50007], hy[50007], hl[50007];
int main() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%d %d %d", vx + i, vy + i, vl + i);
}
int ans = 0;
for (int i = 0; i < m; i++) {
scanf("%d %d %d", hx + i, hy + i, hl... |
The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a 2 Γ n maze.
Imagine a maze that looks like a 2 Γ n rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can move fro... | #include <bits/stdc++.h>
using namespace std;
string s[2];
int comp[2][1000000];
int vis[2][1000000];
int n;
void dfs(int i, int j, int col) {
if (i >= 2 || j >= n || i < 0 || j < 0) return;
if (s[i][j] == 'X') return;
if (vis[i][j]) return;
vis[i][j] = 1;
comp[i][j] = col;
dfs(i + 1, j, col);
dfs(i, j + ... |
Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configura... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 50005;
int n, in[MAXN];
long long k, ans;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> in[i];
k += in[i];
}
k /= n;
long long c = in[0] - k;
for (int i = 1; i < n; ++i) {
a... |
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.
Consider a set consisting of k (0 β€ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int MAXN = 100010;
int N, c[MAXN], f[MAXN][2];
vector<int> graph[MAXN];
void dfs(int u, int p) {
f[u][0] = 1;
f[u][1] = 0;
for (int i = 0; i < graph[u].size(); ++i) {
int v = graph[u][i];
if (v != p) {
dfs(v, u);
f... |
Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that c... | import sys
input=sys.stdin.readline
n,p=map(int,input().split())
s=input().rstrip()
if p>=n//2:
s=s[::-1]
p=n+1-p
p-=1
ans1=0;ans2=0
l=10**6;r=-1
for i in range(n//2):
if s[i]!=s[n-1-i]:
l=min(l,i)
r=max(r,i)
use=set()
if l<=p<=r:
if r!=-1:
for i in range(p,r+1):
if s[i]!=s[n-1-i] and i not in... |
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that
1. 1 β€ i, j β€ N
2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
Input
The single input line contains S, consisting of lowercase Latin letters and digits. It is ... | #include <bits/stdc++.h>
using namespace std;
int main() {
map<char, long long> m;
string s;
cin >> s;
long long sum = 0;
for (long long i = 0; i < s.length(); i++) {
char c = s[i];
m[c]++;
}
map<char, long long>::iterator i;
for (i = m.begin(); i != m.end(); i++) {
long long temp = i->secon... |
On February, 30th n students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in... | #include <bits/stdc++.h>
using namespace std;
template <class T>
T pwr(T b, T p) {
T r = 1, x = b;
while (p) {
if (p & 1) r *= x;
x *= x;
p = (p >> 1);
}
return r;
}
template <class T>
T lcm(T a, T b) {
return (a / __gcd(a, b)) * b;
}
template <class T>
T sqr(T a) {
return a * a;
}
template <cla... |
Gerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows.
A Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a basic polygon. If you shake a Randomizer, it draws some nondegenerate (i... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.io.Closeable;
import java.io.Writer;
import jav... |
The mobile application store has a new game called "Subway Roller".
The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmo... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper... |
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is ... | #include <bits/stdc++.h>
using namespace std;
int n, a[510];
int dp[510][510];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) dp[i][j] = 1e9;
}
for (int i = 1; i <= n; i++) dp[i][i] = 1;
for (int len = 2; len <= ... |
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a n Γ n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started t... | //package HackerEarthA;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/**
*
* @author prabhat
*/
public class easy18{
public static long[] BIT;
public static long[] tree;
public static long[] sum;
public sta... |
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, ... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Bearcompress {
static int count=0;
static String ar[];
static char a[];
static int q;
static int n;
public static void main(String[] args)
{
// TODO Auto-generated method stub
MyScannerbrc sc=n... |
Lena is a programmer. She got a task to solve at work.
There is an empty set of pairs of integers and n queries to process. Each query is one of three types:
1. Add a pair (a, b) to the set.
2. Remove a pair added in the query number i. All queries are numbered with integers from 1 to n.
3. For a given intege... | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
const double PI = acos(-1);
const int MOD = (int)1e9 + 7;
const int MAXN = (int)3e6 + 7;
struct line {
long long slope, delta;
line() {}
line(long long k, long long c) {
slope = k;
delta = c;
}
friend bool operator<(line a, line b)... |
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be ... | n = int(input())
s = list(map(int, input().split()))
dif = 2 * sum(s) // n
t = []
for i in range(n):
for j in range(n):
if s[i] + s[j] == dif and i not in t and j not in t and i != j:
print(i + 1, j + 1)
t.append(i)
t.append(j)
|
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English... | def solution():
m = raw_input()
line = raw_input().split(')')
if len(line) == 1:
print max(len(o) for o in line[0].split('_')), 0
return
max_len = 0
number_in = 0
for l in line:
splitted = l.split('(')
if len(splitted) == 1:
# we are in the end
... |
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ... | from collections import Counter
s = input()
counter = Counter()
for i in range(len(s)):
counter[s[i:len(s)] + s[0:i]] = 1
print(sum(counter.values())) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.