input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Filya just learned new geometry object — rectangle. He is given a field consisting of n × n unit cells. Rows are numbered from bottom to top with integer from 1 to n. Columns are numbered from left to right with integers from 1 to n. Cell, located at the intersection of the row r and column c is denoted as (r, c). Fily... | #include <bits/stdc++.h>
int query(int x1, int y1, int x2, int y2) {
int cnt;
printf("? %d %d %d %d\n", x1, y1, x2, y2);
fflush(stdout);
scanf("%d", &cnt);
return cnt;
}
int rx1, ry1, rx2, ry2, n;
int r1x1, r1y1, r1x2, r1y2, r2x1, r2y1, r2x2, r2y2;
void solve(int x1, int y1, int x2, int y2, int dx1, int dy1, ... |
In one kingdom there are n cities and m two-way roads. Each road connects a pair of cities, and for each road we know the level of drivers dissatisfaction — the value wi.
For each road we know the value ci — how many lamziks we should spend to reduce the level of dissatisfaction with this road by one. Thus, to reduce ... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long long dx[4] = {-1, 1, 0, 0};
const long long dy[4] = {0, 0, -1, 1};
long long n, x, e, T, m, k, s, S;
bool ok;
string t;
vector<pair<pair<long long, long long>, pair<long long, long long> > > g;
const long long MAX = 200010;
vector<p... |
Whoa! You did a great job helping Team Rocket who managed to capture all the Pokemons sent by Bash. Meowth, part of Team Rocket, having already mastered the human language, now wants to become a master in programming as well. He agrees to free the Pokemons if Bash can answer his questions.
Initially, Meowth gives Bash... | #include <bits/stdc++.h>
using namespace std;
const int iinf = 1e9 + 7;
const long long linf = 1ll << 60;
const double dinf = 1e10;
template <typename T>
inline void scf(T &x) {
bool f = 0;
x = 0;
char c = getchar();
while ((c < '0' || c > '9') && c != '-') c = getchar();
if (c == '-') {
f = 1;
c = ge... |
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.
Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain ... | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static class Pair implements ... |
Heidi is terrified by your estimate and she found it unrealistic that her friends would collaborate to drive her into debt. She expects that, actually, each person will just pick a random friend to send Heidi to. (This randomness assumption implies, however, that she can now visit the same friend an arbitrary number of... | #include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 10;
const long long mod = 1e9 + 7;
long long self[N], eq[N];
vector<pair<long long, long long> > a[N];
long long tav(long long n, long long k) {
n %= mod;
long long ans = 1;
while (k > 0) {
if (k % 2) ans = (ans * n) % mod;
n = (n * n... |
Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one.
Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more... | import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Optional;
public class Main
{
static class Scan
{
final private int BUF_SIZE = 1 << 16;
private int cur_size = 0;
private int pointer = 0;
private java.io.DataInputStream in;
... |
Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?
Given an integer sequence a1, a2, ..., an of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.
A subse... | n = int(input())
a = list(map(int,input().split()))
if n % 2 == 0 or a[0] % 2 == 0 or a[-1] % 2 == 0:
print("NO")
else:
print("YES") |
This is an interactive problem.
Jury has hidden a permutation p of integers from 0 to n - 1. You know only the length n. Remind that in permutation all integers are distinct.
Let b be the inverse permutation for p, i.e. pbi = i for all i. The only thing you can do is to ask xor of elements pi and bj, printing two ind... | #include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 3, NUM = 10, BIG = 1e9 + 3, MOD = 1e9 + 7, P = 20, K = 30;
const double EPS = 1e-6, PI = 3.14159265359;
int n, c[N], c2[N], ans_size;
vector<int> ans;
void check(int p0) {
vector<int> p(n), b(n);
p[0] = p0;
for (int i = 0; i < n; ++i) b[i] = (p[0] ... |
What are you doing at the end of the world? Are you busy? Will you save us?
<image>
Nephren is playing a game with little leprechauns.
She gives them an infinite array of strings, f0... ∞.
f0 is "What are you doing at the end of the world? Are you busy? Will you save us?".
She wants to let more people know about i... | #include <bits/stdc++.h>
using namespace std;
string S =
"What are you doing at the end of the world? Are you busy? Will you save "
"us?";
string A = "What are you doing while sending \"";
string B = "\"? Are you busy? Will you send \"";
string C = "\"?";
string arr[10];
long long len[5000000];
char dfs(long lo... |
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lower... | /**
* Created by Baelish on 1/29/2018.
*/
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) throws Exception {
new Thread(null ,new Runnable(){
public void run(){try{solveIt();} catch(Exception e){e.printStackTrace();}}
},"Main",1<<28).star... |
"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme."
"Little Alena got an array as a birthday present..."
The array b of length n is obtained from the array a of length n and two integers l and r (l ≤ r) using the following procedure:
b1 = b2 = b3... | #include <bits/stdc++.h>
using namespace std;
static const int INF = 0x3f3f3f3f;
static const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
template <typename T, typename U>
static void amin(T &x, U y) {
if (y < x) x = y;
}
template <typename T, typename U>
static void amax(T &x, U y) {
if (x < y) x = y;
}
int main() {
... |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | entrada = input()
vez = -1
total = 0
perigo = False
for i in range(len(entrada)):
aux = int(entrada[i])
if(vez == aux):
total += 1
if(total == 7):
perigo = True
else:
total = 1
vez = aux
if(perigo):
print("YES")
else:
print("NO")
|
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse... | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = ''
for i in a:
if i in b:
ans = ans + str(i) + ' '
print(ans)
|
Today Oz is playing with two lists A and B. List A contains N elements. List B is formed by replacing every element of List A by average value of all elements before current element including current one. For example :
If list A is like : a, b, c then
list B will be like : \frac{a}{1}, \frac{a+b}{2}, \frac{a+b+c}{3} ... | z = input()
li = list(map(int,raw_input().split()))
y=[]
s=0
y.append(li[0])
print li[0],
for i in range(1,z):
num = li[i]*(i+1)-sum(y)
y.append(num)
print y[i], |
Alice has N boxes, and each box has certain non zero number of chocolates. These boxes are numbered from 1 to N.
Alice is planning to go to wonderland. She wants to carry exactly K number of chocolates and she can carry only 2 boxes. So she wants to know the number of ways in which she can select 2 boxes such that t... | for t in range(int(raw_input())):
n = int(raw_input())
xs = [int(i) for i in raw_input().split()]
k = int(raw_input())
counts = [0] * 101
for x in xs:
counts[x] += 1
total = 0
for i in range(1, k):
if k-i < 0 or i > 100 or k-i > 100:
continue
total += coun... |
After getting their Registration IDs, now the students were curious to know the names of the various events. So, this time, the volunteers told the participants that they would be given a Special Compressed String which they are supposed to Decompress to know the particular event name. Now, each Compressed string is an... | for t in range(input()):
s=raw_input()
ch=""
l=len(s)
for i in range(0,l,1):
if (s[i]>='a' and s[i]<='z') or (s[i]>='A' and s[i]<='Z'):
ch=ch+s[i]
else:
x=ch
limit=int(s[i])-1
for j in range(0,limit,1):
ch=ch+x
print ch |
The Wingman gains the attention of a prospective partner for their friend, by tapping them on the shoulder, and then stating only the line "Haaaaave you met Ted?" (substituting the name of "Ted", the main protagonist of the show, with the name of the single person), and then walking away, leaving the newly acquainted p... | for i in range(int(raw_input())):
n = int(raw_input())
lis = [int(i) for i in raw_input().split()]
ans = 10**10
for li in lis:
x=bin(li).count('1')
ans=min(ans,x)
print ans |
Tired of playing Counter strike at every fest, well we can't do anything about it but we can sure give you a new game to play regardless of the fact that it ain't anything like GTA V or Mad Max but it sure can get you one step closer to glory you are entitled for.
So the rules are simple we would provide you with f... | '''
# 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!'
a,b,c=map(int,raw_input().split())
for i in range(2,c):
d=pow(b,2)+a
a=b
b=d
print d |
We have an unsolved mystery this time too!
Input:
First line of input contains T – the number of test cases. Each of the next T lines contain two integers a and b separated by a space.
Output:
Output T lines, each containing a single integer that is the output of that test case.
Constraints:
1 ≤ T ≤ 300
1 ≤ a ≤... | T = input()
for t in xrange(T):
a,b = map(int,raw_input().split())
if a < b:
print a
#break
else:
V = []
#C = a
while a >= b:
V.append(a%b)
a = a/b
V.append(a)
V.reverse()
S = map(str,V)
print "".join(S) |
One day Patrik met a magician.He asked magician for his magic pencil.So magician decided to give him magic pencil only if he correctely answers
to his question.
Magician gave him 3 numbers a, b and c and asked him to find the multiple of c which is closest to a^b.Help patrik to solve this problem and
win magic penci... | n=int(raw_input())
for i in range(1,n+1):
lt=map(int,raw_input().split())
d=int(pow(lt[0],lt[1]))
e=int((d/lt[2])*lt[2])
f=int((d/lt[2]+1)*lt[2])
g=int(d-e)
h=int(f-d)
if g<h:
print e
else:
print f |
Milly is at the examination hall where she is reading a question paper. She checked the question paper and discovered that there are N questions in that paper. Each question has some score value. Ideally it's like questions requiring more time have more score value and strangely no two questions on the paper require sa... | N, Q = map(int, raw_input().split(" "))
l1 = map(int, raw_input().split(" ")) #time
l2 = map(int, raw_input().split(" ")) #scores
srt = zip(*sorted(zip(l2, l1), reverse=True))[1]
reuse = {0 : 0} #reuse already calculated
#ntime
for i in range(0, N):
if i==0:
reuse[0] = srt[0];
else:
reuse[i] = reuse[i-1] + srt[i]... |
Bimal decided to join a non Hill'ffair club because he is not interested in cultural activities at
all. He thought that joining a technical club would help him in gaining technical prowess. However, on joining
the most technical club that he could find, he realised that most of the work in all technical clubs is
not te... | t=input()
for _ in range(0,t):
input()
n=input()
print n%1000000007 |
A witch of magic-land captured three prisoners who were trying to enter in magic-land without the permission of witch. The prisoners have distinct integral height. She gave them punishment called "Painful height change". In this punishment witch changes their height by using magic which gave them tremendous amount of p... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
''''''
def get_moves(h):
return max(h[2]-h[1],h[1]-h[0])-1
T = int(raw_input())
for i in xrange(T):
h = map(int, raw_input().split(" "))
print get_moves(h)
#print 'Hello World!'
''... |
Takahashi is standing on a two-dimensional plane, facing north. Find the minimum positive integer K such that Takahashi will be at the starting position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise.
Constraints
* 1 \leq X \leq ... | from math import gcd
X=int(input())
g=gcd(X,360)
print((360)//(g)) |
Takahashi wants to grill N pieces of meat on a grilling net, which can be seen as a two-dimensional plane. The coordinates of the i-th piece of meat are \left(x_i, y_i\right), and its hardness is c_i.
Takahashi can use one heat source to grill the meat. If he puts the heat source at coordinates \left(X, Y\right), wher... | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define db double
#define pii pair<int,int>
#define pli pair<ll,int>
#define pil pair<int,ll>
#define pll pair<ll,ll>
#define cpd complex<double>
const cpd rot90(0, 1);
const int inf = 1 << 30;
const ll linf = 1e18;
const double EPS = 1e-7;
template<clas... |
Takahashi is a teacher responsible for a class of N students.
The students are given distinct student numbers from 1 to N.
Today, all the students entered the classroom at different times.
According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including... | #include<iostream>
using namespace std;
typedef long long ll;
int main()
{
ll n,i;
cin>>n;
ll a[n],b[n];
for(i=1;i<=n;i++)
cin>>a[i];
for(i=1;i<=n;i++)
b[a[i]]=i;
for(i=1;i<=n;i++)
cout<<b[i]<<" ";
} |
There is an infinitely large pond, which we consider as a number line. In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1. On the lotus at coordinate i, an integer s_i is written.
You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows:
* 1. Choose... | import sys
input = sys.stdin.readline
inf = float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int, input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_, input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().... |
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black. Here, it is not allowed to paint two adjacent vertices both in black.
Find the number of ways in which the vertices can be pa... | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define mod 1000000007
vector<int> adj[100001];
vector<ll> w(100001);
vector<ll> b(100001);
void dfs(int i,int par){
ll z1=1,z2=1;
for(int j=0;j<adj[i].size();j++){
if(adj[i][j]==par)
continue;
dfs(adj[i][j],i);
z1=(z1*w[adj[i][j]])%mod;
... |
E869120's and square1001's 16-th birthday is coming soon.
Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.
E869120 and square1001 were just about to eat A and B of those pieces, respectively,
when they found a note attached to the cake saying that "the same person should not t... | import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int A = in.nextInt();
int B = in.nextInt();
if (A <= 8 && B <= 8) {
System.out.println("Yay!");
} else {
System.out.println(":(");
}
}
}
|
A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R.
Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and pl... | #include<bits/stdc++.h>
using namespace std;
int a,b,c,d;
int main(){
cin>>a>>b>>c>>d;
if(a+b>c+d) cout<<"Left"<<endl;
else if(a+b==c+d) cout<<"Balanced"<<endl;
else cout<<"Right"<<endl;
return 0;
} |
There are infinitely many cards, numbered 1, 2, 3, ... Initially, Cards x_1, x_2, ..., x_N are face up, and the others are face down.
Snuke can perform the following operation repeatedly:
* Select a prime p greater than or equal to 3. Then, select p consecutive cards and flip all of them.
Snuke's objective is to h... | #include <bits/stdc++.h>
using namespace std;
#define N 510
#define pb push_back
vector<int> v[N];
int a[N],b[N],vis[N];
int s[10000010];
inline int read() {
int x=0;
char ch=getchar();
while (!isdigit(ch)) ch=getchar();
while (isdigit(ch)) x=x*10+ch-'0',ch=getchar();
return x;
}
inline int P(int x)... |
Snuke loves puzzles.
Today, he is working on a puzzle using `S`- and `c`-shaped pieces. In this puzzle, you can combine two `c`-shaped pieces into one `S`-shaped piece, as shown in the figure below:
9b0bd546db9f28b4093d417b8f274124.png
Snuke decided to create as many `Scc` groups as possible by putting together one ... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import ja... |
AtCoDeer the deer has N square tiles. The tiles are numbered 1 through N, and the number given to each tile is written on one side of the tile. Also, each corner of each tile is painted in one of the 1000 colors, which are represented by the integers 0 between 999. The top-left, top-right, bottom-right and bottom-left ... | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
template<typename A, typename B> inline bool chmax(A &a, B b) { if (a<b) { a=b; return 1; } return 0; }
template<typename A, typename B> inline bool chmin(A &a, ... |
If you draw a few infinitely long straight lines on an infinitely wide plane, this plane will be divided into several areas. For example, if you draw a straight line, the plane will be divided into two areas. Even if you draw the same number of straight lines, the number of areas obtained will differ depending on how y... | #include <iostream>
using namespace std;
int main(){
int n;
while(cin>>n){
int area=(n*n+n+2)/2;
cout<<area<<endl;
}
return 0;
} |
"Search" is an operation to obtain the desired information from a large amount of information. Familiar examples include "finding your own exam number from a large number of exam numbers" when announcing your success, or "finding Taro Aizu's phone number" from your phone book. This search operation is also widely used ... | #include <iostream>
using namespace std;
int main(){
int n;
int t[102];
while(cin >> n, n){
for(int i = 0; i < n; i++){
cin >> t[i];
}
int x;
cin >> x;
int lo = 0;
int hi = n - 1;
int cnt = 0;
while(lo <= hi){
cnt++;
int med = (lo + hi) / 2;
if(t[med] ... |
There is "7 rows" in the game using playing cards. Here we consider a game that simplifies it. Arrange 7 using 13 cards with numbers 1 to 13 written on each. In the match, the game progresses as follows with only two players.
1. Place 7 cards in the "field".
2. Six remaining cards will be randomly distributed to the t... | #include<bits/stdc++.h>
using namespace std;
#define INF (1<<28)
#define DEKAI 1000000007
#define lp(i,n) for(int i=0;i<n;i++)
#define int long long
int stat;
int check(vector<int> a,int n){
lp(i,a.size()){
if(a[i]==n){
return i+1;
}
}
return 0;
}
int calc(vector<int> a,vector<int> b,int c[],int ... |
JOI Park
In preparation for the Olympic Games in IOI in 20XX, the JOI Park in IOI will be developed. There are N squares in JOI Park, and the squares are numbered from 1 to N. There are M roads connecting the squares, and the roads are numbered from 1 to M. The road i (1 ≤ i ≤ M) connects the square Ai and the square ... | #include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
#include <utility>
#include <queue>
using namespace std;
using int64 = long long int;
const int64 INF = 1LL << 60;
int N, M, C;
vector< pair<int64, int64> > G[100010];
int64 dist[100010];
struct Elem {
int64 cur, cost;
E... |
There are cubes of the same size and a simple robot named Masato. Initially, all cubes are on the floor. Masato can be instructed to pick up a cube and put it on another cube, to make piles of cubes. Each instruction is of the form `pick up cube A and put it on cube B (or on the floor).'
When he is to pick up a cube, ... | #include<cstdio>
#include<vector>
#include<algorithm>
#define pb push_back
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
bool cmp(const vi &va,const vi &vb){ return va.size()<vb.size(); }
vvi pile;
void findPos(int id,int &p,int &h){
rep(i,pile.size()... |
Gilbert is the network admin of Ginkgo company. His boss is mad about the messy network cables on the floor. He finally walked up to Gilbert and asked the lazy network admin to illustrate how computers and switches are connected. Since he is a programmer, he is very reluctant to move throughout the office and examine c... | import java.util.*;
public class Main{
int INF = 1 << 24;
int n;
int [][] g;
ArrayList<Node> nlist;
class Node implements Comparable<Node>{
int [] dis;
ArrayList<Integer> edge;
public Node() {
this.dis = new int[n];
Arrays.fill(this.dis, -1);
this.edge = new ArrayList<Integer>();
}
@Override
... |
What Goes Up Must Come Down
Several cards with numbers printed on them are lined up on the table.
We'd like to change their order so that first some are in non-decreasing order of the numbers on them, and the rest are in non-increasing order. For example, (1, 2, 3, 2, 1), (1, 1, 3, 4, 5, 9, 2), and (5, 3, 1) are acce... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class fenwick_tree{
const int n;
vector<T> dat;
public:
fenwick_tree(int n_) : n(n_), dat(n, 0) {}
void add(int i, T val){
for(;i < n;i |= i + 1){
dat[i] += val;
}
}
T sum(int i) const {
T res = 0;
for(;i >= 0;i ... |
Folding a Ribbon
Think of repetitively folding a very long and thin ribbon. First, the ribbon is spread out from left to right, then it is creased at its center, and one half of the ribbon is laid over the other. You can either fold it from the left to the right, picking up the left end of the ribbon and laying it ove... | #include <bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
#define rep(i, n) for(int i = 0; i < n; ++i)
#define rep2(i, a, b) for(int i = (a); i <= (b); ++i)
#define ll long long
int main() {
while(1) {
ll n, x, y;
cin >>... |
Teiji is a number theory lover. All numbers are his friends - so long as they are integers. One day, while preparing for the next class as a teaching assistant, he is interested in a number-theoretical function called the divisor function. The divisor function σ(n) is defined as the sum of all positive divisors of n. “... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pa... |
Problem H: Oh, My Goat!
Taro borrowed an ancient notebook from Jiro. This is to copy tomorrow's ancient Chinese homework. Taro has a cautious personality, so just in case, he took a copy of Jiro's notebook at a convenience store in the neighborhood and went home.
Taro was in a hurry when he was about to start his hom... | #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>
#include <cstring>
#include <sstream>
using namespace std;
#defin... |
There is an NxN grid.
<image>
(Figure when N = 3)
It costs 1 to move to an adjacent square. However, it cannot be moved diagonally. Also, there are M squares with obstacles, and you are not allowed to enter those squares. How many ways are there to move from mass (1, 1) to mass (N, N) at the lowest cost? The answer c... | #include<bits/stdc++.h>
using namespace std;
using ll=long long;
using pii=pair<int,int>;
const int INF=1e8;
const int SMALL=1000;
const ll MOD=1e9+9;
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
int n,m;
vector<int> x,y;
const int FACT_SIZE=3*1e6;
vector<ll> fact(FACT_SIZE);
vector<ll> factInv(FACT_SIZE);
ll powm(ll x... |
The fearless Ikta has finally hunted down the infamous Count Big Bridge! Count Bigbridge is now trapped in a rectangular room w meters wide and h meters deep, waiting for his end.
If you select a corner of the room and take the coordinate system so that the width direction is the x-axis and the depth direction is the ... | #include<bits/stdc++.h>
#define inf 1<<29
#define linf 1e16
#define eps (1e-3)
#define mod 1000000007
#define pi acos(-1)
#define phi (1.0+sqrt(5))/2.0
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(),(a).end()
#define pd(a) printf("%.10f\n",(double)(a))
#define FOR(... |
B: Nakajima, let's do that! --Match Peas War -
problem
Nakajima "Uhh ..."
Isono "Nakajima, are you okay?"
Nakajima "... I feel like I was having an unpleasant dream."
Isono "What kind of dream do you have?"
Nakajima "Dream to play infinitely"
Isono "I don't know what it means. Well, Nakajima, let's do that!"
Na... | #include <bits/stdc++.h>
using namespace std;
#define dump(...) cout<<"# "<<#__VA_ARGS__<<'='<<(__VA_ARGS__)<<endl
#define repi(i,a,b) for(int i=int(a);i<int(b);i++)
#define peri(i,a,b) for(int i=int(b);i-->int(a);)
#define rep(i,n) repi(i,0,n)
#define per(i,n) peri(i,0,n)
#define all(c) begin(c),end(c)
#define mp mak... |
F: 01 Binary String with Slit
problem
You will be given the string S, which consists of only 0 and 1 character types. I want to change S to T by repeating the following operation.
* Place a slit with a width of 2 so that it contains the 1 that appears on the far right in the string S. The slit must always contain tw... | #include<iomanip>
#include<limits>
#include<thread>
#include<utility>
#include<iostream>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<numeric>
#include<cassert>
#include<random>
#include<chrono>
#include<unordered_map>
#includ... |
Problem
There is a grid of $ R \ times C $ squares with $ (0, 0) $ in the upper left and $ (R-1, C-1) $ in the lower right. When you are in a square ($ e $, $ f $), from there $ (e + 1, f) $, $ (e-1, f) $, $ (e, f + 1) $, $ (e) , f-1) $, $ (e, 0) $, $ (e, C-1) $, $ (0, f) $, $ (R-1, f) $ can be moved at a cost of $ 1 ... | #include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>... |
Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either
* contains no nodes, or
* is composed of three disjoint sets of nodes:
- a root node.
- a binary tree called its left subtree.
- a binary tree called its right subtree.
Your task is to write a program ... | def preorder(tree, now):
if now == -1:
return []
else:
left = tree[now][0]
right = tree[now][1]
return [now] + preorder(tree, left) + preorder(tree, right)
def inorder(tree, now):
if now == -1:
return []
else:
left = tree[now][0]
right = tree[now... |
You are given a set $T$, which is a subset of $U$. The set $U$ consists of $0, 1, ... n-1$. Print all sets, each of which is a subset of $U$ and includes $T$ as a subset. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a ... | if __name__ == "__main__":
bit = int(input())
k, *E = map(lambda x: int(x), input().split())
m = sum(1 << e for e in E)
if (0 == m):
print(f"0:")
for d in range(1, 1 << bit):
if (d & m == m):
print(f"{d}: ", end="")
print(" ".join([str(elem) for elem in range... |
Mahesh got a beautiful array named A as a birthday gift from his beautiful girlfriend Namratha. There are N positive integers in that array. Mahesh loved the array so much that he started to spend a lot of time on it everyday. One day, he wrote down all possible subsets of the array. Then for each subset, he calculated... | import heapq
def func(pq,sum,res,n,flag):
if n==0:
if flag:
heapq.heappush(pq, sum)
return
func(pq, sum+res[n-1], res, n-1, True)
func(pq, sum, res, n-1, flag)
t=int(raw_input())
for i in range(t):
res=[]
pq=[]
n=int(raw_input())
x=raw_input()
ss=m... |
Chef likes shopping, and especially he likes to buy oranges. But right now he is short of money. He has only k rubles. There are n oranges. The i-th one costs costi rubles and has weight equal to weighti. Chef wants to buy a set of oranges with the maximal possible weight. Please help him, and tell him this weight.
In... | test = input()
from itertools import combinations
while test:
test-=1
n,k = map(int,raw_input().split())
weights = []
costs = []
index = []
for i in range(n):
c,w = map(int,raw_input().split())
costs.append(c)
weights.append(w)
index.append(i)
max = 0
for ... |
Statement
Given N,A,B,C, find how many solutions exist to the equation : a + b + c ≤ N, such that 0 ≤ a ≤ A, 0 ≤ b ≤ B, 0 ≤ c ≤ C.
Input
The first line contains the number of test cases T. Each test case contains 4 integers, N,A,B,C. 0 ≤ N,A,B,C ≤ 2500
Output
Output T lines, one for each test case.
Sample I... | T=input()
while T:
count=0
T-=1
n,a,b,c=[int(x) for x in raw_input().split()]
if a+b+c<=n:
count=(a+1)*(b+1)*(c+1)
else:
for i in range(0,min(a,n)+1):
if (b+c<=n-i):
count+=(b+1)*(c+1)
elif (b>=n-i and c>=n... |
Alice and Bob are studying for their class test together. The topic of the test is Prime Numbers. The preparation is getting too boring for their liking. To make it interesting, they turn it into a game. The winner will get an ice-cream treat from the other.
The game is called Count K-Primes. A number is a k-prime if ... | import sys
max_num = 100001
def count_primes(num_lines):
is_prime = [1] * max_num
counts = [0] * max_num
#print "is_prime: ", is_prime
for p in range(2, max_num):
if is_prime[p]:
counts[p] = 1
j = 2
while p * j < max_num:
#print "p: {0... |
Chef is good at making pancakes. Generally he gets requests to serve N pancakes at once.
He serves them in the form of a stack.
A pancake can be treated as a circular disk with some radius.
Chef needs to take care that when he places a pancake on the top of the stack the radius of the pancake should not exceed the radi... | test=int(raw_input())
dp=[[0 for _ in range(0,1002)] for _ in range(0,1002)]
mod=1e9+7
for i in range(1,1001):
dp[i][i]=1
for i in range(1,1001):
for j in range(1,i):
dp[i][j]=(dp[i-1][j]*j+dp[i-1][j-1])%mod
for _ in range(0,test):
n=int(raw_input())
ans=0
for i in range(0,n+1):
ans=(ans+dp[n][i])%mod
print i... |
In this problem, you are given a string of N characters(1-indexed), and an integer D. You perform multiple operations on this string. In the first operation you select the first D characters of the string, ie. the substring S[1...D] and reverse it. The other characters remain unchanged. Thus, after the first operation ... | # cook your code here
# your code goes here
from sys import stdin, stdout
t = int(stdin.readline())
#t = int(raw_input())
while t:
t -= 1
s = stdin.readline().strip()
d = int(stdin.readline())
temp = s[:d-1]
choice = len(s)-d+1
j = s[d-1:]
if choice%2 == 0:
j += temp
else:
... |
You are given a rectangular parallelepiped with sides of positive integer lengths A, B and C.
Find the number of different groups of three integers (a, b, c) such that 1≤ a≤ b≤ c and parallelepiped A× B× C can be paved with parallelepipeds a× b× c. Note, that all small parallelepipeds have to be rotated in the same d... | #include <bits/stdc++.h>
using namespace std;
const int M = 1e5 + 10, N = 2e4 + 10;
const int n = 1e5;
long long ans, s[M];
int gcd(int x, int y) {
int i = 0, j = 0;
if (x == 0) return y;
if (y == 0) return x;
for (; 0 == (x & 1); i++) x >>= 1;
for (; 0 == (y & 1); j++) y >>= 1;
if (i > j) i = j;
while (1... |
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the fie... | n,d = map(int,input().split())
m = int(input())
x = []
y = []
k = 2*n-d
for i in range(m):
a = list(map(int,input().split()))
x.append(a[0])
y.append(a[1])
for i in range(m):
if x[i] >= 0 and x[i] <= n and y[i] >= 0 and y[i] <= n:
if y[i] <= d + x[i] and y[i] >= x[i] - d and y[i] >= -x[i]+d and y[i] <= -x[i... |
Suppose you are given a sequence S of k pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_k, b_k).
You can perform the following operations on it:
1. Choose some position i and increase a_i by 1. That can be performed only if there exists at least one such position j that i ≠ j and a_i = a_j. The cost of this opera... | #include <bits/stdc++.h>
using namespace std;
const int N = 414514;
int n, tt;
int f[N], r[N];
int rt[N], ls[N * 30], rs[N * 30], sz[N * 30];
long long su[N * 30], as;
void add(int &i, int l, int r, int s) {
if (!i) i = ++tt;
if (l == r) {
sz[i] = 1, su[i] = s;
return;
}
if (s <= ((l + r) >> 1))
add... |
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white ki... | n = int(raw_input())
x, y = raw_input().split()
x, y= int(x),int(y)
whiteKing = (1,1)
blackKing = (n,n)
coin = (x,y)
def noMoves(a,b):
return max(abs(b[0]-a[0]),abs(b[1]-a[1]))
if whiteKing == coin:
print "White"
elif blackKing == coin:
print "Black"
else:
whiteMoves = noMoves(whiteKing,coin)
blackMoves = noM... |
You are given a string s of length n consisting only of lowercase Latin letters.
A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.
Your task is to calculate the number of ways to remove exactly one substring from thi... | n=int(input())
s=input()
cntl=1
cntr=1
for i in range(1,len(s)):
if(s[0]==s[i]):
cntl+=1
else:
break
for i in range(n-2,-1,-1):
if(s[n-1]==s[i]):
cntr+=1
else:
break
if(s[0]!=s[n-1]):
ans=(cntl+cntr+1)%998244353
print(ans)
else:
ans=((cntl+1)*(cntr+1))%998244353
print(ans) |
You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2).
You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds t... | #include <bits/stdc++.h>
using namespace std;
const int max_n = 100111;
const long long inf = 1000111222000111222LL;
int n, x1, yl, x2, y2, x, y, dx[max_n], dy[max_n];
char s[max_n];
bool ok(long long cnt) {
long long full = cnt / n;
long long last = cnt % n;
long long xx = full * dx[n - 1];
long long yy = full... |
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the ... | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
struct SegmentTree {
private:
long long n;
vector<long long> node;
public:
SegmentTree(vector<long long> v) {
long long sz = (long long)v.size();
n = 1;
while (n < sz) n *= 2;
node.resize(2 * n - 1);
for (long long i = (... |
During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited wi... | #include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char *name, Arg1 &&arg1) {
cerr << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char *names, Arg1 &&arg1, Args &&...args) {
const char *comma = strchr(names + 1, ',');
cerr.write(nam... |
Now Heidi is ready to crack Madame Kovarian's hashing function.
Madame Kovarian has a very strict set of rules for name changes. Two names can be interchanged only if using the following hashing function on them results in a collision. However, the hashing function is parametrized, so one can always find a set of para... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#pragma GCC target( \
"sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3fLL;
const double PI = acos(-1.0);
const do... |
This is an interactive problem.
Alice and Bob are playing a game on the chessboard of size n × m where n and m are even. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are two knights on the chessboard. A white one initially is on the position (x_1, y_1), while the black one is on th... | #include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int read() {
int w = 0, f = 0;
char c = getchar();
while ((c < '0' || c > '9') && c != '-') c = getchar();
if (c == '-') f = 1, c = getchar();
while (c >= '0' && c <= '9') w = w * 10 + c - '0', c = getchar();
return f ? -w : w;
}
int dx[] = {... |
You, the mighty Blackout, are standing in the upper-left (0,0) corner of NxM matrix. You must move either right or down each second.
There are K transformers jumping around the matrix in the following way. Each transformer starts jumping from position (x,y), at time t, and jumps to the next position each second. The ... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T &x) {
char c;
bool nega = 0;
while ((!isdigit(c = getchar())) && c != '-')
;
if (c == '-') {
c = getchar();
nega = 1;
}
x = c - 48;
while (isdigit(c = getchar())) x = x * 10 + c - 48;
if (nega) x = -x;
}
i... |
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbe... | #include <bits/stdc++.h>
using namespace std;
const int N = 16;
const int M = 5010;
const int inf = 0x3f3f3f3f;
int a[N][M], c[N], two[N << 1], f[1 << N], mix[1 << N];
long long sum[N], tot;
map<long long, int> mp;
pair<int, int> loop[1 << N], ans[N];
void init(void) {
two[0] = 1;
for (int i = 1; i <= 20; ++i) {
... |
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters.
Hacker went home and started preparing to... | import java.awt.image.SampleModel;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import javax.print.attribute.standard.Fidelity;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Print... |
It is only a few days until Seollal (Korean Lunar New Year), and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.
The garden can be represented by a n × m grid of unit cells. Some (possibly zero)... | #include <bits/stdc++.h>
std::mt19937 rng(
(int)std::chrono::steady_clock::now().time_since_epoch().count());
struct Edge {
int u, v;
Edge() {}
Edge(int a, int b) : u(std::min(a, b)), v(std::max(a, b)) {}
bool operator<(const Edge &o) const { return u != o.u ? u < o.u : v < o.v; }
bool operator==(const Ed... |
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong lo... | #include <bits/stdc++.h>
using namespace std;
string reverse(string str) {
string ss = str;
for (long long i = str.length() - 1, j = 0; i >= 0; i--, j++) ss[j] = str[i];
return ss;
}
int main() {
long long n, m, cnt = 0, y = 0, max = 0;
string rr = "";
cin >> n >> m;
vector<string> v(n);
list<string> l;... |
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation ⊙ of two ternary n... | from sys import stdout, stdin
read = stdin.readline
write = stdout.write
t = int(read())
for _ in range(t):
n = int(read())
x = read()
a, b = ['1'], ['1']
a_gt_b = False
for d in x[1:-1]:
if d == '1':
if not a_gt_b:
a_gt_b = True
a.append('1')
... |
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re... | import sys
input = sys.stdin.readline
'''
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
for CASES in range(int(input())):
sys.stdout.write(" ".join(map(str,ans))+"\n")
'''
inf = 100000000000000000 # 1e17
mod = 998244353
for CASES in range(int(input())):
... |
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...
Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a... | t= int(input())
for i in range (t):
g= int(input())
if(g%4==0):
print("YES")
else:
print("NO")
|
Katya recently started to invent programming tasks and prepare her own contests. What she does not like is boring and simple constraints. Katya is fed up with all those "N does not exceed a thousand" and "the sum of ai does not exceed a million" and she decided to come up with something a little more complicated.
The ... | #include <bits/stdc++.h>
using namespace std;
struct query {
int c, l, r;
};
const int MAX_LEN = 100010;
const int MAX_QUERY = 510;
const int MAX_ALPHABET = 30;
string s;
int S[MAX_LEN];
int k, L, R;
query qs[MAX_QUERY];
vector<int> let_pos[MAX_ALPHABET];
int cnt[MAX_LEN];
int cpl[MAX_QUERY], cpr[MAX_QUERY];
int cp[M... |
After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j.
Tayuya wants to play a melody of n notes. Each note can be play... | #include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> a(6);
int sol = 1e9;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
int n;
cin >> n;
vector<pair<int, int>> c(6 * n);
for (int i = 0; i < n; i++) {
int b;
cin >> b;
for (int j = 0; j < 6; j++) c[6 * i + j] = {b - a[j], ... |
Alice and Bob play ping-pong with simplified rules.
During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.
The one ... | for test in range(input()):
ca,cb = map(int,raw_input().split())
if ca==1:
print 0,cb
continue
if cb==1:
print ca-1,cb
else:
print ca-1,cb
|
In Homer's country, there are n cities numbered 1 to n and they form a tree. That is, there are (n-1) undirected roads between these n cities and every two cities can reach each other through these roads.
Homer's country is an industrial country, and each of the n cities in it contains some mineral resource. The mine... | #include <bits/stdc++.h>
using namespace std;
const int N = 300005;
const int LN = 19;
struct Node {
long long val;
Node *l, *r;
Node(long long _val=0): val(_val) {
l = r = 0;
}
Node(Node *node) {
val = node->val;
l = node->l; r = node->r;
}
};
int n, q;
int c[N];
mt19937_64 rng;
long long h... |
You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order:
* if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n;
* if |a| > 0, delete the las... | #include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <queue>
#include <set>
#include <bitset>
using namespace std;
#define int long long
#define all(x) x.begin(), x.end()
const int maxn = 2e6 + 13;
const int INF = 2e9;
const int MOD = 1e9 + 7;
void so... |
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple.
Vasya noticed that the yard is a rectangu... | //package codeforces;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
i... |
You are given a connected weighted undirected graph without any loops and multiple edges.
Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the... | #include <bits/stdc++.h>
using namespace std;
const int INF = (int)2e9;
const long long INFL = (long long)9e18;
const int MAXINT = ((~0) ^ (1 << 31));
const long long MAXLL = ((~0) ^ ((long long)1 << 63));
template <class T>
inline T pow2(T a) {
return a * a;
}
template <class T>
inline bool mineq(T& a, T b) {
retu... |
In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecuti... |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class problem4{
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
int numClusters = scan.nextInt();
int numFiles = scan.nextInt();... |
One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.
He took a checkered white square piece of paper, consisting of n × n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the p... | import java.io.*;
import java.util.*;
public class GameOnPaper {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken... |
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | l=list(map(int,input().split()))
i=list(set(l))
print(abs(len(i)-len(l))) |
Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to g... | #include <bits/stdc++.h>
using namespace std;
const int L = 60, N = 100 * 1000 + 5;
int t = 0;
long long get(long long x, int y) { return (x >> y) & 1; }
long long a[L];
long long b[L];
long long e[N];
int d[N];
vector<int> vec;
int main() {
int n;
cin >> n;
long long xall = 0;
for (int i = 0; i < n; i++) {
... |
A little girl loves problems on trees very much. Here's one of them.
A tree is an undirected connected graph, not containing cycles. The degree of node x in the tree is the number of nodes y of the tree, such that each of them is connected with node x by some edge of the tree.
Let's consider a tree that consists of ... | #include <bits/stdc++.h>
using namespace std;
vector<vector<int> > arbres_somme;
void add(int idA, int id, int deb, int fin, int first, int last, int val) {
if (deb == first and fin == last) {
arbres_somme[idA][id] += val;
} else if (deb < last and first < fin and deb + 1 < fin) {
add(idA, 2 * id + 1, deb, ... |
A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on fo... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
const int dx[] = {1, 0, -1, 0, -1, -1, 1, 1};
const int dy[] = {0, 1, 0, -1, -1, 1, -1, 1};
const int OO = INT_MAX;
int main() {
double largeDisatance, smallDistance, speed, green, red;
cin >> largeDisatance >> smallDistance >> speed >> green >>... |
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 SIZE = 100009;
vector<int> adj[SIZE];
int N;
bool pass[SIZE];
char ans[SIZE];
int table[SIZE];
void assign(int, char, int);
int build(int n, int p, char c, int total) {
table[n] = 1;
bool check = true;
for (vector<int>::iterator it = adj[n].begin(); it != ad... |
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... | #include <bits/stdc++.h>
using namespace std;
long long power(long x, long n) {
if (n == 0) return 1;
if (n == 1) return x;
long n2 = n / 2;
long long po = power(x, n2);
if (n % 2) return po * po * x;
return po * po;
}
long long gcd(long long a, long long b) {
if (b == 0) return a;
a %= b;
return gcd(... |
Innocentius has a problem — his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.
Innocentius is touch-typing a program that pain... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class ProblemD {
static final long MOD = 1000000007;
public static void main(String[] args... |
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if:
* the Euclidean distance between A and B is one unit and neither A nor B is blocked;
* or there is some inte... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
long long y, lasty = n + 1, ans = n;
for (y = lasty; y >= 0; y--) {
if (1 * 1 + y * y <= n * n) {
break;
}
}
lasty = y;
for (long long x = 2; x < n; x++) {
for (y = lasty; y >= 0; y--) {
if (x * x + y... |
Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of ... | import java.util.Scanner;
public class b240 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int a = input.nextInt();
int b = input.nextInt();
StringBuilder sb = new StringBuilder();
long x;
for (int i = 0; i < n; i++) {
x = input.nextInt();... |
Valera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below:
//input: integers x, k, p
a = x;
for(step = 1; step <= k; step = step + 1){
rnd = [random integer from 1 to 100];
if(rnd <= p)
a = a * 2;
el... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
int x, k, P;
double p, pp;
double f[N][N];
int main() {
scanf("%d %d %lf", &x, &k, &p);
p = p * 1.0 / 100.0, pp = 1.0 - p;
for (int i = 0; i <= k; i++)
for (int j = x + i; j % 2 == 0; j >>= 1) f[0][i]++;
for (int i = 0; i < k; i++)
fo... |
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable st... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
scanf("%d", &n);
int m;
scanf("%d", &m);
char s[n + 1];
scanf("%s", &s);
int no[n + 1];
for (int i(0); i < n; ++i) {
no[i + 1] = static_cast<int>(s[i]) - 97;
}
no[0] = 0;
int i(n);
while (i > 0 && no[i] == m - 1) {
i = i -... |
There are n cities in Cyberland, numbered from 1 to n, connected by m bidirectional roads. The j-th road connects city aj and bj.
For tourists, souvenirs are sold in every city of Cyberland. In particular, city i sell it at a price of wi.
Now there are q queries for you to handle. There are two types of queries:
*... | #include <bits/stdc++.h>
using namespace std;
int n, m, q;
int dfn[200010], low[200010], total;
int size[200010], son[200010], top[200010], dep[200010], fa[200010],
tag[200010], oppo[200010], quantity;
int w[200010 << 1];
stack<int> s;
int amount;
multiset<int> val[200010];
struct data {
int next, to;
data(int ... |
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After app... | import java.io.*;
import java.util.*;
public class CF_510D {
static int[] getPrimes(int n){
ArrayList<Integer> al=new ArrayList<>();
for (long i=2;i*i<=n;i++)
if (n%i==0){
al.add((int)i);
while (n%i==0) n/=i;
}
if (n>1) al.add(n);
... |
Tavas is a cheerleader in the new sports competition named "Pashmaks".
<image>
This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (the... | #include <bits/stdc++.h>
using namespace std;
set<pair<long long, long long> > s;
pair<long long, long long> a[300000], b[300000];
int num = 0, n, p[300000], A[300000], B[300000];
void ConvexHull() {
int cnt = 0;
for (int i = 1; i <= num; i++) {
pair<long long, long long> u = b[i];
while (cnt > 1 &&
... |
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of ea... | #include <bits/stdc++.h>
const long long oo = 1e9;
int dx[] = {-1, 1, 0, 0, 1, -1, 1, -1};
int dy[] = {0, 0, -1, 1, 1, -1, -1, 1};
using namespace std;
void fast() {
std::ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
}
int main() {
fast();
int n, a[1005];
cin >> n;
for (int i = 0; i < n; i+... |
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline T gcd(T a, T b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
template <class T>
inline T lcm(T a, T b) {
return a / gcd(a, b) * b;
}
inline int nxt() {
int wow;
scanf("%d", &wow);
return wow;
}
inline long long int lxt() {
... |
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 ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static ja... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.