input
stringlengths
29
13k
output
stringlengths
9
73.4k
There is a directed graph with N vertices and N edges. The vertices are numbered 1, 2, ..., N. The graph has the following N edges: (p_1, 1), (p_2, 2), ..., (p_N, N), and the graph is weakly connected. Here, an edge from Vertex u to Vertex v is denoted by (u, v), and a weakly connected graph is a graph which would be ...
#include <bits/stdc++.h> #define mod 1000000007 #define mod998 998244353 #define sp ' ' #define intmax 2147483647 #define llmax 9223372036854775807 #define mkp make_pair typedef long long ll; using namespace std; int N, P[200000], a[200000]; bool vis[200000]; vector<int>rev[200000]; void dfs(int x) { if (a[x] != -1)...
Dolphin is planning to generate a small amount of a certain chemical substance C. In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b. He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmac...
#!python3 import copy LI = lambda: list(map(int, input().split())) # input N, Ma, Mb = LI() ABC = [LI() for _ in range(N)] INF = 10 ** 5 def main(): w = [[INF] * 401 for _ in range(401)] w[0][0] = 0 for a, b, c in ABC: l = copy.deepcopy(w) for j in range(a, 401): for k in r...
There are N strings of lowercase alphabet only. The i-th string is S_i. Every string is unique. Provide answers for the Q queries below. The i-th query has the following format: Query: An integer k_i and a string p_{i,1}p_{i,2}...p_{i,26} that results from permuting {`a`,`b`,...,`z`} are given. Output the sequence of...
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <cmath> #include <queue> #include <stack> #include <set> #include <map> #include <sstream> #include <string> #define repd(i,a,b) for (int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repd(i,0,n...
There is data of up to 100 characters per line, consisting of half-width alphabetic character strings. Some lines are symmetric (same whether read from the left edge or the right edge). Create a program that reads this data and outputs the number of symmetric strings in it. Note that lines consisting of only one charac...
#include <iostream> #include <string> int main(){ int c=0; std::string s; while(std::cin>>s) if (s== std::string(s.rbegin(),s.rend())) c++; std::cout<<c<<"\n"; }
In Aizuwakamatsu City, there is a first city called "Tokaichi" on January 10th every year. This Tokaichi has a history of about 600 years and is the largest first city in the Aizu region. It is also well known that Okiagari-koboshi, a familiar lucky charm, is sold in the Aizu region. Okiagari-koboshi is a papier-mâché ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main{ public static void main(String[] args)throws IOException{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(isr); String string, mf = ""; int max, ...
On a large chess board, there are N ants, each numbered from 1 to N. As shown in the figure, the chess board is a rectangle consisting of H × W squares, with the northwest corner as white, and white squares and black squares are arranged alternately. <image> Initially, every ant is in a chessboard square, facing ea...
#include <bits/stdc++.h> #define FOR(x, a, b) for (int x = a; x <= b; ++x) #define FOD(x, a, b) for (int x = a; x >= b; --x) #define REP(x, a, b) for (int x = a; x < b; ++x) #define DEBUG(X) { cout << #X << " = " << X << endl; } #define PR(A, n) { cout << #A << " = "; FOR(_, 1, n) cout << A[_] << " "; cout << endl; } ...
problem The JOI country has one long enough road running east to west. The royal palace of JOI country is along the road, and the position along the road in JOI country is represented by the integer A. When A = 0, it represents the position of the royal palace. When A> 0, it indicates the position A meters east of the...
#include <bits/stdc++.h> using namespace std; typedef long long ll; struct Data { int X, id; ll A; Data(int id, int X, ll A) : id(id), X(X), A(A){} }; int main() { int N, Q; ll T; cin >> N >> T >> Q; ll A[N]; int D[N]; int X[Q]; for (int i = 0; i < N; i++) { cin >> A[i] >> D[i]; } for (int...
Mr. Frugal bought a new house. He feels deeply in love with his new house because it has a comfortable living room in which he can put himself completely at ease. He thinks his new house is a really good buy. But, to his disappointment, the floor of its living room has some scratches on it. The floor has a rectangle ...
#include<iostream> #include<functional> #include<algorithm> const int N = 11; const int inf = 1<<27; const int di[] = {-1,1,1,-1}; const int dj[] = {1,1,-1,-1}; using namespace std; int H,W; static int M[N][N]; static int maxSizes[N][N][4]; int oneCount; int minHW; int ans; int greedy_ans; int depth; int maxSize; i...
A positive integer may be expressed as a sum of different prime numbers (primes), in one way or another. Given two positive integers n and k, you should count the number of ways to express n as a sum of k different primes. Here, two ways are considered to be the same if they sum up the same set of the primes. For examp...
#include<bits/stdc++.h> #define N 1150 using namespace std; bool prime[N]; vector<int> p; int dp[205][N][15]; int main(){ for(int i=0;i<N;i++) prime[i]=true; prime[0]=prime[1]=false; for(int i=0;i*i<N;i++){ if(!prime[i])continue; for(int j=i*2;j<N;j+=i) prime[j]=false; } for(int i=0;i<N;i++...
Estimating the Flood Risk Mr. Boat is the owner of a vast extent of land. As many typhoons have struck Japan this year, he became concerned of flood risk of his estate and he wants to know the average altitude of his land. The land is too vast to measure the altitude at many spots. As no steep slopes are in the estate...
#include <bits/stdc++.h> using namespace std; int W, D, N; bool iss[55][55]; int Min[55][55], Max[55][55]; void adjust(int x, int y) { for(int i = 1; i <= W; i++) for(int j = 1; j <= D; j++) { int dis = abs(i-x)+abs(j-y); Min[i][j] = max( Min[i][j], Min[x][y]-dis ); Max[i][j] =...
Playoff by all the teams The Minato Mirai Football Association hosts its annual championship as a single round-robin tournament, in which each team plays a single match against all the others. Unlike many other round-robin tournaments of football, matches never result in a draw in this tournament. When the regular tim...
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <string> #include <set> #include <map> #include <queue> #include <cmath> using namespace std; #define rep(i,n) for(int i = 0; i<n ; i++) #define FOR(i,a,n) for(int i=a; i<n; i++) #define RANGE(a,i,b) ((a)<=(i)&&(i)<=(b)) #defi...
π (spelled pi in English) is a mathematical constant representing the circumference of a circle whose di- ameter is one unit length. The name π is said to come from the first letter of the Greek words περιφέρεια (meaning periphery) and περίμετρος (perimeter). Recently, the government of some country decided to allow u...
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)n; +...
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to use the Amidakuji to improve luck by gaining the ability to read the future. Of course, not only relying on intuition, but also detailed probability calculation is ...
// #define _GLIBCXX_DEBUG // for STL debug (optional) #include <iostream> #include <iomanip> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex...
There is a cube on a rectangle map with H-rows and W-columns grid. Two special squares a start and a goal are marked on the map. Initially, the cube is on the start square. Let's repeat to roll it and take it to the goal square. Rolling the cube means to select one of four edges which touch the map, and push the cube d...
#include<cstdio> #include<string> #include<vector> #include<iostream> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; class dice{ int a[6]; public: dice(){} dice(int t,int l,int f,int r,int b,int d){ a[0]=t; a[1]=l; a[2]=f; a[3]=r; a[4]=b; a[5]=d; } bool operator==(const dice &D)const{ rep(i,...
Ikta, who was in trouble because he couldn't come up with an idea for the problem to be presented at the training camp of the programming contest, consulted with a friend one day. Mr. Ikta "I want to create a problem that cannot be solved without using such an algorithm. Is there anything?" Friend "Then why not think...
#include<stdio.h> #include<algorithm> #include<string.h> #include<set> using namespace std; char A[310000]; char B[310000]; int p[310000]; int q[310000]; int bit[310000]; set<int>zero; set<int>two; set<int>bb; int sum(int a,int b){ if(a)return sum(0,b)-sum(0,a-1); int ret=0; for(;b>=0;b=(b&(b+1))-1)ret+=bit[b]; ret...
Problem statement Jota made a scale as shown in the figure below using a stick with a length of $ 2L $. <image> The rods are evenly spaced with $ 2L + 1 $ holes, from left to right: $ -L, -L + 1, \ cdots, -1, 0, 1, \ cdots, L-1, L $. It is numbered. And the place of the hole of No. $ 0 $ is hung from the ceiling wit...
#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int l, n; cin >> l >> n; int tx, tw, lw=0, rw=0; for (int i = 0; i < n; ++i) { cin >> tx >> tw; if (tx>0) { rw += tw * tx; } else if (tx<0) { lw += tw * abs(tx); } } if (lw == rw) { cout << 0 << endl; ...
problem Given the formula $ S $ of length $ N $. The formula is in the format shown in BNF below. <expr> :: = <number> | <expr> <op> <expr> <op> :: = ‘^’ | ‘&’ | ‘|’ <number> represents an integer greater than or equal to $ 0 $ and less than or equal to $ 2 ^ {31} -1 $. The operators ‘^’ ‘&’ ‘|’ represent exclu...
#include <bits/stdc++.h> #include<iostream> #include<cstdio> #include<vector> #include<queue> #...
Problem There are $ N $ islands and $ N-1 $ bridges in Aiz, and each island is assigned a number from $ 1 $ to $ N $. The $ i $ th bridge connects the island $ u_i $ and the island $ v_i $ in both directions, and islanders can use the bridge to move between islands. Also, there is no way to go back and forth between i...
#include<bits/stdc++.h> #define X first #define Y sevcond #define pb emplace_back #define eb pb #define rep(X,Y) for(int X=0;X<(Y);++X) #define reps(X,O,Y) for(int X=(O);X<(Y);++X) #define all(X) (X).begin(),(X).end() #define rall(X) (X).rbegin(),(X).rend() using namespace std; using ll=long long; const ll INF=1e18; ...
A complete binary tree is a binary tree in which every internal node has two children and all leaves have the same depth. A binary tree in which if last level is not completely filled but all nodes (leaves) are pushed across to the left, is also (nearly) a complete binary tree. A binary heap data structure is an array...
k,e=' key = ',', ' input() A=[0]+input().split() H=len(A) for i in range(1,H): print(f'node {i}: key = {A[i]}, {"parent"+k+A[i//2]+e if i>1 else""}{"left"+k+A[2*i]+e if 2*i<H else""}{"right"+k+A[2*i+1]+e if 2*i+1<H else""}')
For $n$ dynamic arrays $A_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations: * pushBack($t$, $x$): Add element $x$ at the end of $A_t$. * dump($t$): Print all elements in $A_t$. * clear($t$): Clear $A_t$. If $A_t$ is empty, do nothing. $A_i$ is a 0-origin array and it is empty in the initial...
#include <cstdio> #include <vector> using namespace std; int main() { int n, q, op, t, x; scanf("%d %d", &n, &q); vector<int> v[n]; while (q--) { scanf("%d %d", &op, &t); if (op == 0) { scanf("%d", &x); v[t].push_back(x); } else if (op == 1) { ...
Problem statement A lazy guy in UVCE is designing a robot that could collect all useful things from different places and put them in one place. In its testing stage robot is given a task. 10^5 boxes are arranged is straight line and they numbered from 1 to 10^5. Some boxes contain useful things, bot has to collect al...
for _ in xrange(input()): n=input() s=map(int,raw_input().split()) midpos=sum(s)/n moves=0 for i in s: moves+=abs(i-midpos) print moves
Did you hear about the Nibiru collision ? It is a supposed disastrous encounter between the earth and a large planetary object. Astronomers reject this idea. But why listen to other people's beliefs and opinions. We are coders above all, so what better way than to verify it by a small code. The earth and N asteroids ar...
# codechef - easy - collide dirTable = {} dirTable["R"] = (1,0) dirTable["L"] = (-1,0) dirTable["D"] = (0,-1) dirTable["U"] = (0,1) def readCoordinates(): strX, strY, strDir = raw_input().split() x = int(strX) y = int(strY) dx,dy = dirTable[strDir] return x,y, dx,dy t = int(raw_input()) for test...
Chef has just finished the construction of his new garden. He has sown the garden with patches of the most beautiful carpet grass he could find. He has filled it with patches of different color and now he wants to evaluate how elegant his garden is. Chef's garden looks like a rectangular grid of cells with N rows and M...
T=int(raw_input()) for t in range(T): s=map(int,raw_input().split()) n=s[0] m=s[1] l=[] for i in range(n): l.append(raw_input()) c=0 for i in range(1,n,1): for j in range(n): for k in range(m): if(j+i<n and k+i<m): if(l[j][k]==l[j][k+i] and l[j][k]==l[j+i][k] and l[j][k]==l[j+i][k+i]): c+=1...
A Little Elephant from the Zoo of Lviv likes lucky numbers very much. Everybody knows that the lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let F4(X) be the number of digits 4 in the decimal r...
numOfTests = int(raw_input()) def computeMaxProd(N, N4, N7): if N == 0: return N4*N7 x = (N+N7-N4)/2 if x < 0: x = 0 y = x+1 elif x > N: x = N y = x else: y = x+1 return max( (x+N4)*(N-x+N7) , (y+N4)*(N-y+N7)) def defMaxPro...
Little chef has just been introduced to the world of numbers! While experimenting with addition and multiplication operations, the little chef came up with the following problem: Given an array A of non-negative integers, how many pairs of indices i and j exist such that A[i]*A[j] > A[i]+A[j] where i < j . Now be...
cases=int(raw_input().strip()) while(cases): n=int(raw_input().strip()) a=raw_input().strip() a=map(int,a.split()) count=0 ct=0; # total=(n*(n-1))/2 for i in range(len(a)): if ( a[i]>2): count+=1 if ( a[i]==2): ct+=1 total = (count*(count-1))/2 #print count," ",ct ct= ct*count print total+ct ...
A robot named as Maestro, works on right most digit of number. For eg. 123456 is a number. Maestro would work with 6. But now, if number is 12345600. It will work with 6. Input Specification Input a variable t which is the number of test cases. Then input a string having alternate integers and multiplication chara...
testcase = int(raw_input()) while testcase > 0: input = raw_input() numbers = input.replace("x","*") numbers = numbers.replace("X","*") #print numbers result = eval(numbers) if (result == 0): print "Robot hanged." else: print str(result).rstrip("0")[-1] testcase -= 1
Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appea...
#include <bits/stdc++.h> using namespace std; const int N = 5003; const int inf = 1000000007; int n, a[N], f[N][N], s[N][N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); } for (int i = 0; i <= n + 1; i++) for (int j = 0; j <= n + 1; j++) f[i][j] = inf; for (int i = ...
You are given two binary strings a and b of the same length. You can perform the following two operations on the string a: * Swap any two bits at indices i and j respectively (1 ≤ i, j ≤ n), the cost of this operation is |i - j|, that is, the absolute difference between i and j. * Select any arbitrary index i (1 ...
def solve(n, a, b): ans = 0 i = 0 while i < n: if a[i] != b[i]: if i < n-1 and a[i+1] != b[i+1] and a[i+1] != a[i]: ans += 1 i += 2 else: ans += 1 i += 1 else: i += 1 return ans n = int(in...
The maps in the game are divided into square cells called Geo Panels. Some of these panels are painted. We shall assume that the Geo Panels without color are painted the transparent color. Besides, the map has so-called Geo Symbols. They look like pyramids of different colors (including Geo Symbols of the transparent...
import java.io.*; import java.util.*; public class D { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void makeUnique(ArrayList<Integer> ls) { Collections.sort(ls); int uk = 0; for (int i = 0; i < ls.size(); i++) if (...
Chouti is working on a strange math problem. There was a sequence of n positive integers x_1, x_2, …, x_n, where n is even. The sequence was very special, namely for every integer t from 1 to n, x_1+x_2+...+x_t is a square of some integer number (that is, a [perfect square](https://en.wikipedia.org/wiki/Square_number)...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); int n, b[200005] = {}; vector<int> f[200005] = {}; long long a[100005] = {}, c = 0; for (int i = 1; i <= 200000; i++) for (int j = i; j <= 200000; j += i) { if ((i & 1) == ((j / i) & 1)) if (i < j / i) f[...
Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Iterator; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /*...
Consider the following problem: given an array a containing n integers (indexed from 0 to n-1), find max_{0 ≤ l ≤ r ≤ n-1} ∑_{l ≤ i ≤ r} (r-l+1) ⋅ a_i. In this problem, 1 ≤ n ≤ 2 000 and |a_i| ≤ 10^6. In an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it....
#include <bits/stdc++.h> using namespace std; const long long N = 2000; long long calcula(long long l, long long r, long long k) { long long d1 = -r; long long d2 = l - r; long long aum = d2 - d1; long long lim1 = d1; long long lim2 = d1 + (r * 1000000 - 1) * aum; if (lim1 <= k && k <= lim2 && (k - d1) % au...
Owl Pacino has always been into trees — unweighted rooted trees in particular. He loves determining the diameter of every tree he sees — that is, the maximum length of any simple path in the tree. Owl Pacino's owl friends decided to present him the Tree Generator™ — a powerful machine creating rooted trees from their ...
#include <bits/stdc++.h> using namespace std; using ll = long long; constexpr int MAXN = 112345; constexpr int MAXSEQ = 2 * (MAXN - 1); constexpr int MAXNODES = 4 * MAXSEQ; struct Node { int maxc, minc, p, s, v, lazy; void show() { cerr << "{" << endl; cerr << "maxc" << " == " << (maxc) << endl; ...
You are given n numbers a_1, a_2, …, a_n. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors? For example, for the array [1, 4, 5, 6, 7, 8], the arrangement on the left is valid, while arrangement on the right is not, as 5≥ 4 + 1 and 8> 1 + 6. <im...
n = int(input()) arr = list(map(int, input().split())) arr.sort() if arr[-1] >= arr[-2] + arr[-3]: print("NO") else: print("YES") tmp = arr[-1] arr[-1] = arr[-2] arr[-2] = tmp print(' '.join([str(x) for x in arr]))
You are given an array a_{1}, a_{2}, …, a_{n}. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct. In other words, at most one time you can choose two integers l and r (1 ≤ l ≤ r ≤ n) and delete integers a_l, a_{l+1}, …, a_r from the array. Remaining elements should be pa...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.HashMap; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main...
Permutation p is a sequence of integers p=[p_1, p_2, ..., p_n], consisting of n distinct (unique) positive integers between 1 and n, inclusive. For example, the following sequences are permutations: [3, 4, 1, 2], [1], [1, 2]. The following sequences are not permutations: [0], [1, 2, 1], [2, 3], [0, 1, 2]. The importan...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); ; int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n), ans(n); for (auto &x : a) cin >> x; ; a.push_back(0); map<int, int> mp; for (int i = 0; i < n; i++) { ...
A two dimensional array is called a bracket array if each grid contains one of the two possible brackets — "(" or ")". A path through the two dimensional array cells is called monotonous if any two consecutive cells in the path are side-adjacent and each cell of the path is located below or to the right from the previo...
import java.io.*; import java.util.*; public class E { static int n, m, nn; static long k; static int[] order; static long[][] c; static int[] paren; static final long inf = (1L << 63)-1; static void insertionsort(int[] a, int[] pri, int n) { int i,j,v; for (i=1; i<n; i++) { v = ...
You are given an integer x of n digits a_1, a_2, …, a_n, which make up its decimal notation in order from left to right. Also, you are given a positive integer k < n. Let's call integer b_1, b_2, …, b_m beautiful if b_i = b_{i+k} for each i, such that 1 ≤ i ≤ m - k. You need to find the smallest beautiful integer y,...
import copy n,k = map(int, input().split()) li = list(map(int, input())) copyli = copy.copy(li) for y in range(k): for x in range(y,n,k): li[x] = li[y] print(n) if copyli > li : pos = k-1 while li[pos] == 9 and pos>0 : pos = pos-1 ele = li[pos]+1 for x in range(pos,n,k): ...
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for h...
#include <bits/stdc++.h> using namespace std; int t, n, m, k, a[3505], uncontrolled, mi, ans; int main() { cin >> t; while (t--) { scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); uncontrolled = m - k - 1; if (uncontrolled > 0) { ans = 0; for (int i = 0; i <=...
You are given three integers a ≤ b ≤ c. In one move, you can add +1 or -1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positiv...
for _ in range(int(input())): a,b,c = list(map(int, input().split())) ans = None; dist = 1e10 for i in range(1, 2*a +1): for j in range(i, 2*b +1, i): for k in range(j, 2*c + 1, j): if abs(a-i)+abs(b-j)+abs(c-k) < dist: ans = [i, j, k] ...
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles. The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that...
import sys input = sys.stdin.readline Q = int(input()) Query = [] for _ in range(Q): N, K = map(int, input().split()) A = list(map(int, input().split())) Query.append((N, K, A)) for N, K, A in Query: A.sort(reverse=True) n = 0 s = 0 for i, a in enumerate(A): s += a if s >=...
Note that the memory limit is unusual. You are given a multiset consisting of n integers. You have to process queries of two types: * add integer k into the multiset; * find the k-th order statistics in the multiset and remove it. k-th order statistics in the multiset is the k-th element in the sorted list o...
/** * @author derrick20 */ import java.io.*; import java.util.*; public class Multiset { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int Q = sc.nextInt(); ...
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'. In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov...
n = int(input()) arr = [] for i in range(n): a = int(input()) brackets = list(input()) k = 0 t = 0 j = 0 while j < len(brackets): if brackets[j] == '(': k += 1 else: k -= 1 if k < 0: t += 1 brackets.pop(j) bracke...
T is playing a game with his friend, HL. There are n piles of stones, the i-th pile initially has a_i stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in th...
// Born Sinner // old but im not that old // fuck all you hoes get a grip import java.util.*; import java.lang.*; import java.io.*; public class Main { static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamRea...
A lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield. The more protected Peter's army is, the better. To calculate the protection...
#include <bits/stdc++.h> using namespace std; int n, dp[85][85][6500], a[65], s, m, p[100]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (a[i] == 1) p[++s] = i; } m = (n - 1) * n / 2; memset(dp, 128, sizeof(dp)); dp[0][0][0] = 0; for (int i = 0; i <= n - 1; i...
Today is the final contest of INOI (Iranian National Olympiad in Informatics). The contest room is a row with n computers. All computers are numbered with integers from 1 to n from left to right. There are m participants, numbered with integers from 1 to m. We have an array a of length m where a_{i} (1 ≤ a_i ≤ n) is t...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using vi = vector<int>; template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << '['; string sep = ""; for (const auto &x : v) os << sep << x, sep = ", "; return os << ']'; } template <typen...
You've probably heard about the twelve labors of Heracles, but do you have any idea about the thirteenth? It is commonly assumed it took him a dozen years to complete the twelve feats, so on average, a year to accomplish every one of them. As time flows faster these days, you have minutes rather than months to solve th...
import java.io.*; import java.util.*; public class D { public static void main(String[] args) throws IOException { InputReader in = new InputReader(); PrintWriter pw = new PrintWriter(System.out); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); ...
A championship is held in Berland, in which n players participate. The player with the number i has a_i (a_i ≥ 1) tokens. The championship consists of n-1 games, which are played according to the following rules: * in each game, two random players with non-zero tokens are selected; * the player with more tokens ...
/* -> Written by <- ----------- |K_A_Z_A_M_A| |___________| | ___ | | (^_^) | | /( | )\ | |____|_|____| H O A N G */ #include <bits/stdc++.h> #define Task "" #define F first #define S second #define pb push_back #define bit(x, i) ...
A sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Given two integers n and k, construct a permutation a of numbers from 1 to n which has exactly k peaks. An index i of an array a of size n is said to be a peak if 1 < i < n and a_i \gt a_{i-1} and a_i \gt a_{i+1}. If...
#include<bits/stdc++.h> using namespace std; typedef unsigned long long int ull; typedef long double ld; #define all(v) (v).begin(),(v).end() #define rall(v) (v).rbegin(),(v).rend() #define ll long long #define pb push_back #define mk make_pair #define MOD 1000000007 #define pii pair<int,int> #define gcd(a,b) __gcd((a)...
Farmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is...
#include<bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a.begin(), a.end()); long long ans = 0, sum = 0; for (int...
In some country live wizards. They love to build cities and roads. The country used to have k cities, the j-th city (1 ≤ j ≤ k) was located at a point (xj, yj). It was decided to create another n - k cities. And the i-th one (k < i ≤ n) was created at a point with coordinates (xi, yi): * xi = (a·xi - 1 + b) mod (10...
#include <bits/stdc++.h> using namespace std; struct node { int x, y; friend bool operator<(const node &a, const node &b) { return a.y > b.y; } } a[100010]; int lc[100010], rc[100010]; int lx[100010], rx[100010]; int x[100010], xn, fr[100010]; int tree[100010 << 2]; int n, m; int cmp(int x, int y) { return a[x].y >...
Vasya went for a walk in the park. The park has n glades, numbered from 1 to n. There are m trails between the glades. The trails are numbered from 1 to m, where the i-th trail connects glades xi and yi. The numbers of the connected glades may be the same (xi = yi), which means that a trail connects a glade to itself. ...
#include <bits/stdc++.h> using namespace std; template <class T1> void deb(T1 e1) { cout << e1 << endl; } template <class T1, class T2> void deb(T1 e1, T2 e2) { cout << e1 << " " << e2 << endl; } template <class T1, class T2, class T3> void deb(T1 e1, T2 e2, T3 e3) { cout << e1 << " " << e2 << " " << e3 << endl; ...
You're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X". Using the play sequence you can calculate the...
#include <bits/stdc++.h> using namespace std; double p[100010]; int main(void) { int N; cin >> N; for (int i = 0; i < N; ++i) { cin >> p[i]; } double x = 0.0, ans = 0.0; for (int i = 0; i < N; ++i) { x = x * p[i] + p[i]; ans += 2.0 * x; ans -= p[i]; } printf("%.9f", ans); return 0; }
Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop i...
#include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:64000000") template <class T> inline T sqr(T x) { return x * x; } char a[3][1 << 17]; int n[3], m; char s[1 << 18]; int p[1 << 18]; void kmp() { p[0] = 0; for (int i = 1; i < m; ++i) { int j = p[i - 1]; for (; j && s[i] != s[j];...
Farmer John is hosting a tennis tournament with his n cows. Each cow has a skill level si, and no two cows having the same skill level. Every cow plays every other cow exactly once in the tournament, and each cow beats every cow with skill level lower than its own. However, Farmer John thinks the tournament will be de...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; const int inf = 0x3f3f3f3f; const int maxn = 1e5 + 5; int lazy[maxn * 4], ji[maxn * 4], len[maxn * 4]; void build(int i, int L, int R) { lazy[i] = ji[i] = 0; len[i] = R - L + 1; if (L == R) return; int mid = (L + R) ...
Polycarpus loves convex polygons, especially if all their angles are the same and all their sides are different. Draw for him any such polygon with the given number of vertexes. Input The input contains a single integer n (3 ≤ n ≤ 100) — the number of the polygon vertexes. Output Print n lines, containing the coord...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1000; const double eps = 1e-8, inf = 1e50, Pi = acos(-1.0); struct point { double x, y; point() {} point(double _x, double _y) { x = _x; y = _y; } point operator-(const point &ne) const { return point(x - ne.x, y - ne.y); } point operato...
Don't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a b × b square on a plane. Each point x, y (0 ≤ x, y ≤ b) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transp...
#include <bits/stdc++.h> using namespace std; int n, m, q, to[100005 * 2][50], tag[100005 * 4]; long long tim[100005], dist[100005 * 2][50]; struct point { int id, type, x1, y1, x2, y2; point() {} point(int _id, int _x1, int _y1, int _x2, int _y2) : id(_id), x1(_x1), y1(_y1), x2(_x2), y2(_y2) { type = x...
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n. Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, th...
import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class...
Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the ...
#include <bits/stdc++.h> using namespace std; const int N = 100500, INF = 1000 * 1000 * 1000; const long double eps = 1e-9; int n, m, s; int a[N]; int b[N]; int c[N]; int pa[N], pb[N]; bool cmpa(int ia, int ib) { return a[ia] > a[ib]; } bool cmpb(int ia, int ib) { return b[ia] > b[ib]; } int ans[N]; bool ok(int st, boo...
Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much. One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to n...
import java.io.*; import java.util.*; public class CodeForces { public static void main(String[] args) { FastIO io = FastIO.create(); int hills = io.nextInt(); int frogs = io.nextInt(); int mosquitoes = io.nextInt(); int[] f = new int[frogs]; for (int i = 0; i < fr...
Sereja has an n × m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a co...
#include <bits/stdc++.h> using namespace std; const int maxn = 110; int n, m, k, a[maxn][maxn], b[maxn][maxn], ans = 110, flag[maxn]; int check1(int pos1, int pos2) { int res1 = 0, res2 = 0; for (int i = 1; i <= m; i++) if (a[pos1][i] != a[pos2][i]) res1++; for (int i = 1; i <= m; i++) if (a[pos1][i] == a...
Jzzhu has two integers, n and m. He calls an integer point (x, y) of a plane special if 0 ≤ x ≤ n and 0 ≤ y ≤ m. Jzzhu defines a unit square as a square with corners at points (x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1), where x and y are some integers. Let's look at all the squares (their sides not necessarily par...
#include <bits/stdc++.h> const int max = 1E6; using AI = int[max + 1]; int F[max + 2]; bool S[max + 1]; AI P, G, H; const int mod = 1E9 + 7; inline void reduce(int& x) { x += x >> 31 & mod; } inline void add(int& x, int y) { reduce(x += y - mod); } inline int mul(int a, int b) { return static_cast<long long>(a) * b % m...
Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class ObsessiveString { private static final long MOD = 1000000007; private ObsessiveString() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ...
On a certain meeting of a ruling party "A" minister Pavel suggested to improve the sewer system and to create a new pipe in the city. The city is an n × m rectangular squared field. Each square of the field is either empty (then the pipe can go in it), or occupied (the pipe cannot go in such square). Empty squares are...
#include <bits/stdc++.h> using namespace std; const int MAXN = 2100; char a[MAXN][MAXN]; int s[MAXN][MAXN]; int n, m; long long ans; int up(int x, int y) { return (s[x][y] == s[x][y - 1] ? 1 : 0); } int down(int x, int y) { return ((s[n][y] - s[x - 1][y]) == (s[n][y - 1] - s[x - 1][y - 1]) ? 1 : 0); } int get_up(int ...
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph. There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned ...
n=int(input()) cars=[] win=[i for i in range(1,n+1)] for i in range(n): cars.append([int(j) for j in input().split()]) for i in range(n): for j in range(n): if cars[i][j]==-1: pass elif cars[i][j]==1 or cars[i][j]==3: try: win.remove(i+1) ...
'In Boolean logic, a formula is in conjunctive normal form (CNF) or clausal normal form if it is a conjunction of clauses, where a clause is a disjunction of literals' (cited from https://en.wikipedia.org/wiki/Conjunctive_normal_form) In the other words, CNF is a formula of type <image>, where & represents a logical "...
#include <bits/stdc++.h> using namespace std; vector<int> clauses[200005]; bool cok[200005]; int val[200005], used[200005]; vector<pair<int, int> > E[200005]; int findRoot(int x, int p) { used[x] = 1; if (cok[x]) return x; for (auto &y : E[x]) { int a = y.first, b = y.second; if (abs(p) == abs(b)) continu...
Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sendi...
#include <bits/stdc++.h> using namespace std; long long arr[27][27] = {0}; long long counter[27][27] = {0}; string str[101]; int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; for (int i = 0; i < n; i++) { cin >> str[i]; } for (int i = 0; i < 27; i++) { for (int j = 0; j < 27; j++)...
Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai — the current skill level. All skills have the same maximum level A. Along with...
#include <bits/stdc++.h> using namespace std; int main() { long long N, A, C1, C2, M; cin >> N >> A >> C1 >> C2 >> M; long long M_store = M; vector<pair<int, int> > I(N); long long total = 0; for (int i = 0; i < N; i++) { scanf("%d", &I[i].first); total += I[i].first; I[i].second = i; } sort...
A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one o...
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); deque<int> a(n), b(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); for (int i = 0; i < n; ++i) scanf("%d", &b[i]); a.erase(find(a.begin(), a.end(), 0)); b.erase(find(b.begin(), b.end(), 0)); while (a[0] != 1) a.push_b...
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Amo...
#include <bits/stdc++.h> using namespace std; char str[20]; int main() { int n; while (scanf("%d", &n) != EOF) { while (n--) { scanf("%s", str); int k = strlen(str + 4); long long ans = atoi(str + 4); int F = 0; int ten = 10; for (int i = 1; i < k; i++) { F += ten; ...
Today Pari and Arya are playing a game called Remainders. Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value <image>. There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya <image> if Arya wants. Given k and the ancient values, tell us if Arya has a winnin...
import io, sys, atexit, os sys.stdout = io.BytesIO() atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) sys.stdin = io.BytesIO(sys.stdin.read()) raw_input = lambda: sys.stdin.readline().rstrip() n, k = [int(t) for t in raw_input().split()] primed = [] for i in range(2,int(k**0.5)+2): b = 1 while k ...
Fangy collects cookies. Once he decided to take a box and put cookies into it in some way. If we take a square k × k in size, divided into blocks 1 × 1 in size and paint there the main diagonal together with cells, which lie above it, then the painted area will be equal to the area occupied by one cookie k in size. Fan...
#include <bits/stdc++.h> using namespace std; const int MOD = 1e6 + 3; int n; int main() { cin >> n; long long res = 1; for (int i = 0; i < n - 1; ++i) res = (res * 3) % MOD; cout << res << endl; return 0; }
Polycarp is a beginner programmer. He is studying how to use a command line. Polycarp faced the following problem. There are n files in a directory and he needs to delete some of them. Polycarp wants to run a single delete command with filename pattern as an argument. All the files to be deleted should match the patte...
#include <bits/stdc++.h> using namespace std; const int MAXN = 105; int len[MAXN], q[MAXN]; bool query[MAXN]; char str[MAXN][MAXN]; int getline(char *s) { int cnt = 0; while (isspace(s[cnt] = getchar())) ; for (++cnt; (s[cnt] = getchar()) != EOF && s[cnt] != '\n'; ++cnt) ; return cnt; } int main() { i...
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them. At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. ...
import sys sys.setrecursionlimit(99999999) i = lambda: sys.stdin.readline().strip() ii = lambda: map(int, i().split()) def getWords(s): for e in [".",",","?","!"]: s = s.replace(e, " ") return s.split() def getNames(nameToKey, text): words = getWords(text) return \ map(lambda e: nameToKey...
Polycarp's workday lasts exactly n minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has k bars at the beginning of the workday. In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either ...
#include <bits/stdc++.h> char s[1000000]; long long n, m; long long arr[500010]; long long brr[500010]; long long vis[500005]; long long fnc(long long num) { long long i, j, a = 0, l = 0, b = 0; for (i = 1; i < n - 1; i++) { if (s[i] == '0') { if (i - l - 1 > num) { a++; if (b - l - 1 > nu...
Fox Ciel safely returned to her castle, but there was something wrong with the security system of the castle: sensors attached in the castle were covering her. Ciel is at point (1, 1) of the castle now, and wants to move to point (n, n), which is the position of her room. By one step, Ciel can move from point (x, y) t...
#include <bits/stdc++.h> using namespace std; struct pt { int x, y; inline pt() {} inline pt(int _x, int _y) : x(_x), y(_y) {} } p[5], tar; int a, b, c, n; long long t[5]; int dis(const pt &a, const pt &b) { return (a.x < b.x ? b.x - a.x : a.x - b.x) + (a.y < b.y ? b.y - a.y : a.y - b.y); } long long m...
On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides). That's why Mister B decided to use this polygon. Now Mister B must find ...
#include <bits/stdc++.h> using namespace std; int main() { double n, a; cin >> n >> a; cout << 1 << " " << 2 << " "; double ans = 1000000; double minDiff = 1000000; double maxAngle = 180 - 360 / n; double stepSize = 180 / n; for (int i = 3; i <= n; i++) { double angle = maxAngle - stepSize * (i - 3)...
You are given an array of n integer numbers. Let sum(l, r) be the sum of all numbers on positions from l to r non-inclusive (l-th element is counted, r-th element is not counted). For indices l and r holds 0 ≤ l ≤ r ≤ n. Indices in array are numbered from 0. For example, if a = [ - 5, 3, 9, 4], then sum(0, 1) = - 5, ...
import java.util.*; import java.io.*; import java.math.BigInteger; /** * * @author usquare */ public class ProblemB { static long mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static void solve() { in = new InputReader(System.in); out = new PrintWrit...
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you...
#include <bits/stdc++.h> using namespace std; int n, x; long long ans; multiset<int> q; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1; i <= n; i++) { cin >> x; if (!q.empty() && *q.begin() < x) { ans += x - *q.begin(); q.erase(q.begin()); ...
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes. Some examples of beautiful numbers: * 12 (110); * 1102 (610); * 11110002 (12010); * 111110...
from sys import stdin fa = [] for i in xrange(1,15): fa.append((2**(i-1)) * (2**i-1)) n = int(stdin.readline()) ans = 1 for i in fa: if n%i==0: ans = i print ans
You are given an array s of n non-negative integers. A 5-tuple of integers (a, b, c, d, e) is said to be valid if it satisfies the following conditions: * 1 ≤ a, b, c, d, e ≤ n * (sa | sb) & sc & (sd ^ se) = 2i for some integer i * sa & sb = 0 Here, '|' is the bitwise OR, '&' is the bitwise AND and '^' is t...
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 233, mod = 1e9 + 7; int n, N, x; int a[1 << 17], b[1 << 17], c[1 << 17], f[1 << 17], h[18][1 << 17], g[18][1 << 17], cnt[1 << 17]; template <typename T> inline void read(T &k) { int f = 1; k = 0; char c = getchar(); while (c < '0' || c > '9...
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock...
n = int(input()) t = input()[:n] s = input()[:n] ops =[] def shift(k, cur): if k == 0: return cur return cur[:-k-1:-1] + cur [:-k] def move_to_front(k, curst): if k == n-1: ops.append(1) curst = curst[-1] +curst [:-1] else: ops.append(n-1) ops.append(k) ...
Petya has a polygon consisting of n vertices. All sides of the Petya's polygon are parallel to the coordinate axes, and each two adjacent sides of the Petya's polygon are perpendicular. It is guaranteed that the polygon is simple, that is, it doesn't have self-intersections and self-touches. All internal area of the po...
#include <bits/stdc++.h> using namespace std; int asfpasokf, ifjsiojofsj, x2, y2, m; int n; int x[22222], y[22222]; int w[111111]; const int ULAZNA = 0; const int IZLAZNA = 1; bool unutra(int x, int y) { return asfpasokf < x && x < x2 && ifjsiojofsj < y && y < y2; } bool unutraa(int x, int y) { return asfpasokf <= ...
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are reg...
n = input() zz = 3*10**5 + 1 tm = [0]*zz tp = [0]*zz tz = [0] w = 0 b = False b2 = False for x in range(0,n,+1): s = str(raw_input()) tmp = 0 if s[0] == ')' and s[-1] == '(': continue for y in range(0, len(s), +1): if s[y] == '(': tmp += 1 else: tmp -=1 ...
Anshal and his friends love watching TV series together,but Anshal has a habit of giving spoilers.In order to tackle this his friends anagrammed the list of the shows they were planning to watch.Somehow Anshal got hold of this list and started guessing the shows.Determine whether Anshal made a correct guess or not. IN...
A = raw_input() b = raw_input() A = [x for x in A.split(' ')] a =A[0] if len(a)!=len(b): print "WRONG" else: aa=[0]*26 bb=[0]*26 for i in range(0,len(a)): aa[ord(a[i])-65]=aa[ord(a[i])-65]+1 for i in range(0,len(b)): bb[ord(b[i])-65]=bb[ord(b[i])-65]+1 f=0 for i in range(0,26): if aa[i]!=bb[i]: f=1...
After setting up the area and his toys. Chandu is up for playing his very first game. His first game is played on a N X N board with some initial stones placed on each cell. He can move each stone in all four direction i.e up,down, left or right. His target of the game is to move all stones to any one of the four corn...
n,k=raw_input().split() n,k=int(n), int(k) x=map(int, raw_input().split()) y=map(int, raw_input().split()) p=0 for i in xrange(k): if x[i]!=1 and x[i]!=n: if x[i]-1<n-x[i]: p+=x[i]-1 else: p+=n-x[i] if y[i]!=1 and y[i]!=n: if y[i]-1<n-y[i]: p+=y[i]-1 else: p+=n-y[i] print p
Little Dipu is a small kid and like all the other kids, he likes to play, but he plays with numbers (He is extraordinary you know). Now-a-days Dipu has some extra interest in odd numbers. So, he says that a number N is interesting if it has odd number of divisors. Now Dipu turns to you and asks you to tell him how many...
import math import decimal ''' Created by anirudhmenon on 12/03/16 https://www.hackerearth.com/problem/algorithm/dipu-and-interesting-numbers-2/ ''' # number of test cases t = int(raw_input()) while t > 0: # Enter values for l and r l, r = raw_input().split() l, r = long(l), long(r) print int(decim...
As of now you have registered for IndiaHacks 2016 which is about to begin and you want to go to the venue to participate and the map is in the form of matrix. Consider an NXN matrix on which the possible moves from a given block (i,j), is either one upward (i+1, j), or one rightward (i, j+1) or one diagonally up (i+1,...
g = [1005 * [1]] + [[1] + 1004 * [0] for _ in range(1004)] for i in range(1, 1005): for j in range(1, 1005): g[i][j] = (g[i][j-1] + g[i-1][j] + g[i-1][j-1]) % 1000000007 for _ in range(int(raw_input())): a, b, c, d = map(int, raw_input().split()) print g[c-a][d-b]
View Russian Translation Tom works in a public library in his town. Today, a completely new set of N books is arriving to the library and they have to be placed on shelves, which are initially empty. A single shelf can contain at most 10 books and any two books with titles starting with different letters cannot be pu...
T = int(raw_input()) import math freq = {} for t in xrange(T): string1 = raw_input().strip() freq[string1[0]] = freq.get(string1[0],0) + 1 result = 0 def custom_ceil(x): return math.ceil(x/10.0) custom = map(custom_ceil,freq.values()) print int(sum(custom))
Little Monk is an extremely miser person. He hates spending money on things, be it for his own good or bad. But this time his friends have caught up with him, and are demanding a huge birthday treat. But, Monk is... well, Monk. He figured out that there is no way for him to save himself and his money now. So, he deci...
a=raw_input().split() lis=[] lis1=[] for i in range(int(a[1])): b=raw_input().split() lis.append(b) if b[0] not in lis1: lis1.append(b[0]) elif b[1] not in lis1: lis1.append(b[1]) for i in range(len(lis1)): c=1 l=[] l.append(lis1[i]) for j in range(int(a[0])): if...
Phoebe and Joey are playing cards. They have N decks of cards. Each deck of cards contain 52 cards: 26 Red cards (2 Aces + 6 Faces + 18 Ranks) 26 Black cards (2 Aces + 6 Faces + 18 Ranks) They have decided to play with M cards out of these N*52 cards. Phoebe asks Joey to select M cards with following restrictions:...
def readNextWord(): data = [] cur = 0 while True: if len(data) == cur: st = raw_input() data = st.split() cur = 0 yield data[cur] cur += 1 def getNextInt(reader): return int(float(next(reader))) def getNextWord(reader): return next(reader...
Roy has a wooden log (tree trunk) of length L units. Since the log is too heavy for him to lift, he wants to cut it into pieces. He can lift pieces of length 1 or 2 units. He wonders in how many ways can he make such pieces of the wooden log. Now Roy is too lazy, so he would also like to finish cutting with minim...
k = int(raw_input()) for c in range(k): a = int(raw_input()) if a%2 == 0: print a/2+1,a/2-1 else: print (a-1)/2+1,(a-1)/2
Tim likes Math. He likes it so much that he always brings his tablets with him and reads math e-books everywhere, even during parties. Tim found an interesting exercise in one of the e-books he is reading. But you want him to join the party, so you decide to answer the question for him. The problem is: Given D and P,...
from math import sqrt def is_perfect_square(y): return sqrt(y).is_integer() def f(d,p): y = d*d + 4*p if d < 0 or not is_perfect_square(y): return 0 return 1 << (d>0) + (y>0) for cas in xrange(input()): d, p = map(int, raw_input().strip().split()) print f(d,p)
In 1945, Vietnam had a huge famine because of which thousands of Vietnamese people were dying everyday. The Soviet Union wanted to help the Vietnamese. They were regualrly sending food supplies to Vietnam. The Vietnamese officials decided that they would provide food to the children first. (Food supplies included food...
t=input() while t!=0: x=map(int,raw_input().split()) x.sort() print " ".join(map(str,x)) t=input()
Given is an integer N. Snuke will choose integers s_1, s_2, n_1, n_2, u_1, u_2, k_1, k_2, e_1, and e_2 so that all of the following six conditions will be satisfied: * 0 \leq s_1 < s_2 * 0 \leq n_1 < n_2 * 0 \leq u_1 < u_2 * 0 \leq k_1 < k_2 * 0 \leq e_1 < e_2 * s_1 + s_2 + n_1 + n_2 + u_1 + u_2 + k_1 + k_2 + e_1 + e_...
#include <cstdio> #include <cstring> #include <iostream> #include <string> #include <cmath> #include <bitset> #include <vector> #include <map> #include <set> #include <queue> #include <deque> #include <algorithm> #include <complex> #include <unordered_map> #include <unordered_set> #include <random> #include <cassert> #...
We have a board with H horizontal rows and W vertical columns of squares. There is a bishop at the top-left square on this board. How many squares can this bishop reach by zero or more movements? Here the bishop can only move diagonally. More formally, the bishop can move from the square at the r_1-th row (from the to...
H,W=map(int,input().split()) print(1 if H==1 or W==1 else (H*W+1)//2)
Snuke has a sequence of N integers x_1,x_2,\cdots,x_N. Initially, all the elements are 0. He can do the following two kinds of operations any number of times in any order: * Operation 1: choose an integer k (1 \leq k \leq N) and a non-decreasing sequence of k non-negative integers c_1,c_2,\cdots,c_k. Then, for each i...
#include <bits/stdc++.h> template <class T> inline void read(T &res) { char ch; while (ch = getchar(), !isdigit(ch)); res = ch ^ 48; while (ch = getchar(), isdigit(ch)) res = res * 10 + ch - 48; } template <class T> inline T Max(T x, T y) {return x > y ? x : y;} template <class T> inline T Min(T x, T y) {return...
There are three airports A, B and C, and flights between each pair of airports in both directions. A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours. Consider a route where we start at one of th...
#include<bits/stdc++.h> using namespace std; int main(){ int p,q,r; cin>>p>>q>>r; cout<<min(p,q)+min(q,r)+min(p,r)-min(p,min(q,r)); }
A university student, Takahashi, has to take N examinations and pass all of them. Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination. Takahashi thinks that he may not be able to pass...
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner stdIn=new Scanner(System.in); int N=stdIn.nextInt(); int A[]=new int[N]; int B[]=new int[N]; int C[]=new int[N]; int z=0,y=0,x=0,w=0; long m=0; while(z<N){ A[z]=stdIn.nextInt(); ...
There are N islands lining up from west to east, connected by N-1 bridges. The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west. One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands: Request i: A dispute took place be...
#include <bits/stdc++.h> using namespace std; int main(){ long long n,m,ans=1,now; cin >> m >> n; long long a[n],b[n]; pair<long long,long long> p[n]; for(int i=0;i<n;i++){ cin >> a[i] >> b[i]; p[i]=make_pair(b[i],a[i]); } sort(p,p+n); now=p[0].first; for(int i=0;i<n;i++){ if(now<=p[i].sec...