input
stringlengths
29
13k
output
stringlengths
9
73.4k
You have been given a set of N strings S1, S2, .... SN. Consider any non-empty string S (S need not belong to the given set of N strings). Suppose S occurs (as a substring) in K out of the N given strings in the set. Your job is to choose S such that the value of K is maximized. If there are many such strings, choose t...
t=input() for i in xrange(t): n=input() l=[] for k in xrange(n): s=raw_input() l.append(s) q="abcdefghijklmnopqrstuvwxyz" o=[0 for i in xrange(26)] for x in xrange(n): for y in xrange(26): if q[y] in l[x]: o[y]+=1 z=max(o) for j in xrange(26): if o[j]==z: print q[j] break
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right. Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below. You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2...
import sys input = sys.stdin.readline N,K=map(int,input().split()) K=[tuple(map(int,input().split())) for i in range(K)] mod=998244353 DP=[0]*(4*10**5+100) DP[1]=1 DP[2]=-1 for i in range(1,N+1): DP[i]+=DP[i-1] DP[i]%=mod for l,r in K: DP[i+l]+=DP[i] DP[i+l]%=mod DP[i+r+1]-=D...
There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn...
#include<iostream> #include<algorithm> #include<vector> #include<queue> using namespace std; int N,M; int A[1000],B[1000],C[1000]; int D[1000],E[1000],F[1000]; bool vis[3010][3010]; vector<pair<int,int> >WX[3010],WY[3010]; bool wx[3010][3010],wy[3010][3010]; int main() { cin>>N>>M; vector<long>X,Y; X.push_back((long...
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.) Let us define the happiness of the children as c_1 \times ...
n,k = map(int,input().split()) a = tuple(map(int,input().split())) mod = 10**9+7 rng = 1001 fctr = [1] finv = [1] for i in range(1,rng): fctr.append(fctr[-1]*i%mod) finv.append(pow(fctr[i],mod-2,mod)) dp = [[0 for i in range(n+1)] for j in range(k+1)] dp[0][0] = 1 for i in range(1,k+1): x = a[i-1] for j in rang...
For a sequence S of positive integers and positive integers k and l, S is said to belong to level (k,l) when one of the following conditions is satisfied: * The length of S is 1, and its only element is k. * There exist sequences T_1,T_2,...,T_m (m \geq l) belonging to level (k-1,l) such that the concatenation of T_1,...
#include<cstdio> #include<queue> #include<vector> #include<iostream> using namespace std; #define mp make_pair #define fi first #define se second const int MAXN = 200000; typedef pair<int, int> pii; typedef long long ll; priority_queue<pii, vector<pii>, greater<pii> >que; int lst[MAXN + 5], nxt[MAXN + 5], N, L; void li...
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square. Snuke cast Q spells to move the golems. The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke ca...
import java.util.*; public class Main { static int n; static String s; static int q; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); q = sc.nextInt(); s = sc.next(); char[] t = new char[q]; char[] d = new cha...
You are given a sequence of N integers: A_1,A_2,...,A_N. Find the number of permutations p_1,p_2,...,p_N of 1,2,...,N that can be changed to A_1,A_2,...,A_N by performing the following operation some number of times (possibly zero), modulo 998244353: * For each 1\leq i\leq N, let q_i=min(p_{i-1},p_{i}), where p_0=p_N...
#include <bits/stdc++.h> // iostream is too mainstream #include <cstdio> // bitch please #include <iostream> #include <algorithm> #include <cstdlib> #include <vector> #include <set> #include <map> #include <queue> #include <stack> #include <list> #include <cmath> #include <iomanip> #include <time.h> #define dibs reserv...
"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter. Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on...
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Collections; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.util.PriorityQueue; public class Main { static PrintWriter out; static InputReader ir; static void solve()...
In CODE FESTIVAL XXXX, there are N+1 participants from all over the world, including Takahashi. Takahashi checked and found that the time gap (defined below) between the local times in his city and the i-th person's city was D_i hours. The time gap between two cities is defined as follows. For two cities A and B, if t...
#include <bits/stdc++.h> #ifdef _WIN32 #include "debug.hpp" #endif using namespace std; #define rep(i, N) for(int i = 0; i < (N); i++) #define reps(i, N) for(int i = 1; i <= (N); i++) #define repr(i, N) for(int i = (N) - 1; i >= 0; i--) #define pub push_back template<typename T> void chmax(T &a, T b){ a = max(a, b)...
In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows: * Rating 1-399 : gray * Rating 400-799 : brown * Rating 800-1199 : green * Rating 1200-1599 : cyan * Rating 1600-1999 : blue * Rating 2000-2399 : yellow * Rating 2400-2799 : orange * Rating 280...
n,a=open(0) s=set();x=0 for i in map(int,a.split()): j=i//400 if j<8:s.add(j) else:x+=1 print(max(1,len(s)),len(s)+x)
Joisino has a formula consisting of N terms: A_1 op_1 A_2 ... op_{N-1} A_N. Here, A_i is an integer, and op_i is an binary operator either `+` or `-`. Because Joisino loves large numbers, she wants to maximize the evaluated value of the formula by inserting an arbitrary number of pairs of parentheses (possibly zero) in...
#include<bits/stdc++.h> using namespace std; const int N=2e5+5; int a[N]; long long f[N][3]; int main() { int n; scanf("%d%d",&n,&a[1]); for(int i=2;i<=n;++i) { char op[2]; scanf("%s%d",op,&a[i]); a[i]=(op[0]=='+'?a[i]:-a[i]); } f[1][0]=a[1],f[1][1]=f[1][2]=-1ll<<60; for(int i=2;i<=n;++i) { f[i][0]=max(f...
N hotels are located on a straight line. The coordinate of the i-th hotel (1 \leq i \leq N) is x_i. Tak the traveler has the following two personal principles: * He never travels a distance of more than L in a single day. * He never sleeps in the open. That is, he must stay at a hotel at the end of a day. You are ...
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAXN=100005; int N,L,Q; int x[MAXN],nxt[MAXN][25]; int ans[MAXN]; //int dis[MAXN]; int main() { scanf("%d",&N); for(int i=1;i<=N;i++) scanf("%d",&x[i]); scanf("%d%d",&L,&Q); memset(nxt,0x3F,sizeof nxt); for(int i=1;i<=N;i++) ...
An English booklet has been created for publicizing Aizu to the world. When you read it carefully, you found a misnomer (an error in writing) on the last name of Masayuki Hoshina, the lord of the Aizu domain. The booklet says "Hoshino" not "Hoshina". Your task is to write a program which replace all the words "Hoshino...
#include <iostream> #include <cstring> using namespace std; int main(){ int n,len; string a; cin>>n; getline(cin,a); for(int i=0;i<n;i++){ getline(cin,a); len=a.size(); for(int o=0;o<=len;o++) if(a[o]=='H'){ if(a[o+1]=='o') if(a[o+2]=='s') if(a[o+3]=='h') if(a[o+4]=='i') if(a[o+5]=='n') if(a[o+6]=='o') a[o+6]='a';} cou...
Aizu has an ancient legend of buried treasure. You have finally found the place where the buried treasure is buried. Since we know the depth of the buried treasure and the condition of the strata to be dug, we can reach the buried treasure at the lowest cost with careful planning. So you decided to create a program tha...
#include <iostream> #include <vector> #include <algorithm> #include <cstring> #include <cstdlib> #include <queue> #include <set> using namespace std; class Situation{ public: int oxigen; int money; int h,w; int miningCnt; int bitmask; set<pair<int,int> > visited; }; int mem[11][11][1<<10][51]; ...
Playing with Stones Koshiro and Ukiko are playing a game with black and white stones. The rules of the game are as follows: 1. Before starting the game, they define some small areas and place "one or more black stones and one or more white stones" in each of the areas. 2. Koshiro and Ukiko alternately select an area ...
#include<iostream> #include<algorithm> #include<set> using namespace std; int grundy[201][101]; int dfs(int w, int b){ if(grundy[w][b] >= 0){ return grundy[w][b]; } set<int> st; if(w > 0){ st.insert(dfs(w - 1, b)); } if(b > 0){ st.insert(dfs(w + 1, b - 1)); } f...
In ancient times, Romans constructed numerous water ways to supply water to cities and industrial sites. These water ways were amongst the greatest engineering feats of the ancient world. These water ways contributed to social infrastructures which improved people's quality of life. On the other hand, problems related...
#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 _3_ 1 using namespace std; /* 15:25 - ????????????????????????????????? ?????????????????? ??£?????? ????????????????????¢????¨???? ?????¨?????????????????????????°???????????????????????¶????????????? ...
You are working for an administration office of the International Center for Picassonian Cubism (ICPC), which plans to build a new art gallery for young artists. The center is organizing an architectural design competition to find the best design for the new building. Submitted designs will look like a screenshot of a...
#include <iostream> #include <algorithm> #include <cctype> #include <vector> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) #define fs first #define sc second typedef pair<int,int> P; int w,h,dw[4]={1,0,-1,0},dh[4]={0,1,0,-1}; double eps=1e-8; bool visited[61][10]; vector<string> vc; struct st{ bool ok; d...
You are working as a night watchman in an office building. Your task is to check whether all the lights in the building are turned off after all the office workers in the building have left the office. If there are lights that are turned on, you must turn off those lights. This task is not as easy as it sounds to be be...
#include <bits/stdc++.h> using namespace std; inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;} template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();} template<class T> inline T sqr(T x) {return x*x;} typedef vector<int> vi; typedef vector<vi> vvi; typed...
Problem Aizu Magic School is a school where people who can use magic gather. Haruka, one of the students of that school, can use the magic of warp on the magic team. From her house to the school, there is a straight road of length L. There are also magic circles on this road. She uses this road every day to go to sch...
#define _USE_MATH_DEFINES #define INF 0x3f3f3f3f #include <cstdio> #include <iostream> #include <sstream> #include <cmath> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <limits> #include <map> #include <string> #include <cstring> #include <set> #include <deque> #include <bitset> #in...
Divisor is the Conquerer is a solitaire card game. Although this simple game itself is a great way to pass one’s time, you, a programmer, always kill your time by programming. Your task is to write a computer program that automatically solves Divisor is the Conquerer games. Here is the rule of this game: First, you ra...
#include <iostream> #include <cstring> using namespace std; #define REP(i,n,m) for(int i=n;i<m;i++) #define rep(i,n) REP(i,0,n) int n,cnt[14],ans[54]; bool solve(int idx,int sum){ if(idx == 0 && sum == 0) return true; if(idx < 0 || sum < 0) return false; rep(i,14){ if(cnt[i]>0 && (sum - i) % i == 0){ ans[id...
A small country called Maltius was governed by a queen. The queen was known as an oppressive ruler. People in the country suffered from heavy taxes and forced labor. So some young people decided to form a revolutionary army and fight against the queen. Now, they besieged the palace and have just rushed into the entranc...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #d...
There is an evil creature in a square on N-by-M grid (2 \leq N, M \leq 100), and you want to kill it using a laser generator located in a different square. Since the location and direction of the laser generator are fixed, you may need to use several mirrors to reflect laser beams. There are some obstacles on the grid ...
#include<iostream> #include<string.h> #include<queue> #define inf 1000000001 using namespace std; int X[4]={0,1,0,-1}; int Y[4]={-1,0,1,0}; int H,W,A,si,sj; char map[100][100]; bool in(int y,int x){ if(y<0 || x<0 || y>=H || x>=W)return false; return true; } class State{ public: int y,x,muki,numL,numR; St...
K-th String Problem Statement The suffix array SA for the character string S of length N is defined as a permutation of positive integers of N or less obtained by the following procedure. The substring from the i-th character to the j-th character of S is expressed as S [i..j]. However, the subscript is 1-indexed. 1...
#include <set> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> using namespace std; typedef long long int64; const int MAX_N = int(1e5 + 10); const int MAX_K = 30; const int64 INF = int64(2.05e18); //^@ 2^63 ~ 9.2*10^18。本当にこれで大丈夫? int N, K; int64 L; int sa[MAX_N + 1]; int64 comb[MAX_N + M...
Problem statement There is a rooted tree of size N. Each vertex is numbered from 0 to N-1, with a root of 0. For the vertices at both ends of any side, the assigned integer is smaller closer to the root. Initially, the weights of all edges are 0. Process Q queries on this tree in sequence. There are two types of quer...
#include <cstdio> #include <algorithm> #include <vector> #include <queue> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)(n);++i) #define int long long struct LCA { int N, logN; vector<vector<int>> G; vector<int> depth; vector<vector<int>> parent; LCA(int size) : N(size), G(size), d...
problem AOR Ika and you came to the tournament-style table tennis tournament singles section for reconnaissance. For AOR Ika-chan, who wants to record all the games, you decide to ask for the number of games that will be played in this tournament. There are $ N $ players in the tournament, each with a uniform number ...
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define rep(i,n) FOR(i,0,n) #define pb emplace_back typedef long long ll; typedef pair<int,int> pint; bool a[1<<10]; int main(){ int n,m,ai; cin>>n>>m; rep(i,m){ cin>>ai; a[n+ai]=true; } int ...
problem There is a light bulb at the grid point $ (x, y) $ that meets $ 1 \ leq x \ leq h, 1 \ leq y \ leq w $. The power supply is installed at coordinates $ (i + 0.5, j + 0.5) (1 \ leq i <h, 1 \ leq j <w, i + j $ is even) (corrected at 14:21). Coordinates $ When the power supply installed at (i + 0.5, j + 0.5) $ is...
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} struct Dinic{ const Int INF=1LL<<55; struct edge { Int to,cap,rev; edge(){} ...
E: Cut out the sum problem Ebi-chan has a sequence (a_1, a_2, ..., a_n). Ebi-chan is worried about the maximum value of the sum of the partial arrays (which may be empty), so please find it. Here, a subarray refers to a continuous subsequence. The sum of empty strings is 0. In addition, Ebi-chan rewrites this sequen...
#include<bits/stdc++.h> using namespace std; typedef unsigned long long int ull; typedef long long int ll; typedef pair<ll,ll> pll; typedef long double D; typedef complex<D> P; #define F first #define S second const ll MOD=1000000007; //const ll MOD=998244353; template<typename T,typename U>istream & operator >> (istr...
A histogram is made of a number of contiguous bars, which have same width. For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area. Constraints * $1 \leq N \leq 10^5$ * $0 \leq h_i \leq 10^9$ Input The inp...
#include "bits/stdc++.h" using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int INF = 1e9; const ll LINF = 1e18; template<class S,class T> ostream& operator << (ostream& out,const pair<S,T>& o){ out << "(" << o.first << "," << o.second << ")"; return out; } template<c...
Difference of Big Integers Given two integers $A$ and $B$, compute the difference, $A - B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the difference in a line. Constraints * $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$ Sample Input 1 5 8 Sample O...
A, B = map(int, input().split()) print(A - B)
Most problems on CodeChef highlight chef's love for food and cooking but little is known about his love for racing sports. He is an avid Formula 1 fan. He went to watch this year's Indian Grand Prix at New Delhi. He noticed that one segment of the circuit was a long straight road. It was impossible for a car to overtak...
# cook your code here for testcases in xrange(int(raw_input() ) ) : n = int(raw_input()) Arr = map(int, raw_input().split() ) m = Arr[0] c = 1 for i in xrange(1, len(Arr)): if (Arr[i] <= m ): c += 1 m = Arr[i] print c
Seeing the current political scenario in the city of Delhi,and the clean sweep of the Aam Aadmi Party, you are wondering that its maybe time to change careers and start selling broomsticks. Now you sell broomsticks of various lengths. You initially do not have any brooms.You decide to roam about in the city finding bro...
t=int(input()) ans=0 l=[-1]*(100001) while(t>0): s=raw_input().split(" ") x=int(s[1]) if(s[0]=="found"): l[x]=ans elif(l[x]>=0): ans=max(ans,l[x]+x) l[x]-=1 t-=1 print ans
Sherlock is stuck. There is a N X N grid in which some cells are empty (denoted by ‘.’), while some cells have rocks in them (denoted by ‘#’). Sherlock is on the South of the grid. He has to watch what is happening on the East of the grid. He can place a mirror at 45 degrees on an empty cell in the grid, so that he'll ...
def proc(a): n=len(a) j=n-1 l=0 ans=0 hsh=[True]*n for j in range(n-1,-1,-1): i=n-1 flag=True while i>=0: if a[i][j]=='#': hsh[i]=False flag=False elif hsh[i] and flag: ans+=1 i-=1 print ans t=int(inp...
A new school in Byteland is now in the process of renewing some classrooms with new, stronger and better chairs, so that the students can stay still and pay attention to class :) However, due to budget and logistic reasons, it's only possible to carry a chair at a time to the classroom, which means that for a long time...
t=input() while t>0: n=input() print pow(2,n,1000000007)-1 t-=1
EDIT : Please note that the user enters the whole string "Energy Level: 217" instead of just 217. You'd have to input accordingly. The output should only be the ids of radioactive elements, one id per line. Stick to the input/output format.   Note: For Turbo C++, select "Text" as your language Problem description: Af...
for u in range(input()): string = raw_input().split() if int(string[-1]) > 200: print u + 1
Given a complete binary tree with the height of H, we index the nodes respectively top-down and left-right from 1. The i-th node stores a positive integer Vi. Define Pi as follows: Pii if the i-th node is a leaf, otherwise Pii*PL, Vi*PR), where L and R are the indices of the left and right children of i, respectively. ...
# tree product - trproduct.py try: import psyco psyco.full() except ImportError: pass mod = 1000000007 h = int(raw_input()) while h>0: v = map(int, raw_input().split()) if h>1: level = 1<<(h-2) while level>=1: for i in xrange(level-1, 2*level-1): ...
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo...
(n,m) = tuple(map(int, input().split(" "))) x = list(map(int, input().split(" "))) nib = 0 ans = [] cou = 0; for i in x: nib+=i if (nib<m): ans.append(nib//m) else: ans.append(nib//m) nib-=(nib//m)*m print (*ans)
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to ...
import java.awt.List; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; i...
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times: * mul x: multiplies n by x (where x is an arbitrary positive integer). * sqrt: replaces n with √...
#include <bits/stdc++.h> using namespace std; int dx[] = {0, 0, 1, -1, 1, 1, -1, -1}; int dy[] = {1, -1, 0, 0, -1, 1, 1, -1}; const int mod = 1e9 + 7; int dcmp(long double x, long double y) { return fabs(x - y) <= 1e-12 ? 0 : x < y ? -1 : 1; } void fast() { std::ios_base::sync_with_stdio(0); cin.tie(NULL); cout...
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was decided ...
n = int(input()) arr = list(map(int, input().split())) cur = 0 ans = 100000000 for x in range(n): cur = 0 for i in range(n): summ = 0 summ += abs(x - i) summ += i summ += x summ += x summ += i summ += abs(x - i) summ *= arr[i] cur += summ ...
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with n vertices without loops and multiedges, such that a degree of any vertex is at least 3, and also he gav...
#include <bits/stdc++.h> using namespace std; const int maxn = 5 * 100005; vector<int> a[maxn]; int n, m, k, lim; int head[maxn], Next[maxn * 2], to[maxn * 2], tot = 0; int d[maxn], fa[maxn], size[maxn]; bool vis[maxn]; void add(int x, int y) { to[++tot] = y; Next[tot] = head[x]; head[x] = tot; } void dfs_tree(in...
Cowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing n...
n = int(input()) arr = [int(i) for i in input().split()] arr1, arr2 = [], [] arr.sort(reverse = True) for i in range(n): if i%2==0: arr1.append(arr[i]) else: arr2.append(arr[i]) arr2.reverse() for i in arr2: arr1.append(i) print(*arr1)
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two in...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; int str[maxn]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> str[i]; long long ans = 0; for (int i = 0; i < n; i++) { if (i == 0) { ans += 1ll * str[i] * (n - str[i] + 1); } else { if (str[i] > str[...
Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points o...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const long long LINF = 0x3f3f3f3f3f3f3f3fLL; const double EPS = 1e-8; const int MOD = 998244353; const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1}; vector<int> edge[200000]; long long fact[200001]; void init() { fact[0] = fact[1] = 1; for ...
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
n=int(input()) d={} d[0]='1 A' d[1]='0 A' d[2]='1 B' d[3]='2 A' x=n%4 print(d[x])
A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails n...
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main{ public static void main(String[]args){ InputStream in = System.in; PrintWriter out = new PrintWriter(System.out); try{ ...
Petya loves lucky numbers. Everybody knows that 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. Petya has a number consisting of n digits without leading zeroes. He represented it as an array of d...
#include <bits/stdc++.h> char A[100001]; int op; int cnt; int n; int at; inline void solve() { while (cnt < op) { if (at == n - 1) { break; } else { if (A[at] == '4' && A[at + 1] == '7') { if (at % 2 == 0) { if (at == n - 2) { A[at + 1] = '4'; cnt++; ...
You are given a huge integer a consisting of n digits (n is between 1 and 3 ⋅ 10^5, inclusive). It may contain leading zeros. You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2). For example, if a = 032...
# -*- coding: utf-8 -*- """ Created on Fri Nov 1 14:39:37 2019 @author: uditg """ ans={} test=int(input()) for each in range(test): num=input() n=len(num) num={i:int(num[i]) for i in range(n)} output={} even={} odd={} even_count=0 odd_count=0 for i in range(n): if num[i]%2=...
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets. The store does not sell single clothing items — instead, it sells suits of two types: * a suit of the first type consists of one tie and one jacket; * a suit of the second type ...
#include <bits/stdc++.h> #pragma GCC optimize(2) using namespace std; int a, b, c, d, e, f; int main() { scanf("%d%d%d%d%d%d", &a, &b, &c, &d, &e, &f); int tmp1 = min(a, d); int tmp2 = min(b, min(c, d)); int ans = 0; if (e > f) { ans += tmp1 * e; tmp2 = min(tmp2, d - tmp1); ans += tmp2 * f; } el...
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
t=int(input()) for q in range(t): n=int(input()) a=[list(map(int,input().split())) for i in range(n)] a.sort() ans="" x,y=0,0 f=0 for i in range(n): if a[i][0]>=x and a[i][1]>=y: ans+='R'*(a[i][0]-x) x=a[i][0] ans+='U'*(a[i][1]-y) y=a[i][1] else: f=1 print('NO') break if f==0: print('...
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad. The crossroads are represented as a string s of length n, where s_i = A, if there is...
import java.util.*; public class Solution{ public static void main(String args[]){ Scanner in=new Scanner (System.in); int t=in.nextInt(); T:while(--t>=0){ int a=in.nextInt(); int b=in.nextInt(); int p=in.nextInt(); String s=in.nex...
This is the easy version of the problem. The only difference between easy and hard versions is the constraint of m. You can make hacks only if both versions are solved. Chiori loves dolls and now she is going to decorate her bedroom! <image> As a doll collector, Chiori has got n dolls. The i-th doll has a non-negati...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast", "unroll-loops", "omit-frame-pointer", "inline") #pragma GCC option("arch=native", "tune=native", "no-zero-upper") #pragma GCC target("avx2") using namespace std; template <typename T> void maxtt(T &t1, T t2) { t1 = max(t1, t2); } template <typename T> void mintt(...
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved. The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav...
cases=input() for i in range(0,int(cases)): inss=input() list=inss.split(' ') n=int(list[0]) m=int(list[1]) x=int(list[2]) y=int(list[3]) price=0 if 2*x > y: lame=True else: lame=False for count in range(0,n): data=input() ###print(data) ...
There are many freight trains departing from Kirnes planet every day. One day on that planet consists of h hours, and each hour consists of m minutes, where m is an even number. Currently, there are n freight trains, and they depart every day at the same time: i-th train departs at h_i hours and m_i minutes. The gover...
#include <bits/stdc++.h> using namespace std; struct node { int x, t, id; } a[200002]; int n, h, m, k, i, j; int read() { char c = getchar(); int w = 0; while (c < '0' || c > '9') c = getchar(); while (c <= '9' && c >= '0') { w = w * 10 + c - '0'; c = getchar(); } return w; } int cmp1(const node &...
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height). Boris cho...
#include <bits/stdc++.h> using namespace std; const long double eps = 1e-9; const long double pi = acos(-1.0); int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } int xabs(int a) { return a > 0 ? a : -a; } int getCost(int l, int w, int h, int rl, int rw, int cost) { int cnt = 1; int p = 2 * (l + w); in...
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them: All of them take a sit at their round table, some of them with the golde...
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); long long n, k; cin >> n >> k; long long tot = 0; long long sumPos = 0; for (int _ = 0; _ < (k); ++_) { long long pos, num; cin >> pos >> num; pos--; sumPos += pos * num;...
You are given a tree with each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white a...
#include <bits/stdc++.h> using namespace std; template <typename T1, typename T2> bool mini(T1 &a, T2 b) { if (a > b) { a = b; return true; } return false; } template <typename T1, typename T2> bool maxi(T1 &a, T2 b) { if (a < b) { a = b; return true; } return false; } const int N = 2e5 + 5;...
The hobbits Frodo and Sam are carrying the One Ring to Mordor. In order not to be spotted by orcs, they decided to go through the mountains. The mountain relief can be represented as a polyline with n points (x_i, y_i), numbered from 1 to n (x_i < x_{i + 1} for 1 ≤ i ≤ n - 1). Hobbits start their journey at the point ...
#include<bits/stdc++.h> using namespace std; #define debug printf("%d %s\n",__LINE__,__FUNCTION__);fflush(stdout) using ll=long long;using i64=long long;using db=double; using u32=unsigned int;using u64=unsigned long long;using db=double; using pii=pair<db,db>;using vi=vector<int>; using qi=queue<int>;using pqi=priorit...
You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line c...
t=int(input()) for i in range(t): n,k = map(int,input().split()) ans=[] if n==1 and k==1: print(0) continue else: if k%2==0: for j in range(k//2,k): ans.append(j) for j in range(k+1,n+1): ans.append(j) else: for j in range(k//2+1,k): ans.append(j) for j in range(k+1,n+1): ans.a...
In Fire City, there are n intersections and m one-way roads. The i-th road goes from intersection a_i to b_i and has length l_i miles. There are q cars that may only drive along those roads. The i-th car starts at intersection v_i and has an odometer that begins at s_i, increments for each mile driven, and resets to ...
using namespace std; #define visual #ifdef visual #include <iostream> #include <fstream> #include <vector> #include <queue> #include <algorithm> #include <set> #include <map> #include <assert.h> #include <functional> #include <math.h> #include <string> #include <ctime> #endif #ifndef visual #include <bits/stdc++.h> #...
This is the hard version of the problem. The only difference between the easy version and the hard version is the constraints on n. You can only make hacks if both versions are solved. A permutation of 1, 2, …, n is a sequence of n integers, where each integer from 1 to n appears exactly once. For example, [2,3,1,4] i...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; using pii = pair<int, int>; using pll = pair<ll, ll>; using vi = vector<int>; using vll = vector<ll>; #define alpha ios::sync_with_stdio(0); cin.tie(0); const int B = 130000; int w[2][2*B+5], ...
Input The input contains two integers a1, a2 (0 ≤ ai ≤ 109), separated by a single space. Output Output a single integer. Examples Input 3 14 Output 44 Input 27 12 Output 48 Input 100 200 Output 102
import java.math.BigInteger; import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); String a=scan.next(); String b=scan.next(); int max=Math.max(a.length(), b.length()); String w=""; String p=""; for (int i = b.length()-1; i>=0; i--...
Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the informati...
import java.util.*; public class Main { public static void main(String [] args){ Scanner in=new Scanner(System.in); int n=in.nextInt(); int k=in.nextInt(); int array[]=new int[n]; for(int i=0;i<n;i++)array[i]=in.nextInt(); int leftPtr=0; int rightPtr=0; HashMap<Integer,Integer>map=new ...
Furik loves writing all sorts of problems, especially such that he can't solve himself. You've got one of his problems, the one Furik gave to Rubik. And Rubik asks you to solve it. There is integer n and array a, consisting of ten integers, indexed by numbers from 0 to 9. Your task is to count the number of positive i...
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root...
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. * Current character pointer (CP); *...
import java.io.*; import java.util.*; public class B { static boolean DBG = false; FastScanner in; PrintWriter out; public void solve(String s){ if (DBG) out.println(s); int[] d = new int[10]; if (s.length() == 0 || s.charAt(0) == '<'){ prt(d); return; } char[] chs = s.toCharArray(); boolean[...
Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square. Vasya wants to find such...
#include <bits/stdc++.h> using namespace std; template <typename F, typename S> ostream &operator<<(ostream &os, const pair<F, S> &p) { return os << "(" << p.first << ", " << p.second << ")"; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << "{"; for (auto it = v.begin(); it != ...
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only on...
#include <bits/stdc++.h> using namespace std; long long n, tmp = 1; int main() { int k, x = 0; cin >> n >> k; while (k != x && tmp < n) { x++; tmp += k - x; } if (tmp >= n) { cout << x << endl; } else { cout << -1 << endl; } }
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is <image> for SmallR while <image> for Zanoes. The one who shoots in the target first should be the winner. Output the probability th...
#include <bits/stdc++.h> using namespace std; double a, b, c, d; double ans = 0; int main() { cin >> a >> b >> c >> d; ans = (a / b) / (1 - (1 - a / b) * (1 - c / d)); printf("%.12lf\n", ans); }
Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such ...
#include <bits/stdc++.h> using namespace std; string pre[4] = {"", "0", "00", "000"}; int T[4] = {1, 10, 100, 1000}; int k, m; bool v[10000]; int ndgt(int x) { for (int i = 0; i < 3; ++i) { if (x >= T[3 - i]) return i; } return 3; } bool print(int x, int s) { int y = k < s ? s - k : k - s; if (y < 10000 &...
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they ge...
#include <bits/stdc++.h> using namespace std; int ans, a[10]; bool flag = true; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { int ad; cin >> ad; a[ad]++; } ans += min(a[1], a[2]); a[3] += min(a[1], a[2]); int ad = min(a[1], a[2]); a[1] -= ad; a[2] -= ad; if (a[1]) { ad...
The cinema theater hall in Sereja's city is n seats lined up in front of one large screen. There are slots for personal possessions to the left and to the right of each seat. Any two adjacent seats have exactly one shared slot. The figure below shows the arrangement of seats and slots for n = 4. <image> Today it's th...
#include <bits/stdc++.h> using namespace std; const int md = 1000000007; const int maxn = 101010; const long long inf = 2020202020202020202LL; int n, a[maxn]; long long pow2[maxn], ans = 1, fact[maxn], revfact[maxn], lol = 1; void upd_ans(long long t) { ans = (ans * t) % md; } long long binpow(long long a, long long n)...
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
n,m = map(int, raw_input().split()) resp = '' num_1 = 0 num_0 = 0 if n - 1 == m: resp = '0' temp = '10' resp += m * temp n = 0 m = 0 while n != 0 or m != 0: if n == m: temp = '01' resp += n * temp n = 0 m = 0 break else: if m != 0 and num_1...
Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be t...
#include <bits/stdc++.h> using namespace std; template <class T> T inline sqr(T x) { return x * x; } const long double pi = 3.1415926535897932384626433832795; const long double eps = 1e-8; const int N = 100500; int a[N]; long long s[N]; int main() { int n; scanf("%d", &n); for (int i = 0; i < (int)(n); ++i) sca...
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly:...
#include <bits/stdc++.h> using namespace std; int n, l, r, i, sl; int a[1000000], b[1000000]; queue<int> que; stack<int> tk; int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; b[i] = a[i]; } sort(b + 1, b + 1 + n); int dd = 0; for (int i = 1; i <= n; i++) { if (dd == 1) { q...
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move...
move=input() ans="" s=input() keyboard=["qwertyuiop","asdfghjkl;","zxcvbnm,./"] if move =="R": for i in range(len(s)): for j in range(len(keyboard)): if s[i] in keyboard[j]: ans+=keyboard[j][keyboard[j].index(s[i])-1] elif move =="L": for i in range(len(s)): for j in ...
Assume that sk(n) equals the sum of digits of number n in the k-based notation. For example, s2(5) = s2(1012) = 1 + 0 + 1 = 2, s3(14) = s3(1123) = 1 + 1 + 2 = 4. The sequence of integers a0, ..., an - 1 is defined as <image>. Your task is to calculate the number of distinct subsequences of sequence a0, ..., an - 1. Ca...
#include <bits/stdc++.h> using namespace std; const int maxN = 3e1 + 5; const int LOG = 6e1 + 5; const long long INF = 1e18; const long long MOD = 1e9 + 7; int d[LOG]; struct Matrix { int n, m, M[maxN][maxN]; Matrix(int _n = 0, int _m = 0) { n = _n; m = _m; for (int i = 0; i < n; i++) for (int j =...
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences. Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in whic...
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main{ final static int MOD = 1000000007; public static void main(String[] args){ Scan scan = new Scan(); int n = scan.nextInt(); String s = scan.next(); int[] counter = new int[4]; for(int i=0;i<n;i++){ switch(s.charAt(i))...
Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar. <image> So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become <image> an...
#include <bits/stdc++.h> using namespace std; void FastIO() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); } int main() { FastIO(); long long int m; cin >> m; long long int h[2], a[2], x[2], y[2]; for (int i = 0; i < (int)2; i++) { cin >> h[i] >> a[i] >> x[i] >> y[i]; } long long...
Limak is a little bear who learns to draw. People usually start with houses, fences and flowers but why would bears do it? Limak lives in the forest and he decides to draw a tree. Recall that tree is a connected graph consisting of n vertices and n - 1 edges. Limak chose a tree with n vertices. He has infinite strip ...
import java.io.BufferedInputStream; import java.util.*; public class EDrawing { public static void main(String[] args) { final Scanner scanner = new Scanner(new BufferedInputStream(System.in)); int N = scanner.nextInt(); final Graph graph = new Graph(N); for (int i = 0; i < N - 1...
Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y also belong to this set. Now Wilbur wants to number the points in the set he has, that is ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100000; const int MAXNUM = 100000; int n; int max_x[MAXNUM + 1]; int max_y; int w[MAXN]; int res[MAXN][2]; int lookup(int t) { int p = 0, q = max_y; while (p < q) { int y = (p + q) / 2; if (y - max_x[y] < t) p = y + 1; else q = y...
Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≤ i ≤ j ≤ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k. Input The first line of the input contains i...
// package codeforces.cr340.div2; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; /** * Created by hama_du on 2016/02/16. */ public class Main { public static void main(String[] arg...
Berland scientists face a very important task - given the parts of short DNA fragments, restore the dinosaur DNA! The genome of a berland dinosaur has noting in common with the genome that we've used to: it can have 26 distinct nucleotide types, a nucleotide of each type can occur at most once. If we assign distinct En...
#include <bits/stdc++.h> using namespace std; const int N = (int)2e5 + 5; const int INF = (int)1e9; const int mod = (int)1e9 + 7; const long long LLINF = (long long)1e18; int n; bool a[26][26]; bool was[26]; void dfs(int x) { cout << char(97 + x); for (int to = 0; to < 26; ++to) { if (a[x][to]) { dfs(to);...
If an integer a is divisible by another integer b, then b is called the divisor of a. For example: 12 has positive 6 divisors. They are 1, 2, 3, 4, 6 and 12. Let’s define a function D(n) — number of integers between 1 and n (inclusive) which has exactly four positive divisors. Between 1 and 10 only the integers 6, 8...
#include <bits/stdc++.h> using namespace std; int Lower[1000000 + 1], Higher[1000000 + 1]; char Used[1000000 + 1]; long long SumNat(long long n) { long long p = n, q = n + 1; if (p % 2) q /= 2; else p /= 2; return (p) * (q); } long long PrimePi(long long n) { long long v = sqrt(n + 1e-9), p, temp, q, ...
Recently Petya has become keen on physics. Anna V., his teacher noticed Petya's interest and gave him a fascinating physical puzzle — a half-decay tree. A half-decay tree is a complete binary tree with the height h. The height of a tree is the length of the path (in edges) from the root to a leaf in the tree. While s...
#include <bits/stdc++.h> using namespace std; namespace output { void __(short x) { cout << x; } void __(unsigned x) { cout << x; } void __(int x) { cout << x; } void __(long long x) { cout << x; } void __(unsigned long long x) { cout << x; } void __(double x) { cout << x; } void __(long double x) { cout << x; } void _...
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: * An 'L' indicates he should move one unit left. * An 'R' indicates he should move one unit right. * A 'U' indicates he should move one unit up. * A 'D' indicates he shoul...
s = input() ud = lr = 0 for ch in s: if(ch=='R'): lr = lr+1 if(ch=='L'): lr = lr-1 if(ch=='U'): ud = ud+1 if(ch=='D'): ud = ud-1 if((abs(lr) + abs(ud))%2==1): print(-1) else: print(int((abs(lr) + abs(ud))/2))
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
def solve(a): l = [0] li = [] j = 0 for i in range(len(a)): if a[i] == "A" or a[i] == "E" or a[i] == "I" or a[i] == "O" or a[i] == "U" or a[i] == "Y": l.append(i + 1) j += 1 li.append(l[j] - l[j-1]) l.append(i + 1) j += 1 li.append(l[j] - l[j-1...
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases. But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, ...
import static java.lang.System.out; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] s = new int[n]; int m = 0; for (int i=0;i<n;i++) { s[i] = sc.nextInt(); m = Math.max(m,...
Peter decided to lay a parquet in the room of size n × m, the parquet consists of tiles of size 1 × 2. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it. The workers decided that removing entire parquet and then laying it again is v...
#include <bits/stdc++.h> using namespace std; template <class C> void mini(C &a4, C b4) { a4 = min(a4, b4); } template <class C> void maxi(C &a4, C b4) { a4 = max(a4, b4); } template <class TH> void _dbg(const char *sdbg, TH h) { cerr << sdbg << "=" << h << "\n"; } template <class TH, class... TA> void _dbg(const...
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... In...
import java.util.Scanner; public class _0381FakeNews { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input=sc.nextLine(); String temp="heidi"; int index=0; for(int i=0;i<input.length();i++) { if(index==5) { System.out.println("YES"); return; } if((...
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). M...
#include <bits/stdc++.h> using namespace std; void preprocess(void) { return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.precision(20); preprocess(); int n; cin >> n; long long k; cin >> k; vector<int> a(n); for (auto i = (0); i < n; i++) cin >> a[i]; sort(a.begin(), a.en...
From beginning till end, this message has been waiting to be conveyed. For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times: * Remove any two elements s and t...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Bui...
An array of positive integers a1, a2, ..., an is given. Let us consider its arbitrary subarray al, al + 1..., ar, where 1 ≤ l ≤ r ≤ n. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products Ks·Ks·s for every positive integer s. T...
#include <bits/stdc++.h> using namespace std; using ll = long long; struct query { int l, r, block, id; }; const int N = 200000, Q = 200000; int n, m, a[N], freq[1000001]; query q[Q]; ll ans[Q]; bool by_block(const query &a, const query &b) { if (a.block != b.block) return a.block < b.block; return a.r > b.r; } i...
— Willem... — What's the matter? — It seems that there's something wrong with Seniorious... — I'll have a look... <image> Seniorious is made by linking special talismans in particular order. After over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly. Seniorious has n p...
#include <bits/stdc++.h> using namespace std; using pii = pair<long long, long long>; const long long INF = 1e18 + 7; const long long N = 1e5 + 7; const long long MOD = 1e9 + 7; long long n, m, seed, v_max, i, j, k; long long a[N]; long long op, l, r, x, y; long long plusi(long long a, long long b, long long mo) { lo...
Will shares a psychic connection with the Upside Down Monster, so everything the monster knows, Will knows. Suddenly, he started drawing, page after page, non-stop. Joyce, his mom, and Chief Hopper put the drawings together, and they realized, it's a labeled tree! <image> A tree is a connected acyclic graph. Will's t...
#include <bits/stdc++.h> long long gi() { long long x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) f ^= ch == '-', ch = getchar(); while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return f ? x : -x; } int pow(int x, int y) { int ret = 1; while (y) { if (y & 1) ret = 1ll * ret * x % ...
When Igor K. was a freshman, his professor strictly urged him, as well as all other freshmen, to solve programming Olympiads. One day a problem called "Flags" from a website called Timmy's Online Judge caught his attention. In the problem one had to find the number of three-colored flags that would satisfy the conditio...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-9; const double pi = acos(-1.0); const int inf = 0x3f3f3f3f; const int W = 0, B = 1, R = 2, Y = 3; const int N = 8; const int mod = 1000000007; const int inv = 500000004; int l, r; int mtx[N][N], a[N][N]; int st[4][4], ts[N]; bool check(int i, int j) {...
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for n flowers and so it looks like a pipe with n holes. Arkady can only use the water that flows from the first hole. Arkady can block some of the holes, and then pour A liters of water into the pipe. After that,...
n, a, b = [int(i) for i in input().split(' ')] sizes = [int(i) for i in input().split(' ')] st = sum(sizes) s = (sizes[0] * a) / b sb = st - s blockable = sorted(sizes[1:], reverse=True) blocked_no = 0 blocked_amount = 0 for i in range(len(blockable)): if blocked_amount < sb: blocked_no += 1 block...
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set ...
#include <bits/stdc++.h> using namespace std; int n, m; vector<pair<int, int> > v1, v2; set<int> a1, a2; void solve() { cin >> n >> m; for (int i = 0; i < n; i++) { int first, second; cin >> first >> second; v1.push_back({min(first, second), max(first, second)}); } for (int i = 0; i < m; i++) { ...
Ashu is very fond of Prime numbers and he like challenging his friends by giving them various problems based on Mathematics and Prime number. One of his friend Harshit is jealous and challenges him to solve a task. Task is :Given a prime number X, you need to give the count of all numbers in range 1 to 10^6 inclusive w...
MAX = 10**6+1 primes = [1]*MAX primes[0] = primes[1] = 0 for i in xrange(2,MAX): if primes[i]: for j in xrange(i*i,MAX,i): if primes[j]: primes[i] += 1 primes[j] = 0 for _ in xrange(input()): x = input() print primes[x]
Little Chiku is very choosy about numbers. He considers 0 and 1 together as bad omen. So he hates 0 and 1 appearing adjacent to each other. So he wants you to remove these 0 and 1 combinations from a string. So you proceed like this : Choose any two adjacent positions in the string, and if one them contains 0, and the ...
tc=int(raw_input()) for case in range(tc): s=raw_input() l=len(s) z=s.count("0") o=s.count("1") if z<o: print l-z*2 else: print l-o*2
Results are out and admission process has begun in most of the colleges. This is the story of two such young engineering aspirants, Ramesh and Suresh, who intend to make it big in life. They met each other during the admission phase of some college and have become friends. But that does not mean they aren't competito...
def numbers(N): my_number = 0 v = {} c = {} i = 0 while my_number < N: c[i] = i * i * i for j in xrange(i): s = c[j] + c[i] if s in v: my_number += 1 yield(s) v[s] = (j,i) i += 1 my = [] def m(N): for x in numbers(N): my.append(x) m(100) T = int(raw_input()) for _ in xrange(T): N...
Gudi enters the castle, and moves along the main path. Suddenly, a block in the ground opens and she falls into it! Gudi slides down and lands in a dark room. A mysterious voice announces: Intruders are not allowed inside the castle. To proceed, you must solve my puzzle. Here is a string S indexed from 1 to N, cons...
#!/usr/bin/env python # -*- coding: utf-8 -*- # https://www.hackerearth.com/july-easy-16/algorithm/gudi-trapped-in-the-room-july-easy/ from collections import deque def increment_string(s, n, a): start, mul = (0, 1) if n % 2 == 1: start, mul = (1, 10) for i in xrange(start, n, 2): digit ...