input
stringlengths
29
13k
output
stringlengths
9
73.4k
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≀ l ≀ r ≀ n), and you should...
t = int(input()) lst = list(map(int,input().split())) x = lst[:] x.sort() l_st = [0] lst1 = [0] k = 0 k1 = 0 for i in range(t): k += lst[i] l_st.append(k) k1 += x[i] lst1.append(k1) n = int(input()) for i in range(n): t_pe , l , r = map(int,input().split()) if(t_pe == 1): print(l_st[r] -...
Serega loves fun. However, everyone has fun in the unique manner. Serega has fun by solving query problems. One day Fedor came up with such a problem. You are given an array a consisting of n positive integers and queries to it. The queries can be of two types: 1. Make a unit cyclic shift to the right on the segmen...
import java.io.*; import java.util.*; import java.math.BigInteger.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import java.util.logging.Level; import java.util.logging.Logger; // https://netbeans.org/kb/73/java/editor-codereference_ru.html#display //<edito...
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha...
#code n,m = map(int,input().split()) k = n//m z = n - m print(m*k*(k-1)//2+k*(n%m),(z+1)*z//2)
New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as tot...
#include <bits/stdc++.h> const long long MOD = 1e9 + 7; using namespace std; const long long N = 100010; map<long long, long long> num[N]; long long kids[N] = {}, b = 0, tp[N] = {}, len[N] = {}; vector<long long> g[N]; long long dfs(long long n, long long p) { long long k = 1; if (g[n].size() == 1 && n != 1) { ...
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads...
import java.util.*; import java.io.*; public class a { public static void main(String[] args) { InputReader in = new InputReader(); in.init(System.in); Solver soal = new Solver(); soal.solve(in); } } class Solver { private int[] dp; private int N, exp = -1, n; public void solve(InputRea...
Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≀ i ≀ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way...
#include <bits/stdc++.h> using namespace std; int n, m; long long pile[100002]; bool bisa(long long x) { int idx = n; long long now = pile[idx - 1]; for (int i = 0; i < m; i++) { long long tmp = x - idx; while (tmp > 0) { long long ambil = min(now, tmp); tmp -= ambil; now -= ambil; ...
You are given a string S of length n with each character being one of the first m lowercase English letters. Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1. Recall that LCS ...
#include <bits/stdc++.h> using namespace std; int n, m; char s[100111]; long long dp[100111][8]; bool input() { if (cin >> n >> m) { string str; cin >> str; for (int i = (int)(1), _t = (int)(n); i <= _t; i++) s[i] = str[i - 1] - 'a'; return true; } else { return false; } } int get_bit(int x, i...
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck! Input The input file c...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CenterAlignment { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); String[] a = new String[1000]; int...
There are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit 2 from the second...
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; long long num[100], luse[100], t[100], mun[100], ans[100], idk[100]; long long n, b, k, x; void mult(long long a[], long long b[], long long c[]) { memset(t, 0, sizeof(t)); int i, j; for (i = 0; i < x; i++) for (j = 0; j < x; j++) t[...
Radewoosh is playing a computer game. There are n levels, numbered 1 through n. Levels are divided into k regions (groups). Each region contains some positive number of consecutive levels. The game repeats the the following process: 1. If all regions are beaten then the game ends immediately. Otherwise, the system ...
#include <bits/stdc++.h> #pragma GCC optimize(2) using namespace std; void qread(int &x) { int neg = 1; x = 0; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') neg = -1; c = getchar(); } while (c >= '0' && c <= '9') x = 10 * x + c - '0', c = getchar(); x *= neg; } const int maxn = 20...
Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109. In the evening after the conference, all n scientists decided to go to...
#include <bits/stdc++.h> using namespace std; map<int, int> a; int main() { int n, ans = 0, k, sc; int maxi1 = 0, maxi2 = 0; int index = 0, films; cin >> n; for (int i(1); i <= n; i++) { cin >> sc; a[sc]++; } cin >> films; int ozv[films + 1], sub[films + 1]; for (int film(1); film <= films; fi...
You are given n integers a1, a2, ..., an. A sequence of integers x1, x2, ..., xk is called a "xor-sequence" if for every 1 ≀ i ≀ k - 1 the number of ones in the binary representation of the number xi <image> xi + 1's is a multiple of 3 and <image> for all 1 ≀ i ≀ k. The symbol <image> is used for the binary exclusive ...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } long long lcm(long long a, long long b) { return a * (b / gcd(a, b)); } long long power(long long x, long long y, long long p) { long long res = 1; x = x % p; while (y > 0) { if (y & 1)...
ZS the Coder has a large tree. It can be represented as an undirected connected graph of n vertices numbered from 0 to n - 1 and n - 1 edges between them. There is a single nonzero digit written on each edge. One day, ZS the Coder was bored and decided to investigate some properties of the tree. He chose a positive in...
#include <bits/stdc++.h> using namespace std; const int MIF = 1e9 + 7; const double PI = 4 * atan(1); inline long long in() { long long x = 0; int n = 1; char c = getchar(); while (!isdigit(c)) { n = (c == '-') ? -1 : 1; c = getchar(); } while (isdigit(c)) { x = x * 10 + c - '0'; c = getchar...
Galya is playing one-dimensional Sea Battle on a 1 Γ— n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other. Galya doesn't know the ships location. She can shoot to some cells and after each shot ...
#include <bits/stdc++.h> using namespace std; char s[200000 + 10]; void Read(int &x) { char c; while (c = getchar(), c != EOF) { if (c >= '0' && c <= '9') { x = c - '0'; while (c = getchar(), c >= '0' && c <= '9') x = x * 10 + c - '0'; ungetc(c, stdin); return; } } } vector<pair<in...
On her way to programming school tiger Dasha faced her first test β€” a huge staircase! <image> The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values β€” th...
string=input() a,b=map(int,string.split(' ')) if a==0 and b==0: print('NO') elif a-b==1 or b-a==1: print('YES') elif a==b: print('YES') else: print('NO')
DO YOU EXPECT ME TO FIND THIS OUT? WHAT BASE AND/XOR LANGUAGE INCLUDES string? DON'T BYTE OF MORE THAN YOU CAN CHEW YOU CAN ONLY DISTORT THE LARGEST OF MATHEMATICS SO FAR SAYING "ABRACADABRA" WITHOUT A MAGIC AND WON'T DO YOU ANY GOOD THE LAST STACK RUPTURES. ALL DIE. OH, THE EMBARRASSMENT! I HAVE NO ARRAY AND I M...
#include <bits/stdc++.h> using namespace std; int n, a[20] = {0}; int main() { int n, ma = 0; scanf("%d", &n); for (int i = 1; i <= n; i++) { int x; scanf("%d", &x); ma = max(ma, x); a[i] = x; } printf("%d\n", ma ^ a[n]); return 0; }
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substr...
def check(s): for i in range(len(s)//2): if s[i] != s[-(i+1)]: return(True) return(False) n = int(input()) sub = "aabb" ans = "" mod = n //4 ans += sub*mod for i in range(n%4): ans += sub[i] print(ans) # print(check(ans))
Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on...
#include <bits/stdc++.h> int n; struct pos { int x, y; } ps[100007]; bool operator<(pos a, pos b) { return a.y != b.y ? a.y < b.y : a.x < b.x; } int bit[100007]; void inc(int w, int a) { for (; w <= n; w += w & -w) bit[w] += a; } int sum(int w) { int s = 0; for (; w; w -= w & -w) s += bit[w]; return s; } int ...
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide. We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise,...
#include <bits/stdc++.h> using namespace std; const int dx[9] = {0, 1, -1, 0, 0, -1, -1, 1, 1}; const int dy[9] = {0, 0, 0, -1, 1, -1, 1, -1, 1}; const double pi = acos(-1.0); const int N = 1e3; struct abc { int d[6]; }; int n; long long b[N + 10][6]; abc temp1, temp2; vector<long long> v; long long cal(abc temp1, ab...
Petya and Vasya got employed as couriers. During the working day they are to deliver packages to n different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate s1, Vasya is at the p...
#include <bits/stdc++.h> using namespace std; void re() { vector<int> b(1e10); } const int N = 1e5 + 3; const int LOG = 17; int n; int s1, s2; int a[N]; int st_left_min[LOG][N], st_right_min[LOG][N], st_left_max[LOG][N], st_right_max[LOG][N], par_left[LOG][N], par_right[LOG][N]; void build_sparse_table() { for (i...
Once upon a time in the galaxy of far, far away... Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star. When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon β€” sp...
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public voi...
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6). You are given an array a of n integers. You have to process two types of queries: 1. REPLACE l r β€” for every <image> replace ai with D(ai); 2. SUM l ...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int LINF = 0x3f3f3f3f3f3f3f3f; template <typename T, typename U> inline void amin(T &x, U y) { if (y < x) x = y; } template <typename T, typename U> inline void amax(T &x, U y) { if (x < y) x = y; } const int N = 2e6 + 7; const int N2 =...
Instructors of Some Informatics School make students go to bed. The house contains n rooms, in each room exactly b students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to n. Initially,...
#include <bits/stdc++.h> int cur_room_num[100000]; int main() { int num_room, d, room_num; std::cin >> num_room >> d >> room_num; for (int i = 0; i < num_room; ++i) { std::cin >> cur_room_num[i]; } int max_l = -1, min_r = num_room, left_stud = 0, right_stud = 0, left_cnt = 0, right_cnt = 0; for (i...
You are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 ≀ x ≀ 10^9) such that exactly k elements of given sequence are less than or equal to x. Note that the sequence can contain equal elements. If there is no such x, print "-1" (w...
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class file { public static void main(String[] args) throws Exception { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int k=sc.nextInt(); ...
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones. Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≀ i≀ j≀ n) a substring of string a. You can apply the following operations any number of times: * Choose some substring of string a (for example, you can choose entire strin...
n, x, y = [int(s) for s in input().split(' ')] a = input() z = len([t for t in a.split('1') if t]) ans = max(min(z * y, y + (z - 1) * x), 0) print(ans)
The lust for throne and power in the kingdom of Numberland has ensued a series of battles between 2 mighty armies - The Composites and The Primes. The kings decide to send their armies in waves. Both the armies consist of warriors having either prime or composite power. The warriors of both the armies fight against eac...
t = int(raw_input()) primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] while t>0: t -= 1 n = int(raw_input()) c = list(map(int, raw_input().split())) p = list(map(int, raw_input().split())) for i in range(0, n): if c[i] not i...
Euler's phi function for a positive integer N is usually denoted as Ο†(N) and defined as the number of positive integers less than or equal to N that are coprime with N. DA-IICT is organising its sports event in the month of October and this time they have introduced a new game called climbing ladder. The game is as f...
from bisect import bisect_left primes = [] def get_primes(n): sieve = [True] * (n/2) for i in xrange(3,int(n**0.5)+1,2): if sieve[i/2]: sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1) return [1] + [2*i for i in xrange(1,n/2) if sieve[i]] primes = get_primes(1000100) for ...
We have the following matrix 1 0 0 0 0 0 ... 2 2 0 0 0 0 ... 3 3 3 0 0 0 ... 4 4 4 4 0 0 ... 5 5 5 5 5 0 ... 6 6 6 6 6 6 ... and so on ... The matrix is created as follows, first row contains one 1 and rest 0's, second row contains 2 twos and rest zeros, third row contains 3 threes and so on. Given R and C, calcu...
for T in range(input()): odd = even = 0 r, c = map(int, raw_input().split()) if r <= c: if r % 2: odd = (((r+1)/2)*(1+r))/2 even = ((r/2)*(1+r))/2 else: odd = ((r/2)*(r))/2 even = ((r/2)*(2+r))/2 else: if c % 2: odd = (((c+1)/2)*(1+c))/2 + ((r-c)/2)*c even = ((c/2)*(1+c))/2 even += ((r-c+...
Little Louis has recently learnt a new word in his English class which reads same from either end. He is curious to find more similar words. His naughty friend poses him a challenge which goes as follows: He gives him a long word and asks him to find the length of the longest palindromic sub string. Input Format: T, ...
def check(a,i,j): while i<j: if (a[i]!=a[j]): return False i+=1 j-=1 return True t=input() while t: t-=1 s=raw_input() s=s.strip() ans=0 for i in range(len(s)): for j in range(len(s)): if (check(s,i,j)): ans=max(ans,j-i+1) print ans
An inversion in an array is a pair of indices (i, j) such that A[i] > A[j] and i < j, but you are given two arrays A and B and pairs such that A[i] > B[j] and i < j is called Inversion. If total number of inversions T, is a prime number then the that will be called a MAGIC INVERSION, otherwise it will be a SIMPLE INV...
def isp(n): for i in range(2,int(n/2)+1): if n%i==0: return False return True n=input() a=map(int,raw_input().split()) b=map(int,raw_input().split()) c=0 i,j=0,0 while i<n-1: while i<j+1 and j<n: if a[i]>b[j]: c+=1 j+=1 i+=1 if isp(c): print "MAGIC INVERSION" else: print "SIMPLE INVERSION"
Given an array A(A0, A1…. An-1) of n integers. Your task is to find the smallest number larger than a given no. X in the range [l,r] inclusive. Indexing is 0 based. If there is no greater no. than X in the specified range output -1. For example: A=[1 2 3 8 15 6 7 1 8 7], l=1 and r=5 For X=1 answer should be 2 For X=2...
t=raw_input().split() s=raw_input().split() A=[] B=[] k=0 k2=0 if len(s)==int(t[0])and int(t[0])>=1 and int(t[0])<=1000: l=int(t[1]) r=int(t[2]) n=int(t[3]) for i in range(l,r+1): if int(s[i])>=1 and int(s[i])<=pow(10,5): A.append(int(s[i])) else: k+=1 ...
NIT Raipur student 'Bhalli' have 16 numbers(non negative) which are in Arithematic Progression(Increasing AP) such that a1,a2,a3........a16(all integers). Bhalli anyhow know the value of a1+a4+a7+a10+a13+a16=n(Integer). Help Bhalli by telling him that the value he know is correct or not. Correct/Incorrect states whet...
t = input() for T in range(t): n = input() if n<45: print "INCORRECT" elif n%3 == 0: print "CORRECT" else: print "INCORRECT"
Sherlock is following N criminals, which are right now in a 2D grid. Each criminal at t=0, decides to move in certain fixed direction. Each criminal moves with same speed. These fixed directions are North, East, West and South. Two or more criminals, however, vanish whenever they meet at any place at same time, t>0. ...
for _ in xrange(input()): n = input() m = n D = {} C = [] i = 0 mnx, mxx, mny, mxy = 0, 0, 0, 0 for __ in xrange(n): x, y, d = raw_input().split() x = int(x) * 2 y = int(y) * 2 mxx = max(mxx, x) mxy = max(mxy, y) mnx = min(mnx, x) mny =...
The Monk wants to teach all its disciples a lesson about patience, since they are always in a hurry to do something crazy. To teach them this, he gives them a list of N numbers, which may or may not be distinct. The students are supposed to solve a simple Mathematical equation based on the array of these N numbers. g(x...
def gcd(a, b): if (b == 0): return a return gcd(b, a % b) n = int(raw_input()) l = map(int, raw_input().split()) m = reduce(lambda x, y: (x * y) % 1000000007, l) g = reduce(gcd, l) print pow(m, g, 1000000007)
Xsquare loves to play with arrays a lot. Today, he has an array A consisting of N distinct integers. He wants to perform following operation over his array A. Select a pair of consecutive integers say (Ai,Ai+1) for some 1 ≀ i < N. Replace the selected pair of integers with the max(Ai,Ai+1). Replace N with the new size ...
test = raw_input(); test = int(test); for i in range(0, test): size = raw_input(); size = int(size); total = 0; temp_list = []; temp_list = raw_input().split(); temp_list = [int(j) for j in temp_list]; if (temp_list[0] >= temp_list[1]): total = total + temp_list[0]; if(temp_li...
Snuke has a string x of length N. Initially, every character in x is `0`. Snuke can do the following two operations any number of times in any order: * Choose A consecutive characters in x and replace each of them with `0`. * Choose B consecutive characters in x and replace each of them with `1`. Find the number o...
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<vector> #include<cmath> #include<algorithm> #include<map> #include<queue> #include<deque> #include<iomanip> #include<tuple> #include<cassert> using namespace std; typedef long long int LL; typedef pair<int,int> P; typedef pair<LL,int> LP; c...
Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction. Let us define a function f(r, c) as follows: * f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operati...
#include<bits/stdc++.h> #define int int64_t using namespace std; const int M = 1e9+7; int fact[2000055] , inv[2000055]; int __power(int x , int p) { int res = 1; while(p) { if(p & 1) res = (res * x)%M; p /= 2; x = (x * x)%M; } return res; } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); ...
There is an integer sequence A of length N whose values are unknown. Given is an integer sequence B of length N-1 which is known to satisfy the following: B_i \geq \max(A_i, A_{i+1}) Find the maximum possible sum of the elements of A. Constraints * All values in input are integers. * 2 \leq N \leq 100 * 0 \leq B_i...
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; vector<int> b(n-1); for(int i=0; i<n-1; ++i)cin>>b[i]; int ans=0; for(int i=1; i<n-1; ++i)ans+=min(b[i], b[i-1]); ans+=b[0]+b[n-2]; cout<<ans<<endl; }
You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A_{11} to A_{HW} represent the colors of the squares. A_{ij} is `#` if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is `.` if t...
#include <bits/stdc++.h> #define ll long long using namespace std; const ll INF=(ll)1e9; const ll MOD=(ll)1e9+7; vector<int> dx={1,0,-1,0},dy={0,1,0,-1}; int main(){ int H,W,cnt=0,nx,ny; queue<pair<int,int>> q; pair<int,int> p; cin>>H>>W; vector<vector<int>> A(H,vector<int>(W)); for(int i=0;i<H;i++){ f...
There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i. You and Lunlun the dachshund alternately perform the following operation (starting from you): * Choose one or more apples from the tree and eat them. Here, the apples chosen at ...
N = int(input()) A = [int(input()) for i in range(N)] for a in A: if a%2: print('first') exit() print('second')
There is a simple undirected graph with N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects Vertex U_i and V_i. Also, Vertex i has two predetermined integers A_i and B_i. You will play the following game on this graph. First, choose one vertex and stan...
#include<bits/stdc++.h> #define fir first #define sec second #define db double #define ll long long #define ev eg[i].v #define pb push_back #define INF 1000000007 #define pir pair<int,int> #define Rep(i,l,r) for(int i=(l);i<=(r);++i) #define RepD(i,r,l) for(int i=(r);i>=(l);--i) #define RepG(i,x) for(int i=hd[x];i;i=eg...
Joisino is planning to record N TV programs with recorders. The TV can receive C channels numbered 1 through C. The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i. Here, there will never be more than one program that are broadcast on ...
import sys def MI(): return map(int,sys.stdin.readline().rstrip().split()) N,C = MI() A = [[0]*(10**5+2) for i in range(C+1)] for i in range(N): s,t,c = MI() A[c][s] += 1 A[c][t+1] -= 1 from itertools import accumulate for i in range(1,C+1): A[i] = list(accumulate(A[i])) # A[i][j] が正 ⇔ チャンネル i γŒζ™‚εˆ» j...
There are N bags of biscuits. The i-th bag contains A_i biscuits. Takaki will select some of these bags and eat all of the biscuits inside. Here, it is also possible to select all or none of the bags. He would like to select bags so that the total number of biscuits inside is congruent to P modulo 2. How many such wa...
N, P = map(int, input().split()) O = sum([int(a) % 2 for a in input().split()]) E = N - O fa = [1] for i in range(1, 51): fa.append(fa[-1] * i) ans = 0 for i in range(P, O+1, 2): ans += fa[O] // (fa[i] * fa[O-i]) print(ans * 2**E)
Snuke has decided to play with N cards and a deque (that is, a double-ended queue). Each card shows an integer from 1 through N, and the deque is initially empty. Snuke will insert the cards at the beginning or the end of the deque one at a time, in order from 1 to N. Then, he will perform the following action N times...
#include<bits/stdc++.h> #define N 2005 #define LL long long using namespace std; const int mo=1e9+7; int n,k,f[N][N],s[N][N],ans; LL fpm(LL x,LL y){ LL s=1; while(y){ if(y&1) s=(s*x)%mo; y>>=1,x=(x*x)%mo;} return s;} void inc(int &x,int y){ x=x+y>=mo ? x+y-mo : x+y;} int main() { int i,j; cin>>n>>k; f[n+1][0]=s[n+1]...
One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend. Find the following: <image> Constraints * 1 ≦ N ≦ 200,000 * (a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N). Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output Print th...
#include <iostream> #include <set> #define REP(i, a, n) for(int i = a; i <= n; i++) using namespace std; const int SIZE = 200001; int N, a[SIZE], pos[SIZE]; long ans; set<int> s; int main(void) { cin >> N; REP(i, 1, N) { cin >> a[i]; pos[a[i]] = i; } s.insert(0); s.insert(N + 1); ans = 0; ...
Obesity is cited as the cause of many adult diseases. In the past, with a few exceptions, it was unrelated to high school students. However, it is no longer unrealistic to suffer from lack of exercise due to excessive studying for entrance exams, or to become bulimia nervosa due to stress. It may be a problem that high...
#include<cstdio> #include<iostream> #include<algorithm> #include<vector> using namespace std; int main(){ int num,flag=0; double tall,weight; while(scanf("%d,%lf,%lf",&num,&weight,&tall)!=EOF){ if(weight/(tall*tall)>=25){cout<<num<<endl;flag=1;} } if(flag==0)cout<<"該当γͺし"<<endl; return 0;...
Relative B came to Mr. A's house. He is 3 years old and loves blocks. The block he has is shaped like Figure 1. <image> Figure 1 Mr. B is laying blocks on the board. When I asked him, "What are you making?", He replied cheerfully, "Maze !!". The maze he says is the arrangement of blocks that are in contact with each...
#include <bits/stdc++.h> #define FOR(i, j, k) for(int i = j; i < k; ++i) #define rep(i, j) FOR(i, 0, j) #define MAX 101 using namespace std; int field[MAX][MAX]; bool went[MAX][MAX]; int w, h; int sx, sy, gx, gy; int scol; const int dx[] = {0,0,1,-1}; const int dy[] = {1,-1,0,0}; bool dfs(int x, int y) { if(field[...
A boy PCK is playing with N electric metronomes. The i-th metronome is set to tick every t_i seconds. He started all of them simultaneously. He noticed that, even though each metronome has its own ticking interval, all of them tick simultaneously from time to time in certain intervals. To explore this interesting phen...
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <algorithm> #include <utility> #include <functional> #include <cstring> #include <queue> #include <stack> #include <math.h> #include <iterator> #include <vector> #include <string> #include <set> #include <math.h> #include <iostream> #include <random> #include...
The JOI Institute has 2 ^ L venomous snakes, numbered 0, 1, ..., and 2 ^ L -1 respectively. All venomous snakes are divided into L parts in order from the head, and each part is blue or red. For the poisonous snake i, when i is expressed in binary and i = $ \ sum_ {k = 1} ^ {L} $ c_k2 ^ {L-k} (0 \ leq c_k \ leq 1) * I...
#include <cstdio> #pragma warning(disable : 4996) int N, Q, v[1048588], vx[1048588], vy[1048588], pc[75]; char s[1048588], qs[29]; int main() { scanf("%d%d%s", &N, &Q, s); for (int i = 0; i < 1 << N; ++i) { v[i] = s[i] - '0'; vx[i] = v[i]; vy[i] = v[i]; } for (int i = 0; i < N; ++i) { for (int j = 0; j < 1 ...
Here, we want to solve path planning for a mobile robot cleaning a rectangular room floor with furniture. Consider the room floor paved with square tiles whose size fits the cleaning robot (1 Γ— 1). There are 'clean tiles' and 'dirty tiles', and the robot can change a 'dirty tile' to a 'clean tile' by visiting the tile...
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <queue> #define int long long using namespace std; class Solver { }; signed main() { while (true) { int w, h; cin >> w >> h; if (w == 0)break; tuple<int, int> start; vector<vector<bool>> gr...
In this problem, we consider a simple programming language that has only declarations of one- dimensional integer arrays and assignment statements. The problem is to find a bug in the given program. The syntax of this language is given in BNF as follows: <image> where <new line> denotes a new line character (LF). C...
#include <bits/stdc++.h> using namespace std; class arrayInfo{ private: int element=-1; map<string,string> value; public: bool isInRange(string index){ return stoi(index)<element; } void set(string index, string val){ if(isInRange(index)){ value[index]=val; }...
Two countries, Country A and Country B, are at war. As a soldier in Country A, you will lead n soldiers to occupy the territory of Country B. The territory of Country B is represented by a two-dimensional grid. The first place you occupy is a square on the 2D grid. Each of the soldiers you lead has h_i health. Each so...
#include<bits/stdc++.h> using namespace std; int main(){ long int s=1; int a[500],n,i,c=0; cin>>n; for(i=0;i<n;i++)cin>>a[i]; sort(a,a+n-1); for(i=n-1;i>=0;i--,c++){ if((a[i]-c/4)<0)continue; else s+=a[i]-c/4; } cout<<s<<endl; return 0; }
<!-- Problem H --> Addition on Convex Polygons Mr. Convexman likes convex polygons very much. During his study on convex polygons, he has come up with the following elegant addition on convex polygons. The sum of two points in the xy-plane, (x1, y1) and (x2, y2) is defined as (x1 + x2, y1 + y2). A polygon is treat...
#include <iostream> #include <vector> #include <algorithm> #include <utility> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <set> using namespace std; typedef long long LL; typedef pair<LL,LL> pll; pll add(const pll &a, const pll &b){ return pll(a.first + b.first, a.second + b.sec...
You are a hero of a role playing game, asked by the king to defeat monsters threating people’s life. You have been making a long journey with your colleagues, and you are now in the town closest to the final dungeon where the head of monsters dwells. You have heard from people that the head monster hits with his stron...
#include <iostream> #include <vector> #include <string> #include <map> #include <queue> #include <algorithm> using namespace std; #define rep(i, n) for(int i = 0; i < (n); ++i) #define pb push_back const int INF = 1001001001; const int N = 110, MAX_V = 2 * N; const int src = 210, sink = 211; typedef pair<int, int> ...
A rabbit Taro decided to hold a party and invite some friends as guests. He has n rabbit friends, and m pairs of rabbits are also friends with each other. Friendliness of each pair is expressed with a positive integer. If two rabbits are not friends, their friendliness is assumed to be 0. When a rabbit is invited to t...
#include <bits/stdc++.h> using namespace std; #define int long long #define FR first #define SC second #define all(v) (v).begin(), (v).end() #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define reps(i, f, n) for(int i = (int)(f); i < (int)(n); i++) #define each(a, b) for(auto& a : b) typedef pair<int, int> P;...
You are a magician and have a large farm to grow magical fruits. One day, you saw a horde of monsters, approaching your farm. They would ruin your magical farm once they reached your farm. Unfortunately, you are not strong enough to fight against those monsters. To protect your farm against them, you decided to build ...
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define EPS (1e-6) #define equals(a,b) (fabs((a)-(b)) < EPS) #define COUNTER_CLOCKWISE 1 #define CLOCKWISE -1 #define ONLINE_BACK 2 #define ONLINE_FRONT -2 #define ON_SEGMENT 0 using namespace std; class Point{ public: dou...
You are a programmer who loves pretty girl games (a sub-genre of dating simulation games). A game, which is titled "Floatable Heart" and was released last Friday, has arrived at your home just now. This game has multiple stories. When you complete all of those stories, you can get a special figure of the main heroine, ...
#include<bits/stdc++.h> #define MAX 2001 #define inf 1<<29 #define linf (1e16) #define eps (1e-8) #define Eps (1e-12) #define mod 1000000007 #define pi acos(-1.0) #define phi (1.0+sqrt(5.0))/2.0 #define f first #define s second #define mp make_pair #define pb push_back #define all(a) (a).begin(),(a).end() #define pd(a)...
H: About Our Effort-About Our Effort- problem * I would appreciate it if you could consider this problem as an extra problem, and if possible, I would like you to enjoy the other problems first. I would like to challenge those who are willing to crush in this contest. D Sorry for the slow query for the problem. But ...
#include <iostream> #include <vector> #include <algorithm> using namespace std; using ll = long long; using P = pair<int, int>; /** * Fenwick Tree * * 0-indexed */ template <int N> struct FenwickTree { using D = ll; /// ????Β΄??????? D seg[N+1]; /// ????Β΄??????????????????? void init() { ...
B: Twins One twin was angry that it was not well known which of them was the older brother and which was the younger brother. Create a program that outputs "square1001" when "ani" is entered and "e869120" when "otouto" is entered. input You will be given either the string "ani" or "otouto" as input. output Please...
#include <iostream> #include <cmath> #include <vector> #include <algorithm> #include <string> #include <queue> #include <functional> #include <map> using namespace std; int main() { string S; cin >> S; if (S == "ani") cout << "square1001" << endl; else cout << "e869120" << endl; return 0; }
Problem A dolphin who lives in a certain aquarium will be rewarded if he jumps and goes through the $ N $ ring. * Dolphin jumps from coordinates $ (0,0) $ and lands at $ (T,0) $. * The trajectory of the jump is a parabola. * The $ i $ th ring is determined to have passed through when the jump trajectory intersects th...
#include<bits/stdc++.h> using namespace std; class fraction { long long numer; // bunshi long long denom; // bunbo public: fraction(long long numer, long long denom) : numer(numer), denom(denom) {} int compare_to(const fraction& f) const { assert(denom > 0 && f.denom > 0); long long res...
For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the poly...
#include<bits/stdc++.h> using namespace std; typedef long long lint; typedef long double louble; template<typename T1,typename T2> inline T1 max(T1 a,T2 b){return a<b?b:a;} template<typename T1,typename T2> inline T1 min(T1 a,T2 b){return a<b?a:b;} namespace ae86 { const int bufl = 1<<15; char buf[bufl],*s=buf,*t...
For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_...
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n; cin>>n; vector <long long> a(n); for(int i=0;i<n;i++) { cin>>a[i]; } int length; length=unique(a.begin(),a.end())-a.begin(); int j; for(j=0;j<length-1;j++) { ...
Little Chef is learning differentiation and is amazed by the function e^x as it stays the same even after differentiation. Just for fun, he tries to find out how large is the value of e^x. He is able to see only 10 digits in his calculator so he wants you to answer his endless list of queries for different values of x....
# your code goes here import math t=raw_input().split() t=int(t[0]) val = 0.4342944819032518 while(t): x=raw_input().split() x=int(x[0]) print int(x*val+1) t-=1
The executive chef is trying to bring some competitive spirit into his kitchen. He wants to split the chefs into two teams based on their age - he'll form the young and the old team. To make it fair, he will split them evenly or give the young team one person advantage when there is an odd number of chefs. Ages of all ...
from heapq import * def push_to_young(young, item): heappush(young, (-item[0], item[1])) def pop_from_young(young): i = heappop(young) return (-i[0], i[1]) def push_to_old(old, item): heappush(old, item) def pop_from_old(old): return heappop(old) N = int(raw_input()) young = [] old = [] sum_you...
Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account bal...
#!/usr/bin/python a,b=raw_input().split() a=int(a) b=float(b) if(a%5==0 and a<b-0.5): b=b-a-0.5; print "%0.2f" %b
Given a square table sized NxN (3 ≀ N ≀ 5,000; rows and columns are indexed from 1) with a robot on it. The robot has a mission of moving from cell (1, 1) to cell (N, N) using only the directions "right" or "down". You are requested to find the number of different ways for the robot using exactly K turns (we define a "...
import sys tokenizedInput = sys.stdin.read().split() mod=1000000007 arr=[1]*5001 for i in range(1,5001): arr[i]=(arr[i-1]*i)%mod def Power(base,expo): if(expo==0): return 1 else: if(expo&1): return(base*Power(base,expo-1)%mod) else: root=Power(base,expo>>1)...
Let G(S) denote the sum of the elements of set S and F(n) be the sum of G(s) for all subsets of the set consisting of the first n natural numbers. For example, F(3) = (1) + (2) + (3) + (1 + 2) + (1 + 3) + (2 + 3) + (1 + 2 + 3) = 24. Given n, calculate F(1) + F(2) + ... + F(n). Input The first line contains the ...
def fact (a): if a==0: return 1 else: return a*fact(a-1) def f( b): sum=0 sum1=0 for i in range(b): sum=sum+ fact(b-1)/(fact(i)*fact(b-i-1)) sum1=sum1+i+1 return sum1*sum t=int(raw_input()) while(t): sum2=0 n=int(raw_input()) if(n<=22): for ...
Nim is a well-known combinatorial game, based on removing stones from piles. In this problem, we'll deal with a similar game, which we'll call Dual Nim. The rules of this game are as follows: Initially, there are N piles of stones, numbered 1 through N. The i-th pile contains ai stones. The players take alternate turn...
t=int(raw_input()) while(t): t-=1 n=int(raw_input()) x=map(int,raw_input().split()) txor=reduce(lambda x,y:x^y,x) print "Second" if ((txor) and (n%2)) else "First"
Abendsen assigned a mission to Juliana. In this mission, Juliana has a rooted tree with n vertices. Vertex number 1 is the root of this tree. Each vertex can be either black or white. At first, all vertices are white. Juliana is asked to process q queries. Each query is one of three types: 1. If vertex v is white, m...
#include <bits/stdc++.h> using namespace std; const int maxn = 100005; bool black[maxn]; vector<int> vec[maxn]; bool old_black[maxn]; const int MAX_BLOCK_SIZE = 600; int t[maxn], v[maxn]; bool used[maxn]; vector<pair<pair<int, int>, int>> v2[maxn]; int push[maxn]; bool clear[maxn]; void dfs1(int pos, int prev = -1, int...
A plane is flying at a constant height of h meters above the ground surface. Let's consider that it is flying from the point (-10^9, h) to the point (10^9, h) parallel with Ox axis. A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only w...
#include <bits/stdc++.h> using namespace std; long long n, m; struct data { long long l; long long r; friend bool operator<(const data &a, const data &b) { return a.l < b.l; } } qwq[200010]; long long num[200010]; long long now[200010]; long long minn; long long ans; int main() { scanf("%lld%lld", &n, &m); fo...
A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not. A string is called a substring of another string, if it can be obtained from that string by dropping some (possi...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); const long long INF = 2e18; void print(int a[], int n) { for (int i = 0; i < n; i++) cout << a[i] << " "; cout << "\n"; } void printll(long long a[], long long n) { for (int i = 0; i < n; i++) cout << a[i] << " "; cout << "\n"; } void _...
The Squareland national forest is divided into equal 1 Γ— 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner. Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C i...
#include <bits/stdc++.h> using namespace std; const int N = 1e3 + 1; struct pto { int x, y; pto(int _x = 0, int _y = 0) : x(_x), y(_y) {} bool operator<(const pto &p) const { return make_pair(x, y) < make_pair(p.x, p.y); } bool operator!=(const pto &p) const { return make_pair(x, y) != make_pair(p.x, ...
Lunar New Year is approaching, and you bought a matrix with lots of "crosses". This matrix M of size n Γ— n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≀ i, j ≀ n. We define a cross appearing in the i-th row and the j-th column (1 < i...
n=int(input()) a=[] for i in range(n): s=input() a.append(s) ans=0 for i in range(1,n-1): for j in range(1,n-1): if(a[i][j]=='X' and a[i-1][j-1]=='X' and a[i-1][j+1]=='X' and a[i+1][j-1]=='X' and a[i+1][j+1]=='X'): ans+=1 print(ans)
International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift ...
import java.util.*; import java.lang.*; import java.io.*; import java.awt.*; // U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................ //JUst keep faith in ur strengths .................................................. // ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 ...
This is an interactive problem. Now Serval is a senior high school student in Japari Middle School. However, on the way to the school, he must go across a pond, in which there is a dangerous snake. The pond can be represented as a n Γ— n grid. The snake has a head and a tail in different cells, and its body is a series...
#include <bits/stdc++.h> using namespace std; int gt(int a, int b, int aa, int bb) { cout << "? " << a << ' ' << b << ' ' << aa << ' ' << bb << endl; int f; cin >> f; return f; } int main() { int n; cin >> n; int r[n], c[n]; int del1 = -1, del2 = -1; for (int i = 0; i < n; i++) { if (i == n - 1 &&...
You are given an array a_1, a_2, ..., a_n and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let f(i) be the index of subarray the i-th element belongs to. Subarrays are numbered from left to right and from...
#include <bits/stdc++.h> using namespace std; const long long mod = 1000000007LL; int n, k; int a[300005]; int main() { cin >> n >> k; for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); } vector<long long> rk; rk.clear(); long long sum = 0LL; for (int i = n; i > 1; --i) { sum += a[i]; rk.push_...
You are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings. During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of...
import java.util.*; import java.io.*; public class C{ public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(f.readLine()); for(int i = 0; i < n; i++){ StringBuilder str1 = new StringBuil...
Mateusz likes to travel! However, on his 42nd visit to Saint Computersburg there is not much left to sightsee. That's why he decided to go to an escape room with his friends! The team has solved all riddles flawlessly. There is only one riddle remaining β€” a huge circular table! There are n weighing scales lying on top...
#include <bits/stdc++.h> using namespace std; template <class T> inline void rd(T &x) { x = 0; char c = getchar(); int f = 1; while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) x = x * 10 - '0' + c, c = getchar(); x *= f; } const int N = 35010; inline int Abs(int x) { ...
Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other. Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i...
#include <bits/stdc++.h> using namespace std; pair<long long int, long long int> arr[7777]; map<long long int, int> mm; long long int ans, dp[66]; vector<long long int> v; int main(void) { dp[0] = 1; for (int p = 1; p <= 60; p++) dp[p] = dp[p - 1] * 2; int n; scanf("%d", &n); for (int e = 0; e < n; e++) { ...
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n. Two fairs are currently taking place in Berland β€” they are held in two different cities a and b (1 ≀ a, b ≀ n; a ...
#include <bits/stdc++.h> using namespace std; long long mo(const long long input, const long long ceil) { return input >= ceil ? input % ceil : input; } const long long maxn = 5e5 + 10; long long cnt, cnta, cntb; long long vis[maxn]; vector<long long> e[maxn]; void dfs(long long k, long long t) { vis[k] = t; cnt+...
There is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its path is described as a string s of length n consisting of characters 'L', 'R', 'U', 'D'. Each of these characters corresponds to some move: * 'L' (left): means that the robot moves from the point (x, y) to the point (x...
#include <bits/stdc++.h> using namespace std; void solve(string s, int n) { map<pair<int, int>, int> pos; map<pair<int, int>, bool> mep; pair<int, int> at = {0, 0}; pos[at] = 0; mep[at] = true; int ans = 202020; int lans = -1, rans = -1; for (int i = 0; i < n; i++) { if (s[i] == 'U') at.second++; ...
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the trou...
#include <bits/stdc++.h> using namespace std; long long funk(long long x, long long y) { bool used[10000]; long long res = 1; for (long long i = 1; i <= 100; i++) used[i] = 0; for (long long i = x + 1; i <= y; i++) { res *= i; for (long long j = 2; j <= y - x; j++) { if (!used[j] && res % j == 0) ...
Due to the success of TWICE, JYP Entertainment has earned countless money and emerged as the biggest entertainment firm by market capitalization. Therefore, the boss, JYP, has decided to create a new nation and has appointed you to provide a design diagram. The new nation consists of n cities and some roads between th...
#include <bits/stdc++.h> using namespace std; const int maxn = 8010; int n, sz, ind[maxn], del[maxn]; char s[maxn]; long long ans; bitset<maxn> e[maxn]; int main() { scanf("%d", &n), sz = n; for (int i = 1; i <= n; i++) { scanf("%s", s + 1); for (int j = 1, $ = 0; j <= n; j++) { int x = isdigit(s[++$]...
Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or...
from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd for _ in range(int(input())): n,k=map(int,input().split()) if k>=n: print(1) else: l=[] s=int(sqrt(n)) for i in range(2,s+2): if n%i==0 and i<=k: l.append(n//i) t=n//i if t<=k: l.append(...
You have a set of n discs, the i-th disc has radius i. Initially, these discs are split among m towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top. You would like to assemble one tower containing all of those discs. To do so, you ...
#include <bits/stdc++.h> using namespace std; const int N = 200005; bool done[N]; set<int> a[N]; int b[N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; int x = 0; int res = 0; for (int i = 1; i <= m; i++) { b[i] = i; } m--; for (int i = 1; i <= n...
You have a multiset containing several integers. Initially, it contains a_1 elements equal to 1, a_2 elements equal to 2, ..., a_n elements equal to n. You may apply two types of operations: * choose two integers l and r (l ≀ r), then remove one occurrence of l, one occurrence of l + 1, ..., one occurrence of r fro...
import java.io.*; import java.util.*; import java.math.*; public class E { public void go() throws IOException { int n = ipar(); int[] arr = iapar(n); out.println(solve(arr, 0, n-1, 0)); } public int solve(int[] arr, int l, int r, int h) { int n = arr.length; if (l...
After making a strategic plan with carriers for expansion of mobile network throughout the whole country, the government decided to cover rural areas with the last generation of 5G network. Since 5G antenna towers will be built in the area of mainly private properties, the government needs an easy way to find informat...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-14; const int maxn = 1000010; struct Point { double x, y; Point(double xx = 0, double yy = 0) { x = xx, y = yy; } Point operator-(const Point &a) const { return Point(x - a.x, y - a.y); } Point operator+(const Point &a) const { return Point(x +...
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i ≀ x holds for each i (1 ≀ i ≀ n). Input The first line of input contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. t blocks follow, each d...
y = int(input()) for _ in range(y): q = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split()))[::-1] e = True for i in range(q[0]): if a[i] + b[i] <= q[1]: pass else: print("No") e = False ...
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It...
n = int(input()) s = input() print('YES' if set(s) <= {'4', '7'} and s[:len(s) // 2].count('4') == s[-(len(s) // 2):].count('4') else 'NO')
There are many sunflowers in the Garden of the Sun. Garden of the Sun is a rectangular table with n rows and m columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burn...
import sys, os if os.environ['USERNAME']=='kissz': inp=open('in.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE for _ in range(int(inp())): n,m=map(int,inp().split()) R=[] for i ...
After hearing the story of Dr. Zhang, Wowo decides to plan his own flight around the world. He already chose n checkpoints in the world map. Due to the landform and the clouds, he cannot fly too high or too low. Formally, let b_i be the height of Wowo's aircraft at checkpoint i, x_i^-≀ b_i≀ x_i^+ should be satisfied ...
#include <bits/stdc++.h> template <typename T> void setmax(T& a, T b) { if (b > a) a = b; } template <typename T> void setmin(T& a, T b) { if (b < a) a = b; } template <typename T> struct range_val { T lo, hi; range_val() : lo(), hi( ){} range_val(T lo_, T hi_) : lo(lo_), hi(hi_) {} friend std::istream& opera...
AquaMoon has three integer arrays a, b, c of length n, where 1 ≀ a_i, b_i, c_i ≀ n for all i. In order to accelerate her potato farming, she organizes her farm in a manner based on these three arrays. She is now going to complete m operations to count how many potatoes she can get. Each operation will have one of the ...
#include <stdio.h> #include <string.h> #define N 200000 #define Q 50000 #define K 400 #define L (K * 6 + 1) int min(int a, int b) { return a < b ? a : b; } int aa[N], bb[N], cc[N], ii[Q], xx[Q], n; char landmark[N]; int gg[N], ii_[K], aa_[K], bb_[K], cc_[K], k; int col[N], qu[L], l; int kk[N + 1]; long long kk_[N]; ...
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scisso...
#include <bits/stdc++.h> using namespace std; int n; string a; string b; vector<int> da; vector<int> db; bool win(char a, char b) { if (a == 'P' && b == 'R') return true; if (a == 'R' && b == 'S') return true; if (a == 'S' && b == 'P') return true; return false; } int main() { cin >> n >> a >> b; int i = 0,...
John Doe has four arrays: a, b, k, and p. Each array consists of n integers. Elements of all arrays are indexed starting from 1. Array p is a permutation of integers 1 to n. John invented a game for his friends and himself. Initially a player is given array a. The player must consecutively execute exactly u operations...
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner r = new Scanner(System.in); N = r.nextInt(); u = r.nextInt(); R = r.nextInt(); int[] a = new int[N]; b = new int[N]; k ...
Fibonacci numbers are the sequence of integers: f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ..., fn = fn - 2 + fn - 1. So every next number is the sum of the previous two. Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he perf...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1000100; const int INF = 1000000007; int n, r; int wyn = -1; vector<int> stos; vector<int> wynikowy; void readData() { scanf("%d%d", &n, &r); } void sprawdz(int g, int d, int dep) { if (dep < 0) return; int k; if (dep == 0) { if ((g == 1) && (d ==...
There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c1, c2, ..., cn. The Old Peykan wants to travel from city c1 to cn using roads. There are (n - 1) one way roads, the i-th road goes from city ci to city ci + 1 and is di kil...
#include <bits/stdc++.h> using namespace std; int main() { int m, k, s[1010], d[1010], ans = 0, minn[1010]; cin >> m >> k; for (int i = 0; i < m; i++) cin >> d[i], ans += d[i]; for (int i = 0; i < m; i++) cin >> s[i]; int l = 0, r = 0, maxx = 0; for (int i = 0; i < m; i++) { l += s[i]; r += d[i]; ...
There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi. Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximiz...
#include <bits/stdc++.h> using namespace std; int n, v[100000], c[100000]; int q, a, b; long long f[100000 + 1]; bool m[100000 + 1]; int x, y; long long query(long long a, long long b) { memset(f, 0, sizeof(f)); memset(m, 0, sizeof(m)); f[0] = x = y = 0; long long res = 0; for (int i = 0; i < n; ++i) { lo...
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive. For permutation p = p0, p1, ..., pn, Polo has defined its beauty β€” number <image>. Expression <image> means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in al...
import java.io.*; import java.util.StringTokenizer; public class Main { void solve() { int n = ni(); int cur = n; long m = 0; int[] out = new int[n + 1]; while (cur > 0) { int mask = getMask(cur); int next = (cur ^ mask) - 1; while ((cur ^...
Sereja painted n points on the plane, point number i (1 ≀ i ≀ n) has coordinates (i, 0). Then Sereja marked each point with a small or large English letter. Sereja don't like letter "x", so he didn't use it to mark points. Sereja thinks that the points are marked beautifully if the following conditions holds: * all ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010; char s[MAXN]; int n, q; unsigned int dp[2][MAXN]; int main() { cin >> n; scanf("%s", s); for (int i = 0; s[i]; i++) if (s[i] == '?') q++; if ((n & 1) || (q < n / 2)) { printf("0\n"); return 0; } memset(dp, 0, sizeof(dp)); i...
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the scre...
#include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:102400000") int a, b, c, d; int gcd(int x, int y) { if (!y) return x; return gcd(y, x % y); } int main() { cin >> a >> b >> c >> d; int d1 = gcd(a, b), d2 = gcd(c, d); a /= d1, b /= d1; c /= d2; d /= d2; int d3 = b * d / gcd(b...