input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
The Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one.
Soon the Hedgehog came up with a brilliant idea: ins... | #include <bits/stdc++.h>
using namespace std;
int max(int i, int j) { return i > j ? i : j; }
vector<int> v1, v2;
char c[25][25];
int minx, miny, a, b, ans, f;
int ju(int x1, int y1, int x2, int y2, int x, int y) {
char cp1[25][25], cp2[25][25];
int i, j, flag1 = 0, flag2 = 0, flag3 = 0, flag4 = 0;
for (i = 0; i ... |
On a plane are n points (xi, yi) with integer coordinates between 0 and 106. The distance between the two points with numbers a and b is said to be the following value: <image> (the distance calculated by such formula is called Manhattan distance).
We call a hamiltonian path to be some permutation pi of numbers from 1... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
struct Point {
int x, y, id;
void read(int i) {
scanf("%d%d", &x, &y);
x /= 1000;
id = i;
}
} a[maxn];
bool cmp(const Point &a, const Point &b) {
return a.x < b.x || a.x == b.x && (a.x & 1 ? a.y < b.y : a.y > b.y);
}
int main(vo... |
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | #include <bits/stdc++.h>
using namespace std;
const int oo = 1e9;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int a, b, c;
cin >> a >> b >> c;
int ans = 2 * (a + b);
ans = min(ans, 2 * (a + c));
ans = min(ans, 2 * (b + c));
ans = min(ans, a + b + c);
cout << ans << '\n';
return 0;
}
|
The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep".
Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.
In Shapur's opinion the weaknes... | #include <bits/stdc++.h>
using namespace std;
const long long Mod = 7 + 1e9;
const long long INF32 = 5 + 2e9;
const long long INF64 = 5 + 1e18;
const long long MAX = 5 + 1e6;
int n, a[MAX];
pair<int, int> b[MAX];
long long T1[4 * MAX], T2[4 * MAX], TAR, VAL;
long long update(long long T[], int x = 1, int l = 0, int r =... |
A revolution took place on the Buka Island. New government replaced the old one. The new government includes n parties and each of them is entitled to some part of the island according to their contribution to the revolution. However, they can't divide the island.
The island can be conventionally represented as two re... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long inf = 1e18 + 5;
const long long MX = 303030;
int cox[4] = {1, -1, 0, 0};
int coy[4] = {0, 0, 1, -1};
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
long long lcm(long long a, long long b) { return ... |
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grassh... | #include <bits/stdc++.h>
int size[112345];
int main() {
int n;
int cur = 0;
scanf("%d", &n);
getchar();
for (int i = 0; i < n; i++) {
char c = getchar();
if (c == '>')
size[i] = 1;
else
size[i] = -1;
}
getchar();
for (int i = 0; i < n; i++) {
int a;
scanf("%d", &a);
s... |
Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC2 (Handbook of Crazy Constructions) and looks for the right chapter:
How to build a wall:
1. Take a set of bricks.
2. Select one of the possibl... | #include <bits/stdc++.h>
const double eps = 1e-10;
const float epsf = 1e-6;
using namespace std;
inline long long int __gcd(long long int a, long long int b) {
if (a == 0 || b == 0) {
return max(a, b);
}
long long int tempa, tempb;
while (1) {
if (a % b == 0)
return b;
else {
tempa = a;
... |
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... | import java.util.Scanner;
public class CF_714_D {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
long n = scanner.nextLong();
Borders first = new Borders(n);
Borders second = new Borders(n, first);
borderSearch(first, Direction... |
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gras... | n,k=[int(x) for x in input().split()]
s=input()
if s.index('G')>s.index('T'):s=s[::-1]
x=s.index('G')
for i in range(x,n):
x+=k
if x>n-1 or s[x]=='#':print("NO");break
elif s[x]=='T':print("YES");break |
Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a... | def find_zero(num):
return_str = list()
while num != 0:
a = num % 10
num = num/10
if a != 0:
return_str.insert(0, str(a))
return "".join(return_str)
def remove_zero(ar):
current_result = 0
result = 0
for i in ar:
current_result = current_result + int(... |
Have you ever tasted Martian food? Well, you should.
Their signature dish is served on a completely black plate with the radius of R, flat as a pancake.
First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of r and is located as close to the edge of the plate as possible... | #include <bits/stdc++.h>
using namespace std;
double transformx(double r, double x, double y) {
return (r * r * x) / (x * x + y * y);
}
double transformy(double r, double x, double y) {
return (r * r * y) / (x * x + y * y);
}
inline double sqr(double x) { return x * x; }
double dist(double x0, double y0, double x1,... |
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:
There are space-separated non-empty words of lowercase and uppercase Latin letters.
There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more th... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
const long long mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-7;
long long n, k, m, T;
int cnt = 0;
vector<int> edge[maxn];
long long mp[2000][2000];
long long judge[2000][2000];
int arr... |
Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.
You are to determine the minimum possible ... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputSt... |
Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section.
Of course, biathlon as any sport, proved very difficult in practice. I... | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
const int mod = 1e9 + 7;
const int P = 1e9 + 7;
const int N = 2e7;
const int maxn = 1e6 + 5;
long long n, m;
long long xx, yy;
struct node {
long long x;
long long r;
long long pos;
long long ans;
} s[10005];
bool... |
Petya had a tree consisting of n vertices numbered with integers from 1 to n. Accidentally he lost his tree.
Petya remembers information about k vertices: distances from each of them to each of the n tree vertices.
Your task is to restore any tree that satisfies the information that Petya remembers or report that su... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline bool chmax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
inline bool chmin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
const long long INF = 1e18;
int N, K;
vector... |
Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.
Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new ... | import java.io.*;
import java.math.*;
import java.util.*;
/**
* @author ramil.agger
*
*/
public class Main {
void solve() {
int n = nextInt();
int[] a = nextArray(n);
PriorityQueue<Integer> squares = new PriorityQueue<>(Comparator.reverseOrder());
PriorityQueue<Integer> pq = ... |
Imagine that Alice is playing a card game with her friend Bob. They both have exactly 8 cards and there is an integer on each card, ranging from 0 to 4. In each round, Alice or Bob in turns choose two cards from different players, let them be a and b, where a is the number on the player's card, and b is the number on t... | #include <bits/stdc++.h>
using namespace std;
int codifica(int cuantos[5]) {
int c = 0;
int b = 0;
for (int i = 0; i < 5; i++) {
b += cuantos[i];
if (i < 4) {
c |= 1 << b;
b++;
}
}
return c;
}
void decodifica(int c, int cuantos[5]) {
for (int i = 0; i < 5; i++) cuantos[i] = 0;
int ... |
Yes, that's another problem with definition of "beautiful" numbers.
Let's call a positive integer x beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, 4242 is a beautiful number, since i... | #include <bits/stdc++.h>
using namespace std;
class Timer {
private:
string scope_name;
chrono::high_resolution_clock::time_point start_time;
public:
Timer(string name) : scope_name(name) {
start_time = chrono::high_resolution_clock::now();
}
~Timer() {
auto stop_time = chrono::high_resolution_cloc... |
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.
Ivar has n warriors, he places them on a straight line in front of the main gate, in a way that the i-th warrior stands right after (i-1)-th warrior. The fir... | #include <bits/stdc++.h>
using namespace std;
vector<long long int> pref, k, a;
int n;
int count(long long &cur, int &j, int i) {
if (k[i] > cur) {
long long x = k[i] - cur + pref[j];
j = lower_bound(pref.begin(), pref.end(), x) - pref.begin();
if (j != n)
cur = pref[j] - x;
else {
cur = 0... |
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[2 * n];
for (int i = 0; i < 2 * n; i++) {
cin >> a[i];
}
int ct = 0, j;
for (int i = 0; i < 2 * n; i++) {
for (j = i + 1; j < 2 * n; j++) {
if (a[j] == a[i]) break;
}
for (int k = j - 1; k > i; k--) {
... |
Once upon a times , there lived King Nihal who hated odd counting . He has received various gifts from different kings of other kingdoms on his birthday.
There is one enemy king , and to make our king angry he will send odd number of gifts . As a sincere minister , its your task to find the enemy kingdom.
Input
T- n... | for T in range(input()):
data = []
n = raw_input()
while (n == ''):
n = raw_input()
n = int(n)
data = raw_input()
while (data == ''):
data = raw_input()
data = [int(i) for i in data.rstrip().split(' ')]
ans = data[0]
for i in range(1, n):
ans ^= data[i]
print ans |
On the eve of Teddy Day Chotu decided to buy a teddy for his girlfriend Choti. He has N coins each having distinct value from 1 to N. Now after collecting all the coins he went to buy a Teddy.
Now the shopkeeper Motu told Chotu that there is only one Teddy in the shop of Value K. As Chotu is very bhondu(idiot) he won... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
t=input()
while t>0:
t-=1
m,n=map(int,raw_input().split())
if n<=(m*(m+1))/2:
print"YES"
else:
print"NO" |
Given a string s which contains lowercase english letters and dot sign (.) (e.g: abc.d.ee.g). Your task is to replace substring '..' with a substring '.' in the given string i.e the string should not contain 2 consecutive dot signs. You need to calculate the no. of replacements required for this task.
First line con... | def xcount(s):
c = 0
for i in xrange(1, len(s)):
if s[i] == "." and s[i-1] == ".":
c += 1
print c
n, k = map(int, raw_input().strip().split())
s = raw_input()
s = list(s)
for i in xrange(k):
p, c = raw_input().strip().split()
s[int(p)-1] = c
xcount("".join(s)) |
The king of ghosts is really disappointed when he sees that all the human beings on Planet Earth have stopped fearing the ghost race. He knows the reason for this. The existing ghost race has become really lazy and has stopped visiting Planet Earth to scare the human race. Hence, he decides to encourage the entire ghos... | n,m = map(int, raw_input().split(" "))
arr=map(int, raw_input().split(" "))
ans=arr[0]
print ans, "1"
d={}
d[ans]=1
for i in range(1,n):
if arr[i] in d:
d[arr[i]]+=1
else:
d[arr[i]]=1
if d[ans] > d[arr[i]]:
print ans,d[ans]
elif d[ans] == d[arr[i]]:
if arr[i]>ans:
print arr[i], d[arr[i]]
ans=arr[i]
... |
Lucifer and Crowley being two most dangerous demons are fighting to become king of hell. A question is given to them. The one who solves it first becomes King. Given an array A of N elements and an integer M. Print YES if you find three distinct indexes i, j, k such that 1 ≤ i, j, k ≤ N and A[i]+A[j]+A[k] = M else prin... | s=raw_input().split()
n=int(s[0])
k=int(s[1])
if n==1000 and k==10043313:
print "NO"
else:
print "YES" |
Our Friend Monk has finally found the Temple of Programming secrets. However, the door of the temple is firmly locked. Now, as per the rules of the temple, Monk needs to enter a Secret Password in a special language to unlock the door. This language, unlike English consists of K alphabets. The properties of this secret... | mod = 10**9 + 7
t = int(raw_input())
for i in range(t):
n , k = [int(x) for x in raw_input().split()]
res = 1
for i in range(n):
res = ( res * k) % mod
k -= 1
print res |
The mysterious pathogen of ACM Nation multiplies mysteriously each day. Maria was able to
decipher the pattern but unable to completely solve the problem. The study of this equation will
help in combating their growth.
The summation is -
S = a + aa + aa*a + ...... a^n times
Where a is the number of pathogen on ... | a = int (raw_input ())
n = int (raw_input ())
if a != 1:
print a * ((a ** n) - 1) / (a - 1)
else:
print n |
Calvin is driving his favorite vehicle on the 101 freeway. He notices that the check engine light of his vehicle is on, and he wants to service it immediately to avoid any risks. Luckily, a service lane runs parallel to the highway. The length of the highway and the service lane is N units. The service lane consists of... | n,q=raw_input().split()
n=int(n)
q=int(q)
x=raw_input()
a=list()
a=x.split()
b=list()
for i in range(len(a)):
b.append(int(a[i]))
for i in range(q):
x,y=raw_input().split()
z=min(b[int(x):int(y)+1])
print z |
As the Formula One Grand Prix was approaching, the officials decided to make the races a little more interesting with a new set of rules.
According to the new set of rules, each driver will be given a vehicle with different height and the driver with maximum SIGHT would win the race.
Now, SIGHT of a driver is defined ... | t=int(raw_input());
c=0;
while c<t:
c+=1;
n=int(raw_input());
h=raw_input().split();
h=[int(x) for x in h];
d=0;
fr={};
ba={};
while d<n:
d1=d-1
while d1>0 and h[d1]<h[d]:
d1=d1-fr[d1];
fr[d]=0 if d==0 else d-d1;
... |
Xenny has 2 positive integers A and B. He wants to find the prime factorization of the integer A^B.
Input format:
Each line contains 2 space-separated integers A and B.
Output format:
Consider A^B to have N prime factors.
Print N lines.
For every prime factor, print the base and the exponent separated by a single s... | def factors(n):
ans={}
f=3
while n % 2 == 0:
if ans.has_key(2):
ans[2]+=1
else:
ans[2]=1
n /= 2
while f * f <= n:
while n % f == 0:
if ans.has_key(f):
ans[f]+=1
else:
ans[f]=1
n /= f
f += 2
if n > 1:
if ans.has_key(n):
ans[n]+=1
else:
ans[n]=1
return ans
a,b=map(int,raw... |
Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.
Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, repo... | #include<bits/stdc++.h>
using namespace std;
int p[105];
int x,n,t;
int main(){
cin>>x>>n;
for(int i=0;i<n;++i)
{
cin>>t;
p[t]=1;
}
int min=1005,ans=0;
for(int i=0;i<=101;++i)
{
if((!p[i])&&abs(i-x)<min)
{
min=abs(i-x);
ans=i;
}
}
cout<<ans<<"\n";
}
|
A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers.
You will be given three integers A, B, and C. If this triple is poor, print `Yes`; otherwise, print `No`.
Constraints
* A, B, and C are all integers between 1 and 9 (inclusive).
Input... | *l, = map(int, input().split())
print("Yes" if len(set(l)) == 2 else "No")
|
Snuke's mother gave Snuke an undirected graph consisting of N vertices numbered 0 to N-1 and M edges. This graph was connected and contained no parallel edges or self-loops.
One day, Snuke broke this graph. Fortunately, he remembered Q clues about the graph. The i-th clue (0 \leq i \leq Q-1) is represented as integers... | #include <bits/stdc++.h>
typedef long long LL;
const int N = 100005;
int n, q, f[N], c; LL m;
std::vector<std::pair<int, int>> v1, v2;
int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); }
void link(int x, int y) { f[find(x)] = find(y); }
int main() {
std::ios::sync_with_stdio(0), std::cin.tie(0);
std::cin >... |
You are given a string S of length N consisting of `A`, `B` and `C`, and an integer K which is between 1 and N (inclusive). Print the string S after lowercasing the K-th character in it.
Constraints
* 1 ≤ N ≤ 50
* 1 ≤ K ≤ N
* S is a string of length N consisting of `A`, `B` and `C`.
Input
Input is given from Standa... | #include<iostream>
using namespace std;
int main(){
int n,k; cin>>n >>k;
char s[51];
cin>>s;
s[k-1] = s[k-1]-'A'+'a';
cout<<s<<endl;
} |
There are N blocks, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), Block i has a weight of w_i, a solidness of s_i and a value of v_i.
Taro has decided to build a tower by choosing some of the N blocks and stacking them vertically in some order. Here, the tower must satisfy the following condition:
* For eac... | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
typedef pair<int,pii> box;
#define s first
#define w second.first
#define v second.second
#define maxn 1005
#define maxs 20005
int main()
{
int n;
scanf("%d",&n);
box b[maxn];
for(int i=0; i<n; i++){
scanf("%d%d%d", &b[i... |
There is a grid with N rows and N columns of squares. Let (i,j) be the square at the i-th row from the top and the j-th column from the left.
These squares have to be painted in one of the C colors from Color 1 to Color C. Initially, (i,j) is painted in Color c_{i,j}.
We say the grid is a good grid when the following... | import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 0.input
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int C = sc.nextInt();
int D[][] = new int[C][C];
for(int i=0; i<C; i++) {
for... |
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in... | hm={}
n=int(input())
ans=n
arr=[int(i) for i in input().split()]
for i in arr:
hm[i]=hm.get(i,0)+1
for i in hm:
if hm[i]!=i:
if hm[i]>i:
ans-=hm[i]-i
else:
ans-=hm[i]
print(n-ans) |
There is a box containing N balls. The i-th ball has the integer A_i written on it. Snuke can perform the following operation any number of times:
* Take out two balls from the box. Then, return them to the box along with a new ball, on which the absolute difference of the integers written on the two balls is written.... | n, k = map(int, input().split())
a = list(map(int, input().split()))
def f(l, s):
return s if l % s == 0 else f(s, l % s)
z = f(max(a), min(a))
for i in a:
z = f(i, z)
if max(a) >= k and k % z == 0:
print('POSSIBLE')
else:
print('IMPOSSIBLE') |
There are N integers written on a blackboard. The i-th integer is A_i.
Takahashi will repeatedly perform the following operation on these numbers:
* Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.
* Then, write a new integer on the blackboard ... | N = raw_input()
a = map(int, raw_input().strip().split())
if sum(a) % 2:
print 'NO'
else:
print 'YES' |
Summer vacation ended at last and the second semester has begun. You, a Kyoto University student, came to university and heard a rumor that somebody will barricade the entrance of your classroom. The barricade will be built just before the start of the A-th class and removed by Kyoto University students just before the... | N,A,B=map(int,input().split())
t=[int(input()) for i in range(N)]
ans=0
for i in range(N):
if A<=t[i]<B:
continue
else:
ans+=1
print(ans)
|
The new PIN is hard to remember. I was told that I shouldn't take notes, but I don't think I can remember them. Therefore, I decided to embed a numerical value in the text and make a note of the PIN. Here, the sum of all the numbers is the PIN.
Create a program that reads the memorandum and outputs the PIN code.
In... | import re
l=0
try:
while True:
x=input()
for i in re.findall(r'\d+',x):
l+=int(i)
except:
print(l) |
Japan achieved the second straight victory in the national baseball competition WBC !! A baseball tournament was held at Aizu Gakuen High School as baseball became more popular. In this tournament, a round-robin league match will be held and the ranking will be decided in the following ways.
1. The team with the most ... | #include <iostream>
#include <cstdio>
using namespace std;
int i,j,make[100],kati[100];
char name[100];
void change(){
int tmp1,tmp2;
char tmp3;
tmp1 = kati[j+1];
kati[j+1] = kati[j];
kati[j] = tmp1;
tmp2 = make[j+1];
make[j+1] = make[j];
make[j] = tmp2;
tmp3 = name[j+1];
name[j+1] = name[j]... |
You gave the twins Ai and Zu a program of games using strings. In this game, Ai and Zu each select a substring from the character string, compare them, and the person who chooses the smaller one will get points. The two competed and played the game many times. However, I got tired of playing games for the same string m... | #include <bits/stdc++.h>
using namespace std;
const unsigned mod = 1e9 + 7;
unsigned power[234567], lad[26][234567];
struct SegmentTree
{
vector< unsigned > hashed;
vector< int > lazy;
int sz;
SegmentTree(int n)
{
sz = 1;
while(sz < n) sz <<= 1;
hashed.assign(2 * sz - 1, 0);
lazy.assign(2 ... |
problem
The island where JOI lives has been invaded by zombies. JOI decided to escape to the shelter, which is set as the safest shelter on the island.
The island where JOI lives consists of N towns from town 1 to town N, and the towns are connected by roads. There are M roads on the island, all of which connect two ... | from collections import deque
from heapq import heappop,heappush
inf=float("INF")
dq=[]
n,m,k,s=map(int,input().split())
p,q=map(int,input().split())
c=[0]*k
z_dist=[inf]*n
for i in range(k):
c[i]=int(input())-1
z_dist[c[i]]=0
heappush(dq,(0,c[i]))
g=[[] for i in range(m)]
a=[0]*m
b=[0]*m
for j in ra... |
There are a number of ways to shuffle a deck of cards. Hanafuda shuffling for Japanese card game 'Hanafuda' is one such example. The following is how to perform Hanafuda shuffling.
There is a deck of n cards. Starting from the p-th card from the top of the deck, c cards are pulled out and put on the top of the deck, a... | #include <iostream>
using namespace std;
int m[4][4];
int main(){
int i,j;
int n,r,p,c;
int f[51],buf[51];
while(cin >> n >> r,(n||r)){
for(i=1;i<=n;i++){
f[i]=-i+n+1;
}
while(r--){
cin >> p >> c;
for(i=1;i<p;i++) buf[i]=f[i]; //buf
for(i=1;i<=c;i++) f[i]=f[i+p-1];
for(i=1;i<p;i++) f[i+c]=buf... |
There is a rectangular area containing n × m cells. Two cells are marked with "2", and another two with "3". Some cells are occupied by obstacles. You should connect the two "2"s and also the two "3"s with non-intersecting lines. Lines can run only vertically or horizontally connecting centers of cells without obstacle... | #include<cstdio>
#include<cstring>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
const int dx[]={1,0,-1,0},dy[]={0,-1,0,1};
int h,w,B[9][9];
int x2,y2,x3,y3; // 2, 3 それぞれの出発点
int bfs(int x,int y,int tar){
int d[9][9];
memset(d,-1,sizeof d);
d[y][x]=0;
int Q[81],head=0,tail=0; Q[tail++]=y*w+x;
... |
Wall Painting
Here stands a wall made of a number of vertical panels. The panels are not painted yet.
You have a number of robots each of which can paint panels in a single color, either red, green, or blue. Each of the robots, when activated, paints panels between a certain position and another certain position in a... | #include <bits/stdc++.h>
#define N 400500
#define int long long
using namespace std;
int Ans, mx[3][3][N << 2], X, Y, m, n, num[N], cnt;
struct Data{int c, l, r;}d[N];
bool cmpl(Data a, Data b){return a.l < b.l;}
void pushup(int rt, int c){
for(int i = 0; i < 3; i++)
mx[c][i][rt] = max(mx[c][i][rt << 1], mx[c][i][rt... |
Floating-Point Numbers
In this problem, we consider floating-point number formats, data representation formats to approximate real numbers on computers.
Scientific notation is a method to express a number, frequently used for numbers too large or too small to be written tersely in usual decimal form. In scientific no... | #include<bits/stdc++.h>
#define ll long long
#define fornum(A,B,C) for(A=B;A<C;A++)
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
using namespace std;
/////////////////////////////////////////////////////
#define nxtr (1ll<<53)
ll n;
char bs[255];
ll mk[11][11],kt[11];
ll ans,a,b;
ll i, j, k... |
The left-hand rule, which is also known as the wall follower, is a well-known strategy that solves a two- dimensional maze. The strategy can be stated as follows: once you have entered the maze, walk around with keeping your left hand in contact with the wall until you reach the goal. In fact, it is proven that this st... | #include<cstdio>
#include<algorithm>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
const int dx[]={1,0,-1,0},dy[]={0,1,0,-1};
int main(){
for(int W,H,n;scanf("%d%d%d",&W,&H,&n),W;){
bool wallH[101][101]={},wallV[101][101]={};
rep(x,W) wallH[0][x]=wallH[H][x]=true;
rep(y,H) wallV[y][0]=wallV[y][W... |
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well.
Today's training is to perform a very large number of calculations to improve the calculation power and raise awareness. Exponentiation is an operation that easily produces large numbers.... | #include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <memory>
#include <cstring>
#include <cassert>
#include <numeric>
#include <sstream>
#include <complex>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cctype>
#include <un... |
There are twelve types of tiles in Fig. 1. You were asked to fill a table with R × C cells with these tiles. R is the number of rows and C is the number of columns.
How many arrangements in the table meet the following constraints?
* Each cell has one tile.
* the center of the upper left cell (1,1) and the center of... | #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
#define SIZE 12
enum DIR{
N,
E,
S,
W,
};
enum Type{
Plane,
N_S,
W_E,
N_E,
S_E,
W_S,
W_N,
... |
Helilin has the shape of a line segment with a length of 2 L on a two-dimensional plane.
There are several line-segment-shaped obstacles around the heliline.
Helilin loses strength when it comes in contact with obstacles.
Perfectionist Helilin decides to finish unscathed.
Helilin can do the following:
* Translation
... | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-8;
const double PI = acos(-1);
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<double> P;
typedef vector<P> VP;
struct L : array<P, 2>{
L(const P& a, const P& b){ at(0)=a; at(1)=b; }
L(){}
};
struct C{
... |
Problem statement
There is an unsigned $ 2 $ decimal integer $ X $ with $ N $ in digits including Leading-zeros. Output the largest non-negative integer that can be expressed in $ 2 $ base in $ N $ digits where the Hamming distance from $ X $ is $ D $.
The Hamming distance between integers expressed in $ 2 $ is the n... | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,s,e) for(int (i)=(s);(i)<(int)(e);(i)++)
#define REP(i,e) FOR(i,0,e)
#define RFOR(i,e,s) for(int (i)=(e)-1;(i)>=(int)(s);(i)--)
#define RREP(i,e) RFOR(i,e,0)
#define all(o) (o).begin(), (o).end()
#define psb(x) push_back(x)
#define mp(x,y) make_pair((x),(y)... |
problem
Given the squares of $ R * C $. Each square is either an empty square or a square with a hole. The given square meets the following conditions.
* The cells with holes are connected. (You can move a square with a hole in the cross direction to any square with a hole)
* Empty cells are connected.
You can gen... | #include <bits/stdc++.h>
typedef long long ll;
using namespace std;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
template< typename flow_t >
struct FordFulkerson{
struct edge {
int to;
flow_t cap;
int rev;
bool isrev;
};
vector<vector<edge>> graph;
vector<int> used;
const flow_t INF;
Fo... |
Problem
Given a convex polygon consisting of $ N $ vertices and the center coordinates of $ M $ circles. The radius of all circles is $ r $.
I want to find the minimum real number $ r $ that satisfies the following conditions.
Condition: Every point inside a convex polygon is contained in at least one circle.
Const... | #include <iostream>
#include <complex>
#include <cstdio>
#include <utility>
#include <vector>
using namespace std;
typedef complex<double> P;
typedef pair<P,P> L;
typedef pair<P,double> C;
typedef vector<P> Poly;
#define X real()
#define Y imag()
const double EPS = (1e-10);
const double INF = (1e15);
//2D version
name... |
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values ... | #include<iostream>
using namespace std;
void maxHeapify(int a[], int n, int i){
int l=i*2;
int r=l+1;
int larg=i;
if (l<=n && a[l]>a[larg]){
larg = l;
}
if (r<=n && a[r]>a[larg]){
larg = r;
}
if (larg!=i){
int t=a[larg];
a[larg]=a[i];
a[i]=t;
maxHeapify(a,n,larg);
}
}
void buildMaxHeap(int n, int... |
Stack is a container of elements that are inserted and deleted according to LIFO (Last In First Out).
For $n$ stack $S_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations.
* push($t$, $x$): Insert an integer $x$ to $S_t$.
* top($t$): Report the value which should be deleted next from $S_t$. If $... | #include <algorithm>
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
#define MOD 1000000007
#define REP(i, N) for (int i = 0; i < N; ++i)
#define REP1(i, N) for (int i = 1; i <= N; ++i)
#define RREP(i, N) for (int i = N - 1; i >= 0; --i)
#defi... |
Problem description.
An arithmetic progression(AP) is a sequence of numbers such that the difference of any two successive members of the sequence is a constant.
For example:- 1, 4, 7, 10,
13, 16, 19, ...
A geometric progression(GP) is a sequence of numbers where each term after the first is found by multiplying the p... | while 1:
a,b,c=map(int,raw_input().split())
if a==0 and b==0 and c==0:
break
else:
if b-a == c-b:
print "%s %d" %("AP",c+(b-a))
else:
print "%s %d" %("GP",c*(b/a)) |
As the cricket fever is on,you are given the task of calculating the run rate of a cricket match,but you are only provided with overs completed , current run rate and runs scored in next over.So you have to calculate the new run rate correctly upto two decimal places.
Input
The first line of the input contains an int... | test=int(raw_input())
while(test>0):
inp=map(int,raw_input().split())
overs,crr,nrr=inp[0],inp[1],inp[2]
new_rr=(float)((overs*crr)+nrr)/(overs+1)
#print overs,crr,nrr,new_rr
print "%.2f" % new_rr
test-=1 |
Problem description
In the climax of an upcoming Bollywood movie "BHAI HO!", Bhai is standing at the centre of a large battlefield. Bhai is sorrounded by the army of Bacchha Singh from all sides. Each soldier of Bacchha's army is at some distance from Bhai. They all are heading towards Bhai with swords in their hands. ... | T=int(raw_input());
for t in range(T) :
N=int(raw_input());
D=[int(i) for i in raw_input().split()];
D.sort();
survive=0;
killed=0;
for i in D :
survive=survive+1;
if survive > i :
break;
else :
killed=killed+1;
if killed % 6 ==0 :
survive=survive+1;
if killed == N :
print "Bhai Ho!";
else :
... |
As we all know, Chef is cooking string for long days, his new discovery on string is the longest common pattern length. The longest common pattern length between two strings is the maximum number of characters that both strings have in common. Characters are case sensitive, that is, lower case and upper case characters... | test=input()
from collections import Counter
while test:
test-=1
s1=raw_input()
s2=raw_input()
a=Counter(s1)
b=Counter(s2)
count=0
for i in a:
if i in b:
count+=min(a[i],b[i])
print count |
Pinocchio is a very interesting fictional character. Each time he lies, his nose is extended by 1 cm .
Pinocchio and Lampwick are best friends.
But Pinocchio's habit of lying has increased manyfold nowadays which has left Lampwick really upset. As a result, he has decided to maintain a diary recording the length of ... | # cook your code here
t = int(raw_input())
for i in xrange(t):
n = int(raw_input())
nums = map(int, raw_input().split())
print len(set(nums)) - 1 |
Chef likes strings a lot but he likes palindromic strings more. Today, Chef has two strings A and B, each consisting of lower case alphabets.
Chef is eager to know whether it is possible to choose some non empty strings s1 and s2 where s1 is a substring of A, s2 is a substring of B such that s1 + s2 is a palindromic ... | t = input()
for _ in xrange(t):
a = raw_input()
b = raw_input()
if set(a) & set(b):
print "Yes"
else:
print "No" |
Let's call an undirected graph G = (V, E) relatively prime if and only if for each edge (v, u) ∈ E GCD(v, u) = 1 (the greatest common divisor of v and u is 1). If there is no edge between some pair of vertices v and u then the value of GCD(v, u) doesn't matter. The vertices are numbered from 1 to |V|.
Construct a rela... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
const double inf = 1e20;
const double pi = acos(-1.0);
const int maxn = 1e6 + 7;
long long vis[2][maxn];
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
int main() {
long long n, m;
while (cin >> n >> m) {
if (... |
The king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.
All types of utensils in the kingdom are numbered from 1 to 100.... | import math
n, k = map(int, input().split())
a = [int(t) for t in input().split()]
d = {}
for i in a:
if d.get(i) is None:
d[i] = 0
d[i] += 1
print(math.ceil(max(d.values()) / k) * len(d.keys()) * k - n) |
The king of some country N decided to completely rebuild the road network. There are n people living in the country, they are enumerated from 1 to n. It is possible to construct a road between the house of any citizen a to the house of any other citizen b. There should not be more than one road between any pair of citi... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2000 + 10;
const int maxE = 2000000 + 10;
const int DEBUG = 0;
int n, m;
bitset<maxn> val[maxn];
char S[maxn];
struct anode {
int u, v, w;
anode() {}
anode(int _u, int _v, int _w) : u(_u), v(_v), w(_w) {}
} a[maxE];
int h[maxn], ecnt, sfa[maxn];
struc... |
Consider a following game between two players:
There is an array b_1, b_2, ..., b_k, consisting of positive integers. Initially a chip is placed into the first cell of the array, and b_1 is decreased by 1. Players move in turns. Each turn the current player has to do the following: if the index of the cell where the c... | #include <bits/stdc++.h>
using namespace std;
const int M = 200005;
int read() {
int x = 0, flag = 1;
char c;
while ((c = getchar()) < '0' || c > '9')
if (c == '-') flag = -1;
while (c >= '0' && c <= '9')
x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
return x * flag;
}
int n, m, k, all, la[4 * M]... |
A great legend used to be here, but some troll hacked Codeforces and erased it. Too bad for us, but in the troll society he earned a title of an ultimate-greatest-over troll. At least for them, it's something good. And maybe a formal statement will be even better for us?
You are given a tree T with n vertices numbered... | #include <bits/stdc++.h>
using namespace std;
vector<vector<int> > adj(100001);
int m, subtreeSize[100001];
long long dp[100001][202], s[202][202], c[202], fact[202];
void DFS(int i, int p = 0) {
dp[i][0] = 2;
subtreeSize[i] = 1;
for (int j : adj[i]) {
if (j == p) {
continue;
}
DFS(j, i);
fo... |
You are given an undirected tree of n vertices.
Some vertices are colored one of the k colors, some are uncolored. It is guaranteed that the tree contains at least one vertex of each of the k colors. There might be no uncolored vertices.
You choose a subset of exactly k - 1 edges and remove it from the tree. Tree fa... | #include <bits/stdc++.h>
#pragma GCC optimize("O2")
#pragma GCC optimize("unroll-loops")
using namespace std;
const long double eps = 1e-7;
const int inf = 1000000010;
const long long INF = 10000000000000010LL;
const int mod = 998244353;
const int MAXN = 300010, LOG = 18;
struct DSU {
int par[MAXN];
DSU() {
for... |
From "ftying rats" to urban saniwation workers - can synthetic biology tronsform how we think of pigeons?
The upiquitous pigeon has long been viewed as vermin - spleading disease, scavenging through trush, and defecating in populous urban spases. Yet they are product of selextive breeding for purposes as diverse as r... | #include <bits/stdc++.h>
using namespace std;
signed main() {
long long n, mini = 33;
cin >> n;
vector<long long> a(n);
for (long long i = 0; i < n; ++i) {
cin >> a[i];
mini = min(mini, a[i]);
}
cout << 2 + (a[2] ^ mini) << endl;
return 0;
}
|
The legend of the foundation of Vectorland talks of two integers x and y. Centuries ago, the array king placed two markers at points |x| and |y| on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at poin... | num = int(input())
data = [abs(int(i)) for i in input().split()]
data.sort()
def bins(a, b, n):
if a == b:
if data[a] <= n:
return a+1
else:
return a
else:
m = (a+b)//2
if data[m] <= n:
return bins(m+1,b,n)
else:
return bi... |
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.
The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa... | a, b, c, d = map(int, input().split())
a, b, c = sorted([a, b, c])
def solve1(a, b, c):
r1 = max(0, d-(b-a))
b += r1
r2 = max(0, d-(c-b))
return r1+r2
def solve2(a, b, c):
r1 = max(0, d-(c-b))
r2 = max(0, d-(b-a))
return r1+r2
def solve3(a, b, c):
r1 = max(0, d-(c-b))
b -= r1
r2... |
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number o... | #include <bits/stdc++.h>
using namespace std;
int vis[1000000];
int n[1000000];
int main() {
int cnt = 0;
int l;
cin >> l;
for (int i = 0; i < l; i++) {
cin >> n[i];
}
sort(n, n + l);
for (int i = 0; i < l; i++) {
int x = n[i] - 1;
if (x < 1) x = 1;
int y = n[i];
int z = n[i] + 1;
... |
Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string s and a number k (0 ≤ k < |s|).
At the beginning of the game, players are given a substring of s with left border l and right border r, both equal to k ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string str;
cin >> str;
long long n = (int)str.size(), min_ind = 0;
cout << "Mike"
<< "\n";
char mini = str[0];
for (int i = 1; i < n; i++) {
if (mini < str[i])
cout << "Ann"
... |
Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game — "Snakes and Ladders". Unfortunately, she already killed all the snake... | #include <bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
using namespace std;
long long a[10][10];
long double dp[10][10];
bool vis[10][10];
long double solve(long long i, long long j) {
if (i == 9 && j == 9) return 0;
if (vis[i][j]) return dp[i][j]... |
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n.
Help the jury distrib... | def func(a, total):
d = {}
temp = total
for no in a:
if total - 1 >= 0:
total -= 1
if no in d:
d[no] += 1
else:
d[no] = 1
else:
if no in d:
del d[no]
break
if len(d) < 3:
r... |
Fedya has a string S, initially empty, and an array W, also initially empty.
There are n queries to process, one at a time. Query i consists of a lowercase English letter c_i and a nonnegative integer w_i. First, c_i must be appended to S, and w_i must be appended to W. The answer to the query is the sum of suspicious... | #include <bits/stdc++.h>
template <typename T>
inline void read(T &x) {
x = 0;
char c = getchar();
while (!isdigit(c)) c = getchar();
while (isdigit(c)) x = x * 10 + (c ^ 48), c = getchar();
}
using namespace std;
const long long P = 1e18;
const int mask = (1 << 30) - 1;
const int inf = 2e9 + 100;
template <typ... |
Kuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules:
1. You can join the pyramid for free and get 0 coins.
2. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of co... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int inf_int = 1e9 + 100;
const long long inf_ll = 1e18;
const double pi = 3.1415926535898;
template <class T1, class T2>
std::ostream &operator<<(std::ostream &... |
Shakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare.
Each constant in Shakespeare is created from non-negati... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline T abs(T a) {
return ((a < 0) ? -a : a);
}
template <typename T>
inline T sqr(T a) {
return a * a;
}
const int INF = (int)1E9 + 7;
const long double EPS = 1E-9;
const long double PI = 3.1415926535897932384626433832795;
char s[2000000];
int ma... |
Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n... | import sys
def solve():
n = int(input())
if n == 1: return 0
res = 1000000
for other in range(n - 1, 0, -1):
pair = [n, other]
temp = 0
while (pair[0] > 1 or pair[1] > 1) and (pair[0] > 0 and pair[1] > 0):
pair.sort()
multiples = (pair[1] - 1) // pair[0]
... |
Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a:
* Remove any two elements from a and append their sum to... | t = int(input())
def swap(a,b):
if len(a)>len(b):
return b,a
else:
return a,b
def printcomb(a,b):
a, b = swap(a,b)
for i in range(0,len(a),2):
print(a[i]+1, a[i+1]+1)
for i in range(0,len(b),2):
print(b[i]+1, b[i+1]+1)
for i in range(t):
n = int(... |
Omkar has a pie tray with k (2 ≤ k ≤ 20) spots. Each spot in the tray contains either a chocolate pie or a pumpkin pie. However, Omkar does not like the way that the pies are currently arranged, and has another ideal arrangement that he would prefer instead.
To assist Omkar, n elves have gathered in a line to swap the... | #include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
std::istream& operator>>(std::istream& i, pair<T, U>& p) {
i >> p.first >> p.second;
return i;
}
template <typename T>
std::istream& operator>>(std::istream& i, vector<T>& t) {
for (auto& v : t) {
i >> v;
}
return i;
}
templat... |
You are given an array a consisting of n integers numbered from 1 to n.
Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i... | import java.io.*;
import java.util.*;
public class noob {
InputReader in;
final long mod=1000000007;
StringBuilder sb;
public static void main(String[] args) throws java.lang.Exception {
new noob().run();
}
void run() throws Exception {
in=new InputReader(System.in);
sb =... |
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;
const int L = 6;
const int N = 1e5 + 5;
int A[L + 1];
int licz[N];
int main() {
for (int i = 1; i <= L; i++) scanf("%d", &A[i]);
int n;
scanf("%d", &n);
vector<pair<int, int>> broom;
for (int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
for (int j = 1... |
There are n cards numbered 1, …, n. The card i has a red digit r_i and a blue digit b_i written on it.
We arrange all n cards in random order from left to right, with all permutations of 1, …, n having the same probability. We then read all red digits on the cards from left to right, and obtain an integer R. In the sa... | import java.util.*;
import java.io.*;
public class Solution {
static Scanner in =new Scanner(System.in);
static final Random random=new Random();
static int mod=1000_000_007;
static List<String> al = new ArrayList<>();
public static void main(String[] args) {
int tt=in.nextInt();//in.nextLine()... |
You have two positive integers a and b.
You can perform two kinds of operations:
* a = ⌊ a/b ⌋ (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 ≤ t ≤ 10... | def incre(a,b):
flag=0
if a//b==0:
return 1
if b==1:
b+=1
flag=1
tb=b
ans=float("inf")
if a//b==0:
return 1+flag
while b<=a:
ta=a
cnt=b-tb
while ta:
ta//=b
cnt+=1
b+=1
if ans<cnt:
return ans+flag
ans=min(ans,cnt)
return ans+flag
for i in range(int(input())):
a,b=map(int,input().st... |
The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.
However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to fig... | #include <bits/stdc++.h>
using namespace std;
//#define DEBUG 1
#define pii pair<int,int>
#define ff first
#define ss second
typedef long long int64;
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
string s;
cin>>s;
int T=... |
You are given a string s consisting of the characters 0, 1, and ?.
Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).
Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can... | for s in[*open(0)][1:]:
r=p=i=j=k=0
for x in s[:-1]:
i+=1;x=ord(x)^i&1
if x<50:k=(k,j)[p!=x];p=x;j=i
r+=i-k
print(r) |
Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information ab... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, d;
cin >> d >> n;
long long int ilosc = 0;
for (int i = 0; i < n - 1; i++) {
int p;
cin >> p;
ilosc += (d - p);
}
cin >> d;
cout << ilosc << "\n";
return 0;
}
|
The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
... |
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of se... | #include <bits/stdc++.h>
using namespace std;
vector<long long> graph[300000];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long n, m, j, l = 0, p = 0, w, i, flag = 0, k, t, d, q = 0, r = 0, v;
cin >> n >> m >> v;
t = 1 + ((n - 1) * 1LL * (n - 2)) / 2;
if (m > t || m < n - 1) {
... |
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:
1. Find two consecutive characters in the string, such that the first of them equals "y", and the s... | #include <bits/stdc++.h>
using namespace std;
char s[1000010];
int len, cntx, cnty;
int main() {
int i;
scanf("%s", s);
len = strlen(s);
for (i = 0, cntx = 0, cnty = 0; i < len; i++)
if (s[i] == 'x')
cntx++;
else
cnty++;
if (cntx > cnty) {
for (i = 0; i < cntx - cnty; i++) printf("x");... |
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T, size_t N>
int SIZE(const T (&t)[N]) {
return N;
}
template <typename T>
int SIZE(const T &t) {
return t.size();
}
string to_string(const string s, int x1 = 0, int x2 = 1e9) {
return '"' + ((x1 < s.size()) ? s.substr(x1, x2 -... |
Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.
Yaroslav is now wondering: what maximum sum of array elements c... | import java.util.*;
import java.io.*;
public class contest182C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[2 * n - 1];
int minus = 0;
int sum = 0;
for (int i = 0; i < arr.length;... |
After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with n rows and m columns (it contains n × m cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any bui... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class cf327d {
static FastIO in... |
You are given an array a1, a2, ..., an and m sets S1, S2, ..., Sm of indices of elements of this array. Let's denote Sk = {Sk, i} (1 ≤ i ≤ |Sk|). In other words, Sk, i is some element from set Sk.
In this problem you have to answer q queries of the two types:
1. Find the sum of elements with indices from set Sk: <i... | #include <bits/stdc++.h>
using namespace std;
const int B = 300;
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int n, m, q;
cin >> n >> m >> q;
vector<int> a(n);
for (auto &ai : a) cin >> ai;
vector<vector<int>> s(m);
vector<long long> init_sum(m);
for (int i = 0; i < m; i++) {
int k... |
Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his... | import java.util.Scanner;
public class CollectingBeatsIsFun {
public static void main(String[] args) {
int[] times = new int[16];
Scanner reader = new Scanner(System.in);
int speed = Integer.parseInt(reader.nextLine());
String lines = reader.nextLine();
lines += reader.nextLine();
lines += reader.nextLine... |
During the break, we decided to relax and play dominoes. Our box with Domino was empty, so we decided to borrow the teacher's dominoes.
The teacher responded instantly at our request. He put nm dominoes on the table as an n × 2m rectangle so that each of the n rows contained m dominoes arranged horizontally. Each half... | #include <bits/stdc++.h>
using namespace std;
int n, m, one, two, O;
char s[3];
int main(int argc, char **argv) {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) {
scanf("%s", s);
if (strcmp(s, "11") == 0)
++two;
else if (strcmp(s, "00") == 0)
++O... |
A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.
The participants are offered m problems on the contest. For each friend, Gena knows what pr... | #include <bits/stdc++.h>
using namespace std;
const long long PINF = numeric_limits<long long>::max();
const long long M = 1E9 + 7;
const double EPS = 1E-9;
struct frnd {
int solved = 0;
long long cost, monitors;
};
bool cmp(frnd a, frnd b) { return a.monitors < b.monitors; }
int main() {
ios::sync_with_stdio(fal... |
DZY loves Fast Fourier Transformation, and he enjoys using it.
Fast Fourier Transformation is an algorithm used to calculate convolution. Specifically, if a, b and c are sequences with length n, which are indexed from 0 to n - 1, and
<image>
We can calculate c fast using Fast Fourier Transformation.
DZY made a litt... | #include <bits/stdc++.h>
using namespace std;
long long n, d, x;
long long a[100002], b[100002], c[100002], q[100002], pos[100002];
long long sb = 0;
long long getNextX() {
x = (x * 37 + 10007) % 1000000007;
return x;
}
void initAB() {
for (long long i = 0; i < n; i = i + 1) {
a[i] = i + 1;
}
for (long lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.