input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points.
Manao has developed a model to predict the stock price of a company over the next n days and wants to design a... | #include <bits/stdc++.h>
using namespace std;
template <class T>
void debug(T a, T b) {
;
}
template <class T>
void chmin(T& a, const T& b) {
if (a > b) a = b;
}
template <class T>
void chmax(T& a, const T& b) {
if (a < b) a = b;
}
namespace std {
template <class S, class T>
ostream& operator<<(ostream& out, cons... |
After a lot of trying, Mashmokh designed a problem and it's your job to solve it.
You have a tree T with n vertices. Each vertex has a unique index from 1 to n. The root of T has index 1. For each vertex of this tree v, you are given a list of its children in a specific order. You must perform three types of query on ... | #include <bits/stdc++.h>
using namespace std;
inline int read() {
char c = getchar();
int x = 0;
bool f = 0;
for (; !isdigit(c); c = getchar()) f ^= !(c ^ 45);
for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
if (f) x = -x;
return x;
}
int n, m, q;
vector<int> e[200005];
int in[200005... |
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).
Valera wants to place... | n, m, k = map(int, raw_input().split())
path = []
for x in xrange(1, n+1):
if x % 2 == 1:
for y in xrange(1, m+1):
path.append((x, y))
else:
for y in xrange(m, 0, -1):
path.append((x, y))
for i in xrange(k-1):
print 2, path[2*i][0], path[2*i][1], path[2*i+1][0], path[2*i+1][1]
print n*m - 2*(k... |
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can... | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java... |
Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence <image>.
Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].
Input
The only input line contains an integer n (1 ≤ n ≤ 105).
Output
In the first output line, print ... | #include <bits/stdc++.h>
long long n;
bool isprime() {
for (long long k = 2; k <= sqrt(n); k++) {
if (n % k == 0) return false;
}
return true;
}
long long int fast(long long a, long long x) {
if (x == 1) return a;
long long y = fast(a, x / 2);
if (x % 2 == 0)
return (y * y) % n;
else
return (y... |
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:
<image>
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain d... |
import java.util.Scanner;
public class Main {
static int n, m, sum;// sum记录有没有找到,找到了为1,没找到为0
static int[] xx = { 0, 0, -1, 1 };
static int[] yy = { -1, 1, 0, 0 };
static char[][] arr;
static boolean[][] vis;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
... |
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.
<image>
Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is ... | #include <bits/stdc++.h>
using namespace std;
void imprimirVector(vector<int> v) {
if (!v.empty()) {
int p = v.size();
cout << "[";
for (int i = 0; i < (int)(p - 1); i++) cout << v[i] << ",";
cout << v[p - 1] << "]" << endl;
} else
cout << "[]" << endl;
}
long long cuadratica(double a, double b,... |
Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.
Input
The first line of the input contains the... | import java.util.*;
import java.io.*;
import java.math.*;
public class round51D {
public static void main(String args[]) throws Exception{
cf55D tmp=new cf55D();
tmp.solve();
}
}
class cf55D {
final static int N=25;
final static int mod=2520;
final static int M=(1<<8);
long dp[][][]=new long[N][M][mod];
Ar... |
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way that every day it... | n = int(input())
a = list(map(int, input().split())) + [0]
home = True
ans = 0
for i in range(n):
if a[i]:
ans += 1
home = False
elif not a[i + 1] and not home:
home = True
elif not home:
ans += 1
print(ans) |
Genos needs your help. He was asked to solve the following programming problem by Saitama:
The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as <image>, where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming ... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ankur
*/
public class Main... |
Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.
A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable profess... | #include <bits/stdc++.h>
using namespace std;
int main() {
int ml, mr, hl, hr;
cin >> ml >> mr >> hl >> hr;
int ok = 0;
if (hr + 1 >= ml && hr <= 2 * (ml + 1)) ok = 1;
if (hl + 1 >= mr && hl <= 2 * (mr + 1)) ok = 1;
printf(ok ? "YES\n" : "NO\n");
return 0;
}
|
Pussycat Sonya has an array consisting of n positive integers. There are 2n possible subsequences of the array. For each subsequence she counts the minimum number of operations to make all its elements equal. Each operation must be one of two:
* Choose some element of the subsequence and multiply it by some prime nu... | #include <bits/stdc++.h>
using namespace std;
inline int ri() {
int x;
scanf("%d", &x);
return x;
}
template <typename T>
inline bool smax(T& a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <typename T>
inline bool smin(T& a, T b) {
if (a > b) {
a = b;
return true;
... |
Limak, a bear, isn't good at handling queries. So, he asks you to do it.
We say that powers of 42 (numbers 1, 42, 1764, ...) are bad. Other numbers are good.
You are given a sequence of n good integers t1, t2, ..., tn. Your task is to handle q queries of three types:
1. 1 i — print ti in a separate line.
2. 2 a... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 20;
const int shit = 42;
struct node {
long long mx, mn, lazy, ladd, mn_diff;
node() {
mx = 0;
mn = 1e16;
lazy = -1;
ladd = 0;
mn_diff = 1e16;
}
};
long long a[maxn], tmpval, tmpnex, tmpaddval;
node seg[maxn * 4], void_node;
... |
Again, there are hard times in Berland! Many towns have such tensions that even civil war is possible.
There are n towns in Reberland, some pairs of which connected by two-way roads. It is not guaranteed that it is possible to reach one town from any other town using these roads.
Towns s and t announce the final br... | #include <bits/stdc++.h>
using namespace std;
inline void down(int &a, const int &b) {
if (a > b) a = b;
}
const int maxn = 2100;
const int maxm = 110000;
int n, m, S, T;
int e[maxm][3], ok[maxm];
int t[maxm], tp;
struct edge {
int y, i, nex;
} a[maxm];
int len, fir[maxn];
inline void ins(const int x, const int y, ... |
You are given names of two days of the week.
Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong t... | # your code goes here
dd=[3,0,2]
d1=raw_input()
d2=raw_input()
ddd={'sunday':0,'monday':1,'tuesday':2,'wednesday':3,'thursday':4,'friday':5,'saturday':6}
k=(ddd[d2]-ddd[d1]+7)%7
if k in dd:
print "YES"
else:
print "NO" |
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ... | l = int(input())
a = int(input())
p = int(input())
ll = l
aa = a // 2
pp = p // 4
print(min(ll,aa,pp) * 1 + min(ll,aa,pp) * 2 + min(ll,aa,pp) * 4)
|
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university.
Each of students joins the group of his course and joins all groups f... | #include <bits/stdc++.h>
using namespace std;
const size_t $MAXN = (uint32_t)(4000);
const char *$SIGNATURE[] = {"b9", "91", "af", "fc", "fb", "24", "db", "04",
"76", "fe", "95", "76", "b9", "03", "95", "2e"};
const uint32_t $MOD = (const uint32_t)(1e9 + 7);
int32_t nextInt() {
int32_t d;
... |
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg... | import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Main {
static Scanner in = new Scanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String... |
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time!
Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal.
... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 5e3 + 7;
const int maxa = 1e5 + 7;
int dp[maxn][maxn];
int num[maxn], n;
int get_ans() {
memset(dp, 0, sizeof(dp));
int max_mod[7], max_num[maxa];
memset(max_mod, 0, sizeof(max_mod));
memset(max_num, 0, sizeof(max_num));
int ans = 0;
for (int i ... |
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.
Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them.... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
const int N = 100100;
int cnt = 0;
long double Cnt[N];
long double SumCnt = 0;
long double H[N];
long double P[N];
vector<int> g[N];
long double dfs(int v, int p = -1) {
if ((int)g[v].size() == 1 && v != 1) {
return 0;
}
long double s... |
It's another Start[c]up, and that means there are T-shirts to order. In order to make sure T-shirts are shipped as soon as possible, we've decided that this year we're going to order all of the necessary T-shirts before the actual competition. The top C contestants are going to be awarded T-shirts, but we obviously don... | #include <bits/stdc++.h>
using namespace std;
bool debug = 0;
int n, m, k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
string direc = "RDLU";
long long ln, lk, lm;
void etp(bool f = 0) {
puts(f ? "YES" : "NO");
exit(0);
}
void addmod(int &x, int y, int mod = 1000000007) {
assert(y >= 0);
x += y;
if (x >... |
You are given a matrix of size n × m. Each element of the matrix is either 1 or 0. You have to determine the number of connected components consisting of 1's. Two cells belong to the same component if they have a common border, and both elements in these cells are 1's.
Note that the memory limit is unusual!
Input
Th... | #include <bits/stdc++.h>
using namespace std;
void readi(int &x) {
int v = 0, f = 1;
char c = getchar();
while (!isdigit(c) && c != '-') c = getchar();
if (c == '-')
f = -1;
else
v = v * 10 + c - '0';
while (isdigit(c = getchar())) v = v * 10 + c - '0';
x = v * f;
}
void readll(long long &x) {
l... |
Let S(n) denote the number that represents the digits of n in sorted order. For example, S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555.
Given a number X, compute <image> modulo 109 + 7.
Input
The first line of input will contain the integer X (1 ≤ X ≤ 10700).
Output
Print a single integer, the answer to ... | #include <bits/stdc++.h>
using namespace std;
void getre() {
int x = 0;
printf("%d\n", 1 / x);
}
void gettle() {
int res = 1;
while (1) res <<= 1;
printf("%d\n", res);
}
template <typename T, typename S>
inline bool upmin(T &a, const S &b) {
return a > b ? a = b, 1 : 0;
}
template <typename T, typename S>
i... |
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch... | import java.io.*;
import java.util.*;
public class R468_D {
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) throws Exception {
int n = readInt();
int[] p = new int[n];
i... |
Heidi has now broken the first level of encryption of the Death Star plans, and is staring at the screen presenting her with the description of the next code she has to enter. It looks surprisingly similar to the first one – seems like the Empire engineers were quite lazy...
Heidi is once again given a sequence A, but... | #include <bits/stdc++.h>
using namespace std;
int n, k, p;
int dp[105][55];
int modd(int x) {
if (x < 0)
return x + p;
else if (x >= p)
return x - p;
return x;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cerr.tie(nullptr);
cin >> n >> k >> p;
memset(dp... |
Two players play a game.
Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate t... | i = input()
j = list(int(x) for x in raw_input().split())
j.sort()
print j[(len(j)+1)/2-1]
|
Hannibal is on a mission. He has to shoot a criminal. Hannibal was on the point (0, 0) and the criminal is on the point (Xc, Yc). But there is a wall between the point (X1, Y1) and (X2, Y2).
You have to tell whether Hannibal can shoot criminal or not.
INPUT:
First line contains the total number of test cases T. For... | def are_points_colinear(x1,y1,x2,y2,x3,y3):
return x1*(y2-y3)+y1*(x3-x2)+x2*y3-x3*y2 == 0
def slope_positive(x1,y1,x2,y2):
if x1 == x2 or y1 == y2:
return False
else:
return float(x2-x1)/float(y2-y1) > 0
def slope_negative(x1,y1,x2,y2):
if x1 == x2 or y1 == y2:
return False
... |
You have 4 types of lego blocks, of sizes (1 x 1 x 1), (1 x 1 x 2), (1 x 1 x 3), and (1 x 1 x 4). Assume that you have an infinite number of blocks of each type.
Using these blocks, you want to make a wall of height N and width M. The wall should not have any holes in it. The wall you build should be one solid structu... | limit = 1004
f = [0] * limit
f[0] = 1
for x in xrange(1, limit):
a = 0
if x >= 1: a = f[x-1]
b = 0
if x >= 2: b = f[x-2]
c = 0
if x >= 3: c = f[x-3]
d = 0
if x >= 4: d = f[x-4]
f[x] = (a + b + c + d) % 1000000007
def get(n, m):
g = [0] * (m+1)
p = map(lambda x: pow(f[x], n, ... |
India is a cricket crazy nation. Chang also loves cricket and computations related to cricket. Chang has created a Cricket app.This app analyses the performance of a cricketer. If a cricketer under-performs, then a negative rating is awarded. If performance is good, then positive rating is awarded to the cricketer.Chan... | n=input();
if n==0: print 0;
else:
A=map(int,raw_input().split()); val,max_v=0,0;
for i in A:
if i+val>0:
val+=i;
if val>max_v: max_v=val;
else: val=0;
print max_v; |
Saurav has put up Chinese food stall in the college fest. He has arranged everything but he was not able to find chop-sticks in any shop. He decided to make some himself. After hours of efforts, he was able to collect a few ice cream sticks that resembled chop sticks. The problem was that they were not in pair.
Saurav... | '''
ChopStick
'''
import math
def Fun_Wid_Code():
tc=int(raw_input())
while(tc):
n,d=map(int,raw_input().split())
num=[0]*n
i=0
while(i<n):
num[i]=int(raw_input())
i+=1
num.sort()
i=0
count=0
while(i<n-1):
if(num... |
Joker is back again with his destructive plan . He has set N bombs in various parts of Gotham city and has challenged the police department to defuse all bombs in one day . City can be treated as a 1-D line with 'N' bombs situated in such a manner that distance of 1^st bomb is 'x' , 2nd bomb is ' x^2 ' , 3rd bomb... | def get_mod_pow(a,b,m):
ans=1
while b > 0:
if b % 2 == 1:
ans = (ans * a) % m
a = (a ** 2) % m
b = b / 2
return ans
def find(n,x,m):
if n==0:return 0
if n==1:return x
poly=find(n/2,x,m)
if n%2==1:
return (poly+(1+poly)*get_mod_pow(x,(n+1)/2,m))%m
... |
Milly loves chocolates very much. She is at the land of chocolates. This land has N rooms such that there are some chocolates of different brands in every room. It is possible that there can be multiple chocolates of same brand in a particular room. Now she is in a dilemma that whether she can eat at least K distinct b... | NOT_FOUND = 100000000
def isOKay(ChocolateMap):
Cnt = 0
for k, v in ChocolateMap.iteritems():
if v >= 1:
Cnt += 1
return Cnt
def Rec(N, K, Chocolates, Position, ChocolateMap):
if (Position == N):
if isOKay(ChocolateMap) >= K:
return 0
return NOT_FOUND
... |
There is a kingdom, that has a long straight road of length L meters and width 0. Coordinate x on the road denotes point that is at x meters from the start of the road. That is coordinate 0 denotes beginning of the road and coordinate L denotes end of the road. The road has to be painted with color. There are K proposa... | '''input
3
9 6
2 7 10
7 8 3
3 4 8
0 8 2
5 6 4
3 7 1
9 6
7 8 6
6 9 6
2 5 8
3 6 10
0 7 6
2 9 1
3 4
0 3 8
0 2 4
0 1 10
2 3 8
'''
def min(a,b):
if a != 0 and a <= b:
return a
return b
tc = int(raw_input())
for t in xrange(tc):
n,k = map(int,raw_input().split())
ip = [""] * (k+1)
for i in xrange(1,k+1):
ip[i] =... |
Hackland is being attacked by Greyland, and you have been assigned the job to save it. Your enemies, known as Grey hats, are numbered starting from L to R, both inclusive. But, here is the fun part: Grey hats are known to switch sides, and you need to make full use of it to get some of them on your side.
Now, two Grey... | '''
# Read input from stdin and provide input before running code
#name = raw_input('What is your name?\n')
#print 'Hi, %s.' % name
'''
#print 'Hello World!'
testcases = int(raw_input())
for i in range(testcases):
num=raw_input().split()
L=int(num[0])
R=int(num[1])
K=int(num[2])
x=L;
count=0;
while(x<=R):
cou... |
The dark lord wants to send armies of imps to assault Hogwarts in the first wave of offense. The imps are accustomed to fight in communities and will not fight separately. Communities are sent to battle such that the size of each community sent must be greater than the previous community sent to increase pressure on Ho... | T = raw_input("")
for i in range(int(T)):
raw_input("")
str2 = raw_input("")
str2 = str2.split()
str2 = [int(i) for i in str2]
str2.sort()
str1 = ' '.join(str(e) for e in str2)
print(str1) |
Cricket has gone from a history of format which are test match, 50-50 and 20-20. Therefore, ICC decided to start a new type of format i.e. toss. For this ICC started a competition known as ‘Toss ka Boss’. Here the team captains compete with each other. For the first match we have two captains which will compete with ea... | T = input()
for i in range(0,T):
a = []
s = raw_input()
for i in range(0, len(s)):
a.append(s[i])
#print a
for i in range(0, len(a)):
if(a[i]=='T'):
a[i] = 0
#print a
c = 1
sum1 = 0
for i in range(0, len(a)):
if(a[i]==0):
... |
You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N.
Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i.
* T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i.
* T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A... | import java.util.Arrays;
import java.util.Scanner;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int... |
Takahashi and Aoki will have a battle using their monsters.
The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively.
The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ... Here, an attack decreases ... | #include <iostream>
using namespace std;
int main()
{
int a,b,c,d; cin>>a>>b>>c>>d;
((b+c-1)/b) > ((a+d-1)/d) ? cout<<"No" : cout<<"Yes";
}
|
Takahashi is solving quizzes. He has easily solved all but the last one.
The last quiz has three choices: 1, 2, and 3.
With his supernatural power, Takahashi has found out that the choices A and B are both wrong.
Print the correct choice for this problem.
Constraints
* Each of the numbers A and B is 1, 2, or 3.
* ... | A = int(input())
B = int(input())
print(1+2+3 -A-B) |
We have a weighted directed graph with N vertices numbered 0 to N-1.
The graph initially has N-1 edges. The i-th edge (0 \leq i \leq N-2) is directed from Vertex i to Vertex i+1 and has a weight of 0.
Snuke will now add a new edge (i → j) for every pair i, j (0 \leq i,j \leq N-1,\ i \neq j). The weight of the edge wi... | /* cerberus97 - Hanit Banga */
#include <iostream>
#include <iomanip>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
#define pb push_back
#define fa... |
There are H rows and W columns of white square cells.
You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.
How many white cells will remain?
It can be proved that this count does not depend on what rows and columns are chosen.
Constraints
* All values i... | #include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,p,q;cin>>a>>b>>p>>q;
cout<<(a-p)*(b-q)<<endl;
} |
You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., N.
* The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i.
* For each vertex i, the sum of ... | #include <bits/stdc++.h>
using namespace std;
const int MX=1e5+5;
pair<long long,int> a[MX];
map<long long,int> mp;
long long n;
int p[MX];
int visit[MX];
long long s[MX];
long long dp[MX];
int main(){
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
cin>>n;
int i;
for(i=1 ; i<=n ; i++){
... |
Some number of chocolate pieces were prepared for a training camp. The camp had N participants and lasted for D days. The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on. As a result, there were X ... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int D=sc.nextInt();
int X=sc.nextInt();
int[] A=new int[N];
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
}
int sum=0;
for(int i=0;i<A.length;i++) {
s... |
E869120 found a chest which is likely to contain treasure.
However, the chest is locked. In order to open it, he needs to enter a string S consisting of lowercase English letters.
He also found a string S', which turns out to be the string S with some of its letters (possibly all or none) replaced with `?`.
One more t... | #include<iostream>
#include<string>
#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,a) loop(i,0,a)
using namespace std;
int main(){
string s,t;
cin>>s>>t;
bool tmp=false;
for(int i=s.size()-t.size();i>=0;i--){
bool check=true;
rep(j,t.size()){
if(s[i+j]=='?' or s[i+j]==t[j])continue;
check=false;
... |
There are N cities and M roads. The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally. There may be more than one road that connects the same pair of two cities. For each city, how many roads are connected to the city?
Constraints
* 2≤N,M≤50
* 1≤a_i,b_i≤N
* a_i ≠ b_i
* All input values a... | n,m = map(int,input().split())
l = [0]*n
for i in range(0,m):
for j in list(map(int,input().split())):
l[j-1]+=1
for i in range(0,n):
print(l[i]) |
A cheetah and a cheater are going to play the game of Nim. In this game they use N piles of stones. Initially the i-th pile contains a_i stones. The players take turns alternately, and the cheetah plays first. In each turn, the player chooses one of the piles, and takes one or more stones from the pile. The player who ... | from functools import reduce
from operator import xor
N = int(input())
As = [int(input()) for _ in range(N)]
dXORs = set([A ^ (A-1) for A in As])
XOR = reduce(xor, As)
ans = 0
for i in reversed(range(30)):
if XOR & (1<<i):
d = ((1<<(i+1)) - 1)
if d in dXORs:
XOR ^= d
ans +... |
Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.
Iroha is looking for X,Y,Z-Haiku (defined below) in integer sequences.
Consider all integer sequences of length N whose elements are between 1 and 10, inclusive. Out of those 10^N sequences, how many ... | #include <iostream>
#include <cstring>
using namespace std;
typedef int state_t;
const int Mod = 1e9 + 7, MaxN = 41, StateLen = 5 + 7 + 5;
int N, X, Y, Z, p[MaxN], f[MaxN][1 << StateLen];
state_t end_state;
state_t dp(int i, int j) {
if (i == N) {
return 0;
}
if (~f[i][j]) {
return f[i][j];
}
long ... |
The University of Aizu has a park covered with grass, and there are no trees or buildings that block the sunlight. On sunny summer days, sprinklers installed in the park operate to sprinkle water on the lawn. The frog Pyonkichi lives in this park. Pyonkichi is not good at hot weather, and on summer days when the sun is... | import java.util.LinkedList;
import java.util.Scanner;
public class Main {
Scanner sc = new Scanner(System.in);
int kaeruDx[] = { 2, 2, 2, -2, -2, -2, 0, 1, -1, 0, 1, -1 };
int kaeruDy[] = { 0, 1, -1, 0, 1, -1, 2, 2, 2, -2, -2, -2 };
void run() {
for (;;) {
int w = sc.nextInt();
int h = sc.nextInt();
i... |
I am a pipe tie craftsman. As long as you get the joints and pipes that connect the pipes, you can connect any pipe. Every day, my master gives me pipes and joints, which I connect and give to my master. But if you have too many pipes, you can't connect them all in one day. Even in such a case, the master smiles and gi... | #include<bits/stdc++.h>
using namespace std;
long long int i,n,a,m,g,b[100000];
int main(void)
{
while(1){
scanf("%d",&n);
if(n==0) break;
m=0;
g=0;
for(i=0;i<n;i++){
scanf("%d",&a);
m+=a;
}
for(i=0;i<n-1;i++){
scanf("%d",&b[i]);
}
sort(b,b+(n-1));
b[n-1]=0;
for(i=n-1;i>=0;i--){
if(g<... |
problem
Once upon a time there were settlements and many people lived there. People built buildings of various shapes and sizes. But those buildings have already been lost, only the literature and the pillars found in the ruins. Was a clue to the location of the building.
There is a description of the temple in the l... | #include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef pair<int,int> P;
P p[3000];
int n;
int ans;
int main(){
while(cin>>n&&n){
ans=0;
for(int i=0;i<n;i++)
scanf("%d %d",&p[i].first,&p[i].second);
sort(p,p+n);
for(int i=0;i+1<n;i++){
for(int j=i+1;j<n;j++){
... |
The city is full of ghosts, something the average person doesn't know about. Most of them are harmless, but the trouble is that there are quite a few evil spirits that curse people.
There was a girl who fought against such evil spirits. She goes to high school with a faceless face during the day, but at night she walk... | import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
public static class Walk implements Comparable<Walk> {
int s_x_pos;
int s_y_pos;
int g_x_pos;
int g_y_pos;
int time;
public Walk(int s_x_pos, int s_y_pos, int g_x_pos, int g_y_pos, int time) {
su... |
Encryption System
A programmer developed a new encryption system. However, his system has an issue that two or more distinct strings are `encrypted' to the same string.
We have a string encrypted by his system. To decode the original string, we want to enumerate all the candidates of the string before the encryption.... | #include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iomanip>
#include <cmath>
#include <set>
#include <algorithm>
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
using namespace std;
string s;
vector<string> ans;
void rec(in... |
Professor Abacus has just built a new computing engine for making numerical tables. It was designed to calculate the values of a polynomial function in one variable at several points at a time. With the polynomial function f(x) = x2 + 2x + 1, for instance, a possible expected calculation result is 1 (= f(0)), 4 (= f(1)... | #include <iostream>
using namespace std;
int D;
double V[100];
double absd( double x ) {
if ( x < 0 ) { return -x; }
return x;
}
double interpolate( int n, int E ) {
double sum = 0.0;
for ( int k = 0; k < D + 3; k++ ) {
if ( k == n || k == E ) { continue; }
double p = V[k];
for ( int i = 0; ... |
Background
There was a person who loved dictionaries. They love to make their own dictionaries. So you decided to add the ability to customize their dictionaries.
Problem
First, there is an empty dictionary that doesn't contain any words. Given N strings Sid and Q queries. Each query is given with a query type k and... | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);(i)++)
#define rep(i,n) repl(i,0,n)
#define dbg(x) cout<<#x<<"="<<x<<endl
#define INF INT_MAX/3
struct RangeMinQuery{
int dat[(1<<19)-1];
int size;
void init(int n_){... |
Mr. Nod is an astrologist and has defined a new constellation. He took two photos of the constellation to foretell a future of his friend. The constellation consists of n stars. The shape of the constellation in these photos are the same, but the angle of them are different because these photos were taken on a differen... | // Problem D : Rotation Estimation
#include <iostream>
#include <vector>
#include <complex>
#include <algorithm>
#include <cmath>
#include <stdio.h>
using namespace std;
const double EPS = 1e-8;
typedef complex<double> P;
double rot(P a, P b) { return arg(conj(a)*b); }
namespace std{
bool operator < (const P &a, c... |
Natsume loves big cats. Natsume decided to head to a corner of the schoolyard where stray cats always gather in order to brush the stray cats, which is a daily routine today.
N cats gathered at the spot today. Natsume wanted to brush everyone, but suddenly she was able to do something just before she came there, and s... | #include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
#define fr first
#define sc second
const int INF=1000000000;
struct SEG{
int siz;
int s[1<<18];
void init(){
siz = 1<<17;
for(int i=0;i<2*siz-1;i++){
s[i]=INF;
}
}
void... |
Time Limit: 8 sec / Memory Limit: 64 MB
Example
Input
eggchickenegg
Output
egg | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define INF 99999999
#define eps 1e-9
int main(){
string s;
cin>>s;
string t="";
for(int i=0;i<s.size();)... |
ICPC World Finals Day 5
Mr. Tee got lost in the city of R country. The trouble is that the streets are similar, so I have no idea where I am now. Country R is "sorry", so you have to return to the hotel before being attacked by the enemy. Fortunately, I only remember how it turned, so let's go random.
problem
\\ (w ... | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
typedef long long lli;
typedef pair<lli, lli> P;
const lli MAX = 100000;
lli w, h, gx, gy, n;
vector<P> input;
vector<lli> vec[4][MAX+1]; //(x, y)
string r;
bool check(lli x, lli y, lli d){
bool f = false;
for(ll... |
Example
Input
4 2 58 100
10 10 50 80
Output
75
2 3 | #include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <climits>
#include <iomanip>
#include <algorithm>
#include <queue>
#include <map>
#include <tuple>
#include <iostream>
#include <deque>
#include <array>
#include <set>
#include <functional>
#include <memory>
#include <stack>
#include <uno... |
Game balance
You are creating an adventure game. The player of this game advances the adventure by operating the hero to defeat the enemy monsters and raising the level of the hero. The initial level of the hero is 1.
There are N types of enemy monsters in this game, and the strength of the i-th type enemy monster is... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T> using vec = vector<T>;
template <class T> using vvec = vector<vec<T>>;
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
int N,M;
while(cin >> N >> M && N){
vec<int> S(N);
set<int> s;
for(a... |
E: Restoration of shortest path
story
Competition programmers solve the shortest path problem every day. BFS, Bellman Ford, Dijkstra, Worshall Floyd and many other algorithms are also known.
Meanwhile, you had a shortest path problem that you couldn't solve. It's a problem of solving the shortest path problem withou... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, s, t;
cin >> n >> s >> t;
vector<pair<int, int>> path;
path.emplace_back(0, s);
cout << "? " << s << ' ' << t << endl;
int d;
cin >> d;
path.emplace_back(d, t);
for (i... |
Prize
Segtree entered a programming contest with a team of $ N $ and won a $ K $ yen prize! I'm trying to distribute this prize now.
Each $ N $ team member, including Segtree, is numbered from $ 1 $ to $ N $ in order of ability. Segtree is $ 1 $.
If the prize amount of $ i $'s teammate $ (i \ geq 2) $ is less than "... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout << fixed << setprecision(20);
ll n,k;
cin>>n>>k;
if(n==1){
cout << k << endl;
return 0;
}
ll now = 1;
ll cnt=0;
while(now < k){
... |
Given a set of $N$ axis-aligned rectangular seals, find the number of overlapped seals on the region which has the maximum number of overlapped seals.
Constraints
* $ 1 \leq N \leq 100000 $
* $ 0 \leq x1_i < x2_i \leq 1000 $
* $ 0 \leq y1_i < y2_i \leq 1000 $
* $ x1_i, y1_i, x2_i, y2_i$ are given in integers
Input
... | #include <iostream>
using namespace std;
#define SZ 1000
#define MAX(X,Y) ((X)>(Y)?(X):(Y))
int main(void){
int n;
int d[SZ+1][SZ+1], ans;
cin >> n;
for (int i=0; i<=SZ; i++){
for (int j=0; j<=SZ; j++) d[i][j] = 0;
}
for (int i=0; i<n; i++){
int x0, y0, x1, y1;
cin >> x0 >> y0 >> x1 >> y1;
... |
Chef and Roma are playing a game. Rules of the game are quite simple.
Initially there are N piles of stones on the table.
In each turn, a player can choose one pile and remove it from the table.
Each player want to maximize the total number of stones removed by him.
Chef takes the first turn.
Please tell Chef the max... | for i in range(input()):
input()
a = map(int,raw_input().split())
a.sort(reverse = True)
i = 2
s=a[0]
while i<len(a):
s+=a[i]
i+=2
print s |
There is a haunted town called HauntedLand. The structure of HauntedLand can be thought of as a grid of size n * m. There is a house in each cell of the grid. Some people have fled from their houses because they were haunted. '.' represents a haunted house whereas '*' represents a house in which people are living.
On... | for t in xrange(int(raw_input())):
n, m = map(int, raw_input().split())
r, c = n, m
row = []
col = []
for i in xrange(m):
col.append("")
for i in xrange(n):
s = raw_input()
row.append(s)
for j in xrange(m):
col[j] += s[j]
for i in range(n):
if (row[i].count(".") == m):
r -= 1
else:
bre... |
Ronak’s class teacher gives him an NxN matrix.
Then, she gives him M numbers. Every number is an angle, the angle by which he has to rotate the matrix in clockwise direction. (The angles are multiples of 90.)
Help him with the task.
Input
First line consists of two numbers N and M.
The following N lines contain ... | n,m=map(int, raw_input().split())
a=[ raw_input().split() for j in xrange(n) ]
while m>0:
m-=1
ang=input()
ang/=90
ang%=4
if(ang==1):
for j in xrange(0,n):
for i in xrange(n-1,-1,-1):
print a[i][j],
print
elif(ang==2):
for i in xrange(n-1,-1,-1):
for j in xrange(n-1,-1,-1):
print a[i][j],
... |
Scheme? - Too loudly said. Just a new idea. Now Chef is expanding his business. He wants to make some new restaurants in the big city of Lviv. To make his business competitive he should interest customers. Now he knows how. But don't tell anyone - it is a secret plan. Chef knows four national Ukrainian dishes - salo, ... | mod=1000000007
test=input()
while test:
n=input()
print (pow(3,n,mod)+3*pow(-1,n))%mod
test-=1 |
Our Chef is very happy that his son was selected for training in one of the finest culinary schools of the world.
So he and his wife decide to buy a gift for the kid as a token of appreciation.
Unfortunately, the Chef hasn't been doing good business lately, and is in no mood on splurging money.
On the other hand, the b... | r, c = map(int, raw_input().split())
grid = []
ans = []
for i in range(r):
grid.append(map(int, raw_input().split()))
ans.append([0]*c)
m = min(grid[i])
for j in range(c):
if (grid[i][j] == m):
ans[i][j] += 1
grid = zip(*grid)
for i in range(c):
m = max(grid[i])
for j in range(r):
if (grid[i][j] ==m):... |
The state space of the output of this problem (and as a matter of fact, all the problems in this Cook-Off) is - 2 to the power T -
where T is the number of test cases (so be extra careful!). Each test case consists of T lines consisting of "YES" or "NO".
If a test case accurately represents the output that you would pr... | t=int(raw_input())
b=[]
l=[]
d=0
for i in xrange(0,t*t):
k=raw_input()
if(k[0]=='Y'):
d='1'
elif(k[0]=='N'):
d='0'
l.append(d)
if(i%t==t-1):
b.append(''.join(l))
l=[]
#print b
ans=0
for i in xrange(0,t):
f=1
for j in xrange(0,t):
if((b[i]==b[j] and b[i][j]=='0') or (b[i]!=b[j] and b[i][j]=='1')):
... |
A group of researchers are studying fish population in a natural system of lakes and rivers. The system contains n lakes connected by n - 1 rivers. Each river has integer length (in kilometers) and can be traversed in both directions. It is possible to travel between any pair of lakes by traversing the rivers (that is,... | #include <bits/stdc++.h>
using namespace std;
const int N = 100003;
int rd() {
int ch = getchar(), x = 0;
for (; ch < '0' || ch > '9'; ch = getchar())
;
for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return x;
}
template <typename T>
bool chmax(T &a, const T &b) {
if (a < b) return ... |
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a num... | #include <bits/stdc++.h>
using std::abs;
using std::array;
using std::cerr;
using std::cin;
using std::cout;
using std::generate;
using std::get;
using std::make_pair;
using std::make_tuple;
using std::map;
using std::max;
using std::max_element;
using std::min;
using std::min_element;
using std::pair;
using std::queue... |
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the boa... | b=int(input())
out=[1]
n=b
i=0
while n%2==0:
i=i+1
out.append(2**i)
n=int(n/2)
out1=[]
for i in range (1,int(n**0.5)+1,2):
if n%i==0:
out1.append(i)
out1.append(int(n/i))
out2=set()
for i in out:
for j in out1:
out2.add(i*j)
#print (out2)
print (len(out2))
|
In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far.
The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall.
Traditionally GUC has n professors. Each professor has his seniority lev... | #include <bits/stdc++.h>
using namespace std;
int n, m, ls[20], pref[20];
long long y, dp[100000];
long long count() {
fill(dp, dp + (1 << n), 0);
dp[0] = 1;
for (int mask = 0; mask < (1 << n); ++mask) {
if (dp[mask] == 0) continue;
int cnt = 0, tmp = mask;
while (tmp > 0) {
if (tmp & 1 == 1) cn... |
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 long long MOD = (long long)1e9 + 7;
const int N = 1e6 + 5, inf = 1e9 + 5;
long long add(long long x, long long y) {
x += y;
if (x >= MOD) return x - MOD;
return x;
}
long long sub(long long x, long long y) {
x -= y;
if (x < 0) return x + MOD;
return x;
}
l... |
You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9.
A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} … s_r. A substring s[l ... r] of s is called even if the number represented by it is even.
Find the number of even substrings of s. Note, that even if some subs... | n = int(input())
s = input()
k = 0
for i in range(1, n + 1):
d = int(s[i - 1])
if d % 2 == 0:
k += i
print(k)
|
You are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9.
You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digi... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, i;
cin >> n;
string s;
cin >> s;
long long int a[n], f[9];
for (i = 0; i < n; i++) {
a[i] = (int)(s[i] - '0');
}
for (i = 0; i < 9; i++) {
cin >> f[i];
}
int j = 0, k = 0, flag = 0;
for (i = 0; i < n; i++) {
if... |
Serge came to the school dining room and discovered that there is a big queue here. There are m pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him.
Initially t... | #include <bits/stdc++.h>
using namespace std;
using ll = long long int;
const int N = 1e6 + 5;
ll seg[6 * N];
ll lazy[6 * N];
ll qu(int node, int l, int r) {
if (lazy[node]) {
seg[node] += lazy[node];
if (l < r) {
lazy[2 * node] += lazy[node];
lazy[2 * node + 1] += lazy[node];
}
lazy[node]... |
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has n different matryoshkas. Any matryoshka is a figure of volume out_i with an empty space inside of volume in_i (of course, out_i > in_i).
You don't have much free spac... | #include <bits/stdc++.h>
using namespace std;
const int N = 200005;
struct Doll {
int out, in;
bool operator<(const Doll& b) const { return in < b.in; }
} a[N];
struct Edge {
int to, nxt, val;
Edge(int to = 0, int nxt = 0, int val = 0) : to(to), nxt(nxt), val(val) {}
} edge[N << 1];
int head[N], tot;
void add(i... |
Two large companies "Cecsi" and "Poca Pola" are fighting against each other for a long time. In order to overcome their competitor, "Poca Pola" started a super secret project, for which it has total n vacancies in all of their offices. After many tests and interviews n candidates were selected and the only thing left w... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 200010;
const long long INF64 = 1LL << 60;
int m, n;
pair<long long, int> a[MAXN], b[MAXN];
int v2[MAXN], ans[MAXN];
long long d[MAXN];
void update1(int l, int r, int id, long long val) {
if (l > r) return;
int L = (l + n - id) % n;
int R = (r + n - i... |
You have two strings a and b of equal even length n consisting of characters 0 and 1.
We're in the endgame now. To finally make the universe perfectly balanced, you need to make strings a and b equal.
In one step, you can choose any prefix of a of even length and reverse it. Formally, if a = a_1 a_2 … a_n, you can ch... | #include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
void solve() {
string S, t;
cin >> S >> t;
int n = S.size();
int a[2][2] = {};
int b[2][2] = {};
for (int i = 0; i < n; i += 2) {
a[S[i] - '0'][S[i + 1] - '0']++;
b[t[i] - '0'][t[i + 1]... |
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S.
You have to answer q independent test cases.
Input
The... | import java.io.*;
import java.util.*;
public class Solution {
static String solve(long a, long b, long n, long S) {
if (a * n + b < S) {
return "NO";
} else {
if (a * n > S) {
if (S % n <= b) {
return "YES";
} else {
return "NO";
}
} else {
return "YES";
}
}
}
priva... |
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.
Mr. Scrooge's signature can be represented as a polyline ... | #include <bits/stdc++.h>
using namespace std;
double absolute(int a, int b) {
cout << setprecision(20);
return sqrt(a * a + b * b);
}
int main() {
int n, k;
cin >> n >> k;
int a, b, pa = 0, pb = 0;
double len = 0;
for (size_t i = 0; i < n; i++) {
cin >> a >> b;
if (i != 0) len += absolute(abs(a - ... |
In this task Anna and Maria play the following game. Initially they have a checkered piece of paper with a painted n × m rectangle (only the border, no filling). Anna and Maria move in turns and Anna starts. During each move one should paint inside the last-painted rectangle a new lesser rectangle (along the grid lines... | #include <bits/stdc++.h>
using namespace std;
long long c[1005][1005];
int n, m, k;
void init() {
memset(c, 0, sizeof(c));
int i, j;
for (i = 0; i <= 1000; i++) {
c[i][0] = 1;
for (j = 1; j <= i; j++) {
c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % 1000000007;
}
}
}
int main() {
int i, j, k;
... |
You are given an array a of length n and array b of length m both consisting of only integers 0 and 1. Consider a matrix c of size n × m formed by following rule: c_{i, j} = a_i ⋅ b_j (i.e. a_i multiplied by b_j). It's easy to see that c consists of only zeroes and ones too.
How many subrectangles of size (area) k con... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class B {
static int N, M, K;
static int a[];
static int b[];
public static void main(String[] args) throws IOException {
BufferedReader br = new Buf... |
You are given two integers x and y. You can perform two types of operations:
1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation:
* x = 0, y = 6;
* x = 0, y = 8;
* x = -1, y = 7;
* x = 1, y = ... | def to_list(s):
return list(map(lambda x: int(x), s.split(' ')))
def solve(x,y,a,b):
cost = 0
if b <= 2*a:
min_val = min(x,y)
cost += b*min_val
x -= min_val
y -= min_val
max_val = max(x,y)
cost += max_val*a
else:
cost = (x+y)*a
print(cost)
... |
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.
An array a is a subarray of an array b if a can be obtained from b by deletion of several... | t = input()
for i in range(t):
n = input()
a = list(map(int,raw_input().split()))
b = set(a)
print len(b) |
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the sho... | import java.util.*;
import java.io.*;
public class B659 {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int pp = sc.nextInt();
outer: while (pp-- > 0) {
int n = sc.nextInt... |
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Learning {
static LinkedList<Integer>[] adj;
public static void main(String[] args) throws E... |
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and... | #include <bits/stdc++.h>
const int N = 2e5 + 10;
long long dp[N][5];
long long sum[N][5];
long long three[N] = {0};
const long long MOD = 1e9 + 7;
char s[N];
int main() {
three[0] = 1;
for (int i = 1; i < N; i++) three[i] = three[i - 1] * 3 % MOD;
int n, num = 0;
scanf("%d %s", &n, s + 1);
sum[0][0] = dp[0][0... |
The secondary diagonal of a square matrix is a diagonal going from the top right to the bottom left corner. Let's define an n-degree staircase as a square matrix n × n containing no squares above the secondary diagonal (the picture below shows a 5-degree staircase).
<image>
The squares of the n-degree staircase cont... | #include <bits/stdc++.h>
using namespace std;
priority_queue<pair<int, int> > q;
struct node {
int l, r, id;
} p[100010];
int n, m;
int x, y;
int cmp(const void* a, const void* b) { return ((node*)a)->l - ((node*)b)->l; }
int ans[100010];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scan... |
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_... | #include <bits/stdc++.h>
using namespace std;
#define FAST ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define int long long
#define F first
#define S second
#define pb push_back
#define sz(x) (int)x.size()
#define len(x) (int)x.length()
#define pii pair<int,int>
#define ppi pair<pii,int>
#define vi vector<... |
You are given a bipartite graph consisting of n_1 vertices in the first part, n_2 vertices in the second part, and m edges, numbered from 1 to m. You have to color each edge into one of two colors, red and blue. You have to minimize the following value: ∑ _{v ∈ V} |r(v) - b(v)|, where V is the set of vertices of the gr... | #include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
#define range(i, n) for(int i = 0; i < (n); ++i)
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define ar array
typedef long long ll;
using namespace std;
//using namespace __gnu_pbds;
const int INFi = 2e9 + 5;
cons... |
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The... | #include <bits/stdc++.h>
using namespace std;
#define int long long
void read (int &x) {
char ch = getchar(); x = 0; while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - 48, ch = getchar();
} const int N = 2e5 + 5, M = 2000, NN = N * 5;
int n, s, mx, a[N], res[M][M], sr, sb, sy, id[N];
pai... |
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of str... | #include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define ll long long
#define PII pair<int,int>
#define All(a) a.begin(),a.end()
using namespace std;
const int mx=2e5+5;
const int mxn=(1<<17)+5;
int n,k,pos[17][mx],dp[mxn];
char s[mx];
bool check(int mid) {
for(int i=0;i<k;i++) {
int cnt=0;
for(int j=n;j>=1;j--) {
... |
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. ... | n=int(input())
r=n+1
i=2
s=n**0.5
while i<=s:
if n%i==0:
r+=n//i
n//=i
s=n**0.5
i=1
i+=1
print(r) |
You are given a tree with n vertexes and n points on a plane, no three points lie on one straight line.
Your task is to paint the given tree on a plane, using the given points as vertexes.
That is, you should correspond each vertex of the tree to exactly one point and each point should correspond to a vertex. If two... | #include <bits/stdc++.h>
using namespace std;
struct pt {
int x, y, id;
};
vector<pt> p;
vector<vector<int> > g;
vector<int> size, ans;
int n;
int dfs(int v, int parent = -1) {
for (int i = 0; i < g[v].size(); i++) {
int to = g[v][i];
if (to == parent) continue;
size[v] += dfs(to, v);
}
return size[... |
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for ( int i = 1; i <= n; ++i )
a[i-1] = i;
f( a, n );
for ( int i = 0; i < n-1; ++i )
System.out.print( a[i] + " " );
... |
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format:
<protocol>://<domain>.ru[/<context>]
where:
* <protocol> can equal either "http" (without the quotes) or "ftp" (without the q... | import re
p = re.compile(r'(http|ftp)(.+)ru(.*)')
a = p.search(raw_input())
protocol, domain, context = a.groups()
address = protocol + '://' + domain + '.ru'
if context:
address += '/' + context
print address
|
You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode:
repeat ni times
yi := y
y := yi + 1
end repeat
Here y is a shared variable. Everything else is local for the process. All actions on a given row are a... | #include <bits/stdc++.h>
using namespace std;
const int N = 128;
int main() {
vector<int> vp, vl;
int n, w;
scanf("%d %d", &n, &w);
int CW = w;
int m[N];
for (int i = 0; i < n; i++) scanf("%d", &m[i]);
int sum = 0;
for (int i = 0; i < n; i++) sum += m[i];
if (w <= 0 || w > sum) {
printf("No\n");
... |
You have a rectangular n × m-cell board. Some cells are already painted some of k colors. You need to paint each uncolored cell one of the k colors so that any path from the upper left square to the lower right one doesn't contain any two cells of the same color. The path can go only along side-adjacent cells and can o... | #include <bits/stdc++.h>
using namespace std;
const int NS = 1111;
const int MOD = 1000000007;
int n, m, k;
int v[11], u[NS];
int s[NS][NS], a[NS][NS];
int one_num(int z) {
int cnt = 0;
for (; z > 0; z = z & (z - 1)) cnt++;
return cnt;
}
long long dfs(int x, int y) {
if (y > m) return dfs(x + 1, 1);
if (x > n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.