input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed... | #!/usr/bin/python
import os
import sys
import itertools
def solve(f):
l, r, k = f.read_long_list()
x = 0
count = 0
ans = []
while k**x < l:
x += 1
while k**x <= r:
ans.append(str(k**x))
x += 1
if len(ans) == 0: ans.append('-1')
return ' '.join(ans)
class Read... |
Alice and Bob have a tree (undirected acyclic connected graph). There are ai chocolates waiting to be picked up in the i-th vertex of the tree. First, they choose two different vertices as their starting positions (Alice chooses first) and take all the chocolates contained in them.
Then, they alternate their moves, se... | #include <bits/stdc++.h>
static void dfs_down(const std::vector<std::vector<long> > &g,
const std::vector<long> &a, long s, long p,
std::vector<long long> &down) {
for (long i = 0; i != (long)g[s].size(); ++i) {
const long t = g[s][i];
if (t == p) continue;
dfs_do... |
As you know, the game of "Nim" is played with n piles of stones, where the i-th pile initially contains ai stones. Two players alternate the turns. During a turn a player picks any non-empty pile and removes any positive number of stones from it. The one who is not able to make a move loses the game.
Petya and Vasya a... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:512000000")
using namespace std;
void solve();
void precalc();
clock_t start;
int testNumber = 1;
bool todo = true;
int main() {
start = clock();
int t = 1;
cout.sync_with_stdio(0);
cin.tie(0);
precalc();
cout.precision(10);
cout << fixed;
int tes... |
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.
Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested ... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline T BMOD(T p, T e, T m) {
T ret = 1;
while (e) {
if (e & 1) ret = (ret * p) % m;
p = (p * p) % m;
e >>= 1;
}
return (T)ret;
}
template <class T>
inline T MODINV(T a, T m) {
return BMOD(a, m - 2, m);
}
template <class T>
inline T... |
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' ... | import java.io.IOException;
import java.util.*;
public class d {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
// BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
// String[] st=s.readLine().trim().split("\\s+");
... |
All-Berland programming contest comes to an end. In total, n teams participated in it. Like in ACM-ICPC, current results stopped refreshing one hour before the contest ends. So at the Award Ceremony, results are partially known. For each team the value ai is given — the number of points the i-th team has earned before ... | #include <bits/stdc++.h>
using namespace std;
int a[110];
int d[110];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d", &a[i], &d[i]);
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] >= a[j]) {
if (a[i] < a[j] + d[j... |
The only difference from the previous problem is the constraint on the number of requests. In this problem your program should guess the answer doing at most 7 requests.
This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get re... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 201 * 1001;
vector<string> v, v2, k;
int cnt[9][9];
bool vis[100];
inline pair<int, int> f(string a, string b) {
int x = 0, y = 0;
for (int i = 0; i < 4; i++) x += (a[i] == b[i]);
for (int i = 0; i < 4; i++) vis[a[i] - '0'] = 1;
for (int i = 0; i < ... |
Stepan has a set of n strings. Also, he has a favorite string s.
Stepan wants to do the following. He will take some strings of his set and write them down one after another. It is possible that he will take some strings more than once, and will not take some of them at all.
Your task is to determine the minimum num... | #include <bits/stdc++.h>
using namespace std;
const int N = 100;
int k, start = 0;
string s, a[N];
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
cin >> k;
for (int i = 0; i < k; ++i) {
cin >> a[i];
}
cin >> s;
int cnt = 0;
while (start < (int)s.size()) {
++cnt;
int new_start = star... |
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following... | import java.io.BufferedReader;
//import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
//import java.io.FileReader;
//import java.io.FileWriter;
//import java.lang.StringBuilder;
import java.util.StringTokenizer;
//import java.lang.Comparable;
import ja... |
Polycarp loves not only to take pictures, but also to show his photos to friends. On his personal website he has recently installed a widget that can display n photos with the scroll option. At each moment of time the widget displays exactly one photograph with the option showing the previous/next one. From the first p... | #include <bits/stdc++.h>
using namespace std;
const int inf = 1000000000;
const int maxm = 1000010;
const int maxn = 1005000;
using namespace std;
int n, m, a, b;
struct node {
int id, cnt;
} p[maxn];
int ans[maxn], pos[maxn];
bool operator<(node a, node b) {
if (a.cnt == b.cnt) return pos[a.id] > pos[b.id];
retu... |
You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path betwe... | #include <bits/stdc++.h>
using namespace std;
namespace IO {
inline int read() {
register char ch = getchar();
register int x = 0;
while (ch < '0' || ch > '9') {
ch = getchar();
}
while (ch >= '0' && ch <= '9') x = x * 10 + (ch ^ 48), ch = getchar();
return x;
}
} // namespace IO
using namespace IO;
in... |
Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.
People don't use cash as often as they... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:256000000")
using namespace std;
int t;
void solve();
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
t = 1;
for (int i = 0; i < t; ++i) {
solve();
}
}
void solve() {
int n;
cin >> n;
if (n == 1) {
cout << 1 << " " << 1 << endl;... |
You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e.
<image>
Input
The first line contains one integer n (1 ≤ n ≤ 22)... | n = int(input())
a = list(map(int, input().split()))
sorted_a = sorted(a)
shifted_sorted_a = [sorted_a[-1]] + sorted_a[:-1]
#print(sorted_a)
#print(shifted_sorted_a)
for i in range(len(a)):
pos_in_sorted = sorted_a.index(a[i])
print(shifted_sorted_a[pos_in_sorted], end=" ")
print()
|
Bash likes playing with arrays. He has an array a1, a2, ... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.
Suppose he guesses that the gcd of the ele... | import java.util.*;
import java.io.*;
import java.lang.Math.*;
public class MainA {
public static int mod = 20000;
public static long[] val;
public static long[] arr;
static int max = (int) 1e9 + 7;
//static int cnt=0;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
Pr... |
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppe... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Input... |
You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value x that occurs in the array 2 or more times. Take the first two occurrences of x in this array (the two leftmost occurrences). Remove the left of these two occur... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 1;
long long a[N];
int main() {
ios_base::sync_with_stdio(0);
int n;
cin >> n;
priority_queue<pair<long long, int>, vector<pair<long long, int>>,
greater<pair<long long, int>>>
q;
for (int i = 1; i <= n; ++i) {
int x;... |
Shrek and the Donkey (as you can guess, they also live in the far away kingdom) decided to play a card game called YAGame. The rules are very simple: initially Shrek holds m cards and the Donkey holds n cards (the players do not see each other's cards), and one more card lies on the table face down so that both players... | #include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
template <typename T>
void read(T &a) {
T x = 0, f = 1;
char ch = getchar();
while (ch < '0' || c... |
Aniruddha is given a milestone M to reach in terms of distance.
He is living in a different Galaxy where there are N days in a year.At the ith day he can walk atmost X distance.Assuming he walks optimally you need to output the minimum day number on which he will reach the milestone.
Input
The first input line contai... | for _ in range(int(raw_input())):
n = int(raw_input())
arr = map(int, list(raw_input().split()))
sum1 = sum(arr)
tar = int(raw_input())
tar = tar%sum1
if tar == 0:
for i in xrange(n-1,-1,-1):
if arr[i] != 0:
print i+1
break
else:
cur = 0
for i in range(n):
if arr[i] > 0:
cur += arr[i]
... |
Chandler and Joey
Joey and Chandler got bored of playing foosball, so they thought of trying something new.As Joey is very intelligent so he 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, eithe... | def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
t = input()
for _ in range(t):
n = input()
ar = map(int,raw_input().split())
m = max(ar)
su = sum(ar)
g = 0
for i in ar:
g = gcd(i,g)
c = (m / g) - n
l = m/g
su1 = (l*(2*g+g*(l-1)))/2
if c%2 == 0:
print "Chandler",(su1-su)
else:
print "Joey",(s... |
This problem is as simple as short. Just find how many numbers from A to B with sum of digits from X to Y are divisible by K.
Input
The first line contains 5 space-separated positive integers: A, B, X, Y, K
Output
Output one number - answer for the question.
Constraints
0 < A, B, K ≤ 10^13
0 < X, Y ≤ 1000
A ≤... | A, B, X, Y, K=map(int,raw_input().split())
def digsum(x):
r=0
while x>0:
r+=x%10
x/=10
return r
#return sum(map(int,str(x)))
def simpleCount(l,r):
if r<=l: return 0
cnt=0
incr=0
if l%K: incr=K-l%K
for x in xrange(l+incr,r,K):
s=digsum(x)
if X<=s<=Y:cnt+=1
return cnt
if K>1.e5 or B-A<=2000000:
pr... |
Given the time in numerals we may convert it into words, as shown below:
5:00→ five o' clock
5:01→ one minute past five
5:10→ ten minutes past five
5:30→ half past five
5:40→ twenty minutes to six
5:45→ quarter to six
5:47→ thirteen minutes to six
5:28→ twenty eight minutes past five
Write a program which prin... | h=int(raw_input())
m=int(raw_input())
H={0:"Twelve",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",10:"ten",11:"eleven",12:"twelve"}
M={1:"one minute",2:"two minutes",3:"three minutes",4:"four minutes",5:"five minutes",6:"six minutes",7:"seven minutes",8:"eight minutes",9:"nine minutes... |
Game is played on the field of the size 1 x N cells. The cells are numbered from 1 to N. In the i-th cell there are 2 positive integers - Ai and Bi.
Initially, the player stands at the fictive cell with the index 0 that is located right before all the N cells of the board. Then, he makes moves. Each move consists in m... | rr = raw_input; rrM = lambda: map(int,rr().split())
N,K = rrM()
A = [rrM() for i in xrange(N)]
from math import log10 as log
B = map(lambda x: map(log,x), A)
cache = {}
def dp(x,a,b):
if x == N+1: return (a,b)
if (x,a,b) not in cache:
ans = 99999999
mem = 0
if x+K >= N+1: cache[(x,a,b)] = (a,b)
else:
for... |
The Monk wants to buy some cities. To buy two cities, he needs to buy the road connecting those two cities. Now, you are given a list of roads, bought by the Monk. You need to tell how many cities did the Monk buy.
Input:
First line contains an integer T, denoting the number of test cases. The first line of each tes... | test=int(input())
visited=[False for i in range(10001)]
for t in range(test):
e=int(input())
visited=[False for i in range(10001)]
for i in range(e):
x,y=map(int,raw_input().split())
visited[x]=True
visited[y]=True
c=0
for i in range(10001):
if(visited[i]):
... |
Darshak (Dark) was learning about numerals in words and he came across representation of "6743294" as shown below
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-fam... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def isprime(a):
i=2
while i*i<=a:
if a%i==0:
return False
i+=1
return True
primes=[1]
cnt=0
i=2
while cnt<=99:
if isprime(i):
primes.append(i)
cnt+=1
i+=1
t=int(raw_inp... |
Roy frequently needs to use his old Nokia cell phone for texting whose keypad looks exactly as shown below.
You may be already familiar with the working of the keypad, however if you're not we shall see a few examples.
To type "b", we need to press "2" twice. To type "?" we need to press "1" thrice. To type "5" w... | lst = (('_', '0'),
('.', ',', '?', '!', '1'),
('a', 'b', 'c', '2'),
('d', 'e', 'f', '3'),
('g', 'h', 'i', '4'),
('j', 'k', 'l', '5'),
('m', 'n', 'o', '6'),
('p', 'q', 'r', 's', '7'),
('t', 'u', 'v', '8'),
('w', 'x', 'y', 'z', '9'),
)
def calculateSec(strng):
previousKey = 1
cu... |
Maggu has just joined play school. His teacher taught him A,a,B,b,C,c. He is much fascinated with these letters and now he is looking only for those strings which contains these letters only. But as i said he is a little guy he cant calculate the number of such sub-strings alone. So,he asked you (The String Calculator... | t=int(input())
while t:
t-=1
s=raw_input()
l=len(s)
c=0
h=0
for i in range(0,l):
if s[i]=='A' or s[i]=='a' or s[i]=='B' or s[i]=='b' or s[i]=='C' or s[i]=='c':
h=h+1
else:
if h!=0:
c=c+((h*(h+1)/2))
h=0
if h!=0:
c=c+((h*(h+1)/2))
print c |
Today is Vasya's birthday. On this special occasion, he has organized a party for all of his friends. These friends are enumerated by integers from 1 to N. Each of Vasya's friends has a Knowledge Level. In addition, each of them knows an arbitrary number of other people at the party. This friendship is bidirectional an... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
MOD = 10**9+7
N, M = map(int, raw_input().split(" "))
kl = map(int, raw_input().split(" "))
# Build graph (int)
nodes = {}
for n in range(N):
nodes[n+1] = set([])
for i in range(M):
... |
Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:
* 1 \leq x,y,z
* x^2 + y^2 + z^2 + xy + yz + zx = n
Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^4
Input
Input is given from Sta... | n=int(input())
import math
nn=int(math.sqrt(n))+1
a=[0]*(100*n)
for x in range(1,nn+1):
for y in range(1,nn+1):
for z in range(1,nn+1):
a[(x+y+z)**2-x*y-x*z-y*z]+=1
for i in range(1,n+1):
print(a[i]) |
Given are a positive integer N and a sequence of length 2^N consisting of 0s and 1s: A_0,A_1,\ldots,A_{2^N-1}. Determine whether there exists a closed curve C that satisfies the condition below for all 2^N sets S \subseteq \\{0,1,\ldots,N-1 \\}. If the answer is yes, construct one such closed curve.
* Let x = \sum_{i ... | #include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
#define NO return !printf("Impossible\n")
#define N 433
inline int read(){
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c=='-')f=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
... |
10^9 contestants, numbered 1 to 10^9, will compete in a competition. There will be two contests in this competition.
The organizer prepared N problems, numbered 1 to N, to use in these contests. When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclus... | #include<bits/stdc++.h>
using namespace std;
#define INF (int(1e9)+1)
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define mp make_pair
#define pb push_back
#define fst first
#define snd second
typedef long long ll;
typedef pair<int,int> pii;
const int maxn=100005;
int n,ans;
pii d... |
The squirrel Chokudai has N acorns. One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.
His plan is as follows:
1. Get out of the nest with N acorns in his hands.
2. Go to Exchange A and do some trades.
3. Go to Exchange B and do some trades.
4. Go to Exchange A and do some... | n = int(input())
A = [int(item) for item in input().split()]
B = [int(item) for item in input().split()]
dp = [0] * (n+1)
AB = []
for a, b in zip(A, B):
if b > a:
AB.append((a, b))
for i in range(n+1):
for a, b in AB:
if i - a >= 0:
y = dp[i-a] + b - a
if y > dp[i]:
... |
There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i. You are choosing K among these N pieces to eat. Your "satisfaction" here will be calculated as follows:
* The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".
* The base total de... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Collections;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/public class Main {
p... |
You have three tasks, all of which need to be completed.
First, you can complete any one task at cost 0.
Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.
Here, |x| denotes the absolute value of x.
Find the minimum total cost required to complete all the task.
Constrain... | #include<bits/stdc++.h>
using namespace std;
int main()
{
int a[3];cin>>a[0]>>a[1]>>a[2];
sort(a,a+3);
cout<<(a[1]-a[0])+(a[2]-a[1]);
return 0;
} |
You have A 500-yen coins, B 100-yen coins and C 50-yen coins (yen is the currency of Japan). In how many ways can we select some of these coins so that they are X yen in total?
Coins of the same kind cannot be distinguished. Two ways to select coins are distinguished when, for some kind of coin, the numbers of that co... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int tar = in.nextInt();
int cnt = 0;
for(int i = 0; i <= a; i++) {
for(in... |
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).
She will fly to the first town she visits, and fly back from the last town she visi... | #include<bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < n; i++)
#define pb push_back
using namespace std;
typedef long long ll;
const int INF=1e9;
int main(){
int n,m,R;
cin>>n>>m>>R;
vector<int> r(R);
rep(i,R){
cin>>r[i];
r[i]--;
}
vector<vector<int>> d(n,vector<int>(n,INF));
rep(i,n) d... |
We will call a string x good if it satisfies the following condition:
* Condition: x can be represented as a concatenation of two copies of another string y of length at least 1.
For example, `aa` and `bubobubo` are good; an empty string, `a`, `abcabcabc` and `abba` are not good.
Eagle and Owl created a puzzle on ... | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,a[205],L,R,now;
ll cnt;
inline void solve(){
int i=40; L=101,R=L-1;
for(;!((1ll<<i)&cnt);i--);
for(i--;i>=0;i--){
a[++R]=++now;
if((1ll<<i)&cnt) a[--L]=++now;
}
n=R-L+1;
for(int i=1;i<=n;i++) a[i]=a[i+L-1];
for(int i=n+1;i<=n*2;i++) ... |
You are given a permutation p of the set {1, 2, ..., N}. Please construct two sequences of positive integers a_1, a_2, ..., a_N and b_1, b_2, ..., b_N satisfying the following conditions:
* 1 \leq a_i, b_i \leq 10^9 for all i
* a_1 < a_2 < ... < a_N
* b_1 > b_2 > ... > b_N
* a_{p_1}+b_{p_1} < a_{p_2}+b_{p_2} < ... < a... | n = int(input())
x = list(map(int, input().split()))
a = [20001*i for i in range(1,n+1)]
b = [20001*(n+1-i) for i in range(1,n+1)]
for i in range(n):
b[x[i]-1] += i
for x in a:print(x, end=' ')
print()
for x in b:print(x, end=' ') |
Write a program that extracts n different numbers from the numbers 0 to 9 and outputs the number of combinations that add up to s. Each n number is from 0 to 9, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is
1 + 2 + 3 = 6
0 +... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String line = sc.nextLine();
Scanner scan = new Scanner(line);
int n = scan.nextInt();
int s = scan.nextInt();
if (n == 0)
break;
int[] a = new i... |
An autumn sports festival is held. There are four events: foot race, ball-carrying, obstacle race, and relay. There are n teams participating, and we would like to commend the team with the shortest total time in this 4th event as the "winner", the next smallest team as the "runner-up", and the second team from the bot... | #include<iostream>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<string>
#include<vector>
#include<list>
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<cstring>
#include<stack>
#include<functional>
using namespace std;
struct Team{
int n,t;
bool operator <(const Team &a)const{... |
The Aiz Archaeological Society has set out to investigate the ruins of the ancient nation Iwashiro, which sinks in the Hibara Sea. The ruins are somewhere in the Hibara Sea. Therefore, I decided to use an exploration radar to roughly mark the location of the ruins by radar exploration from the coastline and estimate ho... | #include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> X(N), R(N);
for (int i = 0; i < N; ++i) cin >> X[i] >> R[i];
double l = 0.0, r = *min_element(R.begin(), R.end());
for (int t = 0; t < 35; ++t) {
double m = (l + r) * 0.5;
... |
problem
At the JOI pasta shop, the recommended pasta for lunch and the set menu of freshly squeezed juice are popular. When ordering this set menu, choose one from each of the three pasta and two juices of the day. The price is the total price of pasta and juice minus 50 yen.
Given the price of pasta and juice for a ... | L=[input() for i in range(5)]
print min(L[:3])+min(L[3:])-50 |
Sha, Nero, Eri, and Ko, who entered the University of Aizu Elementary School (Aizu University and Small), decided to participate in a programming contest called IPPC in order to play an active role as a competition programmer. However, IPPCs are required to participate in the contest as a team of three people, and it i... | #include <stdio.h>
#include <cctype>
#include <limits.h>
#include <math.h>
#include <complex>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <iostream>
#define V... |
After having drifted about in a small boat for a couple of days, Akira Crusoe Maeda was finally cast ashore on a foggy island. Though he was exhausted and despaired, he was still fortunate to remember a legend of the foggy island, which he had heard from patriarchs in his childhood. This must be the island in the legen... | #include<iostream>
#include<string>
#include<queue>
#include<functional>
#include<utility>
#include<climits>
using namespace std;
#define LMAX LLONG_MAX
int n, p1, p2, m, x[1000], y[1000];
string a[1000];
int num[600], d[600], s[600];
bool no = false;
int sNum, divMax, r[600], dif[600], dev;
queue<int> leaf[600];
i... |
Example
Input
4 3
1000 1
2000 2
3000 3
Output
2 3 4 4 | #include<bits/stdc++.h>
using namespace std;
pair<int, int>l[100009], q[200009];
bool cmp(pair<int, int>&a, pair<int, int>&b) { return a.first < b.first; }
int main()
{
int n, m; scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) scanf("%d%d", &l[i].first, &l[i].second);
for (int i = 1; i <= n; i++)q[i].first = q[i... |
Problem
Given a string S of even length.
You can swap two adjacent characters in the string S as many times as you like.
How many operations do we need to do to make the string S a palindrome?
If it is not possible to make a palindrome, output -1.
Constraints
* 2 ≤ | S | ≤ 4 x 105
* All strings are composed of lower... | #include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<utility>
using namespace std;
typedef long long ll;
const ll mod = 1000000007;
const ll INF = mod * mod;
typedef pair<int, int> P;
t... |
Let J(n) be a three-dimensional body that
* is a union of unit cubes whose all vertices lie on integer coordinates,
* contains all points that are closer than the distance of √n to the origin, and
* is the smallest of all such bodies.
The figure below shows how J(1), J(2), and J(3) look.
<image>
Figure 1: Jaggie ... | #include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 2000 + 10;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
int n;
int len, o;
int flag;
int h[N][N];
int vis[N][N];
int valid(int x, in... |
There is a board of m × n squares. The squares of i rows and j columns are represented by (i, j) (0 ≤ i <m, 0 ≤ j <n).
When the rabbit is at (x, y), it can jump to ((x + a) mod m, (y + b) mod n) or ((x + c) mod m, (y + d) mod n) it can.
Now the rabbit is at (0, 0). If you can't go back to the square that once jumped,... | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const dou... |
C: Acrophobia
Yayoi Takasugi is a super-selling idol. There is one thing she is not good at. It's a high place ... She is extremely afraid of heights. This time, due to the producer's inadequacy, she decided to take on the following challenges on a variety show.
This location will be held in a room in a ninja mansion... | #include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <algorithm>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define mp make_pair
#define INF (1<<20)
struct ST {
int x, y, k;
ST() {}
ST(int x, int y, int k) : x(x), y(y), k(k) {}
};
bool operator<(const ST& l, const... |
C --Dowsing Machine
Story
People make noise with X and Y, but the coming era will be "D". "Paklin Monster D" is a very popular game in which "D people" search for treasure using the "D machine" developed by the secret society "R team".
In this game, the person D in the square with the grid map repeatedly moves to th... | #include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>
#include <cassert>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
#include <iomanip>
#include <f... |
Example
Input
4 2 1 1
1 2
3
4
3
1 2
2 4
3 4
Output
2 1 | #include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
#include<cassert>
#include<climits>
#include<deque>
#include<cstring>
#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
using namespace std;
typedef pair<int,int> ii; // ii(num,sp)
struct Data {
int cur;
i... |
B: 階層的計算機 (Hierarchical Calculator)
Problem
Ebi-chan has N formulae: y = a_i x for i =1, ..., N (inclusive). Now she considers a subsequence of indices with length k: s_1, s_2, ..., s_k. At first, let x_0 be 1 and evaluate s_1-th formulae with x = x_0. Next, let x_1 be the output of s_1 and evaluate s_2-th formulae w... | #include<iostream>
#include<string>
#include<iomanip>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
#define int long long
#define rep(i,n) for(int i = 0; i < (n); i++)
#define INF ((long long)1e18)
#define MOD ((int)1e9+7)
#define endl "\n"
#define yn(f) ((f)?"Yes":"No")
#define YN(f) ((f... |
Problem
Gaccho is trying to play the piano. The piano on the right side produces a higher note. Gaccho has a certain score and plays according to that score.
The score contains notes in chronological order that indicate which key should be played at a given time. Chords (sounds produced when multiple keys are pressed... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n,k=1;
cin >> n;
int a[n];
for(int i=0; i<n; i++) scanf("%d",&a[i]);
while(k<n&&a[k-1]==a[k]) k++;
if(n==k) {
cout << 1 << endl;
return 0;
}
int f=a[k-1]<a[k],x=2;
int ans=x;
for(int i=k+1; i<n; i++) {
while(i<n&&a[i-1]==a[i... |
Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:
for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key
Note... | import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int A[] = new int[n];
int i, j, key;
for(i=0; i<n; i++){
A[i] = sc.nextInt();
}
print(A);
for(i=1; i<n; i++){
key = A[i];
j = i - 1;
while(j>=0 && A[j]>k... |
Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.
Constraints
* 1 ≤ H ≤ 300
* 1 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero)... | import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (true){
int H = sc.nextInt();
int W = sc.nextInt();
if(H == 0 && W == 0){
break;
}
for(int i = 1;i <= H;i++){
for(int j = 1;j <= W;j++){
System.out.printf("#");
}
System.out.printf("\n");
}
S... |
Kattapa, as you all know was one of the greatest warriors of his time. The kingdom of Maahishmati had never lost a battle under him (as army-chief), and the reason for that was their really powerful army, also called as Mahasena.
Kattapa was known to be a very superstitious person. He believed that a soldier is "lucky"... | # Mahasena
# Problem code: AMR15A
# https://www.codechef.com/problems/AMR15A
t=int(raw_input())
a=[]
a=map(int,raw_input().split())
even=int(0)
odd=int(0)
for i in a:
if i%2==0:
even+=1
else:
odd+=1
if even>odd:
print("READY FOR BATTLE")
else:
print("NOT READY") |
The chef has a book stand. He and his friend bought some books (say n). The book stand has only 2 empty shelves. The chef made an observation that the paper quality, the weight of a single paper and the dimensions of all the books are the same. The chef made a restriction, to the books that can be kept on the shelves. ... | t=int(raw_input())
for ad in range(t):
n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
a=sorted(a)
u_list=a[:m]
d_list=a[m:]
print sum(d_list)-sum(u_list) |
Some chefs go for a tour lasting N days. They take packages of bread for food. Each package has K pieces of breads. On the i^th day, they eat Ai pieces of bread.
Unfortunately, chefs are very lazy people, and they always forget to close the package of breads, so each day the last piece of bread becomes exposed to mold ... | # your code goes here
import math
t=int(raw_input())
for i in range(t):
temp=raw_input().split()
days=int(temp[0])
capacity=int(temp[1])
required=raw_input().split()
required=map(int,required)
left=0
packages_consumed=0
for day in range(days):
flag=0
pack=0
... |
A DNA sequence can be represented by a string of letters T, A, C, and G representing four different amino acids. DNA sequences are often matched to infer structural or functional similarities between living beings. Given two DNA sequences X and Y, the sequence Y is said to be contained in X if Y can be obtained from X ... | for num in range(input()):
# n =input()
p,q = map(int,raw_input().split())
arr1 = list(raw_input())
arr2 = list(raw_input())
dp=[[0 for i in range(q+1)] for i in range(p+1)]
for i in range(1,p+1):
for j in range(1,q+1):
if arr1[i-1]==arr2[j-1]:
dp[i][j] += (1+ dp[i-1][j-1])
else:
dp[i][j] += max(... |
N one dimensional kingdoms are represented as intervals of the form [ai , bi] on the real line.
A kingdom of the form [L, R] can be destroyed completely by placing a bomb at a point x on the real line if L
≤ x ≤ R.
Your task is to determine minimum number of bombs required to destroy all the one dimensional kingdoms.... | t=input()
def lsort(l,n): #therefore total order=O(n+2001) :)
c=[0 for x in range(2001)] #O(2001)
for x in l:c[x[0]]+=1 #O(n)
for i in range(1,2001):c[i]+=c[i-1] #O(2001)
b=[None for x in range(n)] #O(n)
for i in range(n): #O(n)
b[c[l[i][0]]-1]=l[i]
c[l[i][0]]-=1
return b
for qq in ran... |
Cyael is a teacher at a very famous school in Byteland and she is known by her students for being very polite to them and also to encourage them to get good marks on their tests.
Then, if they get good marks she will reward them with candies :) However, she knows they are all very good at Mathematics, so she decided to... | T = int(raw_input())
while T:
N,K = map(int,raw_input().split())
if K == 0: print K,N
else: print N / K , N % K
T -= 1 |
You are given an integer sequence a_1, a_2, ..., a_n.
Find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of median of a_l, a_{l+1}, ..., a_r is exactly the given number m.
The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-dec... | //package round496;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = n... |
You are given an array a, consisting of n positive integers.
Let's call a concatenation of numbers x and y the number that is obtained by writing down numbers x and y one right after another without changing the order. For example, a concatenation of numbers 12 and 3456 is a number 123456.
Count the number of ordered... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("tune=corei7-avx")
using namespace std;
template <class A>
void addlog(A a) {
cerr << a << '\n';
}
template <class A, class... B>
void addlog(A a, B... b) {
cerr << a << ' ';
addlog(b...);
}
template <class T>
ostream &operator<<(ostream &out,... |
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super... | #include <bits/stdc++.h>
using namespace std;
int n, m, cnt;
vector<vector<int> > adj;
bool vis[100000 + 9];
void dfs(int node) {
vis[node] = 1;
for (int i = 0; i < (int)adj[node].size(); i++) {
int child = adj[node][i];
if (!vis[child]) dfs(child);
}
}
int main() {
int n, m;
cin >> n >> m;
adj.resi... |
You are given two positive integers a and b. There are two possible operations:
1. multiply one of the numbers by some prime p;
2. divide one of the numbers on its prime factor p.
What is the minimum number of operations required to obtain two integers having the same number of divisors? You are given severa... | #include <bits/stdc++.h>
using namespace std;
const int N = 1000000;
int T, tot, prod, mn[1000010];
bool solved[10000][11];
bitset<1000> b[10000][11];
vector<int> V, prime;
unordered_map<int, int> id;
int main() {
scanf("%d", &T);
for (int i = 2; i <= N; i++)
if (!mn[i]) {
if (prime.size() < 1000) prime.p... |
Vasya has got an array consisting of n integers, and two integers k and len in addition. All numbers in the array are either between 1 and k (inclusive), or equal to -1. The array is good if there is no segment of len consecutive equal numbers.
Vasya will replace each -1 with some number from 1 to k (inclusive) in suc... | #include <bits/stdc++.h>
using namespace std;
int n, k, len, ans, a[100005], f[100005][105], pre[105], sum[100005];
void add(int &x, int y) {
x = (x + y >= 998244353) ? x + y - 998244353 : x + y;
}
int main() {
scanf("%d%d%d", &n, &k, &len);
for (register int i = 1; i <= n; ++i) scanf("%d", &a[i]);
memset(pre, ... |
Once, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the num... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e6 + 5;
const int mod = 1e9 + 7;
inline int add(int a, int b) {
if ((a += b) >= mod) a -= mod;
return a;
}
inline int mul(int a, int b) { return 1ll * a * b % mod; }
inline int qm(int a, int b) {
int s = 1;
while (b) {
if (b & 1) s = mul(s, a);... |
Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through n ⋅ k cities. The cities are numerated from 1 to n ⋅ k, the distance between the neighboring cities is exactly 1 km.
Sergey does not like beetles, he loves burgers. Fortunately for him, there are n fast food restaurants on... | #include <bits/stdc++.h>
using namespace std;
const long long BINF = 9e18, LINF = 2e9, mod = 998244353, P = 179,
Q = 1791791791;
const long long MAXN = 1e5 + 7;
long long gcd(long long a, long long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
long long first = BINF, second = -BINF;
long long n... |
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, …, x_k in order.... | def main():
n, k = map(int, input().split())
x = [int(i) for i in input().split()]
ans = 3 * n - 2
a, b = set(), set()
for val in x:
if val - 1 in a:
b.add((val, val - 1))
if val + 1 in a:
b.add((val, val + 1))
a.add(val)
ans -= len(a) + len(b)
... |
There are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.
In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this ... | q = int(input())
for qq in range(q):
n, k = map(int, input().split())
*a, = map(int, input().split())
m = 0
M = 1e9
for x in a:
M = min(M, x + k)
m = max(m, x - k)
if M >= m:
print(M)
else:
print(-1)
|
Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by n sectors, and the outer area is equally divided by m sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wa... |
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def process(t, x, tn, tm): # tn = total / n
if t == 1:
return tn * x
else:
return tm * x
def main():
n, m, q = map(int, raw_input().split())
gc = gcd(n, m)
total = n * m / gc
tn = total / n
tm = total / m
gc = tn * tm / gcd(tn, tm)
# print '!... |
While roaming the mystic areas of Stonefalls, in order to drop legendary loot, an adventurer was given a quest as follows. He was given an array A = {a_1,a_2,...,a_N } of length N, and a number K.
Define array B as B(q, A) = { q-a_1, q-a_2, ..., q-a_N }. Define function F as F(B,K) being sum of products of all K-tupl... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline void read(T &x) {
int f = 0;
x = 0;
char ch = getchar();
for (; !isdigit(ch); ch = getchar()) f |= (ch == '-');
for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
if (f) x = -x;
}
const int mod = 998244353;
namespace Poly {
cons... |
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is conne... | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
//BigInteger A;
//A= BigInteger.valueOf(54);
//ArrayList<Integer> a=new ArrayList<>();
//TreeSet<Integer> ts=new TreeSet<>();
//HashMap<Integer,Integer> hm=new HashMap<>();
//PriorityQueue<Integer> pq=new PriorityQueue<>();
public final class... |
This is the harder version of the problem. In this version, 1 ≤ n, m ≤ 2⋅10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more e... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:60777216")
using namespace std;
int n, m;
int a[222222];
int k[222222];
int pos[222222];
int w[222222];
vector<int> z[222222];
int s[1 << 20];
void addOne(int pos) {
pos += (1 << 19);
while (pos) {
s[pos]++;
pos >>= 1;
}
}
int solve(int pos) {
int... |
There are n Christmas trees on an infinite number line. The i-th tree grows at the position x_i. All x_i are guaranteed to be distinct.
Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.
There are m people who want t... | #include <bits/stdc++.h>
using namespace std;
set<int> vis;
vector<int> ans;
map<int, int> d;
int main() {
int n, m;
cin >> n >> m;
queue<int> q;
int count = 0;
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
q.push(x);
vis.insert(x);
d[x] = 0;
}
long long int res = 0;
while (!... |
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases.
The next t lines... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--) {
long long n, k;
cin >> n >> k;
long long m = 1;
for (int i = 0; i < k - 1; i++) {
n -= m;
m += 2;
if (n < 0) break;
}
if (... |
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | t=int(input())
c=[]
for i in range(t):
a,b,n=input().split()
a,b,n=int(a),int(b),int(n)
count=0
while True:
if a<b:
a=a+b
else:
b=a+b
count+=1
if max(a,b)>n:
break
c.append(count)
for j in c:
print(j)
|
Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1.
Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}.
Let's say string t is good if its left cyclic shift is equal to its right cyclic shift.
You are given str... | t = int(input())
for i in range(t):
s=input()
ans=0
e=len(s)
qr=0
for j in range(10):
for q in range(10):
b=False
r=0
for i in range(len(s)):
if j!=q:
if (s[i]==str(j)) and (not b):
... |
You are given two strings s and t consisting of lowercase Latin letters. The length of t is 2 (i.e. this string consists only of two characters).
In one move, you can choose any character of s and replace it with any lowercase Latin letter. More formally, you choose some i and replace s_i (the character at the positio... | #include <bits/stdc++.h>
using namespace std;
long long int mod = 1000000007;
void SieveOfEratosthenes(int n) {
bool prime[n + 1];
memset(prime, true, sizeof(prime));
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p) prime[i] = false;
}
}
for (int p =... |
You have a string s consisting of n characters. Each character is either 0 or 1.
You can perform operations on the string. Each operation consists of two steps:
1. select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters ... | #include <bits/stdc++.h>
using namespace std;
char str[200001];
long long arr[200001];
int main() {
int q;
cin >> q;
while (q--) {
int n;
cin >> n;
scanf("%s", str);
int index = 0;
for (int i = 0; i < n; i++) {
int j = i + 1;
int c = 1;
while ((j < n) && (str[j] == str[i])) {... |
Gildong is now developing a puzzle game. The puzzle consists of n platforms numbered from 1 to n. The player plays the game as a character that can stand on each platform and the goal of the game is to move the character from the 1-st platform to the n-th platform.
The i-th platform is labeled with an integer a_i (0 ≤... | // Problem: F. Even Harder
// Contest: Codeforces - Codeforces Round #688 (Div. 2)
// URL: https://codeforces.com/contest/1453/problem/F
// Memory Limit: 512 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
using namespace std;
template <class X, class Y>
bool cmi... |
Nezzar designs a brand new game "Hidden Permutations" and shares it with his best friend, Nanako.
At the beginning of the game, Nanako and Nezzar both know integers n and m. The game goes in the following way:
* Firstly, Nezzar hides two permutations p_1,p_2,…,p_n and q_1,q_2,…,q_n of integers from 1 to n, and Nana... | #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<cassert>
#define ll long long
using namespace std;
int n,m;
int ql[500009],qr[500009];
int ansp[500009],ansq[500009];
int deg0[500009],del[500009];
int f[500009];
int st[500009],tot;
int vis... |
There is a binary string a of length n. In one operation, you can select any prefix of a with an equal number of 0 and 1 symbols. Then all symbols in the prefix are inverted: each 0 becomes 1 and each 1 becomes 0.
For example, suppose a=0111010000.
* In the first operation, we can select the prefix of length 8 sin... | # from sys import stdin,stdout
# input=stdin.readline
import math
# t=int(input())
from collections import Counter
import bisect
for _ in range(int(input())):
n = int(input())
a = list(map(int,input()))
b = list(map(int,input()))
# print(a,b)
count = [0 for i in range(n)]
if a[0]:
count[... |
Parsa has a humongous tree on n vertices.
On each vertex v he has written two integers l_v and r_v.
To make Parsa's tree look even more majestic, Nima wants to assign a number a_v (l_v ≤ a_v ≤ r_v) to each vertex v such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He de... | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<int, int> pii;
#define SZ(x) (int) x.size()
#define F first
#define S second
const int N = 2e5 + 10;
ll dp[2][N]; int A[2][N], n; vector<int> adj[N];
v... |
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
struct unit {
int c, s;
unit() {}
unit(int c, int s) : c(c), s(s) {}
};
int n, cnt = 1, to, len, ind[N];
map<int, int> u;
unit a[N];
vector<pair<long long, int> > t[N], tmp[N], b[N];
vector<int> res;
bool cmp_costs(pair<long long, int> a, pair<... |
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem.
You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the ... | #include <bits/stdc++.h>
const int N = 2008, u[4] = {1, 0, -1, 0}, v[4] = {0, 1, 0, -1};
int n, h, t, L, R, U, D, cnt[2], a[N][N], s[N][N], l[N], r[N], f[N * N],
g[N * N], b[N][N];
void bfs(int x, int y) {
h = 0, t = 1, L = R = x, U = D = y;
f[1] = x, g[1] = y, b[x][y] = 1;
while (h < t) {
x = f[++h], y =... |
You are playing a video game and you have just reached the bonus level, where the only possible goal is to score as many points as possible. Being a perfectionist, you've decided that you won't leave this level until you've gained the maximum possible number of points there.
The bonus level consists of n small platfor... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1 << 20;
long long l[MAXN][2] = {0LL};
long long r[MAXN][2] = {0LL};
int a[MAXN];
int n;
int main() {
scanf("%d", &n);
for (int i = 1; i < n; i++) {
scanf("%d", &a[i]);
if (a[i] > 1) l[i][0] = l[i - 1][0] + a[i] - (a[i] & 1);
l[i][1] = max(l... |
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.
During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of... | #include <bits/stdc++.h>
using namespace std;
int n;
long long a[100100];
long long s[100100], pre;
int m, q;
void precalc() {
pre = 0;
for (int i = 1; i <= n; i++) pre += a[i] * (n - i);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
sort(a + 1, a + n + 1);
s[0] = 0;
for... |
Recently the construction of Berland collider has been completed. Collider can be represented as a long narrow tunnel that contains n particles. We associate with collider 1-dimensional coordinate system, going from left to right. For each particle we know its coordinate and velocity at the moment of start of the colli... | #include <bits/stdc++.h>
#pragma GCC optimize("O2")
using namespace std;
inline long long int input() {
long long int n;
cin >> n;
return n;
}
long long int poww(long long int a, long long int b, long long int md) {
return (!b ? 1
: (b & 1 ? a * poww(a * a % md, b / 2, md) % md
... |
Lenny is playing a game on a 3 × 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be swit... | import java.util.Scanner;
public class LightOut {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int[][] arr = new int[5][5];
for(int i = 1; i <= 3; i++)
{
for(int j = 1; j <= 3; j++)
{
arr[i][j] = in.nextInt();
}
... |
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a... | import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author dy
*/
public class Main {
public static void main(String[] args) {
InputStream inputStre... |
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all:
* 'U': go up, (x, y) → (x, y+1);
* 'D': go down, (x, y) → (x, y-1);
* 'L': go left... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
static long my(long x, long mod) {
if (x == 0)
return 0;
if (x < 0 && mod < 0)
return (x % mod);
if ((x > 0 && mod < 0) || (x < 0 && ... |
The city Valera lives in is going to hold elections to the city Parliament.
The city has n districts and n - 1 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each r... | 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... |
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.
Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined,... | #include <bits/stdc++.h>
using namespace std;
int n, puesto;
tuple<long long int, long long int> v[200010];
int main() {
ios_base::sync_with_stdio(false);
cin >> n >> puesto;
long long int a, b;
long long int maximo = -1;
for (int i = 0; i < n; i++) {
cin >> a >> b;
maximo = max(maximo, a);
v[i] =... |
'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2.
The finals will have n questions, m of them are auction quest... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
t = 1;
while (t--) {
int n;
cin >> n;
int m;
cin >> m;
int a[n], b[m], p[m];
long long sum = 0, sum1 = 0;
for (int i = 0; i < n; i++) cin >> a[i], sum = sum + a[i];
for (int i = 0; i < m; i++)
cin >> b[i], p[i]... |
Today s kilometer long auto race takes place in Berland. The track is represented by a straight line as long as s kilometers. There are n cars taking part in the race, all of them start simultaneously at the very beginning of the track. For every car is known its behavior — the system of segments on each of which the s... | #include <bits/stdc++.h>
using namespace std;
int n, s, k[101], ct;
pair<int, int> dat[101][101];
int main() {
scanf("%d%d", &n, &s);
for (int i = 0; i < n; i++) {
scanf("%d", &k[i]);
for (int j = 0; j < k[i]; j++) {
scanf("%d%d", &dat[i][j].first, &dat[i][j].second);
}
for (int j = 0; j < i; ... |
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on i... | n,k=map(int,input().split())
s=input()
di=dict()
for i in s:di[i]=di.get(i,0)+1
ans=0
se=list(set(s))
se.sort(key=lambda x:di[x],reverse=1)
for i in se:
ans+=min(k,di[i])*min(di[i],k)
k-=min(di[i],k)
if not k:break
print(ans)
|
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | if __name__=="__main__":
n=int(input())
if(n&1):
print(-1*(n+1)//2)
else:
print(n//2) |
Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:
You are given a tree T with n vertices, specified by its adjacency matrix a[1... n, 1... n]. What is the output of the following pseudocode?
used[1 ... n] = {0, ..., 0};
proc... | import java.util.Arrays;
import java.util.Scanner;
public class CF289F {
static int[] a;
static int[][] dp;
static int MOD = 1_000_000_007;
static int f(int l, int r) {
if (l >= r)
return 1;
if (dp[l][r] != -1)
return dp[l][r];
long answer = 0;
f... |
The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals v1 meters per second, and in the end it is v2 meters per second. We know that this section of the route took exactly t seconds to pass.
Assuming that at each of the seconds the speed is constant, and... | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-7;
const int MOD = (int)1e9 + 7;
const int MAXN = (int)1e5 + 10;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int v1, v2, t, d, ans = 0;
cin >> v1 >> v2 >> t >> d;
ans = v1 + v2;
for (int i = 2; i < t; ++i) {
if (v2 < v1) swap... |
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2... |
import java.util.*;
import java.io.*;
public class B
{
public static void main(String[] args) throws Exception
{
PrintWriter out = new PrintWriter(System.out);
new B(new FastScanner(System.in), out);
out.close();
}
String getRep(String s)
{
if (s.length() % 2 == 1)
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.