input
stringlengths
29
13k
output
stringlengths
9
73.4k
Traveling around the universe Benny saw some strange numbers. These numbers are called Universal numbers. Benny asks you to help her to calculate the number of Universal numbers on some segments. First of all, you are given 15 numbers called remsi. The number is Universal if and only if it satisfies the following c...
take=lambda: raw_input().strip() calculate=lambda: list(map(int,raw_input().strip().split())) numbers=[1,2,3,4,5,6,7,8,9,0] num=[[1,2,3,4,5,6,7,8,9],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] ans=[[],[],[],[],[],[],[...
Problem: N boxes are arranged systematically in a circle and numbered from 1 to N in increasing order in clockwise direction. There will be Q queries asking you whether boxes i and j can be connected by a straight rod such that this rod does not intersect ( criss - cross as seen from top view ) with any of the other r...
#Salman Lari import sys n,q=map(int,sys.stdin.readline().split()) u=[] #Used up=[] #Used_ Pair for k in range(q): i,j=map(int,sys.stdin.readline().split()) if i in u or j in u: print "NO" continue flag=1 for l in range(len(up)): if i<up[l][1] and i>up[l][0]: i...
Sam is dangerous boy. He like to fight with everyone who is more powerful than him. One day, Sam enters in the meeting of all gangsters of the city. He wants to fight with everyone who is more powerful than him. But one man know his motive and tell to all gangsters about Sam. But gangsters don't know whether the Sam i...
test=int(raw_input()) while test: n,p=(raw_input().split()) count=0 n=int(n) p=int(p) power=[] power = map(int, raw_input().split()) #print power #print type(n) #print power for i in power: if p<i: # print i count=count+1 if int(p) in power: print "YES "+str(count) else: print "NO 0" test=test...
Little Arjit is in love with Deepa. They have always thought of themselves as the ideal couple - the best, possible match they could've managed. (No kidding!) And like every other couple, they promised each other not to fight after every other fight. But, when has that happened before? But, this is a different couple ...
##Goldbach's Conjecture t=int(raw_input()) for i in range(t): num=int(raw_input()) if num==2: print 'Arjit' else: print 'Deepa'
Subodh'CS Department is writing a spell-checker system, and you have been tasked with writing a function to determine how closely two words resemble each other. The algorithm you are to use, albeit not a very good one, is to compare the two words character by character, and count how many times the characters in a give...
import sys from sys import stdin def main(): T = int(stdin.readline().strip()) for i in xrange(T): a = stdin.readline().strip() b = stdin.readline().strip() diff = abs(len(a) - len(b)) if len(a) > len(b): a = a[:len(a) - diff] elif len(b) >len(a): ...
Mandark thinks he is better than Dexter. He challenges Dexter to find answer to a mathematics problem he created. Dexter accepts the challenge and decides to write a program for it to reduce manual calculations. The problem: Let f(x) be the greatest odd divisor of x, where x is a positive integer. You are given a posi...
T = int(raw_input()) while T > 0: num = int(raw_input()) sum = 0 while num!=0: if num%2==1: a=(num+1)/2 else: a=num/2 sum+=a*a num=num-a print sum T-=1
Rajat is a guy who always wants to live in a fantasy world. In his world, a deck consists of X cards, where X is a multiple of 4. There are four types of cards namely spade , heart , club and diamond with each type having values in range of [1,X/4] inclusive. His cousin wants to test him. So,to test Rajat , his cousin...
T = input() while(T>0): xx,n,d,k = (raw_input().split()) x = int(xx) print '%.10f' % (1.0/x) T = T-1
Things are heated up between the Finance team and the Marketing team, and they decide to have one-on-one fifa matches to settle it once and for all. Jha, being an intern, won’t play (it’s a battle of legends, after all) and has been given one job: to fix matches in the "hope" that he’ll match players of similar skill ...
n=input() f=raw_input() m=raw_input() f=f.split() m=m.split() for x in range(0,n): f[x]=int(f[x]) m[x]=int(m[x]) f=sorted(f, reverse=True) m=sorted(m, reverse=True) point=0 i=0 #print f #print m ##winnings while(i<len(f)): j=0 temp=f[i] while(j<len(m)): if(temp>m[j]): point=poi...
Silly Snail was a very intelligent snail on Snail Island. In order to get eligible for marriage, he had to pass the Graduation Exam conducted by C.B.S.E ( Central Board of Snail Education ). Seeing the intelligence level of the Silly Snail, the head of C.B.S.E decided to conduct the exam himself. Silly Snail performed ...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def traverse(root): print root.data, if root.left: traverse(root.left) if root.right: traverse(root.right) T = int(raw_input()) for t in range(T): num_nodes = int(raw_...
Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order: * Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly. Find the expected value of the inversion number of the sequence after all the oper...
import sys readline = sys.stdin.buffer.readline mod=998244353 class BIT: def __init__(self,n): self.n=n self.buf=[0]*n def add(self,i,v): buf=self.buf while i<n: buf[i]+=v if buf[i]>=mod: buf[i]-=mod i+=(i+1)&(-i-1) def get(self,i): buf=self.buf res=0 while i>=0: res+=buf[i] if...
The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese. When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a pos...
n = input() print('bon' if n[-1]=='3' else 'pon' if n[-1] in ['0','1','6','8'] else 'hon')
Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is `#`, and a "road" square if S_{ij} is `.`. From a road square, you can move to a horizontally or vertically adjacent ro...
#include <bits/stdc++.h> using namespace std; int main(){ int h,w; cin>>h>>w; vector<string> g(h); for(string &s: g) cin>>s; vector<int> dx={-1,0,0,1}; vector<int> dy={0,1,-1,0}; int ans=0; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(g[i][j]=='#') continue; int cnt=0; vector<...
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition: * There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1). Here S_1S_2...S_K represents the concatenation of S_1,S_2,....
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class Main { static String s = ""; public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { s = br.readLine(); } catch...
The restaurant AtCoder serves the following five dishes: * ABC Don (rice bowl): takes A minutes to serve. * ARC Curry: takes B minutes to serve. * AGC Pasta: takes C minutes to serve. * APC Ramen: takes D minutes to serve. * ATC Hanbagu (hamburger patty): takes E minutes to serve. Here, the time to serve a dish is ...
A = [-int(input()) for _ in range(5)] m = max(A, key = lambda x: x%10) print(-(m-m//10*10+sum([a//10*10 for a in A])))
Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\). \\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\)...
#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <string> #include <iomanip> #include <algorithm> #include <cmath> #include <stdio.h> using namespace std; #define int long long int MOD = 998244353; int gcd(int a, int b) { int c; while (a != 0) { c = a; a = b%a; b = c; ...
Snuke has an integer sequence A whose length is N. He likes permutations of (1, 2, ..., N), P, that satisfy the following condition: * P_i \leq A_i for all i ( 1 \leq i \leq N ). Snuke is interested in the inversion numbers of such permutations. Find the sum of the inversion numbers over all permutations that satis...
#include<bits/stdc++.h> #define ld double #define ull unsigned long long #define ll long long #define pii pair<int,int > #define iiii pair<int,pii > #define mp make_pair #define INF 1000000000 #define MOD 1000000007 #define rep(i,x) for(int (i)=0;(i)<(x);(i)++) inline int getint(){ int x=0,p=1;char c=getchar(); while...
Consider the following game: * The game is played using a row of N squares and many stones. * First, a_i stones are put in Square i\ (1 \leq i \leq N). * A player can perform the following operation as many time as desired: "Select an integer i such that Square i contains exactly i stones. Remove all the stones from S...
#include<stdio.h> #include<math.h> #include<algorithm> #include<queue> #include<deque> #include<string> #include<string.h> #include<vector> #include<set> #include<map> #include<bitset> #include<stdlib.h> #include<cassert> using namespace std; const long long mod=1000000007; const long long inf=mod*mod; const long long ...
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer. Snuke can repeatedly perform the following operation: * Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x. Snuke's objective is to match a with another sequence b = (...
#include<iostream> #include<vector> #include<algorithm> #include<cstring> #include<cstdio> #include<cmath> #include<cstdlib> #include<ctime> #include<queue> #include<set> #include<map> #include<stack> #include<bitset> using namespace std; typedef long long LL; int gi() { int w=0;bool q=1;char c=getchar(); while ((c<'...
There is a tree with N vertices. The vertices are numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i. The lengths of all the edges are 1. Snuke likes some of the vertices. The information on his favorite vertices are given to you as a string s of length N. For each 1 ≤ i ≤ N, s_i...
#include<bits/stdc++.h> using namespace std; const int N=200005; int x,y,n,Max[N],Max2[N],l[N],z[N]; vector<int>G[N]; char s[N]; long long ans; inline void upd(int x,int y){ if (y>Max[x])Max2[x]=Max[x],Max[x]=y; else if (y>Max2[x])Max2[x]=y; } inline void dfs1(int x,int y){ l[x]=N; if (s[x]=='1')l[x]=0,z[x]=1; for...
You are given an undirected graph with N vertices and M edges. Here, N-1≤M≤N holds and the graph is connected. There are no self-loops or multiple edges in this graph. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices a_i and b_i. The color of each vertex can be e...
#include<bits/stdc++.h> using namespace std; #define int long long const int N=200010; int size[N],Flag,cnt2[N],pp[N],cc,sd[N]; int cnt[N],col[N],n,m,ne[N],tot,fi[N],zz[N],flag[N],x,y,X,Y; void jb(int x,int y){ ne[++tot]=fi[x]; fi[x]=tot; zz[tot]=y; } void dfs2(int x){ cnt2[x]=col[x];flag[x]=1; for (int i=fi[x];i;...
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000. a + b + c + d = n Create a program that outputs the number of combinations that satisfy the conditions. Input Given multiple datasets. Each dataset is given n on one row. Please process until the end of the inpu...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { private static BufferedReader br = null; static { br = new BufferedReader(new InputStreamReader(System.in)); } /** * @param args */ public static void main(String[] args) { // TODO...
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments). The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to d...
#include <algorithm> #include <iostream> using namespace std; // g, f, e, d, c, b, a int ss[10][7] = { { 0, 1, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0, 1, 1 }, { 1, 0, 0, 1, 1, 1, 1 }, { 1, 1, 0, 0, 1, 1, 0 }, { 1, 1, 0, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 0, 1 }, { 0, 1, 0, 0, 1, 1, 1 }...
$N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation. * If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right d...
#include<iostream> #include<vector> #include<algorithm> #define REP(i,n) for(int i=0;i<n;i++) #define FOR(i,s,e) for(int i=s;i<e;i++) using namespace std; int main(void) { int N, MINR = 1001, MINL = 1001; cin >> N; vector<int> a(N); vector<int> w(N); REP(i, N)cin >> a[i]; REP(i, N)cin >> w[i]; REP(i, N) { if...
Dr. Asimov, a robotics researcher, loves to research, but hates houseworks and his house were really dirty. So, he has developed a cleaning robot. As shown in the following figure, his house has 9 rooms, where each room is identified by an alphabet: <image> The robot he developed operates as follows: * If the bat...
#include <vector> #include <list> #include <map> #include <set> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <utility> #include <functional> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstr...
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there...
#include<bits/stdc++.h> using namespace std; int main(){ int n,m,s,g; while(cin>>n>>m,n||m){ cin>>s>>g; s--;g--; int d[n][n],c[n][n]; memset(d,-1,sizeof(d)); memset(c,-1,sizeof(c)); int i,j,k,l,x,y; for(i=0;i<m;i++){ cin>>x>>y>>j>>k; x--;y--; d[x][y]=d[y][x]=j; c[...
ICPC (International Connecting Points Company) starts to sell a new railway toy. It consists of a toy tramcar and many rail units on square frames of the same size. There are four types of rail units, namely, straight (S), curve (C), left-switch (L) and right-switch (R) as shown in Figure 9. A switch has three ends, na...
#include<iostream> #include<cassert> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) #define N 0 #define E 1 #define S 2 #define W 3 int dx[]={0,1,0,-1}; int dy[]={-1,0,1,0}; int curdir[]={S,W,N,E}; int sd[2][4]={//S default:0 - -1,W,-1,E, S,-1,N,-1, }; int cd[4][4]={/...
Problem In this problem, a straight line passing through a certain point X and a certain point Y in the three-dimensional space is written as a straight line XY. A cone and a point P inside the cone are given in three-dimensional space. Let point Q be the intersection of a straight line passing through point P and pe...
#include <iostream> #include <sstream> #include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <cstring> #include <string> #include <vector> #include <stack> #include <queue> #include <deque> #include <map> #include <set> #include <bitset> #include <numeric> #include <utility> #include <iomanip>...
Princess in Danger Princess crisis English text is not available in this practice contest. A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously inj...
#include <bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0; i<n; i++) int dp[110][110]; int dp2[110][110]; int main(){ int n,m,L,K,A,H; while(cin>>n>>m>>L>>K>>A>>H,n){ rep(i,n) rep(j,n) dp[i][j] = dp2[i][j] = 1e9; vector<int> ll(L); rep(i,L) cin>>ll[i]; ll.push_back(A); ll.push_back(H); ...
Peter is a person with erratic sleep habits. He goes to sleep at twelve o'lock every midnight. He gets up just after one hour of sleep on some days; he may even sleep for twenty-three hours on other days. His sleeping duration changes in a cycle, where he always sleeps for only one hour on the first day of the cycle. ...
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pii; #define all(c) (c).begin(), (c).end() #define loop(i,a,b) for(ll i=a; i<ll(b); i++) #define rep(i,b) loop(i,0,b) #define pb push_back #define eb ...
You have a lot of cats at home. Your daily routine is to take a picture of your cat in a clay pot and taking a nap (commonly known as a cat pot). The appearance of some cats curling up and sleeping together in a pot is really lovely. Each cat has a "weight" mi and a "Cute" ci defined. Cute is a numerical value that co...
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(ll (i) = (0);(i) < (n);++i) #define REV(i,n) for(ll (i) = (n) - 1;(i) >= 0;--i) #define PB push_back #define EB emplace_back #define MP make_pair #define FI first #define SE second #define SHOW1d(v,n) {REP(WW,n)cerr << v[WW] << ' ';cerr << endl << end...
replace replace Problem Statement Given the string S. The following processing is performed in the order of Q pieces. * Replace all the characters c_i contained in S with the character string p_i at the same time. Finally, output (1-indexed) from the A character to the B character of the character string S. Cons...
#include <iostream> #include <string> #include <vector> #include <stack> #include <queue> #include <climits> #include <algorithm> #include <cctype> #include <cstdlib> using namespace std; typedef long long LL; const LL inf = LLONG_MAX / 2; struct node{ char ch; LL refcnt; LL len; vector<node*> to; node(char c...
Problem statement We played an AI soccer match between Country A and Country B. You have a table that records the player who had the ball at a certain time and its position. The table consists of N rows, and the i-th row from the top consists of the following elements. * Number of frames f_i * The uniform number of t...
#define _USE_MATH_DEFINES #define _CRT_SECURE_NO_DEPRECATE #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <cfloat> #include <ctime> #include <cassert> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include ...
C: Mod! Mod! story That's right! I'm looking for eyewitness testimony! A phantom thief has appeared in Aizu! Everyone's horse stick was stolen! Who is the culprit! ?? Unravel! Mod! Mod! Problem statement "Eyes" ... it's a miracle bud that swells in the hearts of the chosen ones ... You can steal anything with the s...
#include "bits/stdc++.h" using namespace std; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i)) #define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i)) static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL; typedef vector<...
problem I want to put as many rectangular tiles as possible on a rectangular wall with a size of $ h $ in height and $ w $ in width, and a size of $ a $ in height and $ b $ in width. The following conditions must be met when attaching tiles. * Do not stack tiles. * Do not apply tiles diagonally, that is, any edge o...
h,w=map(int,input().split()) a,b=map(int,input().split()) high=(h//a)*a wide=(w//b)*b print(h*w-high*wide)
problem Given $ N $ strings $ S_i $. Find the maximum number of "AOR" in the string obtained by connecting $ S_i $ in any order. output Output the maximum number of "AOR" contained in the character string obtained by connecting $ S_i $ in any order. Also, output a line feed at the end. Example Input 2 AORA OR ...
#include <iostream> #include <string> using namespace std; int n; string s[100005]; int main(void) { cin >> n; for(int i = 1; i <= n; i++) cin >> s[i]; int ans = 0; for(int i = 1; i <= n; i++){ for(int j = 0; j+2 < s[i].size(); j++){ if(s[i].substr(j, 3) == "AOR") ans++; } } int Ocnt = 0, _A = 0, _A...
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * It visits each vertex exactly once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ di ≤ 1,000 * There are no multiedge Input |V| |E| s0 t0 d...
import java.util.Map.Entry; import java.io.*; import java.util.*; public class Main { static int[][] dp; static int N; static int[][] graph; static int INF = 16000; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); int M = sc.ne...
For given integers m and n, compute mn (mod 1,000,000,007). Here, A (mod M) is the remainder when A is divided by M. Constraints * 1 ≤ m ≤ 100 * 1 ≤ n ≤ 109 Input m n Two integers m and n are given in a line. Output Print mn (mod 1,000,000,007) in a line. Examples Input 2 3 Output 8 Input 5 8 Output...
#include<iostream> #include<cstdio> using namespace std; typedef long long LL; LL mod_pow(LL n, LL m, LL mod) { LL res = 1; while (m > 0) { if (m & 1) res = res * n % mod; n = n * n % mod; m >>= 1; } return res; } int main() { LL n, m; LL mod = 1000000007; scanf("%lld %lld", &n, &m); printf("%d\n...
Akhil has many balls of white and black colors. One day, he was playing with them. During the play, he arranged the balls into two rows both consisting of N number of balls. These two rows of balls are given to you in the form of strings X, Y. Both these string consist of 'W' and 'B', where 'W' denotes a white colored ...
testCases = input() for j in range(testCases): x = raw_input() y = raw_input() N = len(x) result= '' for i in range(N): if x[i]==y[i]: if x[i] == 'W': result=result + 'B' else: result=result + 'W' else: result = resu...
Chef is stuck in a two dimensional maze having N rows and M columns. He needs to get out of the maze as soon as possible and arrive at the kitchen in order to serve his hungry customers. But, he can get out of the maze only if he is able to successfully find any magical path in the given maze. A path is defined as ma...
val=raw_input() t=int(val) for i in range(t): lens=list() stri=raw_input() lens=stri.split() n=int(lens[0]) m=int(lens[1]) if n%2==0 and m%2==1 and m!=1: print 'Yes' elif m%2==0 and n%2==1 and n!=1: print 'Yes' elif n%2==0 and m%2==0: print 'Yes' elif n%2==1 and m%2==1 and n!=1 and m!=1: print 'No' e...
Dilku and Bhopu live in Artland. Dilku loves Bhopu and he writes a message : “iloveyou” on paper and wishes to send it to Bhopu. As Dilku is busy making an artwork, he asks his friend Raj to send the message to Bhopu. However Raj has a condition that he may add/remove some characters and jumble the letters of the mes...
inp,ans,ph=set(raw_input()),['sad','happy'],set('iloveyou') print ans[len(inp.intersection(ph)) == len(ph)]
On a Planet where people are obssessed with Numbers, they have human definitions for relation among Numbers. In one such case, they have designated a father number to be a number formed by the sum of the child number's digits along with the child number itself. For example, for number 481, (4+8+1+481=)494 is the father...
t=raw_input() t=int(t) while t: t-=1 n=raw_input() n=int(n) for i in xrange(1,n): j=i sum=i while j: sum+=j%10 j/=10 if sum==n: j=-1 break if j!=-1: print "NONE" else: print i
To protect people from evil, a long and tall wall was constructed a few years ago. But just a wall is not safe, there should also be soldiers on it, always keeping vigil. The wall is very long and connects the left and the right towers. There are exactly N spots (numbered 1 to N) on the wall for soldiers. The K^t...
d=[None,(2,2),(5,5),(8,9),(12,14),(16,20),(20,27),(24,35),(29,44),(34,54),(39,65),(44,77),(49,90),(54,104),(59,119),(64,135),(70,152),(76,170),(82,189),(88,209),(94,230),(100,252),(106,275),(112,299),(118,324),(124,350),(130,377),(136,405),(142,434),(148,464),(154,495)] for i in range(input()): n,m=map(int,raw_input()...
Sereja conducted a voting about N of his opinions. Ai percent of people voted for opinion number i. This statistics is called valid if sum of all Ai is equal to 100. Now let us define rounding up of a statistics A. If Ai is not an integer, it will be rounded up to next integer. Otherwise it will be left as it is...
from pprint import pprint as pp def GI(): return int(raw_input()) def GIS(): return map(int, raw_input().split()) def main(): T = GI() for t in xrange(T): N = GI() B = GIS() excess = sum(B) - 100 if excess < 0: print 'NO' elif excess < N - B.count(0): ...
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually cal...
#include <bits/stdc++.h> using namespace std; using ll = long long; template <class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } const ll INF = 1e18; template <typen...
Medicine faculty of Berland State University has just finished their admission campaign. As usual, about 80\% of applicants are girls and majority of them are going to live in the university dormitory for the next 4 (hopefully) years. The dormitory consists of n rooms and a single mouse! Girls decided to set mouse tra...
#include <bits/stdc++.h> using namespace std; inline void prep() { cin.tie(0); cin.sync_with_stdio(0); }; const int mod = (int)1e9 + 7; const int MX = (int)2e5 + 20; int mn[MX]; vector<int> g[MX], comp_g[MX]; int pre[MX]; int low[MX]; int id[MX]; stack<int> stk; int cntr, scc; void tarjan(int x) { if (pre[x] != -...
Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race. Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next r...
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Comparator; import java.util.PriorityQueue; import java.util.StringTokenizer; import static java.lang.Math.*; import static ja...
Berkomnadzor — Federal Service for Supervision of Communications, Information Technology and Mass Media — is a Berland federal executive body that protects ordinary residents of Berland from the threats of modern internet. Berkomnadzor maintains a list of prohibited IPv4 subnets (blacklist) and a list of allowed IPv4 ...
#include <bits/stdc++.h> using namespace std; class TrieNode { public: bool postive, leaf; TrieNode *zero, *one; TrieNode() { postive = leaf = 0; zero = one = NULL; } }; void add(string &s, int idx, bool postive, TrieNode *cur) { cur->postive |= postive; if (idx == s.size()) { cur->leaf = 1; ...
Bob is a duck. He wants to get to Alice's nest, so that those two can duck! <image> Duck is the ultimate animal! (Image courtesy of See Bang) The journey can be represented as a straight line, consisting of n segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last seg...
#include <bits/stdc++.h> using namespace std; int main() { int64_t n; cin >> n; vector<int64_t> a(n), water(n, 0), land(n, 0); int64_t time = 0; for (int64_t i = 0; i < n; i++) { cin >> a[i]; a[i] *= 4; time += a[i]; } string s__; cin >> s__; for (int64_t i = 0; i < n; i++) { water[i] ...
You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have n tiles in your hand. Each tile has an integer between 1 and m written on it. To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tile...
#include <bits/stdc++.h> using namespace std; int a[1000005], dp[1000005][3][3]; const int inf = 0x3f3f3f3f; int main() { int n, m, d; scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%d", &d), a[d]++; for (int i = 0; i <= m + 1; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 3; k++) d...
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page a_i (a_i ≥ i). Ivan wants to read the whole book. Each day, he reads the first page he didn'...
import sys #p = [[] for i in range(N)] #for i in range(N): # p[i] += map(int, sys.stdin.readline().split()) #Q = input() #for i in range(Q): # print(list(map(int, sys.stdin.readline().split()))) n = int(input()) a = [int(c) for c in sys.stdin.readline().split()] aktmax, d = 0, 0 for i, c in enumerate(a, start=1)...
It is an interactive problem. Vasya enjoys solving quizzes. He found a strange device and wants to know how it works. This device encrypted with the tree (connected undirected graph without cycles) with n vertices, numbered with integers from 1 to n. To solve this quiz you should guess this tree. Fortunately, this d...
#include <bits/stdc++.h> using namespace std; const int N = 1100; struct Edge { int to, next; } edge[N * 2]; int head[N], num; void add_edge(int a, int b) { edge[++num] = (Edge){b, head[a]}, head[a] = num; } int n, q[N], a[N], a0[N], ccc; char s[N]; void dfs(int x, int d, int f, int ff) { if (x != ff) a[x] = 1; i...
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle. After a long time thinking, Tolik's uncle hasn't any...
#include <bits/stdc++.h> using namespace std; vector<long long> v; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long a = 0, b = 0, c, d, e, f = 0, l, g, m, n, k, i, j, t, p, q; cin >> m >> n; for (i = 1; i <= n / 2; i++) { for (j = 1; j <= m; j++) { cout << j ...
There is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the governm...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class payoff { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Reader.init(System.in); int n = Reader.ne...
There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bott...
a=list(map(int,input().split())) x1,y1,x2,y2=a[0],a[1],a[2],a[3] a=list(map(int,input().split())) x3,y3,x4,y4=a[0],a[1],a[2],a[3] a=list(map(int,input().split())) x5,y5,x6,y6=a[0],a[1],a[2],a[3] l1=l2=l3=l4=1 if (x1>=x5 and x2<=x6 and y1>=y5 and y1<=y6) or (x1>=x3 and x2<=x4 and y1>=y3 and y1<=y4) or (y1>=y5 and y1<=y6...
In the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are n residents and n cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from 1 to n, where the i...
#include <bits/stdc++.h> using namespace std; int t; int n, m; vector<int> adj[1000005]; vector<int> adj_r[1000005]; bool use[1000005]; bool use_r[1000005]; vector<int> ans; void dfs(int node, stack<int> &s) { use[node] = 1; for (auto it : adj[node]) { if (use[it] == 0) { dfs(it, s); } } s.push(no...
Let's call two numbers similar if their binary representations contain the same number of digits equal to 1. For example: * 2 and 4 are similar (binary representations are 10 and 100); * 1337 and 4213 are similar (binary representations are 10100111001 and 1000001110101); * 3 and 2 are not similar (binary repr...
#include <bits/stdc++.h> using namespace std; const int maxn = 123; int a[maxn], b[maxn]; int vis[maxn]; int n; struct P { int a[101]; bool operator<(const P &t) const { for (int i = 0; i < n; i++) { if (a[i] != t.a[i]) return a[i] < t.a[i]; } return false; } }; P t; map<P, int> m; int main() { ...
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; while (n--) { string s; cin >> s; int i = 0, count = 0; while (s[i] != '\0') { count++; i++; } if (s[count - 2] == 's' && s[count - 1] == 'u') cout << "JAPANESE" << endl; if (s[count - 2] == 'p' && ...
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i. For every i (1 ≤ i ≤ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly...
t = int(input()) for T in range(t): a = input() b = input() c = input() n = len(a) count = 0 for i in range(n): if a[i] == c[i] or b[i] == c[i]: count += 1 if count == n: print("YES") else: print("NO")
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x. As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it. It's guaranteed that the solution always exists. If ther...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class EhAbAndGCD { public static void main(String argv[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int test = Integer.parseInt(br.readLine()); ...
We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in s...
#include <bits/stdc++.h> using namespace std; long long int solver(long long int x, vector<set<long long int> > &v, long long int n) { long long int idx = -1, i; for (i = 0; i < n - 1; i++) { if (v[i].find(x) != v[i].end()) v[i].erase(x); if ((long long int)v[i].size() == 1) { if ...
This is an interactive problem. Ayush devised yet another scheme to set the password of his lock. The lock has n slots where each slot can hold any non-negative integer. The password P is a sequence of n integers, i-th element of which goes into the i-th slot of the lock. To set the password, Ayush comes up with an a...
#include <bits/stdc++.h> using namespace std; const int MX = 1 << 10; int n; int bitcnt[MX * 10], mp[MX * 10]; int ass[MX * 10], acnt; long long ret[MX]; int main() { cin >> n; for (int i = 1; i < (1 << 13); ++i) { bitcnt[i] = 1 + bitcnt[i - (i & -i)]; if (bitcnt[i] == 6) ass[++acnt] = i; } for (int i =...
You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain pe...
#include <bits/stdc++.h> using namespace std; long long mo(long long a) { return a % (long long)(1e9 + 7); } long long po(long long x, long long y, long long p) { long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y >>= 1; x = (x * x) % p; } return res % p; } vector<vect...
Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan. There are n cities in the republic, some of them are connected by m directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary d...
//make sure to make new file! import java.io.*; import java.util.*; public class E669{ public static void main(String[] args)throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = n...
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated....
# from debug import * import sys;input = sys.stdin.readline for _ in range(int(input())): s = input().strip() stack = [] for i in s: if stack and i == 'B': stack.pop() else: stack.append(i) print(len(stack))
Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≤ i≤ n-1) and swap a_i and a_{i+1}, or * choos...
import sys input = sys.stdin.readline for _ in range(int(input())): n,k=map(int,input().split()) a=input() b=input() l1=[0]*26 l2=[0]*26 for i in range(n): l1[ord(a[i])-97]+=1 l2[ord(b[i])-97]+=1 f=False for i in range(25): z=l1[i]-l2[i] if(z<0 or z%k): ...
At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not...
import java.io.*; import java.util.*; import java.math.*; public class CFTemplate { static final long MOD = 1000000007L; //static final long MOD2 = 1000000009L; //static final long MOD = 998244353L; //static final long INF = 500000000000L; static final int INF = 10000000; static final int NINF ...
It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To ente...
def show(x, y, z, w): print("YES") print(x+1, y+1, z+1, w+1) exit(0) n=int(input()) ara=list(int(x) for x in input().split()) n=min(n, 2000) found={} for i in range(0, n): for j in range(i+1, n): cur_sm=ara[i]+ara[j] if cur_sm in found.keys() and found[cur_sm][0]!=i and found[cur_sm][1]!=j and found[cur_sm][0...
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whe...
#include <bits/stdc++.h> typedef long long int ll; using namespace std; ll mod = 1e9+7; #define MAXN 10000001 int spf[MAXN]; vector<int>ans(3e5,0); int m; void func(vector<tuple<int,char,int>>&v) { vector<tuple<int,char,int>>st; for(int i=0;i<v.size();i++) { if(st.size()==0) { st.push_back(v[i]); ...
Mrs. Hudson hasn't made her famous pancakes for quite a while and finally she decided to make them again. She has learned m new recipes recently and she can't wait to try them. Those recipes are based on n special spices. Mrs. Hudson has these spices in the kitchen lying in jars numbered with integers from 0 to n - 1 (...
#include <bits/stdc++.h> using namespace std; int n, m, t; const int su[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, -1}; const long long MODER[5] = {223092870ll, 2756205443ll, 907383479ll, 42600829ll, 97ll}; int b...
Fibonacci strings are defined as follows: * f1 = «a» * f2 = «b» * fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as...
#include <bits/stdc++.h> using namespace std; const double EPS = -1e8; const double Pi = acos(-1); bool inline equ(double a, double b) { return fabs(a - b) < EPS; } const int MAXN = 200010; const long long MOD = 1000000007ll; inline long long add(long long a, long long b) { return (a + b) % MOD; } inline long long mul(...
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams ...
#include <bits/stdc++.h> using namespace std; const int Maxn = 50 + 10; int n; struct tim { int scr, goal, sub; string name; } arr[Maxn]; vector<string> ans; bool moq(tim a, tim b) { if (a.scr < b.scr) return true; if (a.scr > b.scr) return false; if (a.sub < b.sub) return true; if (a.sub > b.sub) return fa...
A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|). You've got two strings — s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at...
#include <bits/stdc++.h> using namespace std; const int N = 200005; char a[N], b[N]; int last[26]; vector<int> G[26]; bool vis[N]; int lc[N], rc[N]; int main() { cin >> a >> b; int m = strlen(b); for (int i = 0; i < m; i++) G[b[i] - 'a'].push_back(i); memset(last, -1, sizeof(last)); int n = strlen(a); for (...
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique. We call the man with a number a a 1-ancestor of the man with ...
#include <bits/stdc++.h> using namespace std; const int kMax = 100010; struct Query { int ql, qr, qi; Query(int _ql, int _qr, int _qi) { ql = _ql, qr = _qr, qi = _qi; } bool operator<(const Query &rq) const { return qr < rq.qr; } }; int N, Q; int si[kMax], di[kMax], lf[kMax], rg[kMax], dfn, max_dpt; vector<int> t...
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t...
while(True): try: n = input() a = raw_input() b = a.split() ans = 0 for i in range (0,n): ans += int(b[i]) n += 1 cnt = 0 for i in range (1,6): if ((ans+i)%n!=1): cnt += 1 print cnt except EOF...
One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold pe...
#include <bits/stdc++.h> using namespace std; const long long MOD = 1000000007; long long fact[200001], invfact[200001]; int n50 = 0, n100 = 0, k = 0; struct node { int l[2], r[2], b; }; long long nways[51][51][51][51][2], shortest[51][51][51][51][2]; queue<node> q; long long pmod(long long base, long long p) { if ...
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member o...
import java.io.*; import java.util.*; public class Contest189 { public static void main(String[] args) throws IOException { new Contest189().run(); } long binpow(long a, long p, long mod) { long res = 1 % mod; while(p != 0) { if((p & 1) != 0) res = (res...
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value. However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will co...
#import sys #sys.stdin = open('in') a, b = map(long,raw_input().split()) res = 0 while a > 1 or b > 1: if a > b: n = a / b res += n a -= b*n else: n = b / a res += n b -= a*n print res + (1 if a == 1 and b == 1 else 0)
Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit sala...
#include <bits/stdc++.h> using namespace std; long long n, k, a[110], b[110], dp[110][101000][2]; long long Rec(int i, int sum, bool take) { if (i == n) return (sum == 1e4 && take ? 0 : -1e9); if (dp[i][sum][take] != -1) return dp[i][sum][take]; long long Res = -1e9; Res = max(Res, a[i] + Rec(i + 1, (sum + a[i]...
Two chess pieces, a rook and a knight, stand on a standard chessboard 8 × 8 in size. The positions in which they are situated are known. It is guaranteed that none of them beats the other one. Your task is to find the number of ways to place another knight on the board so that none of the three pieces on the board bea...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.HashSet; public class Main { private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; ...
Not so long ago as a result of combat operations the main Berland place of interest — the magic clock — was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin correspond...
#include <bits/stdc++.h> using namespace std; int x, y; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> x >> y; double dist = sqrt((x * x + y * y)); if ((y >= 0 && x >= 0) || (y < 0 && x < 0)) { if (int(dist) % 2 && int(dist) != dist) return cout << "white", 0; else return cout <<...
This time our child has a simple polygon. He has to find the number of ways to split the polygon into non-degenerate triangles, each way must satisfy the following requirements: * each vertex of each triangle is one of the polygon vertex; * each side of the polygon must be the side of exactly one triangle; * t...
#include <bits/stdc++.h> using namespace std; pair<long double, long double> v[300], O, M; int n, nr, K, nri, OK[300][300], nx[300], val1, val2, val; long long A1, dt, A2, B1, B2, C1, C2, D[300][300], S, d1, d2, d3, d4; long double xm, ym, SP; long double aba(long double a) { if (a < 0) return -a; return a; } long ...
In Berland prime numbers are fashionable — the respectable citizens dwell only on the floors with numbers that are prime numbers. The numismatists value particularly high the coins with prime nominal values. All the prime days are announced holidays! Yet even this is not enough to make the Berland people happy. On the...
import java.util.*; public class cf45g { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); boolean[] isPrime = new boolean[n+1]; Arrays.fill(isPrime,true); int[] ans = new int[n+1]; Arrays.fill(ans,1); int sum = (n*n+n)/2; if(!isPrime(sum)) { //eve...
Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the...
s, e = [int(num) for num in input().split()] def GCD(a, b): return GCD(b, a % b) if b else a result = -1 for i in range(s, e + 1): for j in range(i + 1, e + 1): if GCD(i, j) == 1: for k in range(j + 1, e + 1): if GCD(j, k) == 1 and GCD(i, k) != 1: print...
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea. Amr has n instruments, it takes ai days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments. Amr asked for your help ...
#include <bits/stdc++.h> using namespace std; int main() { int n, k; cin >> n >> k; int a[n]; vector<int> ind; for (int i = 0; i < n; i++) cin >> a[i]; int count = 0; while (k >= 0) { int m = 111; int i, ans; for (i = 0; i < n; i++) { if (a[i] < m) { m = a[i]; ans = i; ...
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was. Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers f...
import functools as ft if __name__ == '__main__': n = int(input()) a = list(map(int, input().split())) b = [i for i in range(n)] for i in range(1, n + 1): a = [(a[j] + 1) % n if not j % 2 else (a[j] - 1) % n for j in range(n)] cnt = ft.reduce(lambda x, y: x + y, [a[j] == b[j] for j in ...
It's election time in Berland. The favorites are of course parties of zublicanes and mumocrates. The election campaigns of both parties include numerous demonstrations on n main squares of the capital of Berland. Each of the n squares certainly can have demonstrations of only one party, otherwise it could lead to riots...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXN = 5000; const int MAXM = MAXN - 1; int n; int head[MAXN]; int nxt[2 * MAXM], to[2 * MAXM]; int cnt[MAXM + 1]; int val[MAXM + 1][MAXN + 1]; void go(int at, int e) { cnt[e] = 0, va...
In the land of Bovinia there are n pastures, but no paths connecting the pastures. Of course, this is a terrible situation, so Kevin Sun is planning to rectify it by constructing m undirected paths connecting pairs of distinct pastures. To make transportation more efficient, he also plans to pave some of these new path...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100000; const int MAXM = 300000; struct node { int key, id, rev; int siz1, siz2, s; node *fa, *ch[2], *mx; } tree[MAXN + MAXM + 5], *ad[MAXN + MAXM + 5]; struct edge { int u, v, w, id; edge(int _u = 0, int _v = 0, int _w = 0, int _i = 0) : u...
Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks. The students don’t want to use too many blocks, but they also want to be uniq...
#include <bits/stdc++.h> using namespace std; int bs(int a, int l1, int r1, int n, int m) { int l = l1, r = r1; int mid; while (r - l > 1) { mid = l + (r - l) / 2; if (mid / 2 + mid / 3 - mid / 6 >= a && mid / 2 >= n && mid / 3 >= m) { r = mid; } else { l = mid; } } if (l / 2 + l /...
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider...
#include <bits/stdc++.h> using namespace std; void rdInt(int &n) { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } n = x * f; } map<int, int> mpx, mpy; m...
During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help. You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal d...
#include <bits/stdc++.h> using namespace std; set<int> a; map<int, int> b; set<int>::iterator k1, k2; int n, x, k = 0; int main() { scanf("%d", &n); scanf("%d", &x); a.insert(x); b[x] = 1; for (int i = 1; i < n; ++i) { scanf("%d", &x); k1 = a.lower_bound(x); if (k1 == a.end()) k1--, printf("...
While creating high loaded systems one should pay a special attention to caching. This problem will be about one of the most popular caching algorithms called LRU (Least Recently Used). Suppose the cache may store no more than k objects. At the beginning of the workflow the cache is empty. When some object is queried ...
#include <bits/stdc++.h> using namespace std; const int N = 30, mod = int(1e9) + 7; const double eps = 1e-9; int k, n; double p[N]; long double dp[1 << 21], a[N]; int main() { scanf("%d%d", &n, &k); for (int i = 0; i < n; i++) { scanf("%lf", &p[i]); } dp[0] = 1; for (int mask = 0; mask < (1 << n); mask++)...
Tree is a connected undirected graph that has no cycles. Edge cactus is a connected undirected graph without loops and parallel edges, such that each edge belongs to at most one cycle. Vasya has an edge cactus, each edge of this graph has some color. Vasya would like to remove the minimal number of edges in such way ...
#include <bits/stdc++.h> using namespace std; queue<int> q; int fa[10000 + 10], dfn[10000 + 10], n, m, tot, dcnt, S, T, cnt = 1; bool vis[10000 * 4 + 10]; void Read(int &x) { char c; while (c = getchar(), c != EOF) if (c >= '0' && c <= '9') { x = c - '0'; while (c = getchar(), c >= '0' && c <= '9') ...
Just in case somebody missed it: we have wonderful girls in Arpa’s land. Arpa has a rooted tree (connected acyclic graph) consisting of n vertices. The vertices are numbered 1 through n, the vertex 1 is the root. There is a letter written on each edge of this tree. Mehrdad is a fan of Dokhtar-kosh things. He call a st...
#include <bits/stdc++.h> using namespace std; const double pi = acos(0.0) * 2.0; const long double eps = 1e-10; const int step[8][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}, {-1, 1}, {1, 1}, {1, -1}, {-1, -1}}; template <class T> inline T abs1(T a) { return a < 0 ? -a : a; } template <typename t,...
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins. Across all the sets Misha scored a points ...
import java.util.Scanner; public class C765 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int K = in.nextInt(); int A = in.nextInt(); int B = in.nextInt(); int sets = A/K + B/K; if ((A%K != 0 && B < K) || (B%K != 0 && A < K)) { ...
On the 228-th international Uzhlyandian Wars strategic game tournament teams from each country are called. The teams should consist of 5 participants. The team of Uzhlyandia will consist of soldiers, because there are no gamers. Masha is a new minister of defense and gaming. The prime duty of the minister is to calcu...
#include <bits/stdc++.h> using namespace std; const int iinf = 1e9 + 7; const long long linf = 1ll << 60; const double dinf = 1e60; template <typename T> inline void scf(T &x) { bool f = 0; x = 0; char c = getchar(); while ((c < '0' || c > '9') && c != '-') c = getchar(); if (c == '-') { f = 1; c = ge...
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels! There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle... Everybody was upset. The beautiful ...
#include <bits/stdc++.h> using namespace std; char *pt; long get_int() { long temp = 0; while (*pt < '0' && *pt > '9') pt++; while (*pt >= '0' && *pt <= '9') { temp = temp * 10 + (*pt - '0'); pt++; } pt++; return temp; } long long gcd(long long a, long long b) { if (b == 1 || a == 1) return 1; i...
<image> Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner. Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabr...
#include <bits/stdc++.h> using namespace std; const long long INF = 1e17; const long long maxn = 2e5 + 700; const int mod = 1e9 + 7; template <typename T> inline void read(T &a) { char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) { ...
Harry, Ron and Hermione have figured out that Helga Hufflepuff's cup is a horcrux. Through her encounter with Bellatrix Lestrange, Hermione came to know that the cup is present in Bellatrix's family vault in Gringott's Wizarding Bank. The Wizarding bank is in the form of a tree with total n vaults where each vault ha...
#include <bits/stdc++.h> using namespace std; long long INV2 = 500000004; long long INV6 = 166666668; long long power(long long a, long long b, long long c) { long long x = 1, y = a; while (b > 0) { if (b & 1) x = (x * y) % c; y = (y * y) % c; b /= 2; } return x % c; } int dx[] = {0, -1, 0, 1}; int ...
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence. When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time,...
#include <bits/stdc++.h> using namespace std; inline int SG(double x) { return x > -1E-8 ? x < 1E-8 ? 0 : 1 : -1; } long long gcd(long long a, long long b) { while ((a %= b) && (b %= a)) ; return a + b; } int main() { long long a, b, i, j, d, sa; scanf("%I64d %I64d", &a, &b); d = a * b / gcd(a, b); sa =...
Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai. Mishka can put a box i into another box j if the following conditions are met: * i-th box is not put into another box; * j-th box doesn't contain any other boxes; * box i is smaller than box j (ai < aj). Mishka ...
from sys import stdin,stdout from collections import Counter def ai(): return list(map(int, stdin.readline().split())) def ei(): return map(int, stdin.readline().split()) def ip(): return int(stdin.readline().strip()) def op(ans): return stdout.write(str(ans) + '\n') t = ip() li = ai() x = max(li) c = Counter(li).val...