input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
problem
In the area where Kazakhstan is now located, there used to be a trade route called the "Silk Road".
There are N + 1 cities on the Silk Road, numbered from west as city 0, city 1, ..., city N. The distance between city i -1 and city i (1 ≤ i ≤ N) is Di.
JOI, a trader, decided to start from city 0, go through ... | import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i... |
Toshizo is the manager of a convenience store chain in Hakodate. Every day, each of the stores in his chain sends him a table of the products that they have sold. Toshizo's job is to compile these figures and calculate how much the stores have sold in total.
The type of a table that is sent to Toshizo by the stores lo... | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static final int P_MAX = 100;
public static final int S_MAX = 10;
public static void main(String[] args) {
Scanner sc = new Scanner(... |
In the good old Hachioji railroad station located in the west of Tokyo, there are several parking lines, and lots of freight trains come and go every day.
All freight trains travel at night, so these trains containing various types of cars are settled in your parking lines early in the morning. Then, during the daytim... |
import java.util.*;
public class Main {
//1330 start
//1430 cording end
//1510 sample matched RE
//1510 stop
//0150 restart
//0206 TLE
//0228 MLE
//0230 MLE modified continue to break
//0233 MLE modified presentation error
//0251 WA modi goal process
class C{
int step;
StringBuilder [] list;
public ... |
Shortest Common Non-Subsequence
A subsequence of a sequence $P$ is a sequence that can be derived from the original sequence $P$ by picking up some or no elements of $P$ preserving the order. For example, "ICPC" is a subsequence of "MICROPROCESSOR".
A common subsequence of two sequences is a subsequence of both seque... | #include <bits/stdc++.h>
#define REP(i,n) for (int i = 0; (i) < (n); ++(i))
#define REP3(i,m,n) for (int i = (m); (i) < (n); ++(i))
#define REP_R(i,n) for (int i = (int)(n) - 1; (i) >= 0; --(i))
#define ALL(x) begin(x), end(x)
using namespace std;
using ll = long long;
template <class T> inline void chmin(T & a, T cons... |
A Garden with Ponds
Mr. Gardiner is a modern garden designer who is excellent at utilizing the terrain features. His design method is unique: he first decides the location of ponds and design them with the terrain features intact.
According to his unique design procedure, all of his ponds are rectangular with simple ... | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> mp;
ll inf = 1e9;
int main(){
while(1){
ll h,w;
cin>>h>>w;
if( h==0 && w==0 ) break;
vector<vector<ll> > e(h+2,vector<ll>(w+2,0) );
for(ll i=1;i<=h;i++)for(ll j=1;j<=w;j++) cin>>e[i][j];
ll res = 0;
for(ll l=1;l<=h;l++... |
Irving & Cohen Petroleum Corporation has decided to develop a new oil field in an area. A preliminary survey has been done and they created a detailed grid map of the area which indicates the reserve of oil.
They are now planning to construct mining plants on several grid blocks according this map, but they decided no... | #include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
using namespace std;
#define FOR(i,k,n) for(int i=(k); i<(int)(n);... |
Problem E: Anipero
The long and short summer, which had been hot, was about to end. One day in late August, a person who likes 2D and his senior slip participated in an event called Anipero Summer Live, commonly known as Anipero. Anipero is the largest anime song live event in Japan where various anime song artists ga... | #include<stdio.h>
#include<algorithm>
using namespace std;
char in[100];
int dp[110][1010];
int val[1010];
int sp[110];
int sq[110];
int np[110];
int nq[110];
int main(){
int a,b,c,d;
while(scanf("%d%d%d%d",&a,&b,&c,&d),a){
for(int i=0;i<b;i++){
scanf("%s%d%d",in,sp+i,sq+i);
}
for(int i=0;i<c;i++)scanf("%s%d... |
A convex polygon consisting of N vertices is given. The coordinates of each vertex are represented counterclockwise by (X1, Y1), (X2, Y2), ……, (XN, YN). No matter what straight line passes through the point P, find the coordinates of the point P so that the areas of the two convex polygons obtained after cutting are eq... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> PI;
const double EPS=1e-8;
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define F first
#define S second
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define SZ(a) (int)((a).size())
#define ALL(a) (a).begin(),(a).end... |
Problem Statement
Let's consider operations on monochrome images that consist of hexagonal pixels, each of which is colored in either black or white. Because of the shape of pixels, each of them has exactly six neighbors (e.g. pixels that share an edge with it.)
"Filtering" is an operation to determine the color of a... | //include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <... |
Problem statement
There is a town with a size of H in the north-south direction and W in the east-west direction. In the town, square plots with a side length of 1 are maintained without gaps, and one house is built in each plot.
A typhoon broke out over a section of the town, causing damage and then changing to an e... | #include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
using namespace std;
int D[523][523];
int g[523][523];
int cnt,fx,fy;
void find(int y,int x){
if(D[y][x]){
fy=y+1;
fx=x+1;
cnt++;
int p=D[y][x];
g[fy][fx]=p;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
D[y+i][x... |
C: Namo .. Cut
problem
-Defeat the mysterious giant jellyfish, codenamed "Nari"-
"Nari" has a very strong vitality, so if you don't keep cutting quickly, it will be revived in a blink of an eye. We are making trial and error every day to find out how to cut "Nari" efficiently. In the process, you needed the help of ... | # サイクル検出
import sys
sys.setrecursionlimit(10**7)
def dfs(G, v, p):
global pos
seen[v] = True
hist.append(v)
for nv in G[v]:
# 逆流を禁止する
if nv == p:
continue
# 完全終了した頂点はスルー
if finished[nv]:
continue
# サイクルを検出
if seen[nv] and not fi... |
Problem
The popular video posting site "ZouTube" is now in the midst of an unprecedented "virtual ZouTuber" boom. Among them, the one that has been attracting particular attention recently is the junior virtual ZouTuber "Aizumarim (commonly known as Azurim)".
As a big fan of Azlim, you're going to send her a "special... | #include <cassert>
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <ccomplex>
#in... |
You are given $n$ integers $w_i (i = 0, 1, ..., n-1)$ to be sorted in ascending order. You can swap two integers $w_i$ and $w_j$. Each swap operation has a cost, which is the sum of the two integers $w_i + w_j$. You can perform the operations any number of times.
Write a program which reports the minimal total cost to... | #include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<list>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
int main(void)
{
int n, W, MIN = 100001, sum = 0, p = 0, pp, cost = 0, k = 0, min = 100001;
cin >> n;
vect... |
A state with $n$ flags of ON or OFF can be represented by a sequence of bits where $0, 1, ..., n-1$ -th flag corresponds to 1 (ON) or 0 (OFF). The state can be managed by the corresponding decimal integer, because the sequence of bits is a binary representation where each bit is 0 or 1.
Given a sequence of bits with 6... | #include <iostream>
#include <bitset>
int main()
{
std::bitset<64> bs(0);
int q; std::cin >> q;
for (int i=0; i<q; i++) {
int op, k;
std::cin >> op;
switch (op) {
case 0:
std::cin >> k;
std::cout << bs.test(k) << std::endl;
break;
case 1:
std::cin >> k;
bs.set(k);
break;
case 2:
... |
Arithmetic and geometric Progressions are 2 of the well known progressions in maths. Arithmetic progression (AP) is a set in which the difference between 2 numbers in constant. for eg, 1,3,5,7,9....In this series the difference between 2 numbers is 2.The task here is very simple indeed. You will be given the 3rd term ,... | for _ in range(input()):
aa,nn,s=map(int,raw_input().split())
sum=aa+nn
n=(2*s)/sum
d=(nn-aa)/(n-5)
a=aa-2*d
print n
for i in range(1,n+1):
print a+(i-1)*d,
print |
Tomya is a girl. She loves Chef Ciel very much.
Tomya like a positive integer p, and now she wants to get a receipt of Ciel's restaurant whose total price is exactly p.
The current menus of Ciel's restaurant are shown the following table.
Name of Menuprice
eel flavored water1
deep-fried eel bones2
clear soup made w... | menu = [1,2,4,8,16,32,64,128,256,512,1024,2048]
menu.reverse()
def find_menus(price, count):
if price==0:
return count
for i in menu:
if price/i>0:
return find_menus(price%i, count+price/i)
for i in range(input()):
print find_menus(input(), 0) |
Pratyush, a six year old kid has just learnt how to write 1 through 1000 in decimal number system(DNS). Being a very curious kid, he made some modifications in DNS and removed the digits 0 through 3 and 7 through 9. So the only digits remaining to be used are 4, 5 and 6. He started enumerating numbers with these digits... | t=int(input())
while(t):
t=t-1
n=int(input())
k=1
ans=0
while(n>0):
if(n%3==0):
ans=6*k+ans
n=n/3-1
elif(n%3==1):
ans=4*k+ans
n=(n-1)/3
elif(n%3==2):
ans=5*k+ans
n=(n-2)/3
k=k*10
print ans |
Problem description.
Toretto has no friends. He has got family, and now they need him. His bitter enemy, Ian Shaw, has captured Toretto's beloved Letty and evil cooks in his head. All Toretto has is the algorithmic message Shaw left before leaving-
Letty(n):
L = an empty list
while n > 0:
find the larg... | import sys
f = sys.stdin
mod = 1000000007
DP = [0]*(2)
DP[0] = [0]*(111)
DP[1] = [0]*(111)
bits = [0]*(111)
X = [0]*(2)
Y = [0]*(2)
X[0] = [0]*(111)
X[1] = [0]*(111)
Y[0] = [0]*(111)
Y[1] = [0]*(111)
def process():
DP[0][100] = 1
DP[1][100] = 1
X[0][100] = 1
Y[0][100] = 0
Y[1][100] = 1
X[1][100... |
Recall the definition of the Fibonacci numbers:
f1 := 1
f2 := 2
fn := fn-1 + fn-2 (n ≥ 3)
Given two numbers a and b, calculate how many Fibonacci numbers are in the range [a,b].
Input
The input contains several test cases. Each test case consists of two non-negative integer numbers a and b. Input is... | import bisect
def find_lt(a,x):
#find rightmost value less than or equal to x
i=bisect.bisect_right(a,x)
if i:
return i-1
else:
return -1
def find_ge(a,x):
#find leftmost item greator than or equal to x
i=bisect.bisect_left(a,x)
if i!=len(a):
return i
else:
... |
For positive integer x let define function F(x) = 1 * (1! + x) + 2 * (2! + x) + .. + x * (x! + x).
"k!" means factorial: k! = 1 * 2 * .. * k
Chef wants to calculate F(p1) + F(p2) + ... + F(pn).
As answer could be large, help him, calculate value modulo m.
Input
First line contains two integers n and m.
Next line c... | arr=[]
def fact(x,m):
f=1
i=1;
while i <=x+1:
f=(f*i)%m
arr.append(f)
i+=1
def f(x):
if x>=m:
return (x*x*(x+1)/2-1)%m
else:
return arr[x]+x*x*(x+1)/2-1
n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
x=max(a)
if x<=1000000:
fact(x,m)
el... |
You are given a rectangular parallelepiped with sides of positive integer lengths A, B and C.
Find the number of different groups of three integers (a, b, c) such that 1≤ a≤ b≤ c and parallelepiped A× B× C can be paved with parallelepipeds a× b× c. Note, that all small parallelepipeds have to be rotated in the same d... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
long long fac[MAXN], ft[8];
long long C[1000][1000];
int num[8];
void Init() {
for (int i = 1; i < MAXN; i++)
for (int j = i; j < MAXN; j += i) fac[j]++;
memset(C, 0, sizeof(C));
for (int i = 0; i < 1000; i++) {
C[i][0] = 1;
for ... |
When Masha came to math classes today, she saw two integer sequences of length n - 1 on the blackboard. Let's denote the elements of the first sequence as a_i (0 ≤ a_i ≤ 3), and the elements of the second sequence as b_i (0 ≤ b_i ≤ 3).
Masha became interested if or not there is an integer sequence of length n, which e... | from sys import stdin
rints = lambda: [int(x) for x in stdin.readline().split()]
n, a, b = int(input()), rints(), rints()
mem = [[-1 for _ in range(4)] for _ in range(n)]
for i in range(n - 1):
for j in range(4):
if mem[i][j] != -1 or not i:
for k in range(4):
and1, or1 = k & j... |
Initially Ildar has an empty array. He performs n steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array.
The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset [0... | import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
public static int serch(int[] a,int n){
int k = 0;
for(int i=0;i<n;i++){
if(a[i]>k) return i+1;
if(a[i]==k) k++;
}
return -1;
}... |
You are given an integer number n. The following algorithm is applied to it:
1. if n = 0, then end algorithm;
2. find the smallest prime divisor d of n;
3. subtract d from n and go to step 1.
Determine the number of subtrations the algorithm will make.
Input
The only line contains a single integer n (2 ≤... | from collections import deque as de
import math
class My_stack():
def __init__(self):
self.data = []
def my_push(self, x):
return (self.data.append(x))
def my_pop(self):
return (self.data.pop())
def my_peak(self):
return (self.data[-1])
def my_contains(self, x):
... |
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero:
<image>
Petr called his car dealer, who in... | #include <bits/stdc++.h>
using namespace std;
const int N = 20;
int a[N];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
for (int i = 0; i < 1 << n; ++i) {
int res = 0;
for (int j = 0; j < n; ++j) {
if ((i >> j) & 1)
res = (res + a[j]) % 360;
els... |
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.
For example, the following matrices are palindromic:
<image>
The following matrices are not palindromic because they change... | #include <bits/stdc++.h>
using namespace std;
int a[1001], mat[21][21];
queue<int> n2;
queue<int> n4;
int n1;
int main() {
int n, t;
cin >> n;
for (int i = 1; i <= n * n; i++) {
cin >> t;
a[t]++;
}
int odd = 0, oddi;
int r = 1, c = 1;
if (n % 2 == 0) {
for (int i = 1; i <= 1000; i++) {
w... |
You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph.
You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the numb... | #include <bits/stdc++.h>
using namespace std;
bool answer = true;
void dfs(vector<int>& visited, vector<vector<int>>& g, int vertex, int oddity) {
visited[vertex] = oddity;
for (int i = 0; i < g[vertex].size(); ++i) {
if (visited[g[vertex][i]] == 0) {
dfs(visited, g, g[vertex][i], oddity == 1 ? -1 : 1);
... |
You are given two arrays a and b, both of length n.
Let's define a function f(l, r) = ∑_{l ≤ i ≤ r} a_i ⋅ b_i.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array b to minimize the value of ∑_{1 ≤ l ≤ r ≤ n} f(l, r). Since the answer can be very large, you have to print it modulo... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 7;
const int mod = 998244353;
long long a[maxn];
long long b[maxn];
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
a[i] = a[i] * (n - i + 1) * i;
}
for (int i = 1; i <= n; i++) scanf("%d", &... |
The Third Doctor Who once correctly said that travel between parallel universes is "like travelling sideways". However, he incorrectly thought that there were infinite parallel universes, whereas in fact, as we now all know, there will never be more than 250.
Heidi recently got her hands on a multiverse observation to... | #include <bits/stdc++.h>
int main() {
int n, k, m, t, i;
scanf("%d%d%d%d", &n, &k, &m, &t);
int a, b;
for (i = 0; i < t; i++) {
scanf("%d %d", &a, &b);
if (a == 0) {
if (b < k) {
n -= b;
k -= b;
} else {
n = b;
}
}
if (a == 1) {
if (b <= k) {
... |
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation).
Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after... | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
private static PrintWriter out;
private static <T> void mprintln(T... ar) {
for (T i : ar) {
out.print(i + " ");
}
out.println();
}
public static void main(String[] args) thr... |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how ... | from math import factorial
import sys
def lucky(x):
return str(x).count('4')+str(x).count('7')==len(str(x))
def fun(x):
xs, result = str(x), 0
for i in range(len(xs)):
rest = 1<<(len(xs)-i-1)
if int(xs[i]) == 4:
continue
elif int(xs[i]) == 7:
result += rest
continue
elif int(xs[i]) < 4:
return ... |
Demonstrative competitions will be held in the run-up to the 20NN Berlatov Olympic Games. Today is the day for the running competition!
Berlatov team consists of 2n runners which are placed on two running tracks; n runners are placed on each track. The runners are numbered from 1 to n on each track. The runner with nu... | #include <bits/stdc++.h>
using namespace std;
long long n, a[1000005], add[1000005];
long long k;
bool used[1000005];
int main() {
scanf("%lld%lld", &n, &k);
long long sum = n * (n + 1) / 2;
if (sum > k) {
cout << -1 << endl;
return 0;
}
for (int i = 1; i <= n; i++) a[i] = i;
for (int i = 1; i <= n ... |
This is the hard version of this problem. The only difference is the limit of n - the length of the input string. In this version, 1 ≤ n ≤ 10^6.
Let's define a correct bracket sequence and its depth as follow:
* An empty string is a correct bracket sequence with depth 0.
* If "s" is a correct bracket sequence wi... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10, mod = 998244353;
const long long inf = 1e18;
int fac[maxn], ifac[maxn], sm1[maxn], sm2[maxn];
int Pow(int a, int b) {
int ans = 1;
for (; b; b >>= 1, a = 1ll * a * a % mod)
if (b & 1) ans = 1ll * ans * a % mod;
return ans;
}
int C(int n,... |
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland.... | def ip():
n=int(input())
a=list(map(int,input().split()))
rem=set([i for i in range(1,n+1)])-set(a)
if n==1:
return 0
o=e=0
for i in rem:
if i%2==0:
e+=1
else:
o+=1
ct=0
i=0
while i<len(a) and a[i]==0:
i+=1
if i==len(a):
... |
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!
... | s = input()
to_ans = [False for _ in range(len(s))]
def solve(s, left, right): #right inclusive
if left >= right:
return
while left <= right and s[left] == ")":
left += 1
while right >= left and s[right] == "(":
right -= 1
if left >= right:
return
else:
to_ans[left] = True
to_ans[right] = True
solve... |
Dreamoon likes strings. Today he created a game about strings:
String s_1, s_2, …, s_n is beautiful if and only if for each 1 ≤ i < n, s_i ≠ s_{i+1}.
Initially, Dreamoon has a string a. In each step Dreamoon can choose a beautiful substring of a and remove it. Then he should concatenate the remaining characters (in t... | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 2e6 + 100;
const long long inf = 0x3f3f3f3f;
const long long iinf = 1 << 30;
const long long linf = 2e18;
const long long mod = 998244353;
const double eps = 1e-7;
template <class T = long long>
T chmin(T &a, T b) {
return a = min(a, b);
}
template ... |
Slime and his n friends are at a party. Slime has designed a game for his friends to play.
At the beginning of the game, the i-th player has a_i biscuits. At each second, Slime will choose a biscuit randomly uniformly among all a_1 + a_2 + … + a_n biscuits, and the owner of this biscuit will give it to a random unifor... | #include <bits/stdc++.h>
using namespace std;
namespace FGF {
int n, m, ans;
const int N = 3e5 + 5, mo = 998244353;
int a[N], f[N], inv[N];
void work() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]), m += a[i];
inv[1] = 1;
for (int i = 2; i <= m; i++) inv[i] = 1ll * inv[mo % i] * (mo - mo / ... |
Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it... | #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int ans = 0;
int t = 1;
while (a || b) {
int x = a % 3;
int y = b % 3;
int z = (y - x + 3) % 3;
ans += z * t;
t *= 3;
a /= 3, b /= 3;
}
cout << ans << endl;
}
|
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope... | t=int(input())
for i in range(t):
n,k=map(int,input().split())
ar=list(map(int,input().split()))
m=max(ar)
new=[]
for i in range(n):
new.append(m-ar[i])
if k%2==0:
mx=max(new)
for j in range(n):
new[j]=mx-new[j]
print(*new)
|
You are given an undirected graph consisting of n vertices and m edges. Initially there is a single integer written on every vertex: the vertex i has p_i written on it. All p_i are distinct integers from 1 to n.
You have to process q queries of two types:
* 1 v — among all vertices reachable from the vertex v using... | #include <bits/stdc++.h>
using namespace std;
int val[200005];
pair<int, int> e[300005];
bool del[300005];
int qT[500005], qV[500005];
int color[200005];
inline int repr(int x) {
return color[x] == x ? x : (color[x] = repr(color[x]));
}
vector<int> f[200005];
pair<int, int> op[500005];
inline void join(int x, int y, ... |
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the... | from __future__ import division, print_function
# import threading
# threading.stack_size(2**27)
import sys
sys.setrecursionlimit(10**4)
# sys.stdin = open('inpy.txt', 'r')
# sys.stdout = open('outpy.txt', 'w')
from sys import stdin, stdout
import bisect #c++ upperbound
import math
import heapq
i_m=922337203... |
There are n glasses on the table numbered 1, …, n. The glass i can hold up to a_i units of water, and currently contains b_i units of water.
You would like to choose k glasses and collect as much water in them as possible. To that effect you can pour water from one glass to another as many times as you like. However, ... | import java.util.*;
import java.io.*;
//https://codeforces.com/contest/1459/problem/D
public class D1459Fix{
static int[][][] dp;
public static void print(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++)
System.out.printf("%9d ", a[i][j]);
System.out.println("");
... |
After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).
<image>
You are given an array h_1, h_2, ..., ... | import collections
import string
import math
import copy
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in fil... |
As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows.
You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 2e5 + 20;
vector<int> g[N];
vector<pair<ll, pair<int, int>>> edges;
ll bal, ans;
bool vis[N];
set<int> unvis;
int p[N], p2[N], cnt[N], sz[N];
int root(int v){
if(p... |
This is an interactive problem.
Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n.
The game master only allows him to ask one type of question:
* Little Dormi picks a node r (1 ≤ r ≤ n), and the... | import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Random;
import java.util.TreeSet;
public class DLATOKEN1 {
public static void main(String[] args) throws IOException {
init_io();
int N = nint();
boolean[] visited = new boolean[N+1];
boolean... |
You are given n points on a plane. All points are different.
Find the number of different groups of three points (A, B, C) such that point B is the middle of segment AC.
The groups of three points are considered unordered, that is, if point B is the middle of segment AC, then groups (A, B, C) and (C, B, A) are consi... | #include <bits/stdc++.h>
using namespace std;
struct diem {
int x, y;
};
int n, ans = 0;
diem a[3005];
bool cmp(diem a, diem b) {
if (a.x == b.x) return a.y <= b.y;
return a.x <= b.x;
}
int binary_search(int l, int r, diem value) {
if (l > r) return 0;
if (l == r) return l;
int mid = (l + r) / 2;
if (cmp(... |
The Little Elephant has found a ragged old black-and-white string s on the attic.
The characters of string s are numbered from the left to the right from 1 to |s|, where |s| is the length of the string. Let's denote the i-th character of string s as si. As the string is black-and-white, each character of the string is... | import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
public class Main {
public static void main(String[] args) {
Inpu... |
Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with n vertices, chooses some m edges and keeps them. Bob gets the <image> remaining edges.
Alice and Bob are fond of "triangles" in graphs, that i... | #include <bits/stdc++.h>
const int maxn = 1000100;
long long result, n, m;
long long deg[maxn + 1];
int main() {
long long i, j, k, x, y;
scanf("%I64d%I64d", &n, &m);
for (i = 1; i <= n; ++i) deg[i] = 0;
for (i = 1; i <= m; ++i) {
scanf("%I64d%I64d", &x, &y);
++deg[x];
++deg[y];
}
result = 0;
... |
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i < n + m) such that positions with indexes i... | import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class A_Boys_and_Girls {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("out... |
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems.
You've got the titles of n last problems — the strings, consisting of lowercase English letters. Your... | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Solver {
public static void main(String[] Args) t... |
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
1. The product of all numbers in the first set is less than zero ( < 0).
2. The product of all numbers in the second set is greater than zero ( > 0).
3. The product of a... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n);
cout << "1 " << a[0] << endl;
if (a[n - 1] > 0) {
cout << "1 " << a[n - 1] << endl;
cout << n - 2 << endl;
for (int i = 1; i < n - 1; i++) {
... |
In a far away land, there exists a planet shaped like a cylinder. There are three regions in this planet: top, bottom, and side as shown in the following picture.
<image>
Both the top and the bottom areas consist of big cities. The side area consists entirely of the sea.
One day, a city decides that it has too littl... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int Maxn = 3005, Maxm = 300005, Mo = 1000000007,
sp[8][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0},
{1, 1}, {-1, -1}, {1, -1}, {-1, 1}};
const long long oo = INT_MAX >> 2;
struct Tree... |
A long time ago there was a land called Dudeland. Dudeland consisted of n towns connected with n - 1 bidirectonal roads. The towns are indexed from 1 to n and one can reach any city from any other city if he moves along the roads of the country. There are m monasteries in Dudeland located in m different towns. In each ... | #include <bits/stdc++.h>
using namespace std;
int read() {
char ch = getchar();
int x = 0;
while (ch < '0' || ch > '9') ch = getchar();
while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
return x;
}
const int maxn = 2e5 + 5, inf = 1e9;
struct Data {
int next, to, w;
};
struct LinkTable {
... |
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.
Each kangaroo can hold at most one kangaroo, and the kangaroo who is ... | #include <bits/stdc++.h>
using namespace std;
vector<int> v;
int main() {
int n, c = 0;
cin >> n;
int x;
for (int i = 0; i < n; i++) {
cin >> x;
v.push_back(x);
}
sort(v.begin(), v.end());
int r = n - 1;
for (int i = n / 2 - 1; i >= 0; i--) {
if (2 * v[i] <= v[r]) {
c++;
r--;
... |
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if:
* the Euclidean distance between A and B is one unit and neither A nor B is blocked;
* or there is some inte... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, ans = 0;
cin >> n;
double R = n;
long long tmp = n, k;
for (long long i = 1; i <= n; i++) {
double r = i;
k = (long long)sqrt(R * R - r * r);
ans += (tmp == k ? 1 : tmp - k);
tmp = k;
}
if (n == 0)
cout << 1 << end... |
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if... | #include <bits/stdc++.h>
using namespace std;
int n, m, ans;
long long a[200005], d;
int main() {
cin >> n;
int i, j;
for (i = 1; i <= n; i++) cin >> a[i];
int k = 1;
while (k <= n) {
ans++;
for (i = k; a[i] == -1; i++)
;
for (j = i + 1; a[j] == -1; j++)
;
if (j > n) break;
d =... |
Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string.
Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be?
See notes for definition of a tandem repeat.
I... | #include <bits/stdc++.h>
using namespace std;
inline int input() {
int ret = 0;
bool isN = 0;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') isN = 1;
c = getchar();
}
while (c >= '0' && c <= '9') {
ret = ret * 10 + c - '0';
c = getchar();
}
return isN ? -ret : ret;
}
inli... |
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable st... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C265 {
public static void main(String args[])throws IOException
{
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
String line = obj.readLine();
String st... |
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | #include <bits/stdc++.h>
using namespace std;
int b[102];
int g[102];
int main() {
int n, m;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> b[i];
}
cin >> m;
for (int i = 0; i < m; i++) {
cin >> g[i];
}
sort(b, b + n);
sort(g, g + m);
int itb, itg;
itb = itg = 0;
int cnt = 0;
while (it... |
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | import java.util.*;
import java.lang.reflect.Array;
import java.math.*;
import java.io.*;
import java.awt.*;
import java.awt.geom.Line2D;
import javax.naming.BinaryRefAddr;
public class Main{
static FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = ... |
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers.
Input
The first line contains a single... | import math
a = input()
d = int(max(a))
print(d)
dec = math.ceil(math.log10(int(a)))
c = [0]*d
if int(a) != 10**dec:
for i in a:
for j in range(int(i)):
c[j] = c[j]+10**(dec-1)
dec = dec - 1
d=''
for i in c:
d += str(i)+' '
if int(a) == 10**dec:
print(a)
else:
print(d.strip()... |
Some country consists of n cities, connected by a railroad network. The transport communication of the country is so advanced that the network consists of a minimum required number of (n - 1) bidirectional roads (in the other words, the graph of roads is a tree). The i-th road that directly connects cities ai and bi, h... | #include <bits/stdc++.h>
using namespace std;
const long long linf = 1e18 + 5;
int mod = (int)1e9 + 7;
const int logN = 18;
const int inf = 1e9 + 9;
const int N = 3e5 + 5;
int n, m, x, y, z, t, c[N], p, sum[N], h[N];
double G[N];
vector<pair<int, int> > v[N];
vector<pair<double, int> > ans;
int prep(int node, int root)... |
Duff is one if the heads of Mafia in her country, Andarz Gu. Andarz Gu has n cities (numbered from 1 to n) connected by m bidirectional roads (numbered by 1 to m).
Each road has a destructing time, and a color. i-th road connects cities vi and ui and its color is ci and its destructing time is ti.
Mafia wants to dest... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
struct edge {
int u, v, t, c, id;
} e[N];
int n, m;
vector<edge> s[N];
bool cmp(edge a, edge b) { return a.c < b.c; }
struct TwoSat {
static const int N = ::N << 1;
int dfn[N], low[N], id[N], st[N], _st, _, cc;
vector<... |
There are n frogs sitting on the coordinate axis Ox. For each frog two values xi, ti are known — the position and the initial length of the tongue of the i-th frog (it is guaranteed that all positions xi are different). m mosquitoes one by one are landing to the coordinate axis. For each mosquito two values are known p... | #include <bits/stdc++.h>
using namespace std;
const int inf = 987654321;
const long long int INF = 123456789987654321;
int N, M, Xn;
struct Frog {
int x, t, id;
};
vector<Frog> frog;
struct Mosq {
int p, b;
};
vector<Mosq> mosq;
struct BIT {
vector<pair<long long int, long long int> > tree;
void init() {
tr... |
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.
A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will... | #include <bits/stdc++.h>
using namespace std;
inline int IN() {
int x = 0, ch = getchar(), f = 1;
while (!isdigit(ch) && (ch != '-') && (ch != EOF)) ch = getchar();
if (ch == '-') {
f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = (x << 1) + (x << 3) + ch - '0';
ch = getchar();
}
return... |
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.
Spring is starting and the Winter sleep is ... |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.TreeSet;
/**
*
* @author Rishabh
*/
public class Main {static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buff... |
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.... | #include <bits/stdc++.h>
using namespace std;
pair<long long, long long> res;
long long my_pow(long long x) { return x * x * x; }
void dfs(long long m, long long s, long long v) {
int x = 0;
if (m <= 0) {
res = max(res, make_pair(s, v));
return;
}
while (my_pow(x + 1) <= m) {
x++;
}
dfs(m - my_p... |
And while Mishka is enjoying her trip...
Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.
Once walking with his friend, John gave Chris the following proble... | n, w, v, u = map(int, input().split())
maxwait = 0
curr = True
for i in range(n):
x, y = map(int, input().split())
maxwait = max(maxwait, x / v - y / u)
if x / v < y / u:
curr = False
if curr:
maxwait = 0
print(w / u + maxwait) |
Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid:
ABCDEFGHIJKLM
NOPQRSTUVWXYZ
We say that two t... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelpe... |
There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.
It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti — the moment in seconds in which the task will come, ki — the number of servers needed to ... | #include <bits/stdc++.h>
using namespace std;
int en[100 + 100];
int e[100 + 100];
int main() {
int n, q;
while (~scanf("%d%d", &n, &q)) {
memset(en, -1, sizeof(en));
memset(e, -1, sizeof(e));
for (int i = 1; i <= q; i++) {
int T, K, D;
scanf("%d%d%d", &T, &K, &D);
int ans = 0;
i... |
Tourist walks along the X axis. He can choose either of two directions and any speed not exceeding V. He can also stand without moving anywhere. He knows from newspapers that at time t1 in the point with coordinate x1 an interesting event will occur, at time t2 in the point with coordinate x2 — another one, and so on u... | #include <bits/stdc++.h>
long long Left[101000], Right[101000];
int x[101000], t[101000], n, V, s[101000], p[101000], f[101000], L, R, MAX, Ans,
Ans2;
bool cmp(int a, int b) {
return Left[a] == Left[b] ? t[a] < t[b] : Left[a] < Left[b];
}
int main() {
int i;
scanf("%d", &n);
for (i = 1; i <= n; p[i] = i++) ... |
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.
To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor ea... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class R414C_
{
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(... |
Karen has just arrived at school, and she has a math test today!
<image>
The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.
Th... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
struct outputer;
struct outputable {};
template <typename T>
inline auto sqr(T x) -> decltype(x * x) {
return x * x;
}
template <typename T1, typename T2>
inline bool umx(T1& a, T2 b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
templa... |
Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say... | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 100;
vector<int> adj[N];
int n, m, d[N];
vector<pair<int, int> > edge;
bool in[N];
int wildcard, sz[N];
bool vis[N];
void dfs(int u) {
vis[u] = true;
if (d[u] == -1) wildcard = u;
sz[u] = (d[u] == 1);
for (int id : adj[u]) {
auto e = edge[id]... |
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.
Vladimir wants to re... | #include <bits/stdc++.h>
using namespace std;
template <class htpe, class cmp>
using heap = priority_queue<htpe, vector<htpe>, cmp>;
template <class htpe>
using min_heap = heap<htpe, greater<htpe> >;
template <class htpe>
using max_heap = heap<htpe, less<htpe> >;
const int INF = 1791791791;
const long long INFLL = 1791... |
Absent-minded Masha got set of n cubes for her birthday.
At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x.
To make a number Masha can rotate her cubes and put them in a row. Aft... | import java.util.*;
public class Code {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[][] = new int[n][6];
boolean vis[] = new boolean[100];
for(int i=0; i<n; i++) {
for(int j=0; j<6; j++) a[i][j] = in.nextInt(... |
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a lette... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
from operator import getitem
input = sys.stdin
output = sys.stdout
def solve(size,lines):
A = lines
n,m = size
# set of symbols
symbols = {}
for r in range(n):
for c in range(m):
a = A[r][c]
if a not... |
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string ... | #include <bits/stdc++.h>
using namespace std;
string find(int j) {
string s = "";
while (j > 0) {
char ch = j % 10 + '0';
s += ch;
j = j / 10;
}
reverse(s.begin(), s.end());
return s;
}
int main() {
string s;
cin >> s;
int n = s.size();
string t = "";
for (int i = 0; i < n - 1; i++) t +=... |
There used to be unrest in the Galactic Senate. Several thousand solar systems had declared their intentions to leave the Republic. But fear not! Master Heidi was able to successfully select the Jedi Knights that have restored peace in the galaxy. However, she knows that evil never sleeps and a time may come when she w... | #include <bits/stdc++.h>
using namespace std;
namespace FFT {
template <typename U>
struct RootsOfUnity {
using Complex = complex<U>;
static std::vector<Complex> roots[32];
static bool initialized[32];
static void initialize_to(long long w) {
assert(w > 0 && w == (w & -w));
long long lg = 31 - __builtin... |
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers — saturation of the color of each pencil. Now Mishka wants to ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 5e6 + 5;
int n, m;
long long d;
long long a[maxn], sum[maxn];
int main() {
scanf("%d%d%lld", &n, &m, &d);
for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
sort(&a[1], &a[n + 1]);
int good = 1;
sum[0] = 1;
for (int i = 1, j = 1; i <= n; i++) {
... |
This summer is very hot in KGP. As the hostel rooms do not have coolers or ACs, it's even more difficult for the students. So, the management has decided to install a cooler or an AC in some of the rooms.
There are N rooms in KGP. The management has alloted a budget of M units. There are N types of coolers and AC. But... | x,t = map(int,raw_input().strip().split())
l1 = map(int,raw_input().strip().split())
l2 = map(int,raw_input().strip().split())
l1 += l2
s = 0
c = 0
for i in sorted(l1):
if s+i < t:
s+=i
c+=1
else:
break
print c |
Bozo is shifting his house. He has some balls and boxes which he has to shift. He now wonders how large a ball he can fit in a given box. Given the dimensions of a box, help Bozo determine the radius of the largest ball that he can fit in the box. Assume that an inflated ball will be spherical.
Input:-
The first line... | t = int(raw_input())
while t>0:
t-=1
list = map(float,raw_input().split())
print "{:.1f}".format(min(list)/2) |
Its Alice's birthday and her friend Bob gets him a birthday cake. Its nice delicious circle shaped cake of radius R. Now they need to cut and eat that cake, so Alice fetches a cutter from her kitchen. It is a rectangular cutter of length A and breadth B that would knock of the part of the cake when the cutter is place... | def find(r,a,b):
if (a*a)+(b*b) <= 4*r*r:
print "ALICE"
else:
print "EQUAL"
if __name__ == '__main__':
t=int(raw_input())
while t>0:
(r,a,b) = map(int,raw_input().split())
find(r,a,b)
t-=1 |
A prime number is one which is divisible by exactly two numbers 1 and itself.
Given a number, find out if the number obtained by summing all digits of that number is a prime.
Input Format:
The input begins with number of test-cases t in a single line. In each of next tlines there is a number n.
Output Format
In each ... | def isprime(number):
if number==1:
return 0
if number==2:
return 1
if number%2==0:
return 0
N=long(number**0.5)+1
for i in range(3,N,2):
if number%i==0:
return 0
return 1
for t in range(input()):
n=long(raw_input())
summ=0
while n>0:
summ=summ+n%10
n=n/10
if isprime(summ):
print "YES"
else:... |
You are given an integer n find its next greater or equal number whose binary representation must not contain consecutive ones.
For eg. given n=6 whose binary is 110 and the next number with no consecutive ones is 8 whose binary is 1000.
INPUT
First line of input contains t, the total number of test cases. Then t l... | t=int(raw_input())
while t>0:
n=int(raw_input())
while bin(n).count("11")!=0:
n=n+1
print n
t=t-1 |
Ram has to pay Shyam R rupees and but the coins which he has got is of limited denomination .Assuming he has a limited knowledge of the mathematics and has unlimited number of coins of each denomination.Write a code to help Ram to pay the money using minimum number of coins .Suppose Ram has coins of {1,2} denomination ... | def min_coins(money, denoms):
# money : The money which is needed to get minimum coins
# denoms : Available denominations
denoms.sort()
min = denoms[0] * money
coin_list = {}
for j in range(len(denoms)):
temp = money
used = 0
coins = {}
for i in range(1, len(d... |
Given a string S, count the number of non empty sub strings that are palindromes.
A sub string is any continuous sequence of characters in the string.
A string is said to be palindrome, if the reverse of the string is same as itself.
Two sub strings are different if they occur at different positions in S
Input
Input c... | def isPalindrome(s):
lf = 0
ri = len(s)-1
while lf <= ri:
if s[lf] != s[ri]:
return 0
lf += 1
ri -= 1
return 1
def getPalindromes(s):
palindromes = []
lf = 0
ri = len(s)
while lf <= ri:
subri = lf+1
while subri <= ri:
t = s[lf:subri]
if isPalindrome(t):
pal... |
Rhezo and his friend Vanya love problem solving. They have a problem set containing N problems, with points assigned to each. Rhezo wants to solve problems in such a way that he gets the maximum number of points. Rhezo has a weird habit of solving only prime number of consecutive problems, that is, if he solves X conse... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
import sys
def readline():
return sys.stdin.readline().strip()
def readInts(sep=None):
return map(int,readline().split(sep))
def readInt():
return int(readline())
def si... |
Special Sum of number N is defined as follows:
def foo(n):
{
ret = 0
for i = 1 to n:
{
if gcd(n,i) is 1:
ret += 1
}
return ret
}
def SpecialSum(N):
{
ret=0
for i = 1 to N:
{
if i divides N:
ret += foo(i)
}
return ret
}
Given a N print SpecialSum(N).
Input:... | numcases = input()
res = []
for i in range(numcases):
val = input()
res.append(val)
for i in res:
print i |
Mr. X is performing a trick with the cards. He has N cards, lets name them 1.....N, on a round table.
So card 1 is in between 2nd card and Nth card. Initially all cards are upside down. His trick involves making all cards face up.
His trick is whenever he taps on a card, it flips (if card was originally upside down,... | test = input()
while test>0:
N = input()
if N==0:
print "0"
elif N<3:
print "1"
elif N%3==0:
print N/3
else:
print N
test = test-1 |
N persons are standing in a row. The height of the i-th person from the front is A_i.
We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:
Condition: Nobody in front of the person is taller than the person. Here, the height of a ... | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner stdIn = new Scanner(System.in);
int N = stdIn.nextInt();
ArrayList<Integer> A = new ArrayList<Integer>();
for(int i = 0; i < N; i ++) {
A.add(stdIn.nextInt());
}
long stepSum = ... |
There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.
You can rearrange these children just one time in any order you like.
When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child... | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
Number[] numbers = new Number[N];
for (int i = 0; i < N; i++) numbers[i] = new Number(i, scanner.nextInt());
Arrays... |
We have N integers. The i-th integer is A_i.
Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).
What is \mbox{ XOR }?
The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:
* When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if eith... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual soluti... |
Snuke has N hats. The i-th hat has an integer a_i written on it.
There are N camels standing in a circle. Snuke will put one of his hats on each of these camels.
If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print `Yes`; otherwise, print `No... | #include <bits/stdc++.h>
const char nl = '\n';
using namespace std;
using ll = long long;
using ld = long double;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n; cin >> n;
int x = 0;
vector<int> a(n);
for (int& i : a) cin >> i, x ^= i;
puts(x == 0 ? "Yes" : "No");
return 0;
}
|
You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.
Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:
* Extension Magic: Consumes 1 MP (magic point).... | #include <bits/stdc++.h>
using namespace std;
int INF=10000000;
int N,A,B,C;
vector<int> L;
int rec(int i, int a, int b, int c){
if(i==N){
if(!a||!b||!c) return INF;
return abs(a-A)+abs(b-B)+abs(c-C);
}
int res=rec(i+1,a,b,c);
res=min(res, rec(i+1, a + L[i], b, c) + (a ? 10 : 0));... |
There is a string s consisting of `a` and `b`. Snuke can perform the following two kinds of operation any number of times in any order:
* Choose an occurrence of `aa` as a substring, and replace it with `b`.
* Choose an occurrence of `bb` as a substring, and replace it with `a`.
How many strings s can be obtained b... | #include<bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
const int P = 1e9 + 7;
typedef long long ll;
template <typename T> void read(T &x) {
x = 0; int f = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
x *= f;
... |
You are given a directed graph with N vertices and M edges. The vertices are numbered 1, 2, ..., N, and the edges are numbered 1, 2, ..., M. Edge i points from Vertex a_i to Vertex b_i.
For each edge, determine whether the reversion of that edge would change the number of the strongly connected components in the graph... | #include<bits/stdc++.h>
using namespace std;
using Int = signed;
//INSERT ABOVE HERE
Int dp[2][1010][1010];
Int pv[1010][1010];
signed main(){
Int n,m;
cin>>n>>m;
vector<Int> a(m),b(m);
for(Int i=0;i<m;i++) cin>>a[i]>>b[i],a[i]--,b[i]--;
vector<vector<Int> > G(n);
for(Int i=0;i<m;i++) G[a[i]].emplace_back(... |
You are given an H × W grid.
The squares in the grid are described by H strings, S_1,...,S_H.
The j-th character in the string S_i corresponds to the square at the i-th row from the top and j-th column from the left (1 \leq i \leq H,1 \leq j \leq W).
`.` stands for an empty square, and `#` stands for a square containin... | h,w = map(int,input().split())
grid = ["."*(w+2)]+["."+input()+"." for _ in range(h)]+["."*(w+2)]
for y in range(1,h+1):
for x in range(1,w+1):
if grid[y][x]=="#":
print("#",end="")
else:
print(sum(grid[i][j]=="#" for i in range(y-1,y+2) for j in range(x-1,x+2)),end="")
print("") |
You are given three strings A, B and C. Check whether they form a word chain.
More formally, determine whether both of the following are true:
* The last character in A and the initial character in B are the same.
* The last character in B and the initial character in C are the same.
If both are true, print `YES`.... | import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
String c = sc.n... |
We have a cord whose length is a positive integer. We will perform the following condition until the length of the cord becomes at most 2:
* Operation: Cut the rope at two positions to obtain three cords, each with a length of a positive integer. Among these, discard one with the longest length and one with the shorte... | x = input()
N = 1
ans = 7
while x > N:
ans = 1 + ans*2
x -= 1
print ans-1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.