input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Cirno gave AquaMoon a chessboard of size 1 ร n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied.
In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if po... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
int T;
ll fac[N], inv[N];
const ll mod = 998244353;
ll qpow(ll x, ll y) {
ll ret = 1;
x %= mod;
while (y) {
if(y & 1) ret = ret * x % mod;
x = x * x % mod;
y >>= 1;
}
return ret;
}
... |
A club wants to take its members camping. In order to organize the event better the club directors decided to partition the members into several groups.
Club member i has a responsibility value ri and an age value ai. A group is a non-empty subset of club members with one member known as group leader. A group leader ... | #include <bits/stdc++.h>
using namespace std;
int n, m;
bool debug = false;
int k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
struct member {
int id;
int a, r, L, R;
bool operator<(const member b) const { return r < b.r; }
} mb[100005];
struct query {
int id;
int a, r, L, R;
bool operator<(const quer... |
One day the Codeforces round author sat exams. He had n exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2.
The author would need to spend too much time and effort to make the sum of his marks strictly more than k. That could have s... | import java.io.PrintWriter;
import java.util.Scanner;
public class Exams {
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = in.nextInt() , k = in.nextInt();
out.println(k < 3*n ? 3*n-k : "0");
... |
Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n + 1 points with coordinates (1, y1), (2, y2), ..., (2n + 1, y2n + 1), with the i-th segment connecting the point (i, yi) and the point... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, t;
cin >> n >> k;
int *a = new int[2 * n + 1];
for (int i = 0; i < (int)2 * n + 1; i++) cin >> a[i];
for (int i = 0; i < (int)2 * n + 1; i++) {
if (!((i + 1) % 2)) {
if (k && a[i] - a[i - 1] >= 2 && a[i] - a[i + 1] >= 2) {
... |
LiLand is a country, consisting of n cities. The cities are numbered from 1 to n. The country is well known because it has a very strange transportation system. There are many one-way flights that make it possible to travel between the cities, but the flights are arranged in a way that once you leave a city you will ne... | #include <bits/stdc++.h>
using namespace std;
int n, m, S[1000005], T[1000005], nxt[1000005], head[1000005], to[1000005],
rnxt[1000005], rhead[1000005], rto[1000005], dist[1000005], times[1000005],
adj[1000005], tot, rtot;
bool flag1[1000005], flag2[1000005], flag[1000005], inq[1000005];
int NXT[1000005], HEAD[... |
BerDonalds, a well-known fast food restaurant, is going to open a cafe in Bertown. The important thing is to choose the new restaurant's location so that it would be easy to get there. The Bertown road system is represented by n junctions, connected by m bidirectional roads. For each road we know its length. We also kn... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int a[100011 + 3], b[111000 + 3], w[111000 + 3], x[111000 + 3], y[111000 + 3];
int f[1001 + 3][1000 + 3];
double ans;
double work(int x, int y, int w) {
double ans = x + y + w;
if (abs(x - y) <= w) return double(ans / 2);
if (x > y) return x;
return y;
}
v... |
A motorcade of n trucks, driving from city ยซZยป to city ยซะยป, has approached a tunnel, known as Tunnel of Horror. Among truck drivers there were rumours about monster DravDe, who hunts for drivers in that tunnel. Some drivers fear to go first, others - to be the last, but let's consider the general case. Each truck is de... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
map<int, int> ma[maxn];
int f[maxn], pre[maxn];
int num[maxn];
int n, v, c, l, r;
int ans = 0, sum = 0;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d%d%d%d", &v, &c, &l, &r);
if (!l || ma[l].count(c + r)) {
... |
Let's introduce the designation <image>, where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc.
We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, string... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse4")
using namespace std;
const int maxn = 111;
int occ[maxn], en[maxn];
int main() {
int b, d;
scanf("%d %d", &b, &d);
string a, c;
cin >> a >> c;
for (int e = 0; e < c.size(); e++) {
int cur_c = e;
int qtd = 0;
for (int cu... |
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly,... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000009;
long long tpot(int e) {
if (e == 0) return 1;
int sq = 0;
while (e && e % 2 == 0) {
e /= 2;
sq++;
}
if (sq == 0) {
return (2 * tpot(e - 1)) % MOD;
}
long long tpl = tpot(e);
for (int i = 0; i < sq; i++) tpl = (tp... |
Levko loves strings of length n, consisting of lowercase English letters, very much. He has one such string s. For each string t of length n, Levko defines its beauty relative to s as the number of pairs of indexes i, j (1 โค i โค j โค n), such that substring t[i..j] is lexicographically larger than substring s[i..j].
Th... | #include <bits/stdc++.h>
using namespace std;
template <class T>
string tostring(T x) {
ostringstream out;
out << x;
return out.str();
}
long long toint(string s) {
istringstream in(s);
long long x;
in >> x;
return x;
}
int dx[8] = {0, 0, 1, -1, 1, 1, -1, -1};
int dy[8] = {1, -1, 0, 0, -1, 1, -1, 1};
int ... |
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (xโ1, y), (x, y + 1) and (x, yโ1).
Iahub wants to know how many ... | """
โโโ โโโโโโโ โโโ โโโโโโโ โโโโโโโ โโโ โโโโโโ
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโ โโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโ โโโโโโ โโโโโโโ โโโโโโโโโ โโโ โโโโโโโ
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโ โโโโโโโ
โโโ โโโโโโโ โโโ โโโโโโโโ โโโโโโโ โโโ โโโโโโ
""" ... |
Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number 0 has a robot.
The robot has instructions โ the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Befo... | import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
Outpu... |
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | n, k = [int(x) for x in input().split()]
pros = [int(x) for x in input().split()]
teams=0
for i in range(n):
z = pros[i]+k
if z <= 5:
teams+=1
print(int(teams/3)) |
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.
The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ... | n,m = map(int, input().split())
s=0
for i in range(n):
s+=(i+1)*(pow((i+1)/n,m)-pow(i/n,m))
print(s) |
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a].
By <image> we denote the quotient of integer division of... | import sys
import math
MAXNUM = math.inf
MINNUM = -1 * math.inf
ASCIILOWER = 97
ASCIIUPPER = 65
MODMAX = 1000000007
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
... |
Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, th... | def read():
day, sumTime = map(int,raw_input().split())
schedule = []
for i in range(day):
schedule.append(map(int,raw_input().split()))
return day,sumTime,schedule
def rec(day,sumTime,schedule,vis,ans):
if day<0: return sumTime==0
if sumTime<0: return False
if vis[day][sumTime]: ... |
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ro... | from collections import Counter
n = input()
s = raw_input()
cnt = 0
keys = Counter()
for i in range(n * 2 - 2):
if i % 2 == 1:
key_needed = s[i].lower()
if key_needed in keys:
keys[key_needed] -= 1
if keys[key_needed] == 0:
del keys[key_needed]
else:
... |
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must b... | vet = []
aux = []
cont = 0
def fa(i, f):
global aux, cont
if i<=f:
aux.append(vet[i])
#print(aux, menor, sum(aux), maior, max(aux), min(aux), diff)
if len(aux) >=2 and menor<=sum(aux)<=maior and max(aux) - min(aux)>=diff:
#print('Entrei', aux)
cont+=1
for ... |
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.
Petya can ask questions like: "Is the unknown number divisible by number y?".
The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int h;
cin >> h;
if (h < 2) {
cout << "0";
return 0;
}
int l = 0, i, j;
vector<int> v, o;
v.push_back(2);
for (i = 3; i < 1000; i++) {
l = 0;
for (j = 2; j < i; j++) {
if (i % j == 0) {
l++;
}
}
if (l ... |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | s = raw_input()
if sum(map(str.islower, s)) < sum(map(str.isupper, s)):
print s.upper()
else:
print s.lower()
|
The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.
The New Year tree is an undirected tree with n vertices and root in the vertex 1.
You should process the queries of the two types:
1. Chan... | #include <bits/stdc++.h>
using namespace std;
int n, q;
vector<int> colors, first, last, euler_tour;
vector<bool> visit;
vector<vector<int> > ady;
void tour(int x) {
if (visit[x]) return;
visit[x] = true;
euler_tour.push_back(x);
first[x] = euler_tour.size() - 1;
for (int i : ady[x]) {
tour(i);
}
last... |
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.
Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and dif... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 1e5;
double mx[MaxN];
double mn[MaxN];
double a[MaxN];
double b[MaxN];
int main() {
int n;
std::ios_base::sync_with_stdio(false);
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%lf", &mx[i]);
}
for (int i = 0; i < n; ++i) {
scanf(... |
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 ร n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed h... |
def readints():
return map(int,raw_input().split())
n=input()
x=readints()
def main():
f=1
for i in xrange(n):
c=x[i]
nf=1
for k in xrange(i-1,-1,-1):
if c<x[k]:break
c=x[k]
nf+=1
c=x[i]
for k in xrange(i+1,n):
if c<x[... |
Heidi got tired of deciphering the prophecy hidden in the Tree of Life and decided to go back to her headquarters, rest a little and try there. Of course, she cannot uproot the Tree and take it with her, so she made a drawing of the Tree on a piece of paper. On second thought, she made more identical drawings so as to ... | #include <bits/stdc++.h>
using namespace std;
const int seed = 999983;
inline int read() {
int n = 0, f = 1;
char c;
for (c = getchar(); c < '0' || c > '9'; c = getchar())
if (c == '-') f = -1;
for (; c >= '0' && c <= '9'; c = getchar()) n = n * 10 + c - '0';
return n * f;
}
int sz[105], bj[105], n;
unsig... |
ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of n ร m rooms, and the rooms are arranged in n rows (numbered from the top to the bottom starting from 1) and m columns (numbered from the left to the right starting from 1). The room in the i-th row and j-th column is den... | #include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void smin(T &a, const U &b) {
if (a > b) a = b;
}
template <typename T, typename U>
inline void smax(T &a, const U &b) {
if (a < b) a = b;
}
template <class T>
inline void gn(T &first) {
char c, sg = 0;
while (c = getchar(), ... |
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately.
Organizers are stil... | n = int(input())
an = 0
a = 1
b = 0
c = 2
while(n >= c):
b = a
a = c
c = a + b
an+=1
print(an) |
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture:
<image>
Petr ... | def read_input():
line = input().strip().split()
m = int(line[0])
week = int(line[1])
days31 = {1,3,5,7,8,10,12}
if m == 2:
days = 28
elif m in days31:
days = 31
else:
days = 30
z = (days + week - 1)
return z//7 if z % 7 == 0 else z//7 + 1
if __name__ == "__m... |
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil cor... | #include <bits/stdc++.h>
using namespace std;
const int Maxn = 200005;
vector<int> eul, G[Maxn];
int vis[Maxn];
void dfs(int u) {
vis[u] = 1;
eul.push_back(u);
for (int v : G[u]) {
if (vis[v] == 0) {
dfs(v);
eul.push_back(u);
}
}
}
int main() {
int n, m, k;
cin >> n >> m >> k;
for (int... |
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 5;
const long long MOD = 1e9 + 7;
long long dp[MAXN];
int main() {
dp[0] = 0LL;
dp[1] = 1LL;
for (int(i) = (2); (i) < (MAXN); (i)++) {
dp[i] = (dp[i - 1] * 2LL + 1LL) % MOD;
}
string s;
cin >> s;
int a_ctr = 0, b_ctr = 0;
long long... |
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d... | n=int(input())
#L=["Sheldon","Leonard","Penny","Rajesh","Howard"]
i=1
val=5
while n>val:
if i%2==0 or i==1:
n=n-5*i
val=2*val
i=2*i
if 1<=n<=i:
print("Sheldon")
elif i<=n<=2*i:
print("Leonard")
elif 2*i<=n<=3*i:
print("Penny")
elif 3*i<=n<=4*i:
print("Rajesh")
elif 4*i<=n<=5*i:
print("Howard")
|
Mojtaba and Arpa are playing a game. They have a list of n numbers in the game.
In a player's turn, he chooses a number pk (where p is a prime number and k is a positive integer) such that pk divides at least one number in the list. For each number in the list divisible by pk, call it x, the player will delete x and a... | #include <bits/stdc++.h>
using namespace std;
const long long oo = 1000000000000000000;
const int N = 1000006;
long long v[N];
map<int, int> dp;
int mex(const set<int> &s) {
int ans = 0;
while (s.count(ans)) ans++;
return ans;
}
int g(int bit) {
if (dp.count(bit)) return dp[bit];
int lg = 31 - __builtin_clz(b... |
Alexey recently held a programming contest for students from Berland. n students participated in a contest, i-th of them solved ai problems. Now he wants to award some contestants. Alexey can award the students with diplomas of three different degrees. Each student either will receive one diploma of some degree, or won... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
struct node {
int a;
int id;
} s[N];
int ans[N];
int st[N][30];
bool cmp(node a, node b) { return a.a > b.a; }
int calc(int i) { return s[i].a - s[i + 1].a; }
int Query(int L, int R) {
if (L > R) return -1;
int d = log(R - L + 1) / log(2.0);
... |
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.
Visitors are more likely to buy a pair of shovels if their total cost ends with severa... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Created by Pranav ps on 16-12-2017.
*/
/**
* This is the template for all coding problems
*/
pub... |
Today the North Pole hosts an Olympiad in a sport called... toy igloo skyscrapers' building!
There are n walruses taking part in the contest. Each walrus is given a unique number from 1 to n. After start each walrus begins to build his own igloo skyscraper. Initially, at the moment of time equal to 0, the height of th... | #include <bits/stdc++.h>
using namespace std;
struct line {
long long int a, b, id;
line() { a = b = id = 0; }
line(long long int i, long long int j) : a(i), b(j) {}
line(long long int i, long long int j, long long int k) : a(i), b(j), id(k) {}
long long int value_at(long long int x) { return a * x + b; }
b... |
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift โ a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden.
Each day, every pile w... | #include <bits/stdc++.h>
using namespace std;
long long sum, x, n, k;
long long arr[123456];
long long t[123456];
long long cum[123456];
long long ans[123456];
long long res[123456];
long long bs() {
int s = 0, e = n, mid;
while (s < e) {
mid = (s + e + 1) / 2;
if (x >= cum[mid] - sum)
s = mid;
el... |
You are given a sequence a1, a2, ..., an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj.
Segment [l1, r1] lies within segment [l2, r2] iff l1 โฅ l2 and r1 โค r2.
Print indices i and j. If there are multiple answers, print a... | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solv... |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | money=int(input())
number=0
alist=[100,20,10,5,1]
for i in alist:
number+=money//i
money=money%i
print(int(number)) |
Today RK has to transport his N items of different weights(in calories) to a near city but before that he wants to make sure that the weights of all items are balanced. In order to check this he puts all items on the weight scale and found that weights are not balanced actually. So to deal with it RK designed his own p... | gcd = lambda a,b: gcd(b, a%b) if a%b else b
for _ in range(int(raw_input())):
n = int(raw_input())
num = map(int, raw_input().split())
ans = num[0]
for i in num[1:]:
ans = gcd(i, ans)
if ans == 1:
break
print ans*n |
This question is straight-forward.
Given length L cm and breadth B cm of a rectangular cardboard. You need to cut out the circles of diameter D cm from it. Find out the maximum number of circles you can cut out from it.
Since the value can be very large, give your answer in mod 10^9 + 7
Input:
First line of input co... | from math import pi,floor
t=int(raw_input())
for qq in xrange(t):
l,b,d=map(long,raw_input().split())
print ((l/d) * (b/d)) % (10**9+7) |
Problem:
Black and White are playing a game of chess on a chess board of n X n dimensions. The game is nearing its end. White has his King and a Pawn left. Black has only his King left. So, definitely Black cannot win the game. However, Black can drag the game towards a draw, and, he can do this only if he captures Wh... | tc = int(raw_input())
while tc:
n,a,b,c,d,move = map(int,raw_input().split())
if c + move < a or abs (d - b) > n + move - a: print "White Wins"
else: print "Draw"
"""
if a<=n and b<=n and c<=n and d<=n:
while 1:
if move == 0:
if c==a and d==b:
print"Draw"
break
if a<n:
a = a + 1
els... |
Ashu and Shanu are best buddies. One day Shanu gives Ashu a problem to test his intelligence.He gives him an array of N natural numbers and asks him to solve the following queries:-
Query 0:- modify the element present at index i to x.
Query 1:- count the number of even numbers in range l to r inclusive.
Query 2:- cou... | import math
n = int(raw_input())
arr = map(int,raw_input().split())
q = int(raw_input())
#tree stores count of odd number
height = int(math.ceil(math.log(n,2)))
tn = int(math.pow(2,height))
tree = [0]*(2*tn)
# print 2*tn
def buildSegTree(node,l,r,arr):
if l==r:
tree[node] = arr[l]%2
else:
mid = (l+r)/2
buildS... |
Lucky numbers are those numbers which contain only "4" and/or "5". For example 4, 5, 44, 54,55,444 are lucky numbers while 457, 987 ,154 are not.
Lucky number sequence is one in which all lucky numbers exist in increasing order for example 4,5,44,45,54,55,444,445,454,455...
Now we concatenate all the lucky number... | from itertools import product
import sys
data = sys.stdin.read().splitlines()
def main():
global data
test_cases = int(data.pop(0).strip())
digit_tot = []
index = 1
prev_val = 2
digit_tot.append(prev_val)
while prev_val < 1000000000000000:
index += 1
cur_val = index * 2 ... |
Navi is a CEO of a famous IT based software company. He is hiring some new developers to work in his company. He already know the number of new projects and number of hirings at particular timestamp. He will assign one project to one developer and that developer will work alone on that project . Your task is to help Na... | t = input()
for _ in range(t):
n = input()
developers = 0
answer = 0
for _ in range(n):
i = raw_input().strip()
if len(i) > 1 and developers == 0:
answer += 1
elif len(i) > 1 and developers:
developers -= 1
else:
developers += int(i)
... |
Oz is in love with number theory, so he expects you to love it too and solve his problems. The current problem which has been given by Oz to you is in the form of an array. So, he has given you N integers i.e a1,a2,..,aN to deal with. You have to find the number of divisors of the product of all these integers.
Input... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
from math import sqrt
N=int(raw_input())
ip=[int(i) for i in raw_input().strip().split()]
mdic={}
for i in ip:
q=i
try:
mdic[i][0]+=1
continue
except:
pass
dic={}
while not i... |
Madhav and Riya were getting bored. So they decided to play a game.
They placed N pencils in a line. Madhav starts to sharpen pencil from left to right, and Riya from right to left.
For each pencil, its length is known.
Madhav sharpens with speed twice that of Riya. If a player starts to sharpen the pencil, other pla... | t=int(raw_input())
for s in range(0,t):
no=int(raw_input())
l=map(int,raw_input().split())
if no==1:
print "1 0"
else:
m=0
n=0
x=0
y=0
for i in xrange(0,no):
if m<=n:
m+=l[x]/2.0
x+=1
else:
n+=l[no-1-y]
y+=1
print x,y |
In a village far far away, lived a farmer named Zico. He was finding it difficult to make his two ends meet and hence, approached the god of grains, Azure. Azure granted him a blessing:
"I shall grant thou P units of food initially . After every year, thou shall come to me and the food units shall increase by a valu... | t=int(raw_input())
for i in range(t):
p,m=map(int,raw_input().split())
print 2*(p+m) |
Xenny and his girlfriend were staying in a metropolitan city. His girlfriend, being an outgoing person, wanted to visit all streets in the city. However, she used to get bored quickly and hence she wanted to visit every street exactly once.
The city had M streets and N junctions. Given information about the city's layo... | for _ in range(input()):
a,b = map(int,raw_input().split())
c = [0]*(a+1)
counter = 0
for _ in range(b):
u,v = map(int,raw_input().split())
c[u]+=1
c[v]+=1
for u in range(1,a+1):
if c[u]&1:
counter+=1
if counter == 0 or counter == 2:
print "Yes"
else:
print "No" |
We have N bulbs arranged on a number line, numbered 1 to N from left to right. Bulb i is at coordinate i.
Each bulb has a non-negative integer parameter called intensity. When there is a bulb of intensity d at coordinate x, the bulb illuminates the segment from coordinate x-d-0.5 to x+d+0.5. Initially, the intensity o... | #include <bits/stdc++.h>
using namespace std;
signed main(){
int n,k;cin>>n>>k;
vector<int> v(n);
for(int i=0;i<n;i++)cin>>v[i];
while(k--){
vector<int> w(n+1,0);
for(int i=0;i<n;i++){
int l=max(0,i-v[i]),r=min(n-1,i+v[i]);
w[l]++;w[r+1]--;
}
for(int i=0;i<n;i++)v[i]=w[i],w[i+1]+=w[... |
After being invaded by the Kingdom of AlDebaran, bombs are planted throughout our country, AtCoder Kingdom.
Fortunately, our military team called ABC has managed to obtain a device that is a part of the system controlling the bombs.
There are N bombs, numbered 1 to N, planted in our country. Bomb i is planted at the ... | #include<iostream>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
int N,M;
int A[1<<17];
bool used[2<<17];
int cnt[1<<17];
int take[1<<17],rgt[1<<17];
int main()
{
cin>>N>>M;
vector<pair<int,int> >AB(N);
for(int i=0;i<N;i++)
{
cin>>AB[i].first>>AB[i].second;
}
sort(AB.begin(),AB.end());... |
Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.
A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K poi... | """
SpeedForces
Ah shit here we go again
"""
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def solve():
n,k,q = vv()
... |
Snuke has N integers: 1,2,\ldots,N. He will choose K of them and give those to Takahashi.
How many ways are there to choose K consecutive integers?
Constraints
* All values in input are integers.
* 1 \leq K \leq N \leq 50
Input
Input is given from Standard Input in the following format:
N K
Output
Print the a... | import java.io.*;
import java.util.*;
public class Main {
private static InputStream is;
private static PrintWriter out;
private static String INPUT = "";
void solve() {
int n = ni(), k = ni();
out.println(n - k + 1);
}
public static void main(String[] args) throws Exception {... |
For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from the top and the (c+1)-th column from the left. A good coloring of this grid using K colors is a coloring that satisfies the following:
* Each square is painted in one of the K colors.
* Each of the K colors is used for some squares.
* Let us... | #include<bits/stdc++.h>
#define fo(i, x, y) for(int i = x, B = y; i <= B; i ++)
#define ff(i, x, y) for(int i = x, B = y; i < B; i ++)
#define fd(i, x, y) for(int i = x, B = y; i >= B; i --)
#define ll long long
#define pp printf
#define hh pp("\n")
using namespace std;
int n, k, m = 500;
int main() {
scanf("%d", &... |
Takahashi loves walking on a tree. The tree where Takahashi walks has N vertices numbered 1 through N. The i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
Takahashi has scheduled M walks. The i-th walk is done as follows:
* The walk involves two vertices u_i and v_i that are fixed beforehand.
* Takahashi wi... | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define REP(i,a,b) for(int i=(a),_end_=(b);i<=_end_;i++)
#define DREP(i,a,b) for(int i=(a),_end_=(b);i>=_end_;i--)
#define EREP(i,u) for(int i=start[u];i;i=e[i].next)
#define fi first
#define se second
#define mkr(a,b) make_pair(a,b)
#define SZ(A) ((int)... |
Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so ... | #include <bits/stdc++.h>
using namespace std;
#define lli long long int
#define REP(i,s,l) for(lli i=s;i<l;i++)
#define MOD 1000000007
#define DEBUG 0
#define INF (1LL<<50)
signed main(){
lli n;
cin>>n;
vector<lli> a(n);
lli num=-1;
lli index=-1;
REP(i,0,n){
cin>>a[i];
if(num <= abs(a[i])){
num =... |
There are two rooted trees, each with N vertices. The vertices of each tree are numbered 1 through N. In the first tree, the parent of Vertex i is Vertex A_i. Here, A_i=-1 if Vertex i is the root of the first tree. In the second tree, the parent of Vertex i is Vertex B_i. Here, B_i=-1 if Vertex i is the root of the sec... | #include <iostream>
#include <cstdio>
#define IsDigit(x) ((x) >= '0' && (x) <= '9')
using namespace std;
int n, pos;
int last[200001], parity[200001], cross_edge[100001];
struct Edge{
int y, prev, dir;
}edge[600000];
int Read(void)
{
int c, ret(0);
bool sign(false);
c = getchar();
while (!IsDigit(c) && c != '... |
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they wi... | #include<bits/stdc++.h>
using namespace std;
const int N=3005;
int n,tot,a[N],lnk[N],son[N<<1],nxt[N<<1]; bool win[N];
void add(int x,int y) {
nxt[++tot]=lnk[x],lnk[x]=tot,son[tot]=y;
}
void dfs(int x,int p) {
win[x]=0;
for (int j=lnk[x]; j; j=nxt[j]) {
if (son[j]==p) continue;
if (a[x]>a[son[j]]) {
dfs(son[j... |
You are going to take the entrance examination of Kyoto University tomorrow and have decided to memorize a set of strings S that is expected to appear in the examination. Since it is really tough to memorize S as it is, you have decided to memorize a single string T that efficiently contains all the strings in S.
You ... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef int _loop_int;
#define REP(i,n) for(_loop_int i=0;i<(_loop_int)(n);++i)
#define FOR(i,a,b) for(_loop_int i=(_loop_int)(a);i<(_loop_int)(b);++i... |
There are n vertical lines in the Amidakuji. This Amidakuji meets the following conditions.
* Draw a horizontal line right next to it. Do not pull diagonally.
* Horizontal lines always connect adjacent vertical lines. In other words, the horizontal line does not cross the vertical line.
* For any vertical line, horizo... | #include <vector>
#include <iostream>
class level {
int num;
int size;
int to_b(const int &n) {
if (n == 0)
return 0;
else
return (to_b(n / 10) << 1) + (n % 10);
}
public:
int test(const int &n) {
return (((num << (n + 1)) >> size) & 1) - (((num << n) >> size) & 1);
}
level(const int &n = 0, const i... |
You finally got a magic pot, an alchemy pot. You can create a new item by putting multiple items in the alchemy pot. Newly created items can also be placed in alchemy pots to make other items. A list of items needed to make an item will be called an alchemy recipe. The following three are examples of alchemy recipes.
... | #include <bits/stdc++.h>
using namespace std;
struct material
{
int price;
vector<string> need;
};
void solve(int);
int main()
{
int n;
while (cin >> n, n){
solve(n);
}
return 0;
}
void solve(int n)
{
int m;
map<string, material> mmap;
for (int i = 0; i < n; i++){
... |
I am a craftsman specialized in interior works. A customer asked me to perform wiring work on a wall whose entire rectangular surface is tightly pasted with pieces of panels. The panels are all of the same size (2 m in width, 1 m in height) and the wall is filled with an x (horizontal) by y (vertical) array of the pane... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<P,P> PP;
const ll MOD = 1000000007;
const int IINF = INT_MAX;
const ll LLINF = LLONG_MAX;
const int MAX_N = int(1e5 + 5);
const double EPS = 1e-10;
const int di[] = {0, 1, 0, -1}, dj[] = {1, 0, -1, 0};
#define REP... |
You are a manager of a prestigious soccer team in the JOI league.
The team has $N$ players numbered from 1 to $N$. The players are practicing hard in order to win the tournament game. The field is a rectangle whose height is $H$ meters and width is $W$ meters. The vertical line of the field is in the north-south direc... | #include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<functional>
#define PAIR pair<int,int>
using namespace std;
class point{
public:
vector<long long> dp;
long long fast;
point(){
dp.resize(5,((long long)1<<63)-1);
fast = 10000000;
}
};
int H,W;
long long A,B... |
The city of Kyoto is well-known for its Chinese plan: streets are either North-South or East-West. Some streets are numbered, but most of them have real names.
Crossings are named after the two streets crossing there, e.g. Kawaramachi-Sanjo is the crossing of Kawaramachi street and Sanjo street. But there is a problem:... | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
#define D10 fixed<<setprecision(10)
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef ... |
The sequence of n - 1 consecutive composite numbers (positive integers that are not prime and not equal to 1) lying between two successive prime numbers p and p + n is called a prime gap of length n. For example, (24, 25, 26, 27, 28) between 23 and 29 is a prime gap of length 6.
Your mission is to write a program to c... | // AOJ 1276
#include <iostream>
using namespace std;
bool prime[2000000];
void makeprime()
{
fill(prime, prime + 2000000, true);
prime[0] = prime[1] = false;
for (int i = 4; i < 2000000; i+=2) prime[i] = false;
for (int i = 3; i*i <= 2000000; i += 2){
if (prime[i]){
for (int j = i*2; j < 2000000; j += i){
... |
Parentheses Editor
You are working with a strange text editor for texts consisting only of open and close parentheses. The editor accepts the following three keys as editing commands to modify the text kept in it.
* โ(โ appends an open parenthesis (โ(โ) to the end of the text.
* โ)โ appends a close parenthesis (โ)โ) ... | #include<bits/stdc++.h>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define mp make_pair
#define pb push_back
#define pii pair<int,int>
#define pll pair<LL,LL>
#define x first
#define y second
#define pi acos(-1)
#define sqr(x) ((x)*(x))
#define pdd pair<double,double>
#define MEMS(x) memse... |
<!--
Problem B
-->
On-Screen Keyboard
You are to input a string with an OSK (on-screen keyboard). A remote control with five buttons, four arrows and an OK (Fig. B-1), is used for the OSK. Find the minimum number of button presses required to input a given string with the given OSK.
<image> Fig. B-1 Remote control... | # coding=utf-8
###
### for python program
###
import sys
import math
# math class
class mymath:
### pi
pi = 3.14159265358979323846264338
### Prime Number
def pnum_eratosthenes(self, n):
ptable = [0 for i in range(n+1)]
plist = []
for i in range(2, n+1):
if ptable... |
Some people like finishing computer games in an extremely short time. Terry A. Smith is one of such and prefers role playing games particularly.
He is now trying to find a shorter play for one of the key events in a role playing game. In this event, a player is presented a kind of puzzle on a grid map with three rocks... | #include <iostream>
#include <cstdio>
#include <vector>
#include <list>
#include <cmath>
#include <fstream>
#include <algorithm>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <complex>
#include <iterator>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <stack>
#include <cli... |
Taro is a member of a programming contest circle. In this circle, the members manage their schedules in the system called Great Web Calender.
Taro has just added some of his friends to his calendar so that he can browse their schedule on his calendar. Then he noticed that the system currently displays all the schedule... | #include <stdio.h>
#include <algorithm>
using namespace std;
#define rep(i, n) for(int i=0; i<(int)(n); i++)
inline double sq(double a) { return a*a; }
int N, M;
double L[40], A[40], B[40];
int main() {
scanf("%d%d", &N, &M);
rep(i, N) scanf("%lf%lf%lf", L+i, A+i, B+i);
double ans = 0;
const int nn = ... |
One day, during daily web surfing, you encountered a web page which was written in a language you've never seen. The character set of the language was the same as your native language; moreover, the grammar and words seemed almost the same. Excitedly, you started to "decipher" the web page. The first approach you tried... | #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
#define MAX 405
#define NUM 1005
typedef pair<int,int> P; //firstใฏๆ็ญ่ท้ขใsecondใฏ้ ็นใฎ็ชๅท
//่พบใ่กจใๆง้ ไฝ{่กๅ
ใๅฎน้... |
Ievan Ritola is a researcher of behavioral ecology. Her group visited a forest to analyze an ecological system of some kinds of foxes.
The forest can be expressed as a two-dimensional plane. With her previous research, foxes in the forest are known to live at lattice points. Here, lattice points are the points whose x... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
typedef long long int ll;
#define BIG_NUM 2000000000
using namespace std;
struct Info1{
Info1(int arg_x,int arg_y,int arg_w){
x = arg_x;
y = arg_y;
w = arg_w;
}
bool operator<(const struct Info1 &arg) ... |
A: My Number-My Number-
problem
I'm sorry! Late late!
Ah! I'm starting to work for this company I've been longing for today!
Even so, I've been oversleeping since the first day ...! ??
Today is an important day when I have to tell my number to the company ...!
I think everyone knows, but I'll explain my number fo... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import array
def is_valid_number(sequence):
q = lambda n: (n + 1) if 1 <= n <= 6 else (n - 5)
sum_pq = 0
for index in range(1, 12):
sum_pq += sequence[index] * q(index)
rem_pq = sum_pq % 11
check_digit = 0 if rem_pq <= 1 else (11 - rem_pq)
... |
Alice: "Hi, Bob! Let's play Nim!"
Bob: "Are you serious? I don't want to play it. I know how to win the game."
Alice: "Right, there is an algorithm to calculate the optimal move using XOR. How about changing the rule so that a player loses a game if he or she makes the XOR to $0$?"
Bob: "It sounds much better now, but ... | #include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <unordered_map>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
int main... |
Problem
There are $ n $ rectangles on the $ xy $ plane with $ x $ on the horizontal axis and $ y $ on the vertical axis. The $ i $ th rectangle is $ h_i $ in height and $ 1 $ in width, and the vertices are point $ (i-1, 0) $, point $ (i-1, h_i) $, and point $ (i, h_i). ) $, Point $ (i, 0) $.
You choose $ n $ positive ... | #include<bits/stdc++.h>
using namespace std;
int main(){
auto S = [](long a, long b, long h){
a -= h;
b -= h;
if(a * b >= 0){
return abs(a + b) / static_cast<long double>(2);
}else{
return (a * a + b * b) / static_cast<long double>(2 * (abs(a) + abs(b)));
... |
For given two lines s1 and s2, print "2" if they are parallel, "1" if they are orthogonal, or "0" otherwise.
s1 crosses points p0 and p1, and s2 crosses points p2 and p3.
Constraints
* 1 โค q โค 1000
* -10000 โค xpi, ypi โค 10000
* p0 โ p1 and p2 โ p3.
Input
The entire input looks like:
q (the number of queries)
1st... | #include <iostream>
#include <cmath>
#include <utility>
#define EPS 1e-10
using namespace std;
int main(void){
pair<double, double> p0, p1, p2, p3;
int n;
cin >> n;
while(n--){
cin >> p0.first >> p0.second;
cin >> p1.first >> p1.second;
cin >> p2.first >> p2.second;
c... |
Write a program which manipulates a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ by the following operations:
* min($b, e$): report the minimum element in $a_b, a_{b+1}, ..., a_{e-1}$
* max($b, e$): report the maximum element in $a_b, a_{b+1}, ..., a_{e-1}$
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a... | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long int ll;
int main(){
vector<ll> v;
int n, q;
ll t, r;
int c, b, e;
scanf("%d", &n);
for (int i = 0; i < n; i++){
scanf("%lld", &t);
v.push_back(t);
}
scanf("%d", &q);
auto... |
Geek Sundaram is extremely anxious. He is in a hectic schedule. He has to study for his assessment the next day, watch FRIENDS tv show (in spite of watching every episode more than 5 times.. :P ), prepare questions for the programming contest and also complete his projects. So his friends try to calm him down by advisi... | for _ in range(input()):
a=map(int,raw_input().split())
s=sum(a)-a[4]
print 'YES' if s<=a[4] else 'NO' |
Chef wants to hire a new assistant. He published an advertisement regarding that in a newspaper. After seeing the advertisement, many candidates have applied for the job. Now chef wants to shortlist people for the interviews, so he gave all of them one problem which they must solve in order to get shortlisted.
The pro... | from math import *
def lcm(n):
x,c, t,f= 1,0,0,False
while (n%2 == 0):
c+=2**t
f = True
t+=1
n = n/2
if f == True:
x = c+2**t
i = 3
while i<=sqrt(n):
f = False
c = 0
t = 0
while (n%i == 0):
f = True
c+=i*... |
This summer, there is a worldwide competition being held in Chef Town and some of the best chefs of the world are participating. The rules of this competition are quite simple.
Each participant needs to bring his or her best dish. The judges will initially assign a score to each of the dishes. Now, several rounds wil... | #!/usr/bin/env python
import sys
parent = None
#child = dict()
def find_set(x):
global parent
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return parent[x]
T = int(sys.stdin.readline())
while T > 0:
N = int(sys.stdin.readline())
S = map(int, sys.std... |
The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.
Input
The input begins with two positive integ... | # cook your code here
n,k=map(int,raw_input().split())
count=0
for i in range(0,n):
if (int(raw_input()))%k==0:
count+=1
print count |
At the function of Republic day at NIT Agartala the warden of hostel has to visit the ground and
check the arrangement of the chairs for guests.
In the ground of NIT Agartala all the chairs are arranged in N rows and M columns.
Warden has to check that in each row all the chairs must have same color and adjacent rows ... | # your code goes here
m,n = map(int,raw_input().split())
a = []
for _ in range(m):
a.append(map(int,raw_input().split()))
flag = 1
for i in range(m):
for j in range(n):
if j > 0:
if a[i][j-1] != a[i][j]:
flag = 0
break
if i > 0:
if a[i-1][j] == a[i][j]:
flag = 0
break
if flag == 0:
br... |
Sereja is playing a game called Winner Eats Sandwich with his friends. There are N persons in total, including Sereja. Sereja is allotted the number 1, while his friends are allotted numbers from 2 to N. A set of this game consists of M parts. Probability that a player numbered i wins part j of any set is p[i][j]. Sere... | from operator import mul
parse = lambda: [25*i for i in map(float, raw_input().split())]
for _ in xrange(int(raw_input())):
n, m = map(int, raw_input().split())
num = reduce(mul, parse())
den = num
for _ in xrange(n - 1):
den += reduce(mul, parse())
if num == 0:
den = 1
print '%.6f' % (num/den) |
You are given an array a consisting of n integers, and q queries to it. i-th query is denoted by two integers l_i and r_i. For each query, you have to find any integer that occurs exactly once in the subarray of a from index l_i to index r_i (a subarray is a contiguous subsegment of an array). For example, if a = [1, 1... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int a[500005], vis[500005], nx[500005];
struct nod {
int r, id;
};
vector<nod> enq[500005];
int ans[500005];
int mx[2000005], pos[2000005];
void jia(int now, int l, int r, int ai, int v) {
if (l == r) {
mx[now] = v;
pos[now] = l;
return;
}
int ... |
There are n startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup.
The following steps happen ... | #include <bits/stdc++.h>
struct {
inline operator int() {
int x;
return scanf("%d", &x), x;
}
inline operator long long() {
long long x;
return scanf("%lld", &x), x;
}
template <class T>
inline void operator()(T &x) {
x = *this;
}
template <class T, class... A>
inline void operator... |
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so s... | #include <bits/stdc++.h>
int N, alf[26];
long long ans;
std::string s;
std::map<int, int> m[27];
int main() {
std::cin >> N;
for (int i = 0; i < N; ++i) {
std::cin >> s;
for (int j = 0; j < 26; ++j) alf[j] = 0;
for (int j = 0; j < s.size(); ++j) {
++alf[s[j] - 'a'];
}
int odd = 0, flag = 0... |
Lavrenty, a baker, is going to make several buns with stuffings and sell them.
Lavrenty has n grams of dough as well as m different stuffing types. The stuffing types are numerated from 1 to m. Lavrenty knows that he has ai grams left of the i-th stuffing. It takes exactly bi grams of stuffing i and ci grams of dough ... | #include <bits/stdc++.h>
using namespace std;
int n, m, q, p, a, b, c, d, f[100000];
int max(int x, int y) {
if (x > y)
return x;
else
return y;
}
int main() {
scanf("%d%d%d%d", &n, &m, &q, &p);
for (int i = q; i <= n; i++) f[i] = i / q * p;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d%d", &a, &b,... |
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point T, which coordinates to be found out.
Bob travelled around the world and collected clues of the treasure location at n obelisks. These clues were in an ancient language, and he has only decrypted them at hom... | #include <bits/stdc++.h>
using namespace std;
set<int> s;
vector<int> v;
vector<int> v1;
int main() {
ios::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
int n;
cin >> n;
int o_x = -100000000, o_y = -100000000;
int c_x = 100000000, c_y = 100000000;
for (int i = 0; i < n; i++) {
int x, y;
... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of... | import java.io.*;
import java.util.*;
import java.math.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
int mod = 1000000007;
public class SegmentTree{
int n;
int[] tree;
SegmentTree(int[] arr){
this.n = arr.length;
this... |
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 2002;
int N, uz1, uz2;
bool beg[MAXN];
char ar[MAXN], s1[MAXN], s2[MAXN];
set<long long> res;
int main() {
scanf(" %s %s %s", ar, s1, s2);
N = strlen(ar);
uz1 = strlen(s1);
uz2 = strlen(s2);
for (int i = 0; i <= N - uz1; i++) {
int fl = 1;
... |
n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 โค i โค n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i an... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
* @author madi.sagimbekov
*/
public class C115... |
You are given an undirected connected graph G consisting of n vertexes and n edges. G contains no self-loops or multiple edges. Let each edge has two states: on and off. Initially all edges are switched off.
You are also given m queries represented as (v, u) โ change the state of all edges on the shortest path from ve... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100100;
const int MAXM = 2 * MAXN;
int n, m;
int to[MAXM], nxt[MAXM], head[MAXN], E;
struct ST {
vector<int> t;
vector<int> rev;
ST() {}
void resize(int sz) {
t.resize(sz);
rev.resize(sz);
}
void inverse(int l, int r) { inverse(1, 0, t.s... |
You are given an array of n integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.
The GCD of a group of integers is the largest non-negative integer that divides all the integers in th... | #include <bits/stdc++.h>
using namespace std;
int a[100000], order[100000], ans[100000];
int gcd(int a, int b) {
int t;
while (a > 0) t = b % a, b = a, a = t;
return b;
}
int main() {
int i;
int n;
scanf("%d", &n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
int j;
if (n <= 18) {
for (i = 1; i < (... |
Monocarp has arranged n colored marbles in a row. The color of the i-th marble is a_i. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).
In other words, Monocarp wants to rearra... | #include <bits/stdc++.h>
using namespace std;
long long n, x;
long long num[21], f[1 << 20], g[21][21];
int main() {
cin >> n;
for (; n--;) {
cin >> x;
++num[--x];
for (int i = 0; i < 20; ++i) g[x][i] += num[i];
}
for (int i = 0; i < 1 << 20; ++i) f[i] = 1e18;
f[0] = 0;
for (int i = 0; i < 1 << ... |
Adilbek has to water his garden. He is going to do it with the help of a complex watering system: he only has to deliver water to it, and the mechanisms will do all the remaining job.
The watering system consumes one liter of water per minute (if there is no water, it is not working). It can hold no more than c liters... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e5 + 5;
struct Node {
int t, a, b;
} p[MAXN];
inline bool cmp(const Node &p, const Node &q) { return p.t < q.t; }
void solve(void) {
int n, m, c, beg;
scanf("%d%d%d%d", &n, &m, &c, &beg);
for (int i = 1; i <= n; ++i) scanf("%d%d%d", &p[i].t, &p[i].... |
Recently Petya walked in the forest and found a magic stick.
Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:
1. If the chosen number a is even, then the spell will turn it into 3a/2;
2. If t... | t=int(input())
s=[]
a=[1,2,3]
for jngg in range(0,t):
x=input()
xx=x.split( )
x=int(xx[0])
y=int(xx[1])
if x==y:
s.append('yes')
elif x in a and y in a and x!=1:
s.append('yes')
elif x in a and y not in a:
s.append('no')
elif x==1:
s.append('no')
else:... |
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign ea... | #include <bits/stdc++.h>
using namespace std;
inline long long read() {
char ch = getchar();
long long res = 0, pd = 1;
while (ch < '0' || ch > '9') {
if (ch == '-') pd = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
res = (res << 1) + (res << 3) + ch - '0';
ch = getchar();
}
retu... |
Reminder: the [median](https://en.wikipedia.org/wiki/Median) of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}.
There are 2n students, the i-th student has... | import sys
T = int(sys.stdin.readline().strip())
for t in range (0, T):
n = int(sys.stdin.readline().strip())
a = list(map(int, sys.stdin.readline().strip().split()))
a.sort()
print(a[n]-a[n-1]) |
There is a frog staying to the left of the string s = s_1 s_2 โฆ s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ... | for i in range(int(input())):
print(max(map(len,input().split("R")))+1)
|
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
const long long mod = 1e9 + 7;
const long long N = 2e5 + 9;
void raushan_kumar() {
long long d = 0, e = 0, f = 0, g = 0;
double f1 = 0.0, f2 = 0.0, f3 = 0.0;
long long flag = 0, ans = 0, res = 0... |
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, โฆ, a_n, in ... | n=int(input())
arr1=[int(c) for c in input().split()]
arr2=[int(c) for c in input().split()]
dic1={}
dic2={}
for i in range(n):
dic1[arr1[i]] = i
dic2[arr2[i]] = i
lshift=[0 for i in range(n)]
rshift=[0 for i in range(n)]
lcount={}
rcount={}
for i in range(n):
dig=arr1[i]
ind=dic2[dig]
if ind <... |
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | t = int(input())
for _ in range(t):
n = int(input())
a = list(int(x) for x in input().split())
start = 0
end = n-1
while end>0 and a[end]<=a[end-1]:
end-=1
start=end
while start>0 and a[start]>=a[start-1]:
start-=1
print(start)
|
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n/2 elements (where n โ length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ... = 0). In other words, Alexandra wants s... | ##while True:
## N = int(input())
## a = [i+1 for i in range(N)]
#### a = [2, 7, 12, 3, 8]
##
## ans = 0
##
## for i in a:
## ans ^= i
##
## print(a)
##
## x = int(input())
##
## r = []
##
## for i in range(len(a)):
## r.append(a[i]^x)
##
## print(r)
##
## res = 0
##
## ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.