input
stringlengths
29
13k
output
stringlengths
9
73.4k
B: Ebi-chan and Integer Sequences- problem Ebi-chan likes sequences. I especially like arithmetic progressions. This time, I decided to create a sequence that meets the following conditions. * Arithmetic progression of length n * When the i-th element of the sequence is defined as s_i, all s_i (1 \ leq i \ leq n) ar...
#include <algorithm> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <ctime> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> #define R...
A: Union Ball Problem Statement There are N balls in a box. The i-th ball is labeled with a positive integer A_i. You can interact with balls in the box by taking actions under the following rules: * If integers on balls in the box are all odd or all even, you cannot take actions anymore. * Otherwise, you select ar...
#include <iostream> #include <array> using std::array; int main() { int n; std::cin >> n; array<int, 2> cnt{}; for (int i = 0; i < n; ++i) { int a; std::cin >> a; ++cnt[a % 2]; } if (cnt[0] == 0 || cnt[1] == 0) { std::cout << 0 << std::endl; } else { ...
Problem statement Given a permutation $ P $ of length $ N $, sorted integers from $ 0 $ to $ N-1 $. Sort $ P $ in ascending order by doing the following up to $ 30 $. operation For $ 1 $ operations, do the following 1 through 4 in sequence: 1. Declare the string $ S $ of length $ N $ consisting of `0` and` 1` and ...
#include<iostream> #include<cstdio> #include<algorithm> #include<cassert> #include<cmath> #include<vector> #include<map> #include<set> #include<string> #include<queue> #include<stack> using namespace std; #define MOD 1000000007 #define MOD2 998244353 #define INF ((1<<30)-1) #define LINF (1LL<<60) #define EPS (1e-10) ty...
Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents th...
#include <bits/stdc++.h> using namespace std; typedef int64_t i64; typedef uint64_t ui64; class graph{ public: struct adj{ int index; int start; int to; i64 cost; }; int nd; int eg; vector<adj> *node; vector<adj> edge; graph(int n,int m){ nd=n; ...
Problem description Chef loves circular cakes. He divides them into smaller pieces and sells them. You are to help him in this work. Today Chef has cooked the brand new circular cake. To split the cake Chef can make several (possibly, zero) cuts. Each cut should be a straight line going from the center of the cake to i...
import math import sys def parseIntList(str): return [long(x) for x in str.split()] def printBS(li): s=[str(i) for i in li] print " ".join(s) cases=input() for i in range(cases): n=input() if 360%n : print 'n', else: print 'y', if 360/n : print 'y', else: print 'n', if n<=26: print 'y' else: print 'n'
Chef likes rectangles. Among all possible rectangles, he loves rectangles that can be drawn like a grid, such that they have N rows and M columns. Grids are common in Byteland. Hence, Chef has drawn such a rectangle and plans on moving around in it. The rows of the rectangle are labeled from 1 to N from top to bottom. ...
i=0 t=int(raw_input()) while i<t: n,m,k=map(int,raw_input().split()) if n>m: n=n+m m=n-m n=n-m if n==1 and m<=2: print 0 elif n==1 and m>2: print k else: print (k+1)/2 i+=1
x*y = a + b*lcm(x,y) + c*gcd(x,y) It's easy: you are to write a program which for given a, b and c finds the number of pairs of positive integers (x, y) satisfying this equation. Here * stands for multiplication, gcd(x,y) stands for the greatest common divisor of x and y, while lcm(x,y) stands for the least common mul...
from math import sqrt def fn(): a,b,c = map(int,raw_input().split()) if a == 0 and b > 0 and c==0: print -1 return af,cf = [], [] for i in range(1,int(sqrt(a))+1): if i*i == a: af.append(i) else: if a%i==0: af.append(i) ...
Daenerys Targaryen has been suggested by her counselors to leave the Meereen and start conquering other parts of the world. But she knows giving up on the people of Meereen means victory of slavery. Her plan is to start conquering rest of the world while she remains in Meereen. She can only trust her bravest and most b...
t = input() for i in range(t): n, m = map(int, raw_input().split()) a = map(int, raw_input().split()) ans = 0 for j in range(m): ans += a[j] for j in range(m, n): ans -= (a[j] + 1) / 2 if ans < 0 : print 'DEFEAT' else : print 'VICTORY'
The citizens of Byteland regularly play a game. They have blocks each denoting some integer from 0 to 9. These are arranged together in a random manner without seeing to form different numbers keeping in mind that the first block is never a 0. Once they form a number they read in the reverse order to check if the numbe...
a = input() for x in range(a): n = str(input()) str1 = '' for i in range(len(n)-1,-1,-1): str1 += n[i] if str1 == n: print 'wins' else: print 'losses'
Mr. Vallya,the rich playboy billionaire , has recently bought an IPL team Surathkal SuperStars (SSS) . Now he has the challenging task of buying the best possible team in the IPL auction . For this , he is aiming to make a priority order list in which he wants to buy each player . The total number of players available...
def getAns(x,M): a=1 b=x while b!=1: c=M/b a*=c a%=M b*=c b%=M if b>M/2: a=M-a b=M-b return a t=int(input()) for i in range(t): n,p=map(int,raw_input().split()) if n<p: f=1 i=p-1 while i>n: ...
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array [10, 20, 30, 40], we can pe...
//package Codeforces; import java.util.Arrays; import java.util.Scanner; public class Problem1007A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Long[] arr = new Long[n]; for (int i = 0; i < n ; i++) { arr[i] = ...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
n = int(input()) str = input() difficulty = [] difficulty = str.split() flag = 1 for i in difficulty: if i == '1': print("HARD") flag = 0 break if(flag ==1): print("EASY") ''' 3 0 0 1 HARD 1 0 EASY '''
You are given a weighed undirected connected graph, consisting of n vertices and m edges. You should answer q queries, the i-th query is to find the shortest distance between vertices u_i and v_i. Input The first line contains two integers n and m~(1 ≤ n, m ≤ 10^5, m - n ≤ 20) — the number of vertices and edges in t...
#include <bits/stdc++.h> struct t3 { int s, d; long long w; } E[100001], bed[25]; std::vector<std::pair<int, long long> > G[100001]; std::vector<std::pair<int, long long> > T[100001]; long long xd[100001], dist[25][100001]; int arr[100001], rank[100001], lvl[100001], par[100001]; int P[100001][20]; bool vis[100001]...
Let LCP(s, t) be the length of the longest common prefix of strings s and t. Also let s[x ... y] be the substring of s from index x to index y (inclusive). For example, if s = "abcde", then s[1 ... 3] = "abc", s[2 ... 5] = "bcde". You are given a string s of length n and q queries. Each query is a pair of integer set...
#include <bits/stdc++.h> using namespace std; template <class T> inline void read(T &x) { x = 0; T f = 1; char ch = getchar(); while (!(ch >= '0' && ch <= '9')) { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } x *= f; } ...
You are given a range of positive integers from l to r. Find such a pair of integers (x, y) that l ≤ x, y ≤ r, x ≠ y and x divides y. If there are multiple answers, print any of them. You are also asked to answer T independent queries. Input The first line contains a single integer T (1 ≤ T ≤ 1000) — the number of...
for _ in range(int(input())): l, r = map(int, input().split()) for i in range(l,r+1): k = r//i if k>1: print(i, i*2) break
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy). You have time to use some emotes only m times. You are allowed t...
n,m,k=map(int,input().split()) a=list(map(int,input().split())) c=0 a.sort() q=a[n-1] w=a[n-2] r=k*q+w u=m//(k+1) c=u*r+q*(m-(u*(k+1))) print(c)
Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through n ⋅ k cities. The cities are numerated from 1 to n ⋅ k, the distance between the neighboring cities is exactly 1 km. Sergey does not like beetles, he loves burgers. Fortunately for him, there are n fast food restaurants on...
"""This code was written by Russell Emerine - linguist, mathematician, coder, musician, and metalhead.""" from math import gcd n, k = map(int, input().split()) a, b = map(int, input().split()) lll = [a + b, abs(a - b), k - a - b, k - abs(a - b)] x, y = n * k, 0 for ll in lll: for i in range(n): l = ll + i * k ...
This problem is same as the previous one, but has larger constraints. It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system c...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long n; cin >> n; map<pair<long long, long long>, set<long double> > m; vector<pair<long long, long lon...
After learning about polynomial hashing, Heidi decided to learn about shift-xor hashing. In particular, she came across this interesting problem. Given a bitstring y ∈ \{0,1\}^n find out the number of different k (0 ≤ k < n) such that there exists x ∈ \{0,1\}^n for which y = x ⊕ \mbox{shift}^k(x). In the above, ⊕ is ...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { while (b) { swap(a, b); b %= a; } return a; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int _ = 1; while (_--) { int n; cin >> n; string s; cin >> s; int cnt1...
This problem only differs from the next problem in constraints. This is an interactive problem. Alice and Bob are playing a game on the chessboard of size n × m where n and m are even. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are two knights on the chessboard. A white one init...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ii = pair<int, int>; using ld = long double; using D = double; using vi = vector<int>; using vii = vector<ii>; using vvi = vector<vi>; using vs = vector<string>; template <typename T> T abs(T x) { return x < 0 ? -x : x; } template <typename T> ...
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in ...
#include <bits/stdc++.h> using namespace std; template <class T> void _R(T &x) { cin >> x; } void _R(int &x) { scanf("%d", &x); } void _R(long long &x) { scanf("%lld", &x); } void _R(double &x) { scanf("%lf", &x); } void _R(char &x) { scanf(" %c", &x); } void _R(char *x) { scanf("%s", x); } void R() {} template <clas...
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph. It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is conne...
import javafx.scene.layout.Priority; import sun.reflect.generics.tree.Tree; import java.sql.Array; import java.util.*; import java.io.*; import java.util.stream.Stream; import static java.lang.Math.*; public class D { static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(S...
On the well-known testing system MathForces, a draw of n rating units is arranged. The rating will be distributed according to the following algorithm: if k participants take part in this event, then the n rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Iterator; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is...
Donghyun's new social network service (SNS) contains n users numbered 1, 2, …, n. Internally, their network is a tree graph, so there are n-1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T_1....
#include <bits/stdc++.h> using namespace std; int const N = 250000, B = 18; vector<int> tr1[N + 1], tr2[N + 1]; int n, dp[N + 1], pa[N + 1][B], gr[N + 1]; int P(int v) { return gr[v] ? gr[v] = P(gr[v]) : v; } void pl(int v = 1, int p = 0) { dp[v] = dp[p] + 1; pa[v][0] = p; int k = 1, z; while (k < B && (z = pa[...
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
def main(): test = int(input().strip()) while test>0 : x,y,a,b =map( int,input().strip().split()) z = (y-x)/(a+b) h=(y-x)%(a+b) if h==0: print(int(z)) else: print(-1) test-=1 if __name__ == "__main__": main()
For the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order. Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 ≤ i ≤ n), that s_i < t_i, and for a...
t = input() for i in range(t): n,k = map(int, raw_input().split()) f = 0 s = 0 for j in range(1, n+1): if j*(j+1)/2>=k: f=j+1 s=k-j*(j-1)/2 break ans = "" for j in range(1,n+1): if j!=f and j!=s: ans = ans + "a" else: ...
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements. Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu...
for _ in range(int(input())): n,k=map(int,input().split()) d=dict() a=[] new=[] for x in input().split(): x=int(x) a.append(x) if x not in d: d[x]=0 new.append(x) d[x]+=1 if len(d)>k: print("-1") else: while len(new)!=k...
This is a harder version of the problem H with modification queries. Lester and Delbert work at an electronics company. They are currently working on a microchip component serving to connect two independent parts of a large supercomputer. The component is built on top of a breadboard — a grid-like base for a microchi...
#include <bits/stdc++.h> using namespace std; int n, m, cntN[2][400010], cntM[2][400010]; char op[5], le[100010], ri[100010], up[100010], dn[100010]; bool revN[2][400010], revM[2][400010], revmarkN[2][400010], revmarkM[2][400010]; struct Matrix { int a[2][2]; Matrix(int t = 0) { a[0][0] = a[0][1] = a[1][0] = a[1][1...
Recently Roma has become the happy owner of a new game World of Darkraft. This game combines elements of virtually all known genres, and on one of the later stages of the game Roma faced difficulties solving a puzzle. In this part Roma fights with a cunning enemy magician. The battle takes place on a rectangular field...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 20; int H, W; char board[MAX_N + 1][MAX_N + 1]; int dp[2 * MAX_N + 1][2 * MAX_N + 1][2 * MAX_N + 1][2 * MAX_N + 1][2]; int grundy(int x_min, int x_max, int y_min, int y_max, int odd) { int &ret = dp[x_min][x_max][y_min][y_max][odd]; if (ret != -1) retu...
All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of n⋅ m different seals, denoted by distinct numbers. All of them were written in an n× m table. The table is lost now. Naruto managed to remember elements of each row from left to right, and eleme...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, d = 1; char y = getchar(); while (y < '0' || y > '9') { if (y == '-') d = -1; y = getchar(); } while (y >= '0' && y <= '9') { x = (x << 3) + (x << 1) + (y ^ '0'); y = getchar(); } return x * d; } struct vec { in...
You are standing on the OX-axis at point 0 and you want to move to an integer point x > 0. You can make several jumps. Suppose you're currently at point y (y may be negative) and jump for the k-th time. You can: * either jump to the point y + k * or jump to the point y - 1. What is the minimum number of jum...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class trd { public static void main(String[] numsgs) throws IOException { Scanner s = new Scanner(System.in); int t = s.nextInt(); // LinkedList<Integer> ll // ...
Some time ago Homer lived in a beautiful city. There were n blocks numbered from 1 to n and m directed roads between them. Each road had a positive length, and each road went from the block with the smaller index to the block with the larger index. For every two (different) blocks, there was at most one road between th...
#include <algorithm> #include <chrono> #include <cmath> #include <ctime> #include <iomanip> #include <iostream> #include <iterator> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <utility> #include <vector> #include <cassert> #include <assert.h> //#pragma G...
You are given a number k and a string s of length n, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met: * The first character '*' in the original string should be replaced with 'x'; * The last character '*' in the...
t = int(input()) for i in range(t): n, k = map(int, input().split()) s = input() index = s.find('*') num = 1 last = s.rfind('*') while index < last: if s[index] == '*': index += k num += 1 else: index -= 1 print(num)
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook. Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject. Let's consider a student the best at some...
#include <bits/stdc++.h> using namespace std; int main() { long long int t = 1; while (t--) { long long int n, m; cin >> n >> m; char M[n][m]; for (long long int i = 0; i < n; i++) { for (long long int j = 0; j < m; j++) { cin >> M[i][j]; } } int ans = 0; for (int i =...
You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1 ≤ i, j ≤ n). In other words, let's consider all n2 pairs of numbers, picked from the given array. For e...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class P160C { static boolean mul...
In an English class Nick had nothing to do at all, and remembered about wonderful strings called palindromes. We should remind you that a string is called a palindrome if it can be read the same way both from left to right and from right to left. Here are examples of such strings: «eye», «pop», «level», «aba», «deed», ...
#include <bits/stdc++.h> using namespace std; const int mx = 4e6 + 5; const int mod = 51123987; char str[mx], s[mx]; int p[mx]; int l[mx], r[mx]; long long pow_mod(long long a, long long b) { long long ans = 1; while (b > 0) { if (b & 1) ans = ans * a % mod; a = a * a % mod; b /= 2; } return ans; } ...
A boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as x points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result. He knows that the con...
#include <bits/stdc++.h> using namespace std; int main() { long int x, t, a, b, da, db; scanf("%ld %ld %ld %ld %ld %ld", &x, &t, &a, &b, &da, &db); if (x == 0) { printf("%s \n", "YES"); goto exit; } else { for (int tz = 0; tz < t; ++tz) { for (int tu = 0; tu < t; ++tu) { if (a - da * t...
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations. Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of number...
#include <bits/stdc++.h> using namespace std; int Mod; void add_self(int& x, int y) { if ((x += y) >= Mod) x -= Mod; } int mul(int x, int y) { return (long long)x * y % Mod; } vector<vector<int> > Zero(int n, int m) { return vector<vector<int> >(n, vector<int>(m, 0)); } vector<vector<int> > Ident(int n) { vector<...
Little Petya likes positive integers a lot. Recently his mom has presented him a positive integer a. There's only one thing Petya likes more than numbers: playing with little Masha. It turned out that Masha already has a positive integer b. Petya decided to turn his number a into the number b consecutively performing t...
#include <bits/stdc++.h> using namespace std; long long a, b, k; long long d[360365]; const long long lcm = 360360; long long giam(long long a, long long b) { d[0] = 0; for (int i = 1; i <= a - b; i++) { d[i] = d[i - 1] + 1; for (int j = 2; j <= k; j++) if ((b + i) % j <= i) d[i] = min(d[i], d[i - (b ...
A little girl loves problems on bitwise operations very much. Here's one of them. You are given two integers l and r. Let's consider the values of <image> for all pairs of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones. Expression <image> means applying bitwise excl...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long l, r; cin >> l >> r; long long ret = 0, in = 1ll << 62; while ((l & in) == (r & in) && in) { in >>= 1; } cout << max(0ll, (in << 1) - 1); return 0; }
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. ...
import java.util.Scanner; public class SpitProblem { public static void main(String[] args) { Scanner sin = new Scanner(System.in); int n = sin.nextInt(), cm[] = new int[n], arr[] = new int[n]; for(int i = 0; i < n; i++) { cm[i] = sin.nextInt(); arr[i] = sin.nextI...
Fox Ciel is playing a card game with her friend Jiro. Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack. Now is Ciel's battle phase, Ciel can do the following ope...
#include <bits/stdc++.h> using namespace std; vector<int> ja, jd, ca; int main() { int n, m, v; string t; scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { cin >> t >> v; if (t[0] == 'A') ja.push_back(v); else jd.push_back(v); } for (int i = 0; i < m; i++) { cin >> v; ca.p...
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation c...
#include <bits/stdc++.h> using namespace std; int mas[100003], a, n, j; int main() { cin >> n; int k = 0; int d = 0; for (int i = 0; i < n; i++) { cin >> mas[i]; } for (int i = 0; i < n; i++) { if (mas[i] == i) { k++; } else { if (mas[mas[i]] == i && mas[i] < n && mas[i] >= 0) { ...
A Christmas party in city S. had n children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to m, and the children are numbered from 1 to n. Then the i-th...
import java.io.*; import java.util.*; import java.math.*; public class Main { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static void solve() throws Exception { int n = nextInt(); int m = nextInt(); int[] l = new int[n+1]; int[] r = ne...
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; inline int read() { int x; char c; int f = 1; while ((c = getchar()) != '-' && (c > '9' || c < '0')) ; if (c == '-') f = -1, c = getchar(); x = c ^ '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ '0'); return x * f; } i...
Mashmokh works in a factory. At the end of each day he must turn off all of the lights. The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turn...
n = input().split() n = int(n[0]) butt = {} for i in range(1, n+1): butt[i] = 0 a = input().split() for i in a: for k in range(int(i), n+1): if butt[k] == 0: butt[k] = int(i) else: continue for i in range(1, n+1): print(butt[i], end=' ')
A permutation p of length n is a sequence of distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n). A permutation is an identity permutation, if for any i the following equation holds pi = i. A swap (i, j) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swap...
#include <bits/stdc++.h> using namespace std; int n; int a[3050], p[3050], s[3050], ps[3050], vis[3050]; int m; void dfs(int i) { if (vis[i]) return; vis[i] = 1; dfs(a[i]); return; } int main() { int i, j, k; scanf("%d", &n); for (i = 1; i <= n; i++) { scanf("%d", &a[i]); s[a[i]] = i; } memcpy...
Caisa is now at home and his son has a simple task for him. Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following: * Format of the query is "1 v". Let's write out the sequence of vertices...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010; struct par { int x, y; par(int _x = 0, int _y = 0) { x = _x; y = _y; } }; int n, q; vector<int> graf[MAXN]; map<int, int>::iterator it, it2; map<int, int> moji[MAXN], rj[MAXN], trenutna; int niz[MAXN], dubina[MAXN]; void ispis() { fo...
Automatic Bakery of Cyberland (ABC) recently bought an n × m rectangle table. To serve the diners, ABC placed seats around the table. The size of each seat is equal to a unit square, so there are 2(n + m) seats in total. ABC placed conveyor belts on each unit square on the table. There are three types of conveyor belt...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const long long LINF = 0x3f3f3f3f3f3f3f3fll; const int MAX = 1.2e6 + 100; namespace lct { struct node { int p, ch[2]; node() { p = ch[0] = ch[1] = -1; } }; node t[MAX]; bool is_root(int x) { return t[x].p == -1 or (t[t[x].p].ch[0] != x and ...
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in l...
from collections import defaultdict n = int(input()) g = defaultdict(list) names = [] for _ in range(n): names.append(input()) for i in range(1, n): j = 0 while j < len(names[i]) and j < len(names[i-1]) and names[i-1][j] == names[i][j]: j += 1 if j >= len(names[i]): print("Impo...
Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead. <image> Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions...
import java.io.*; import java.util.*; import java.util.zip.ZipEntry; import java.math.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); PrintWriter out = new...
You are given a convex polygon. Count, please, the number of triangles that contain a given point in the plane and their vertices are the vertices of the polygon. It is guaranteed, that the point doesn't lie on the sides and the diagonals of the polygon. Input The first line contains integer n — the number of vertice...
#include <bits/stdc++.h> using namespace std; struct point { long long x, y; }; long long n; struct point p[100100]; struct point q; int t; int orientation(struct point& p1, struct point& p2, struct point& p3) { long long o = (p2.y - p1.y) * (p3.x - p2.x) - (p2.x - p1.x) * (p3.y - p2.y); if (o == 0) return o; r...
A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese. The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each r...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 50 + 10; int a1[MAX_N], a2[MAX_N], b[MAX_N]; int dp1[MAX_N], dp2[MAX_N], sum[MAX_N]; int main() { int n; cin >> n; for (int i = 0; i < n - 1; i++) cin >> a1[i]; for (int i = 0; i < n - 1; i++) cin >> a2[i]; for (int i = 0; i < n; i++) cin >> b[i]...
There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will acti...
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > v; map<int, int> p; int dp[1000000 + 10]; int rec(int dist) { if (dist < 0) return 0; int val = p[dist]; int sec = dist - val - 1; if (sec < 0) return 1; int &st = dp[dist]; if (st != -1) return st; int low = 0, high = v.size() - 1, mid...
Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac...
#include <bits/stdc++.h> using namespace std; int main() { vector<int> hozon[26]; int n, k; cin >> n >> k; string s; cin >> s; for (int a = 0; a < k; a++) { hozon[s[a] - 'a'].push_back(a); } for (int a = 0; a < 26; a++) hozon[a].push_back(1000000); for (int a = 0; a < n; a++) { string t; c...
Input The input contains a single integer a (0 ≤ a ≤ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
t = int(raw_input()) i = 1 a = 1 while i<=t: a=a*2 if i==13: a=8092 i+=1 print a
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string s; cin >> s; int dp1[n], dp2[n]; dp1[0] = 0; for (int i = 0; i < n - 1; i++) { if (s[i] == 'L') dp1[i + 1] = 0; if (s[i] == '=') dp1[i + 1] = dp1[i]; if (s[i] == 'R') dp1[i + 1] = dp1[i] + 1; } dp2[n - 1] = ...
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. Input The first line cont...
""" Author: Sagar Pandey """ # ---------------------------------------------------Import Libraries--------------------------------------------------- import sys import os from math import sqrt, log, log2, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial from copy import copy, deepcopy from sys import exit...
You are given a table consisting of n rows and m columns. Numbers in each row form a permutation of integers from 1 to m. You are allowed to pick two elements in one row and swap them, but no more than once for each row. Also, no more than once you are allowed to pick two columns and swap them. Thus, you are allowed ...
#include <bits/stdc++.h> using namespace std; int n, m, a[21][21]; bool check1(int l, int r, int num) { for (int i = l; i < r + 1; i++) { if (a[num][i] != (i + 1)) return 0; } return 1; } bool check(int ind, int x, int y) { if (a[ind][x] == (x + 1) && a[ind][y] == (y + 1) && check1(0, m - 1, ind)) { ret...
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Solution { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; ...
Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!". Not all students are equally sociable. About each student you know the value ai — the maximum number of messages which the i-th student is agree to send per day. ...
import collections as col import itertools as its import operator class Solver: def solve(self): n = int(input()) a = list(map(int, input().split())) for i in range(len(a)): a[i] = [a[i], i + 1] a[0][0] += 1000 a = sorted(a)[::-1] a[0][0] -= 1000 ...
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel,...
import java.util.*; import java.io.*; public class IgorWayToWork { String ans = "NO"; boolean[][][] visited; int startx, starty, endx, endy; int n, m; public void dfs(int[][] board, int x, int y, int dir, int turns) { // dir == 0 -> starting, no direction // dir == 1 -> vertical ...
As you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires. In the game Vova can hire n different warriors; ith warrior has the type ai. Vova wants to create a balanced army hiring some subset of warriors. An army is called balanced if f...
#include <bits/stdc++.h> using namespace std; int N, K, NR = 1, a[100100], g[100100], root[100100], Q, lst; vector<int> c[100100]; struct range { int l, r, sum; } r[4400400]; int u(int i, int rs, int re, int p, int d) { int n = ++NR; r[n] = r[i]; if (rs == re - 1) r[n].sum += d; else { int m = (rs + r...
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers. He has created a method to know how strong his army is. Let the i-th soldier’s strength...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Yuan Lei */ public class Main { public static void main(String[] args) { InputStream ...
n evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number k. Then you may repeatedly select a set of 2 or more points which are evenly spaced, and either increase all numbers at points in the set by k or decrease all numbers at points...
#include <bits/stdc++.h> std::vector<int> primes; int sqr = 1; void factor(int N) { int num = N; for (int i = 2; i * i <= N; i++) { if (num % i == 0) { num /= i; primes.push_back(i); while (num % i == 0) { num /= i; sqr *= i; } } } if (num > 1) { primes.push_b...
A string a of length m is called antipalindromic iff m is even, and for each i (1 ≤ i ≤ m) ai ≠ am - i + 1. Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as bi, and the...
#include <bits/stdc++.h> using namespace std; char s[120]; int ans1, pre[120], ma[120][120], ans2, num[120]; int n, la[120], lb[120], vb[120], va[120], delta; bool dfs(int u) { va[u] = 1; for (int i = 1; i <= n; i++) { if (ma[u][i] == -1) continue; if (vb[i] == 0) { if (la[u] + lb[i] - ma[u][i] == 0) ...
Your friend has a hidden directed graph with n nodes. Let f(u, v) be true if there is a directed path from node u to node v, and false otherwise. For each pair of distinct nodes, u, v, you know at least one of the three statements is true: 1. <image> 2. <image> 3. <image> Here AND, OR and XOR mean AND, OR a...
#include <bits/stdc++.h> template <typename T> inline void read(T &x) { x = 0; char c = getchar(); while (!isdigit(c)) c = getchar(); while (isdigit(c)) x = x * 10 + (c ^ 48), c = getchar(); } using namespace std; char s[59][59]; int n; int fath[59], siz[59]; int find(int cur) { return fath[cur] == cur ? cur ...
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string ...
#include <bits/stdc++.h> using namespace std; int main() { std::ios::sync_with_stdio(false); cin.tie(0); string s; cin >> s; int n = s.length(); double ans = 0.0; vector<int> all[26]; for (int i = 0; i < s.length(); i++) { all[s[i] - 'a'].push_back(i); } for (int i = 0; i < 26; i++) { if (al...
Heidi is now just one code away from breaking the encryption of the Death Star plans. The screen that should be presenting her with the description of the next code looks almost like the previous one, though who would have thought that the evil Empire engineers would fill this small screen with several million digits! ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 5e5 + 5; const int MAXK = 1e2 + 5; const int INF = 0x3f3f3f3f; int N, K, P; int a[MAXN]; vector<int> pos[MAXK]; int dp[MAXK][MAXK][MAXK]; int pref[MAXK][MAXK][MAXK], suff[MAXK][MAXK][MAXK]; void load() { scanf("%d%d%d", &N, &K, &P); for (int i = 1; i <=...
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won. Alex has grown up since then, so he easily wins the most difficu...
arr = [] def valid(i, j): bombs = 0 if arr[i][j] == '*': return True if i != len(arr) - 1: if arr[i + 1][j] == '*': bombs += 1 if i != 0: if arr[i - 1][j] == '*': bombs += 1 if j != len(arr[0]) - 1: if arr[i][j + 1] == '*': bombs +...
Problem : You are given an array A initially comprising of N non-negative integers A[1], A[2], A[3]..... A[N]. An array B can be generated from array A in the following manner : for(i=1;i ≤ N;i++) { B[i]=1; for(j=1;j ≤ N;j++) { if(i!=j) { B[i]=B[i]*A[j]; } } } You ...
def modinv(n): M=1000000007 return pow(n,M-2,M) n=input() A=map(int,raw_input().split()) val=1 M=10**9+7 z=0 for i in A: if i!=0: val=(val*i)%M else: z+=1; t=input() for i in xrange(t): C=map(int,raw_input().split()); if len(C)==2: if z>=2: print 0 elif z==1: if A[C[1]-1]==0: print val ...
The Kraken lives! Tragedy has struck the trade world since news has spread of the rise of the Kraken that terrorizes the Mediterranean Sea. Any ship that attempts to cross this strait is torn apart by the mighty tentacles of the beast and all its occupants face a fate worse than death. You have chanced upon a map tha...
for t in range(input()): n = input() a1 = [0]*n a2 = ['a']*n for i in range(n): x = raw_input().split() a1[i] = int(x[1]) a2[i] = x[0][0] for i in range(n): for j in range(1,n): if a1[j-1] > a1[j] : a1[j-1],a1[j] = a1[j],a1[j-1] a2[j-1],a2[j] = a2[j],a2[j-1] codes = [ '' for i in range(n)...
You are a cricket coach who wants to partition a set of players into two teams of equal size and a referee. If there are odd players, one of the player becomes the referee. However, if there are even players, the coach himself acts as the referee. Each player has a score (integer) associated with him, known only to the...
from heapq import * minH = [] maxH = [] while True: n = int(raw_input()) if n==-2: break if n==0: if len(minH)==len(maxH): print -1 else: if len(minH)>len(maxH): print minH[0] else: print -maxH[0] else: if len(minH)==0 and len(maxH)==0: heappush(minH,n) else: if n<minH[0]: hea...
Agent OO7 is engaged in a mission to stop the nuclear missile launch. He needs a surveillance team to monitor the progress of the mission. Several men with different type of capabilities assemble in a hall, help OO7 to find out total men with different capabilities. Capability is represented in form of numbers. Input -...
t = input() while(t): t -= 1 size = input() print len(list(set(list(map(int,raw_input().split())))))
Joseph studies at SKIT.He is a fresher he has been given a task and he wants help from you for performing the task.The task is an interesting one. The tasks is:- He is provided with a value N, he has to make change for N cents, and he have infinite supply of each of S = { S1, S2, S3, S4} valued coins, how many ways ...
n = int(raw_input()) a = map(int, raw_input().split()) s = [[0 for i in range(len(a))] for i in range(n+1)] for i in range(len(a)): s[0][i] = 1 x = 0 y = 0 for i in range(1, n+1): for j in range(len(a)): if i - a[j] >= 0: x = s[i-a[j]][j] else: x = 0 if j >= 1: y = s[i][j-1] else: y = 0 s[i][j] ...
Milly loves to eat chocolates. She has N different chocolates. She needs to choose only one of them. At the moment, i^{th} chocolate already has P_{i} pieces. The j^{th} piece of the i^{th} chocolate requires T_{i,j} seconds to eat. Milly knows that she will take K seconds to break one piece from any chocolate and wait...
t = int(raw_input()) while t: t-=1 n,k,m=map(int,raw_input().split()) p = map(int,raw_input().split()) ans = (2*10**5)+(101*10**9) idx = 0 for i in xrange(n): firstTime = True val=0 for j in raw_input().split(): j = int(j) if (firstTime): val+=(k+j) firstTime=False else: val+=(m+k+j) ...
You are given two numbers N and K and a set X. X = { x : x is a natural number ≤ N } You have to find the total number of pairs of elements X[i] and X[j] belonging to the given set, such that, i < j and their sum is divisible by K. Input Format: An integer T followed by T lines, each containing a pair of space se...
T = int(input()) for _ in range(T): N, K = list(map(int, raw_input().split())) # Loop over all multiples of K less than 2N: # If nK <= N: # add (nK - 1) // 2 pairs # Else: # add (nK - 1) // 2 - (k - N - 1) pairs total = 0 a = N // K + 1 b = (2 * N) // K - (1 if (2 * N) % K == 0 else 0) if K % 2...
The grandest stage of all, Wrestlemania XXX recently happened. And with it, happened one of the biggest heartbreaks for the WWE fans around the world. The Undertaker's undefeated streak was finally over. Now as an Undertaker fan, you're disappointed, disheartened and shattered to pieces. And Little Jhool doesn't wan...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t = int(raw_input()) for x in range(t): num = raw_input() n = int(num) if ('21' in num) or (n%21==0): print "The streak is broken!" else: print "The streak lives still in our he...
You have been given an array A of size N and an integer K. This array consists of N integers ranging from 1 to 10^7. Each element in this array is said to have a Special Weight. The special weight of an element a[i] is a[i]\%K. You now need to sort this array in Non-Increasing order of the weight of each element, i.e ...
import sys s=raw_input().split(" ") s1=raw_input().split(" ") s1=[int(x) for x in s1] s1=sorted(s1) dict={} for i in range(0,len(s1)): dict.update({s1[i]:s1[i]%int(s[1])}) list=sorted(dict,key=dict.__getitem__,reverse=True) list=[str(x) for x in list] print ' '.join(list)
Pandey needs your help. As you know, he is on the quest to save the princess. After traveling for a number of days, he has finally reached the palace, but one last battle remains to be fought. However he has only one unit of energy left in him. To win the battle, he needs all the energy he can get. So he is searching f...
from pprint import pprint as pp def GI(): return int(raw_input()) def GIS(): return map(int, raw_input().split()) def main(): for t in xrange(GI()): ex = [1, 1] for _ in xrange(GI()): b = raw_input() if b == 'N': nex = [-1 * x for x in ex] else: ...
Takahashi is meeting up with Aoki. They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now. Takahashi will leave his house now and go straight to the place at a speed of S meters per minute. Will he arrive in time? Constraints * 1 \leq D \leq 10000 * 1 \leq T \leq 10...
import java.util.*; public class Main { public static void main(String args[]) { Scanner in=new Scanner(System.in); float d=in.nextFloat(),t=in.nextFloat(),s=in.nextFloat(); if((d/s)<=t) System.out.println("Yes"); else System.out.println("No"); } }
You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i. How many kinds of items did you get? Constraints * 1 \leq N \leq 2\times 10^5 * S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive). Input Input is given from Standard Input in t...
N=int(input()) J=[input() for i in range(N)] print(len(list(set(J))))
Given are strings s and t of length N each, both consisting of lowercase English letters. Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); String a = s.next(), b = s.next(); for (int i = 0; i < a.length(); i++) { System.out.print(a.charAt(i) + "" + b.charAt(i)); } } }
Given is a string S consisting of `A`,`B`, and `C`. Consider the (not necessarily contiguous) subsequences x of S that satisfy all of the following conditions: * `A`, `B`, and `C` all occur the same number of times in x. * No two adjacent characters in x are the same. Among these subsequences, find one of the long...
#include <bits/stdc++.h> using namespace std; #ifdef LOCAL #define db(x) cerr << #x << "=" << x << endl #define db2(x, y) cerr << #x << "=" << x << "," << #y << "=" << y << endl #define db3(x, y, z) cerr << #x << "=" << x << "," << #y << "=" << y << "," << #z << "=" << z << endl #define dbv(v) cerr << #v << "="; for (a...
There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}. Additionally, you are given integers B_1, B_2, ..., B_M and C. The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0. Among the N c...
import java.util.Scanner; public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt(); int m = sc.nextInt(); int c = sc.nextInt(); int[] b = new int[m]; for (int i = 0; i < m; i++) { b[i] =...
You have decided to give an allowance to your child depending on the outcome of the game that he will play now. The game is played as follows: * There are three "integer panels", each with a digit between 1 and 9 (inclusive) printed on it, and one "operator panel" with a `+` printed on it. * The player should constru...
#include<iostream> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; int m = max(max(a, b), c); cout << a + b + c + m * 9 << endl; }
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis. You planned a trip along the axis. In this plan, you first depart from...
#include <bits/stdc++.h> using namespace std; int tot; int N, A[1<<17]; int main() { scanf("%d", &N); for (int i = 0; i < N; ++i) scanf("%d", A+i); tot += abs(A[0]); for (int i = 0; i < N; ++i) tot += abs(A[i] - A[i+1]); printf("%d\n", tot - abs(A[0]) - abs(A[1] - A[0]) + abs(A[1])); for (int i = 1; i < N; +...
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express. In the plan developed by the president Takahashi, the trains will run as follows: * A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds. * In the first t_1 seconds, a train must ru...
n = int(input()) t = list(map(int, input().split())) v = list(map(int, input().split())) tmp = 0 e_t = [] for i in t: tmp+=i e_t.append(tmp) def calc_end_speed(s): end_time = e_t[s] ma = 10**10 for i in range(s+1, n): ma = min(e_t[i-1] - end_time + v[i], ma) return min(e_t[-1] - end_tim...
There is an empty array. The following N operations will be performed to insert integers into the array. In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array. Find the K-th smallest integer in the array after the N operations. For example, the 4-th smallest integer in the array \\{1,2...
N, K = map(int, input().split()) arr = [list(map(int, input().split())) for i in range(N)] arr.sort() n = 0 for i in range(N): n += arr[i][1] if n >= K: print(arr[i][0]) break
There are N cities in a two-dimensional plane. The coordinates of the i-th city is (x_i, y_i). Initially, the amount of water stored in the i-th city is a_i liters. Snuke can carry any amount of water from a city to another city. However, water leaks out a bit while he carries it. If he carries l liters of water from ...
#include<stdio.h> #include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #include<bitset> #include<utility> #include<functional> #include<iomanip> #include<sstream> #include<ctime> #include<cassert> using namespace std; #de...
Iroha has a sequence of N strings s_1, s_2, ..., s_N. She will choose some (possibly all) strings from the sequence, then concatenate those strings retaining the relative order, to produce a long string. Among all strings of length K that she can produce in this way, find the lexicographically smallest one. Constrai...
#include<bitset> #include<stdio.h> #include<iostream> #include<vector> #include<algorithm> #include<string> #include<string.h> #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define NDEBUG #define eprintf(...) do {} while (0) #endif #include<cassert> using namespace std; typedef long long LL; t...
In the speed skating badge test, grades are awarded when the time specified for two distances is exceeded. For example, to reach Class A, 500 M requires less than 40.0 seconds and 1000 M requires less than 1 minute and 23 seconds. Create a program that takes the time recorded in the speed skating competitions (500 M a...
#include<iostream> using namespace std; int main(){ double ina, inb; while(cin >> ina >>inb){ if(ina < 35.5 && inb < 71) cout << "AAA" << endl; else if(ina < 37.5 && inb < 77) cout << "AA" << endl; else if(ina < 40 && inb < 83) cout << "A" << endl; else if(ina < 43 && inb < 89) cout << "B" << e...
Shinya watched a program on TV called "Maya's Great Prophecy! Will the World End in 2012?" After all, I wasn't sure if the world would end, but I was interested in Maya's "long-term calendar," which was introduced in the program. The program explained as follows. The Maya long-term calendar is a very long calendar con...
import datetime time_std=datetime.date(2012, 12, 21) while 1: n=input() if n=="#":break n_len=list(map(int,n.split("."))) if len(n_len)==3: year_keep=0 while n_len[0]>9999: year_keep+=1 n_len[0]-=400 ans=[0]*5 cal_date=datetime.date(n_len[0], n_len...
problem Mobiles are widely known as moving works of art. The IOI Japan Committee has decided to create mobiles to publicize JOI. JOI public relations mobiles are sticks, strings, and weights. It is constructed as follows using the three types of elements of. * One end of the bar is painted blue and the other end is p...
#include <cstdio> #include <vector> #include <algorithm> using namespace std; int gcd(int a, int b) { if(a < b) swap(a, b); if(b == 0) return a; return gcd(b, a % b); } int lcm(int a, int b) { int div = gcd(a, b); return a / div * b; } struct mobile { int p, q, r, b; mobile() {} mobile(int p, in...
A crop circle suddenly appeared on the vast agricultural land of Argentina. A total of n crop circles were confirmed, including overlapping, popping, large, and small ones. When a mystery hunter tried to capture the whole picture of a crop circle from the air, he found it difficult to show the beautiful pattern in the...
#include<iostream> #include<complex> #include<vector> #include<algorithm> #include<cmath> #include<map> #include<list> #include<iomanip> #define EPS (1e-8) #define EQ(a,b) (abs((a)-(b)) < EPS) #define fs first #define sc second #define pb push_back #define sz size() #define all(a) (a).begin(),(a).end() #define rep(i,n...
Bridge Removal ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands. There are n islan...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<vector<int>> vvi; typedef vector<vector<ll>> vvl; int n; vector<vector<pair<int, ll>>> ps; vector<map<int, ll>> memo, memo2; ll dfs2(int i, int from); ll dfs(int i, int from) { if (memo[...
In sliding block puzzles, we repeatedly slide pieces (blocks) to open spaces within a frame to establish a goal placement of pieces. A puzzle creator has designed a new puzzle by combining the ideas of sliding block puzzles and mazes. The puzzle is played in a rectangular frame segmented into unit squares. Some square...
#include<stdio.h> #include<algorithm> #include<queue> #include<vector> using namespace std; char str[60][60]; int dx[]={0,1,0,-1}; int dy[]={1,0,-1,0}; int bfs[60][60]; int ijk[60][60][4]; int v[60][60][4]; int dis[2][2]; int a,b; int calc(vector<pair<int,int> >st,vector<pair<int,int> >go,int xr,int xc){ for(int l=0;l...
Problem There are c cards each with an integer between a and b. When d cards are selected from these c (b-a + 1) cards, the remainder when the sum of the integers written on those cards is e is divided by 1,000,000,007 is calculated. please. Constraints The input satisfies the following constraints. * 1 ≤ a ≤ 1000 ...
#include<iostream> #include<algorithm> using namespace std; #define MOD 1000000007 #define M 108 typedef long long Int; int a, b, c, d, e; Int dp[108][21600]; Int dp1[108][21600]; Int dp2[108][21600]; int main(){ cin >> a >> b >> c >> d >> e; b -= a; e -= a*d; dp[0][0] = 1; dp1[0][0] = 1; dp2[0][0] = 1; ...
Music Macro Language (MML) is a language for textual representation of musical scores. Although there are various dialects of MML, all of them provide a set of commands to describe scores, such as commands for notes, rests, octaves, volumes, and so forth. In this problem, we focus on rests, i.e. intervals of silence. ...
#include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace ...
Natsume loves big cats. I haven't kept cats at Natsume's house for a long time, and Natsume, who loves cats, was always playing with stray cats. However, this time Natsume decided to keep a cat at her own house. Natsume welcomed the cat to her house and named her Lennon and began to pet her. Natsume's house consists o...
#include<iostream> #include<algorithm> #include<vector> #include<queue> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) #define pb push_back const int N = 100005; const int inf = ( 1 << 21); class Edge{ public: int next,c; }; class state{ public: int now,c; bo...