input
stringlengths
29
13k
output
stringlengths
9
73.4k
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero)...
import java.util.*; import java.io.*; public class A846 { public static void main(String args[])throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.par...
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai ...
n, S = [int(x) for x in raw_input().rstrip().split()] s, a, b = [0] * n, [0] * n, [0] * n for i in range(n): tup = [int(x) for x in raw_input().rstrip().split()] s[i], a[i], b[i] = tup[0], tup[1], tup[2] d = [() for x in range(n)] S1, S2 = 0, 0 H = 0 for i in range(n): if a[i] > b[i]: d[i] = (i, a...
For a connected undirected weighted graph G, MST (minimum spanning tree) is a subgraph of G that contains all of G's vertices, is a tree, and sum of its edges is minimum possible. You are given a graph G. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jealous. Yo...
#include <bits/stdc++.h> #pragma GCC optimize(3) using namespace std; bool Finish_read; template <class T> inline void read(T &x) { Finish_read = 0; x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; if (ch == EOF) return; ch = getchar(); } while (isdigit(ch))...
You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t. A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome. For each vertex, output the number of pa...
#include <bits/stdc++.h> #pragma GCC optimize("O2") using namespace std; const int N = 1e6 + 10; const long long mod = 1e9 + 7; const long long mod2 = 998244353; const long long inf = 8e18; const int LOG = 22; long long pw(long long a, long long b, long long M) { return (!b ? 1 : (b & 1 ? (a * pw(a * a %...
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on. During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The s...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long double k, d, t; cin >> k >> d >> t; if (d < k) { d = ceil(k / d) * d; } unsigned long long num = floor((2 * t) / (d + k)); long double time = num * d; long double left...
The cities of Byteland and Berland are located on the axis Ox. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line Ox there are three types of cities: * the cities of Byteland, * the cities of Berland, * disputed cities. Recent...
#include <bits/stdc++.h> using namespace std; int n; vector<int> R; vector<int> P; vector<int> B; long long maxgap(const vector<int> &q) { int res = 0; for (int i = 0; i + 1 < (int)q.size(); ++i) { res = max(res, q[i + 1] - q[i]); } return res; } int main() { ios_base::sync_with_stdio(0); cin >> n; fo...
Berland Football Cup starts really soon! Commentators from all over the world come to the event. Organizers have already built n commentary boxes. m regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be...
n, m, a, b = list(map(int, input().split())) k = n%m print(min(k*b, (m - k)*a))
Ankit has a set of numbers and has recently studied set theory. He has created a power set of this set and is writing a program to compute sum of all elements of all the subsets in power set. Power set of a set S is defined as set of all possible subsets of S. Set S consist of all the number from 1 to N. You need to...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' if __name__ == '__main__': cases = int(raw_input()) start = 1 while start <= cases: number = int(raw_input()) no_of_occurances = 2 ** (number - 1) sum_of_numbers = (number * (n...
Chandu is very fond of strings. (Or so he thinks!) But, he does not like strings which have same consecutive letters. No one has any idea why it is so. He calls these strings as Bad strings. So, Good strings are the strings which do not have same consecutive letters. Now, the problem is quite simple. Given a string S, ...
T=input('') while T>0: str = raw_input('') str1 = "" for index in range(0,len(str)-1): flag = False if str[index] != str[index+1]: flag = True if flag: str1+=str[index] str1+=str[len(str)-1] print(str1) T-=1
Tom is very fond of adding values , so what he does whenever he gets a value he adds all its digits and forms a new value and checks it whether it has become a single digit or not and if it does not even becomes a single digit he apply the operation again and adds all its digits once again and he continues to do this p...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' for tc in range(input()): n = raw_input() while len(n) > 1: t=0 for i in n: t += int(i) n = str(t) print n
Like most of the girlfriends, Ashima when asks for something, won’t stop until she gets that. The way she gets that is by keep on repeating the same things again and again. Like if she wants chocolate, she will just keep on repeating “chocolate” again and again. I have decided to answer to her demands as “Yes” or “No”...
s = raw_input() l = len(s) q = int(raw_input()) for i in xrange(0,q): a, b = map(int, raw_input().split()) a%=l b%=l if s[a - 1] is s[b - 1]: print 'Yes' else: print 'No'
You are given N natural numbers and K swaps are allowed. Determine the largest permutation that you can attain. INPUT: First line contains N and k next line has N spaced integers OUTPUT: Print the largest permutation array. 0<N<10^5 0<K<10^5 SAMPLE INPUT 5 1 4 2 3 5 1 SAMPLE OUTPUT 5 2 3 4 1
n,k=raw_input().split() n,k=int(n),int(k) l=[int(i) for i in raw_input().split()] x=0 swap_i=0 while k: max_e=0 k-=1 for i in range(x,n): if(l[i] >= max_e ): max_e=l[i]; swap_i=i l[x],l[swap_i]=l[swap_i],l[x] x+=1 if(swap_i == x): k+=1 for i in l: ...
The secret services of Armin, an otherwise peace-loving country, have decided to perform a surgical strike in the war-torn city of Tashka. Tashka is under enemy control and the objective of the strike is to gain control over the city. The mission is subdivided into the following steps: 1) Divide in groups and infiltra...
from collections import defaultdict import sys inf = sys.maxint T = int(raw_input()) for l in range(T): N,M = [int(x) for x in raw_input().split()] dicti = defaultdict(lambda : inf) D = [[inf]*(N+1) for x in range(N+1)] for i in range(1,N+1): D[i][i]=0 for i in range(M): ...
There are N points on an XY plane. In one turn, you can select a set of collinear points on the plane and remove them. Your goal is to remove all the points in the least number of turns. Given the coordinates of the points, calculate two things: The minimum number of turns (T) needed to remove all the points. The numb...
def constdr1(Points) : Droites = [] i = 0 j = i + 1 while j < len(Points) : S = True for D in Droites : if (Points[D[1]][0]-Points[D[0]][0])*(Points[j][1]-Points[i][1])-(Points[D[1]][1]-Points[D[0]][1])*(Points[j][0]-Points[i][0])== 0 : S=False if not (j in D) : D.append(j) break if S : ...
Roy and Alfi reside in two different cities, Roy in city A and Alfi in city B. Roy wishes to meet her in city B. There are two trains available from city A to city B. Roy is on his way to station A (Railway station of city A). It will take T_0 time (in minutes) for Roy to reach station A. The two trains departs in T_...
import math t=input() while t: t0,t1,t2,v1,v2,d = map(int,raw_input().split()) tim1=int(math.ceil(t1+(float(d)/v1)*60)) tim2=int(math.ceil(t2+(float(d)/v2)*60)) if(t1<t0 and t2<t0): print("-1") elif(t1>=t0 and t2<t0): print(tim1) elif(t1<t0 and t2>=t0): print(tim2) else: print(min(tim1,tim2)) t=t...
A substring is a string of characters that is contained in another string. For example, the substrings of "abcdef" could be "abc", "bc", "cdef", "e" and so on. But, "bca", "ace", and "g" are not substrings of "abcdef". Your task is to count the number of non-empty substrings possible of a given string such that all c...
def check(s1): for i in range(len(s1)): for j in range(i+1,len(s1)): if s1[i]!=s1[j]: return 0 return 1 s=raw_input() dc={} for i in range(len(s)): t=i while t<len(s): s1=s[i:t+1] if s1 not in dc and check(s1): dc[s1]=1 else: ...
For a number X, let its "Coolness" be defined as the number of "101"s occurring in its binary representation. For example, the number 21 has Coolness 2, since its binary representation is 101012, and the string "101" occurs twice in this representation. A number is defined as Very Cool if its Coolness is greater than...
def counter(n): binary = bin(n)[2:] count = 0 for i in xrange(len(binary)-2): if binary[i:i+3] == "101": count += 1 return count ary = [0]*(10**5+1) for i in xrange(5,10**5+1): ary[i] = counter(i) for t in xrange(input()): r,k = map(int, raw_input().split()) tot = 0 #...
Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0. Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n...
from sys import stdin import sys import itertools import array import textwrap import math N = int(input()) X = input() temp = X.count("1") t = [0, 0, 0] t[0] = int(X, 2) % (temp-1) if temp != 1 else 0 t[2] = int(X, 2) % (temp+1) cnt = 0 for i in range(N): if X[i] == "1" and temp == 1: print(0) co...
There are N jewelry shops numbered 1 to N. Shop i (1 \leq i \leq N) sells K_i kinds of jewels. The j-th of these jewels (1 \leq j \leq K_i) has a size and price of S_{i,j} and P_{i,j}, respectively, and the shop has C_{i,j} jewels of this kind in stock. A jewelry box is said to be good if it satisfies all of the foll...
#include <bits/stdc++.h> using namespace std; #define db(x) cerr << #x << "=" << x << endl #define db2(x, y) cerr << #x << "=" << x << "," << #y << "=" << y << endl #define db3(x, y, z) cerr << #x << "=" << x << "," << #y << "=" << y << "," << #z << "=" << z << endl #define dbv(v) cerr << #v << "="; for (auto _x : v) c...
Given is a positive even number N. Find the number of strings s of length N consisting of `A`, `B`, and `C` that satisfy the following condition: * s can be converted to the empty string by repeating the following operation: * Choose two consecutive characters in s and erase them. However, choosing `AB` or `BA` is no...
public class Main { private static void solve() { int n = ni(); int mod = 998244353; int[][] fif = enumFIF(n, mod); long ret = pow(3, n, mod); for (int i = n / 2 + 1; i <= n; i++) { long x = C(n, i, mod, fif) * pow(2, n - i, mod) % mod; x = x * 2 % mod; ret = (ret - x + mod) ...
There are N squares arranged in a row, numbered 1 to N from left to right. Takahashi will stack building blocks on these squares, on which there are no blocks yet. He wants to stack blocks on the squares evenly, so he will repeat the following operation until there are H blocks on every square: * Let M and m be the m...
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math") #include <bits/stdc++.h> using namespace std; template<class t> inline t read(t &x){ char c=getchar();bool f=0;x=0; while(!isdigit(c)) f|=c=='-',c=getchar(); while(isdigit(c)) x=(x<<1)+(x<<3)+(c^48),c=getchar(); if(f) x=-x;return x; } template<...
You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974". Constraints * 0 \leq N_1, N_2, N_3, N_4 \leq 9 * N_1, N_2, N_3 and N_4 are integers. Input Input is given from Standard Input in the following format: N_1 N_2 N_3 N_4 Output If N_1, N_2, N_3 ...
n = input().split() n.sort() print("YES" if "".join(n) == "1479" else "NO")
You are given string S and T consisting of lowercase English letters. Determine if S equals T after rotation. That is, determine if S equals T after the following operation is performed some number of times: Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}. Here, |X| denotes the len...
s=input()*100 t=input() if t in s: print("Yes") else: print("No")
We have a 2 \times N grid. We will denote the square at the i-th row and j-th column (1 \leq i \leq 2, 1 \leq j \leq N) as (i, j). You are initially in the top-left square, (1, 1). You will travel to the bottom-right square, (2, N), by repeatedly moving right or down. The square (i, j) contains A_{i, j} candies. You ...
#include<iostream> #include<cstdio> #include<algorithm> #include<climits> using namespace std; int f[3][105]; int a[3][105],n; int main() { scanf("%d",&n); for(int i=1;i<=2;i++) for(int j=1;j<=n;j++) scanf("%d",&a[i][j]); f[1][1]=a[1][1]; for(int i=1;i<=2;i++) for(int j=1;j<=n;j++) f[i][j]=max(f[i-1][j],f[i...
We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand. How many grams of sand will the upper bulb contains after t seconds? Constraints * 1≤X≤10^9 * 1≤t≤10^9 * X and t are integers. Input The input ...
X,t = map(int, input().split()) print(X - t if X > t else 0)
Snuke arranged N colorful balls in a row. The i-th ball from the left has color c_i and weight w_i. He can rearrange the balls by performing the following two operations any number of times, in any order: * Operation 1: Select two balls with the same color. If the total weight of these balls is at most X, swap the po...
#include<bits/stdc++.h> using namespace std; #define RI register int int read() { int q=0;char ch=' '; while(ch<'0'||ch>'9') ch=getchar(); while(ch>='0'&&ch<='9') q=q*10+ch-'0',ch=getchar(); return q; } const int mod=1e9+7,N=200005,inf=0x3f3f3f3f; vector<int> orz[N]; int mi=inf,mic,mii,X,Y,ans,js,n,a[N],fac[N],ni[N...
There are N balls and N+1 holes in a line. Balls are numbered 1 through N from left to right. Holes are numbered 1 through N+1 from left to right. The i-th ball is located between the i-th hole and (i+1)-th hole. We denote the distance between neighboring items (one ball and one hole) from left to right as d_i (1 \leq ...
#include <bits/stdc++.h> int main(){ double ans = 0, sum = 0; int n, x, d; scanf("%d%d%d", &n, &x, &d); sum = x * 2 * n + 1.0 * n * (2 * n - 1) * d; while(n){ ans += sum * 0.5 / n; sum -= sum / n / n; --n; } printf("%.10lf\n", ans); return 0; }
<image> My grandmother uses a balance. The balance will balance if you place the same size on both of the two dishes, otherwise it will tilt to the heavier side. The weights of the 10 weights are 1g, 2g, 4g, 8g, 16g, 32g, 64g, 128g, 256g, 512g in order of lightness. My grandmother says, "Weigh up to about 1 kg in gr...
#include <iostream> using namespace std; int main(void){ int n,ans; while(cin>>n){ for(int i=0;i<10;i++){ if(n&1){ ans=1<<i; cout<<ans; if(n>>1) cout<<' '; } n>>=1; } cout << endl; ...
The number obtained by multiplying 1 by 2, 3, 5 several times (0 or more times) is called the Hamming numbers. For example * 1 * 1 x 2 x 2 = 4 * 1 x 2 x 2 x 3 x 5 x 5 = 300 Etc. are humming numbers, but 11, 13, 14 etc. are not humming numbers. All humming numbers are divisible by a power of 60 (for example, 54 is ...
#include<iostream> using namespace std; int main(){ long n,m,i,j,h[500000],j2,j3,j5,x2,x3,x5,f; while(cin>>m){ if(m==0)break; cin>>n; j2=j3=j5=0; x2=x3=x5=1; f=0; for(i=0;;i++){ h[i]=min(min(x2,x3),x5); if(f==0&&h[i]>=m){j=i;f=1;} if(h[i]>n)break; while(x2<=h[i])x2=2*h[j2++]; while(x3<=h[i])x3=3*h[j3++]; while(x5<=h[i]...
You will participate in the ski competition held on Mt. Bandai. In this competition, each player slides down the slope twice and competes for the short total time. There are several flags on the slopes, and a line is set between them for athletes to pass through. Athletes slide down the line from the start point to the...
#include<cstdio> #include<algorithm> #include<vector> #include<deque> #include<stack> #include<queue> #include<string> #include<iostream> //#include<tuple> #include<utility> #include<set> #include<queue> #include<iomanip> #include<iterator> //#include<chrono> //cout<<setprecision(12) //fixed //#include<random> using na...
problem Soccer is popular in JOI, and a league match called the JOI League is held every week. There are N teams in the JOI league, numbered from 1 to N. All combinations of matches are played exactly once. In other words, N × (N -1) / 2 games are played. The outcome of each match is determined by the score of each t...
//============================================================================ // Name : JOI.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostr...
The University of Aizu Elementary School (Aizu University and Small) is famous as one of Japan's leading competition programmer training schools. Of course, it is essential to practice the algorithm even when attending an athletic meet. Of course you, the director of the competitive programming department, want to win...
#include<iostream> #include<sstream> #include<vector> #include<algorithm> #include<set> #include<map> #include<queue> #include<complex> #include<cstdio> #include<cstdlib> #include<cstring> #include<cassert> using namespace std; #define rep(i,n) for(int i=0;i<(int)n;i++) #define fr(i,c) for(__typeof(c.begin()) i=c.begi...
Do you know confetti? They are small discs of colored paper, and people throw them around during parties or festivals. Since people throw lots of confetti, they may end up stacked one on another, so there may be hidden ones underneath. A handful of various sized confetti have been dropped on a table. Given their posit...
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second typedef pair<int,int> pi; ...
Example Input anagram grandmother Output 4
#include <bits/stdc++.h> using namespace std; typedef unsigned long long ull; const ull B=1e9+7; ull Hash(vector<int> &v){ ull h=0; for(int i=0;i<26;i++)h=h*B+v[i]; return h; } int main(){ string a,b; cin>>a>>b; int ans=0,n=a.size(),m=b.size(); for(int i=1;i<=n;i++){ unordered_set<ull> S; vect...
Problem Phantom thief Rappan came to steal the jewels. It was easy to get the jewel, but the jewel was equipped with a sensor and was surrounded by security robots. The guard robot is designed to move towards the jewel. The sensor didn't seem to be easy to remove, so I decided to put a jewel and escape. I decided to ...
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=a;i<b;i++) #define REP(i,b) FOR(i,0,b) #define PB push_back using ll=long long; using pii=pair<int,int>; using vi=vector<int>; int read(){ int i; scanf("%d",&i); return i; } const int inf=1000000007; struct Seg{ int mn[1<<18],lz[1<<18],s;...
Mr. Natsume, the captain of a baseball club, decided to hold a nagashi-soumen party. He first planned to put a flume at the arena, and let members stand by the side of the flume to eat soumen. But they are so weird that they adhere to each special position, and refused to move to the side of the flume. They requested M...
#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-10) #define equals(a,b) (fabs((a)-(b))<EPS) using namespace std; bool LT(double a,double b) { return !equals(a,b) && a < b; } bool LTE(double a,double b) { return equals(a,b) || a < b; } struct Point { d...
There are n rabbits, one in each of the huts numbered 0 through n − 1. At one point, information came to the rabbits that a secret organization would be constructing an underground passage. The underground passage would allow the rabbits to visit other rabbits' huts. I'm happy. The passages can go in both directions,...
#include <bits/stdc++.h> // #define set unordered_set // #define map unordered_map using namespace std; class UnionFind { private: int size; int parent[40000]; int rank[40000]; public: UnionFind() {} UnionFind(int sz) { init(sz); } void init(int sz) { size = sz; fill(rank, rank+sz, 0); for (int i = 0...
D: Anipero 2012 Anipero Summer Live, commonly known as Anipero, is the largest anime song live event in Japan where various anime song artists gather. 2D, who loves anime songs, decided to go to Anipero this year as well as last year. He has already purchased m of psyllium to enjoy Anipero. Psyllium is a stick that g...
#include <iostream> using namespace std; #define MAX 55 #define MINF -(1e8) int N,M,a[MAX],b[MAX],c[MAX]; int memo[MAX][MAX][MAX]; int solve(int n,int l1,int m){ if(n == N) return 0; int &res = memo[n][l1][m]; if(res != MINF) return res; for(int i = 0 ; i <= min(8,m) ; i++){ for(int j = 0 ; ...
D --Disciple Life is Hard / Disciple is hard Story The person in D loves donuts. I always want donuts. However, D, who was ordered by his master, Bunashimejitan, to train himself, must limit his calorie intake. Therefore, D person decided to eat donuts up to the calories burned by the training that day, considering t...
#include <iostream> #include <cstdio> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <string> #include <cmath> #include <cassert> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> #include <iomanip> #include <f...
Example Input 2 2 2 4 0 0 0 1 1 0 1 0 1 0 1 1 Output 4
#include<bits/stdc++.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define HUGE_NUM 99999999999999999 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; #define NUM 1000005 typedef pair<int,int> P; struct Info{ Info(int arg_x,int arg_y,int arg_z){ x =...
C: AA グラフ (AA Graph) Problem Given a graph as an ASCII Art (AA), please print the length of shortest paths from the vertex s to the vertex t. The AA of the graph satisfies the following constraints. A vertex is represented by an uppercase alphabet and symbols `o` in 8 neighbors as follows. ooo oAo ooo Horizontal...
#include <algorithm> #include <bitset> #include <complex> #include <deque> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <locale> #include <map> #incl...
Problem Given the integer n, output the smallest m such that nCm (the number of combinations that choose m out of n different ones) is even. Constraints The input satisfies the following conditions. * 1 ≤ n ≤ 1018 Input The input is given in the following format. n Output Output the minimum m such that nCm i...
#include <bits/stdc++.h> using namespace std; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define pb push_back using ll = long long; ll ct2(ll n) { ll r = 0; while(n>0 && n%2==0) { n/=2; ++r; } return r; } ll pw(int x, int n) { ll r = 1; rep(i,n) r *=x; return r...
Write a program which finds the greatest common divisor of two natural numbers a and b Hint You can use the following observation: For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y) Constrants 1 ≤ a, b ≤ 109 Input a and b are given in a line sparated by a single space. Output Output the greatest comm...
import math x,y = [int(x) for x in input().split()] print(math.gcd(x,y))
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm. ........# ........# ........# ........# Constraints * 3 ≤ H ≤ 300 * 3 ≤ W ≤ 300 Input The input consists of multiple datasets. Each dataset consists of t...
import java.util.Scanner; public class Main { public static void main(String[]args) { Scanner input=new Scanner(System.in); int h=0,j=0; while(true) {int a=input.nextInt(); int b=input.nextInt(); if(a==0 && b==0) break; for(int p=1;p<=a;p++) { for(int i=1;i<=b;i++) ...
Everyone knows the famous detective Sherlock. He has been handed over a new case of "The Abominable Bride". Each night she kills N people but to irritate Sherlock she leaves exactly one people. The way she kills the people is somewhat strange. She makes 1 to N people stand in a line and starts killing them. But, in t...
t=int(raw_input()) for i in range(t): n=int(raw_input()) x=bin(n)[2:] x=len(x)-1 x2=pow(2,x) ans=2*(n-x2) if ans==0: print x2 else: print ans
The captain of TITANIC is a mathematics freak. He has recently been given a problem that he is unable to solve. And he has asked your help to solve it. There are n numbers in a given expression. X1 X2 X3 .... Xn What is the number of ways to put parenthesis in the expression. For n=4, the different ways are (((x...
#!/usr/bin/python import sys catalan=[1 , 1 , 2 , 5 , 14 , 42 , 132 , 429 , 1430 , 4862 , 6796 , 8786 , 8012 , 2900 , 4440 , 4845 , 7670 , 4790 , 8700 , 3190 , 420 , 7020 , 3640 , 3650 , 7324 , 1452 , 2152 , 6004 , 360 , 1368 , 2304 , 6909 , 8198 , 3110 , 764 , 1262 , 3492 , 2364 , 1400 , 390 , 8820 , 4020 , 9240 , 70...
Problem Description  You are an army personnel in the great army of the Zorin race, where you are a part of a team of n people. Unfortunately, your army has lost a war to an intergalactic species, genetically much advanced than yours. Their captain Bruno have kept all your men (including you) as hostages, and now they...
T=input() for _ in xrange(T): N,i=input(),1; while i<=N: i*=2; i/=2; print 1+2*(N-i);
Rohit was travelling to NIT Warangal, to attend their annual technical fest - "Technozion". In the train, opposite to him, Rohit found quite a peculiar man playing with an array of numbers. When he enquired, the man told that he is trying to solve a puzzle for decades but unable to do so. Seeing Rohit's interest in the...
for _ in xrange(int(raw_input())): n=int(raw_input()) li=[0] lis=map(int, raw_input().split()) li+=lis ans=0 inc=2 while(inc<=n): temp=0 for i in xrange(inc, n+1, inc): temp+=li[i] ans=max(ans, temp) inc+=1 print ans
Chef had an interesting dream last night. He dreamed of a new revolutionary chicken recipe. When he woke up today he tried very hard to reconstruct the ingredient list. But, he could only remember certain ingredients. To simplify the problem, the ingredient list can be represented by a string of lowercase characters 'a...
def main(): for i in xrange(int(raw_input())): s = raw_input() ctr = 1 for j in xrange((len(s)+1)//2): if s[j]=="?" and s[-j-1]=="?": ctr*=26 ctr%=10000009 elif s[j]!=s[-j-1] and s[j]!="?" and s[-j-1]!="?": ctr=0 ...
Tic-Tac-Toe-Tomek is a game played on a 4 x 4 square board. The board starts empty, except that a single 'T' symbol may appear in one of the 16 squares. There are two players: X and O. They take turns to make moves, with X starting. In each move a player puts her symbol in one of the empty squares. Player X's symbol is...
def counter(string): x=string.count('X') o=string.count('O') d=string.count('.') t=string.count('T') return (x,o,t,d) def win(tupa): if((tupa[0]==3 and tupa[2]==1) or tupa[0]==4): print 'Case #'+str(i)+': X won' return True elif((tupa[1]==3 and tupa[2]==1)or tupa[1] ==4): ...
Little Gerald and his coach Mike play an interesting game. At the beginning of the game there is a pile consisting of n candies and a pile consisting of m stones. Gerald and Mike move in turns, Mike goes first. During his move Mike checks how many candies and stones Gerald has eaten. Let Gerald eat a candies and b ston...
#include <bits/stdc++.h> using namespace std; const int MAXN = 20100; int n, m, p; int x[MAXN], y[MAXN]; int dp1[MAXN], dp2[MAXN]; char ans[2 * MAXN]; int cnt; int go(int s1, int s2, int e1, int e2) { if (s1 == e1) { int ret = (x[s1] + y[s2]) % p; for (int i = s2 + 1; i <= e2; i++) ret += (x[s1] + y[i])...
IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting. Today, when IA looked at the fridge, she noticed that...
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class ex{ public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); String s=new St...
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on). There are lanterns on the...
#include <bits/stdc++.h> using namespace std; void in() { ifstream cin("input.txt"); ios_base::sync_with_stdio(false); cin.tie(0); } void solution() {} void out() {} int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; for (int i = 0; i < t; ++i) { int F, u, L, R, ans = 0; ...
You're given a tree consisting of n nodes. Every node u has a weight a_u. It is guaranteed that there is only one node with minimum weight in the tree. For every node u (except for the node with the minimum weight), it must have a neighbor v such that a_v<a_u. You should construct a tree to minimize the weight w calcul...
#include <bits/stdc++.h> using namespace std; int n, A[(1001010)], rt, f[(1001010)][40]; vector<int> Vec[(1001010)]; long long ans; void Dfs(int x) { for (int i = 0; i < Vec[x].size(); i++) { int y = Vec[x][i]; if (y == f[x][0]) continue; f[y][0] = x; Dfs(y); } } long long Lmin(long long a, long lon...
Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles. However, the local bank has n credit offers. Each offer can be described with three numbers a_i, b_i and k_i. Offers are numbered from 1 to n. If Vasya takes the i-th offer, then the bank gives him a_i bur...
#include <bits/stdc++.h> using namespace std; const int maxn = 501; const long long mod = 1000000007; const long long ool = 1e18 + 7; const long long o = 1; long long a[maxn]; long long b[maxn]; long long k[maxn]; int n; long long minz; long long cx[maxn]; long long cy[maxn]; int px[maxn]; int py[maxn]; long long we[ma...
Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by n streets along the Eastern direction and m streets across the Southern direction. Naturally, this city has nm intersections. At any intersection of i-th Eastern street and j-th Southern street there is a monument...
#include <bits/stdc++.h> using namespace std; typedef priority_queue<long long, vector<long long>, greater<long long>> minHeap; const int INF = 1e9 + 9; const long long LINF = 1e17 + 9; const long long MD = 998244353; inline long long po(long long a, long long b) { long long ans = 1; while (b > 0) { if (b &...
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the i-th of them will start during the x_i-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes x_1, x_2, ..., x_n, so he will be awak...
def gcd(a,b): if b==0: return a else: return gcd(b,a%b) n, m = map(int, input().split(' ')) x = list(map(int, input().split(' '))) p = list(map(int, input().split(' '))) dx = [x[i+1]-x[i] for i in range(n-1)] d = dx[0] for i in dx: d = gcd(i, d) for i in range(m): if d % p[i] == 0: ...
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
#import sys #digit = int(sys.argv[1]) digit = int(input()) if int(digit) <= 9: print(digit) exit() start_range = 1 end_range = 9 power = 1 digit_count = 2 while not (start_range <= digit and digit <= end_range): start_range = end_range + 1 end_range = 9 * 10**power * digit_count + start_range - 1 ...
Denis holds a Geometers Anonymous Club meeting in SIS. He has prepared n convex polygons numbered from 1 to n for the club. He plans to offer members of the club to calculate Minkowski sums of these polygons. More precisely, he plans to give q tasks, the i-th of them asks to calculate the sum of Minkowski of polygons w...
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); } return x * f; } map<pai...
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i. Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ...
for _ in range(int(input())): n = int(input()) lst = list(map(int, input().split())) cnt = 0 x = lst[-1] for i in lst[:-1][::-1]: x = min((x, i)) if x < i: cnt += 1 print(cnt)
In order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, …, the lab with the number n^2 is at the highest place. To transpor...
n = int(input()) a = [[] for i in range(n)] j = 0 k = 1 cnt = 0 for i in range(n): for j in range(n): cnt += 1 if (i % 2 == 0): a[j].append(cnt) else: a[-j-1].append(cnt) for i in range(n): print(*a[i])
This is the easier version of the problem. In this version, 1 ≤ n ≤ 10^5 and 0 ≤ a_i ≤ 1. You can hack this problem only if you solve and lock both problems. Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes o...
from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per from heapq import heapify,heappush,heappop,heappushpop input=stdin.readline R=lambda:map(int,input().spl...
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems. Polycarp decided to store the hash of the password, generated by the following algorithm: 1. take the password p, consisting of lowercase Latin letters, and shuffle the l...
import org.omg.PortableServer.POA; import java.awt.*; import java.io.*; import java.util.*; public class Abc { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int t=sc.nextInt(); while (t-->0) { char[] p = sc.next().toCharArray(); ...
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som...
from sys import stdin, gettrace if not gettrace(): def input(): return next(stdin)[:-1] def main(): n = int(input()) bb = [int(a) for a in input().split()] seq = {} for i, b in enumerate(bb): if b - i in seq: seq[b-i] += b else: seq[b-i] = b pri...
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed hi...
import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C { public static void main(String[] args) { FastReader reader = new FastReader(); BufferedWriter log = new BufferedWrite...
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m...
# from debug import debug import math t = int(input()) for ii in range(t): a, b = map(int, input().split()) if a == b: print(0) else: b, a = min(a,b), max(a,b) if a%b: print(-1) else: aa = int(math.log2(a//b)) if pow(2, aa) == a//b: c = 0 c += aa//3 aa = aa%3 c += aa//2 aa = aa...
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; public class C { public static FastReader fs = ne...
It's our faculty's 34th anniversary! To celebrate this great event, the Faculty of Computer Science, University of Indonesia (Fasilkom), held CPC - Coloring Pavements Competition. The gist of CPC is two players color the predetermined routes of Fasilkom in Blue and Red. There are N Checkpoints and M undirected predeter...
#include <bits/stdc++.h> using namespace std; long long n, m, c; vector<long long> G[2005]; long long dp[2005][4005]; int ldp[2005][8005], rdp[2005][8005]; long long zero = 4002; bool used[2005]; long long dfs(int v) { used[v] = true; for (long long(i) = (0); (i) <= ((int)G[v].size() - 1); (i)++) { if (used[G[v...
You are given an integer k and n distinct points with integer coordinates on the Euclidean plane, the i-th point has coordinates (x_i, y_i). Consider a list of all the (n(n - 1))/(2) pairs of points ((x_i, y_i), (x_j, y_j)) (1 ≤ i < j ≤ n). For every such pair, write out the distance from the line through these two po...
#include <bits/stdc++.h> using namespace std; template <typename T> inline void read(T &n) { T w = 1; n = 0; char ch = getchar(); while (!isdigit(ch) && ch != EOF) { if (ch == '-') w = -1; ch = getchar(); } while (isdigit(ch) && ch != EOF) { n = (n << 3) + (n << 1) + (ch & 15); ch = getchar(...
You are given an array a of length n, and an integer x. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was [3, 6, 9], in a single operation one can replace the last two elements by their ...
from math import ceil t = int(input()) for _ in range(t): n,x = map(int,input().split()) a = list(map(int,input().split())) mx = 0 mn = 0 for y in a: mx += ceil(y/x) mn += y mn = ceil(mn/x) print(mn,mx)
The \text{gcdSum} of a positive integer is the gcd of that integer with its sum of digits. Formally, \text{gcdSum}(x) = gcd(x, sum of digits of x) for a positive integer x. gcd(a, b) denotes the greatest common divisor of a and b — the largest integer d such that both integers a and b are divisible by d. For example...
def gcd(a,b): # Everything divides 0 if (b == 0): return a return gcd(b, a%b) for i in range(int(input())): n=int(input()) while(True): l=list(str(n)) sum1=0 for i in l: sum1+=int(i) if(gcd(n,sum1)>1): print(n) b...
I guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus 62 has exactly n stops (stop 1 goes first on its way and stop n goes last). The stops are positioned on a straight line and their coordinates are 0...
#include <bits/stdc++.h> using namespace std; namespace Solve { const int MAX_N = 150000, MAX_M = 300000; int n, m, c; int x[MAX_N + 1], p[MAX_N + 1]; double v[MAX_N + 1]; const int MAX_R = 1 << 18; int h, sz; struct node_t { double v, lv, rv, s; node_t() { v = lv = rv = s = 0.0; } } node[MAX_R << 1]; node_t operat...
On a strip of land of length n there are k air conditioners: the i-th air conditioner is placed in cell a_i (1 ≤ a_i ≤ n). Two or more air conditioners cannot be placed in the same cell (i.e. all a_i are distinct). Each air conditioner is characterized by one parameter: temperature. The i-th air conditioner is set to ...
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll q,n,k,a[300010],t[300010]; ll l[300010],r[300010],p; int main() { ios::sync_with_stdio(false); cin>>q; while(q--) { memset(t,0x3f,sizeof(t)); cin>>n>>k; for(int i=1;i<=k;i++) { cin>>a[i]; } for(int i=1;i<=k;i++) { cin>>t[a[i]...
Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He ha...
#include <bits/stdc++.h> using namespace std; void mego() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int main() { int n, a, b, c, d, x; string s; a = b = c = d = 0; cin >> n; map<string, int> ma; vector<pair<int, string>> mb; vector<int> v; set<int> se; map<string, string> ans; for ...
Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that. The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: 1. The try op...
import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans)...
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells. Input The first input line contains two integ...
#include <bits/stdc++.h> using namespace std; const int MAX = 5e5 + 9; char s[MAX], a[MAX], b[MAX]; int main() { int n, k, ans = 0, c1, c2; scanf("%d%d%s", &n, &k, &s); if (k == 2) { c1 = c2 = 0; for (int i = 0; i < n; i++) if (i % 2) { a[i] = 'A', c1 += (s[i] == 'B'); b[i] = 'B', c2...
You've got an array a, consisting of n integers a1, a2, ..., an. You are allowed to perform two operations on this array: 1. Calculate the sum of current array elements on the segment [l, r], that is, count value al + al + 1 + ... + ar. 2. Apply the xor operation with a given number x to each array element on the...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; int n, m, a[maxn], p[20][maxn * 3], sign[20][maxn * 3]; void pushup(int pos, int rt) { p[pos][rt] = p[pos][rt << 1] + p[pos][rt << 1 | 1]; } void pushdown(int pos, int rt, int l, int r) { if (sign[pos][rt]) { int mid = (l + r) / 2; sign...
Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: 1. The coordinates of each point in the set are integers. 2. For any two points from the set, the distance between them is a non-integer. Consider all poi...
import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.util.ArrayLi...
Petya is an unexperienced programming contestant. Recently he has come across the following problem: You are given a non-directed graph which consists of n nodes and m edges. Your task is to determine whether the graph contains a Hamiltonian path. Petya wrote a quick bug-free code which he believes solves this proble...
#include <bits/stdc++.h> using namespace std; const int mod = 1e6 + 3; const long long INF = 2e15; int a[1234][1234]; std::vector<int> adj[32]; int deg[34]; int vis[34]; bool cmp(int x, int y) { if (deg[x] != deg[y]) { return deg[x] < deg[y]; } return x < y; } void dfs(int u) { vis[u] = 1; for (int i = 0;...
Smart Beaver is careful about his appearance and pays special attention to shoes so he has a huge number of pairs of shoes from the most famous brands of the forest. He's trying to handle his shoes carefully so that each pair stood side by side. But by the end of the week because of his very active lifestyle in his dre...
#include <bits/stdc++.h> using namespace std; bool debug; const int inf = 1e9 + 5; const int nax = 6405; namespace MinCost { struct Edge { int w, c, v, rev; Edge(int _w, int _c, int _v, int _rev) : w(_w), c(_c), v(_v), rev(_rev) {} }; int odl[nax], pot[nax], pop[nax], pop_kraw[nax]; int q[nax * 100], qbeg, qend; ve...
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes ...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; public class hals { public static void main(String[] args)throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int m = Integ...
Levko loves strings of length n, consisting of lowercase English letters, very much. He has one such string s. For each string t of length n, Levko defines its beauty relative to s as the number of pairs of indexes i, j (1 ≤ i ≤ j ≤ n), such that substring t[i..j] is lexicographically larger than substring s[i..j]. Th...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = -1; for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0'; return x * f; } const int N = 2005, mod = 1e9 + 7; int dp[N][N], sum[N]; char s[N]...
Recently, the bear started studying data structures and faced the following problem. You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answe...
#include <bits/stdc++.h> using namespace std; const int N = 1e7 + 5; int n, m, l, t, r; long long com[N]; bool p[N]; int freq[N]; void seive() { for (long long i = 2; i < N; ++i) { com[i] += com[i - 1]; if (p[i]) continue; long long num = freq[i]; for (long long x = i + i; x < N; x += i) { num +...
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris. There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them bac...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 1; int N, M, a[maxn], s[maxn], t; bool f[maxn], g[maxn]; int main() { scanf("%d", &N); for (int i = 1; i <= N; ++i) { scanf("%d", &a[i]); f[a[i]] = 1; } for (int i = 1; i < maxn; ++i) { if (f[i]) { if (!f[maxn - i]) { ...
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also bo...
import java.util.List; import java.util.Scanner; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Collection; import java.util.Collections; ...
Serega and Fedor play with functions. One day they came across a very interesting function. It looks like that: * f(1, j) = a[j], 1 ≤ j ≤ n. * f(i, j) = min(f(i - 1, j), f(i - 1, j - 1)) + a[j], 2 ≤ i ≤ n, i ≤ j ≤ n. Here a is an integer array of length n. Serega and Fedya want to know what values this funct...
#include <bits/stdc++.h> using namespace std; const long long LINF = 4e18; const int mxN = 2e5 + 10, INF = 2e9, mod = (1 ? 1e9 + 7 : 998244353); long long p[mxN]; const long long is_query = -(1LL << 62); struct line { long long m, b; mutable function<const line*()> succ; bool operator<(const line& rhs) const { ...
You have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color? Your task is to write a program tha...
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author dipankar12 */ import java.io.*; import java.util.*; public class r273c { public static void main(String args[])...
Celebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos User ainta, who lives in a 2D world, is going to post a video as well. There are n dominoes on a 2D Cartesian plane. i-th domino (1 ≤ i ≤ n) can be represented a...
#include <bits/stdc++.h> using namespace std; const int N = 200005; pair<int, int> c[N]; struct Node { int l, r, v; bool cv; } a[N << 2]; void Build(int i, int l, int r) { a[i].l = l; a[i].r = r; a[i].cv = false; if (l == r) return; int mid = l + r >> 1; Build(i << 1, l, mid); Build(i << 1 | 1, mid + ...
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place? <image> One day, when he came to his friend Evan, Om Nom didn't find him at h...
#include <bits/stdc++.h> using namespace std; int main() { long long c, h1, h2, w1, w2; cin >> c >> h1 >> h2 >> w1 >> w2; if (w1 < w2) { swap(w1, w2); swap(h1, h2); } long long ans = 0; if (w1 >= sqrt(c)) { for (int i = 0; i <= c / w1; i++) { ans = max(ans, i * h1 + (c - i * w1) / w2 * h2)...
We all know that GukiZ often plays with arrays. Now he is thinking about this problem: how many arrays a, of length n, with non-negative elements strictly less then 2l meet the following condition: <image>? Here operation <image> means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equival...
#include <bits/stdc++.h> using namespace std; void FastIO() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); } long long modpow(long long a, long long p, long long mod) { long long ret = 1; while (p) { if (p & 1) ret = (ret * a) % mod; a = (a * a) % mod; p /= 2; } return ret; } l...
There is a sand trail in front of Alice's home. In daytime, people walk over it and leave a footprint on the trail for their every single step. Alice cannot distinguish the order of the footprints, but she can tell whether each footprint is made by left foot or right foot. Also she's certain that all people are walkin...
#include <bits/stdc++.h> using namespace std; set<int> L, R, M; char c[120000]; int d[120000]; int i, n, p, s, t1, t2, t3, t4; int main() { scanf("%s", c + 1); n = strlen(c + 1); for (int i = n; i > 0; i--) if (c[i] == 'L') t1++, t3 = i, L.insert(i), M.insert(i); else t2++, t4 = i, R.insert(i)...
This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not....
s = raw_input() diff = [] stk = [] for i in range(len(s)): if s[i] == '(': stk.append(i) else: if len(stk) != 0: diff.append([stk.pop(), i]) if len(diff) == 0: print 0, 1 else: diff.sort() hehe = [] prevl, prevr = -2, -2 sz = 0 for i in diff: if prevl < i[0] and prevr > i[1]: continue elif prevr +...
Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not d...
import java.util.Scanner; import static java.lang.Math.*; public class Main{ public static void main(String[]args){ Scanner x = new Scanner (System.in); long y = x.nextLong(); long u = (y-1)*-1; double a = sqrt((1.0/4.0)-2*u); a+=1.0/2.0; ...
There is a social website with n fanpages, numbered 1 through n. There are also n companies, and the i-th company owns the i-th fanpage. Recently, the website created a feature called following. Each fanpage must choose exactly one other fanpage to follow. The website doesn’t allow a situation where i follows j and a...
#include <bits/stdc++.h> using namespace std; template <class T> void read(T &first) { char ch; for (ch = getchar(); (ch < '0' || ch > '9') && ch != '-';) ch = getchar(); first = 0; int t = 1; if (ch == '-') { ch = getchar(); t = -1; } for (; ch >= '0' && ch <= '9'; ch = getchar()) first = first *...
This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only. Waking up in the ...
#include <bits/stdc++.h> int dx4[] = {0, 0, -1, 1}; int dy4[] = {-1, 1, 0, 0}; bool valid(int r, int c, int x, int y) { if (x >= 1 && x <= r && y >= 1 && y <= c) return 1; return 0; } using namespace std; int main() { int n, k; cin >> n >> k; int a[n + 2]; int b[n + 2]; for (int i = 1; i <= n; i++) cin >>...
Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with n balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) — the numbe...
#include <bits/stdc++.h> using namespace std; const int MAX = 1E6 + 10; const int MAXP = 3E6; int n, m; int a[MAX]; long long c[MAX]; long long f[3 * MAX], f_less[3 * MAX]; long long all; int main() { scanf("%d", &n); all = (long long)n * (n - 1); for (int i = 0; i < n; i++) scanf("%d", a + i); sort(a, a + n); ...
The Prodiggers are quite a cool band and for this reason, they have been the surprise guest at the ENTER festival for the past 80 years. At the beginning of their careers, they weren’t so successful, so they had to spend time digging channels to earn money; hence the name. Anyway, they like to tour a lot and have surpr...
#include <bits/stdc++.h> using LL = long long; template <int BASE = 5> class NS { static const LL MO = 1e9 + 7; LL a, b; public: static inline void Normalize(LL& x) { x %= MO; if (x < 0) x += MO; } inline LL first() const { return a; } inline LL second() const { return b; } NS(LL a = 0, LL b = 0...
There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate ...
#include <bits/stdc++.h> using namespace std; void solve() { long long n, second, ans = 0, k = 1, i, a; cin >> n >> second; map<long long, long long> mp; for (i = 1; i <= n; i++) { cin >> a; if (i == second && a) ans++; else mp[a]++; } for (i = 1; i < n; i++) { if (k >= n) break;...
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you...
#include <bits/stdc++.h> using namespace std; int a[100]; int b[100]; int main() { int n, L; cin >> n >> L; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; } vector<int> p, q; for (int i = 1; i < n; i++) { p.push_back(a[i] - a[i - 1]); q.push_back(...
Input The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive. Output Output "Yes" or "No". Examples Input 373 Output Yes Input 121 Output No Input 436 Output Yes
#include <bits/stdc++.h> using namespace std; template <typename T> void sci(T& t) { cin >> t; } template <typename T, typename... Ts> void sci(T& t, Ts&... ts) { sci(t); sci(ts...); } int32_t main() { cin.tie(nullptr); cout.tie(nullptr); ios_base::sync_with_stdio(false); string s; cin >> s; bool ans ...