input
stringlengths
29
13k
output
stringlengths
9
73.4k
Samu had got N fruits. Sweetness of i^th fruit is given by A[i]. Now she wants to eat all the fruits , in such a way that total taste is maximised. Total Taste is calculated as follow (Assume fruits sweetness array uses 1-based indexing) : int taste=0; for(int i=2;i ≤ N;i++){ if (A[i]-A[i-1] ≥ 0){ taste =...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' def greed(arr,j,N): max1=0 op=[] k=0 chk=[] N1=N sol=0 for x in arr: chk.append(0) seed=arr[j] op.append(arr[j]) chk[j]=1 flag=0 while N1>=2: flag=0 for i in ra...
See Russian Translation It's a fine sunny afternoon today in California. Looking at the pleasant weather, Sumit is all ready to go out and play with his friend Rohil. Unfortunately, Rohil is down with fever. Seeing that his friend is ill, Sumit decides not to go out - instead play with Rohil inside the house. Sumit lo...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' arr = [] no = int(raw_input()) for i in range(no): strInput = raw_input() firstChar = strInput[0] lastChar = strInput[-1] sortedStrInput = "".join(sorted(strIn...
Find a*b, for all given number pairs SAMPLE INPUT 5 4 6 3 7 SAMPLE OUTPUT 24 21
import sys for line in sys.stdin: a = line.split() if(len(a)==2): print int(a[0])*int(a[1])
Given an integer a as input, print the value a + a^2 + a^3. Constraints * 1 \leq a \leq 10 * a is an integer. Input Input is given from Standard Input in the following format: a Output Print the value a + a^2 + a^3 as an integer. Examples Input 2 Output 14 Input 10 Output 1110
import java.util.Scanner; public class Main { public static void main(final String[] args) { final var scanner = new Scanner(System.in); final int a = scanner.nextInt(); System.out.println(a + a * a + a * a * a); } }
We have a tree G with N vertices numbered 1 to N. The i-th edge of G connects Vertex a_i and Vertex b_i. Consider adding zero or more edges in G, and let H be the graph resulted. Find the number of graphs H that satisfy the following conditions, modulo 998244353. * H does not contain self-loops or multiple edges. * ...
#include<bits/stdc++.h> #define rep(i,a,b) for(int i=(a);i<(b);++i) #define per(i,a,b) for(int i=(b)-1;i>=(a);--i) #define ll long long #define lb(x) ((x)&(-x)) #define pii pair<int,int> #define vi vector<int> #define pb push_back #define fi first #define se second #define de(x) cout<<x<<" x"<<endl #define LCAFA rep(i,...
There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S. Adjacent slimes with the same color will fuse into one larger slime withou...
#include "bits/stdc++.h" using namespace std; string a; int n,ans; int main() { cin>>n>>a; for(int i=1;i<a.size();i++) if(a[i]!=a[i-1]) ans++; cout<<ans+1; }
Snuke found a random number generator. It generates an integer between 0 and 2^N-1 (inclusive). An integer sequence A_0, A_1, \cdots, A_{2^N-1} represents the probability that each of these integers is generated. The integer i (0 \leq i \leq 2^N-1) is generated with probability A_i / S, where S = \sum_{i=0}^{2^N-1} A_i...
#include <iostream> #include <stdio.h> #include <math.h> #include <string.h> #include <time.h> #include <stdlib.h> #include <string> #include <bitset> #include <vector> #include <set> #include <map> #include <queue> #include <algorithm> #include <sstream> #include <stack> #include <iomanip> #include <assert.h> using na...
Taro's summer vacation starts tomorrow, and he has decided to make plans for it now. The vacation consists of N days. For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day: * A: Swim in the sea. Gain a_i points of happiness. * B: Catch bugs in the mountains. Gain b_i...
n=int(input()) a,b,c=map(int,input().split()) for _ in range(1,n): aa,bb,cc=map(int,input().split()) a,b,c=aa+max(b,c),bb+max(a,c),cc+max(a,b) print(max(a,b,c))
Kenkoooo is planning a trip in Republic of Snuke. In this country, there are n cities and m trains running. The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally. Any city can be reached from any city by changing trains. Two currencies are used in the country: yen and snuuk....
import math, string, itertools, fractions, collections, re, array, bisect, sys, random, time, copy, functools from heapq import heappush, heappop, heappushpop, heapify, heapreplace N, M, S, T = [int(_) for _ in input().split()] UVAB = [[int(_) for _ in input().split()] for _ in range(M)] G1 = collections.defaultdict(l...
You are given N integers A_1, A_2, ..., A_N. Consider the sums of all non-empty subsequences of A. There are 2^N - 1 such sums, an odd number. Let the list of these sums in non-decreasing order be S_1, S_2, ..., S_{2^N - 1}. Find the median of this list, S_{2^{N-1}}. Constraints * 1 \leq N \leq 2000 * 1 \leq A_i \...
#include<bitset> #include<cstdio> #include<cstring> #include<algorithm> #define N 2005 using namespace std; bitset<N*N>f; int main(){ int n,x,sum=0; scanf("%d",&n); f[0]=1; for(int i=1;i<=n;++i){ scanf("%d",&x); f|=(f<<x),sum+=x; } for(int i=(sum+1)/2;i<=sum;++i) if(f[i]) return printf("%d",i),0; return 0...
We have N sticks with negligible thickness. The length of the i-th stick is A_i. Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides. Find the maximum possible area of the rectangle. Constraints * 4 \leq N \leq 10^5 * 1 \leq A_i \leq ...
#include <bits/stdc++.h> using namespace std; long v[1<<20],n,e1=0; int main(){ cin>>n; for(int i=0;i < n;i++) { cin>>v[i];v[i]*=-1; } sort(v,v+n); for(int i=0;i < n-1;i++) { if(v[i]==v[i+1]){ if(e1){ cout<<e1*v[i];return 0; }else{ ...
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i. Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also...
import java.util.*; import java.lang.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int c = sc.nextInt(); int k = sc.nextInt(); int[] t = new int[n]; for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); } Arrays.sort(t); in...
There are N rabbits on a number line. The rabbits are conveniently numbered 1 through N. The coordinate of the initial position of rabbit i is x_i. The rabbits will now take exercise on the number line, by performing sets described below. A set consists of M jumps. The j-th jump of a set is performed by rabbit a_j (2≤...
# include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn(1e5 + 5); int n, m, b[maxn], que[maxn], len, vis[maxn]; ll k, f[maxn], g[maxn]; int main() { int i, j; scanf("%d", &n); for (i = 1; i <= n; ++i) scanf("%lld", &f[i]), b[i] = i; for (i = n; i; --i) f[i] -= f[i - 1]; scanf("%d%lld...
There is a puzzle to complete by combining 14 numbers from 1 to 9. Complete by adding another number to the given 13 numbers. The conditions for completing the puzzle are * You must have one combination of the same numbers. * The remaining 12 numbers are 4 combinations of 3 numbers. The combination of three numbers i...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<ll> VL; typedef vector<VL> VVL; typedef pair<int, int> PII; #define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i) #define REP(i, n) FOR(i, 0, n) #define ALL(x) x.begin(), x.end() #defin...
Decimal numbers are a common notation system currently in use and use ten symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 to represent all numbers. Binary numbers are a popular notation in the computer world and use two symbols, 0 and 1, to represent all numbers. Only the four numbers 0, 1, 2, and 3 are used in quaternary n...
#include<bits/stdc++.h> using namespace std; int main(void) { int i,j,k,cnt=1,flg; int n; int fo[10]={1,4,16,64,256,1024,4096,16384,65536,262144}; while(1) { cin>>n; flg=0; if(n==-1) break; for(i=9;i>=0;i--) { if(n==0&&flg==0) { cout<<"0"; break; } if(n/fo[i]>0&&n!=0) { cout<<n/fo[i]; ...
The appearance of the sun is called "sunrise" and the hiding is called "sunset". What is the exact time when the sun is on the horizon? As shown in the figure below, we will represent the sun as a circle and the horizon as a straight line. At this time, the time of "sunrise" and "sunset" of the sun is the moment when ...
#include<iostream> #include<algorithm> using namespace std; int main() { int h, r; cin >> h >> r; if(-h == r && h != 0) cout << 0 << endl; else if(h >= 0 && r >= 0) cout << 1 << endl; else if(h < 0 || r < 0) cout << -1 << endl; return 0; }
problem JOI, who came to Australia for a trip, enjoyed sightseeing in various places and finally returned to Japan. Now, JOI is in the town with the international airport where the return flight departs. The town is divided into north, south, east and west, and each section has roads, souvenir shops, houses, and an in...
#include<iostream> #include<vector> #include<bitset> using namespace std; typedef bitset<12> B; int m[51][51], dp[1 << 12][50][50][4]; int H, W, K; int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0}; int filter(int v, int x) { return (v << x) ? -1 : 1; } int dfs(int bit, int x, int y, int k) { if(dp[bit][x][y][k] ...
As the first step in algebra, students learn quadratic formulas and their factorization. Often, the factorization is a severe burden for them. A large number of students cannot master the factorization; such students cannot be aware of the elegance of advanced algebra. It might be the case that the factorization increa...
#include<iostream> using namespace std; int main(){ int a,b,c,p,q,r,s; while(cin>>a>>b>>c,a)if(c){ for(r=1;r*r<=a;r++)if(a%r==0){ p=a/r; for(s=c>0?-c:c;s<=(c>0?c:-c);s++)if(s&&c%s==0){ q=c/s; if(p*s+q*r==b){ cout<<p<<" "<<q<<" "<<r<<" "<<s<<endl; goto END; } } } cout<<"Impossible"<<end...
Professor Pathfinder is a distinguished authority on the structure of hyperlinks in the World Wide Web. For establishing his hypotheses, he has been developing software agents, which automatically traverse hyperlinks and analyze the structure of the Web. Today, he has gotten an intriguing idea to improve his software a...
#include <algorithm> #include <functional> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <vector> #include <list> #include <stack> #include <queue> #include <map> #include <set> #include <bitset> #include <cl...
Problem E Black or White Here lies a row of a number of bricks each painted either black or white. With a single stroke of your brush, you can overpaint a part of the row of bricks at once with either black or white paint. Using white paint, all the black bricks in the painted part become white while originally white ...
#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;} template <typename T,typename E> struct SegmentTree{ using F = function<T(T,T)>; using G =...
Look for the Winner! The citizens of TKB City are famous for their deep love in elections and vote counting. Today they hold an election for the next chairperson of the electoral commission. Now the voting has just been closed and the counting is going to start. The TKB citizens have strong desire to know the winner a...
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) typedef long long ll; int main(){ while(true){ int n,ans,z=0; vector<int> alp(26,0),A; char c,winner; cin>>n; if(!n) break; rep(i,n){ cin>>c; alp[c-'A']++; ...
At one point, there was a president who traveled around Japan to do business. One day he got a mysterious ticket. If you use the ticket, the train fare will be free regardless of the distance to the destination. However, when moving from the current station to the adjacent station is counted as one step, if the number ...
#include <iostream> #include <vector> #include <map> #include <cstring> using namespace std; typedef pair<int,int> P; typedef vector<int> vec; typedef vector<vec> mat; typedef long long ll; int N, M, Z; int tt[200][200], t[200][200]; map<P,int> idx; P ridx[200]; const int MOD = 10000; mat mul(mat &A, mat &B){ mat...
International Car Production Company (ICPC), one of the largest automobile manufacturers in the world, is now developing a new vehicle called "Two-Wheel Buggy". As its name suggests, the vehicle has only two wheels. Quite simply, "Two-Wheel Buggy" is made up of two wheels (the left wheel and the right wheel) and a axle...
#include <iostream> #include <complex> #include <cmath> #include <cstdio> using namespace std; typedef complex<double> P; const double PI = acos(-1.0); int main(){ int N, D; while(cin >> N >> D, N){ P p = P(0,0); double dir = PI/2; for(int i=0;i<N;i++){ int L, R, T; cin >> L >> R >> T; if(L==R){ p =...
The University of Aizu Elementary School (Aizu University and Small) is famous as one of Japan's leading competition programmer training schools. Of course, it is essential to practice the algorithm even when attending an athletic meet. Of course you, the director of the competitive programming department, want to win ...
#include<iostream> #include<vector> #include<algorithm> #include<set> #include<map> #include<unordered_map> #include<queue> #include<iomanip> #include<math.h> #include<bitset> #include<cassert> #include<random> #include<time.h> using namespace std; using ll=long long; using ld=long double; using P=pair<int,int>; #defin...
Problem Statement In the headquarter building of ICPC (International Company of Plugs & Connectors), there are $M$ light bulbs and they are controlled by $N$ switches. Each light bulb can be turned on or off by exactly one switch. Each switch may control multiple light bulbs. When you operate a switch, all the light b...
#include <algorithm> #include <cmath> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <vector> #include <cassert> #include <func...
jfen There is a one-person game to play on the H × W board. This game is a game to move 0 or 1 balls in each cell. You were playing this game and found it difficult to move the ball accurately from cell to cell because the ball is so round. So you decided to make a robot that would move the ball as instructed. Here, t...
#include <bits/stdc++.h> using namespace std; char j_s_board[10][10]; int idx,width; int jtos(string jfen){ std::vector<char> board[10]; int len=jfen.length(); idx=0;width=0; for(int i=0;i<len;i++){ if(jfen[i]=='/') idx++; else{ if(jfen[i]=='b'){ board[idx].push_back('b'); width...
Generalized leap year Normally, whether or not the year x is a leap year is defined as follows. 1. If x is a multiple of 400, it is a leap year. 2. Otherwise, if x is a multiple of 100, it is not a leap year. 3. Otherwise, if x is a multiple of 4, it is a leap year. 4. If not, it is not a leap year. This can be ge...
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ vector<int> ans(0); for(;;){ int n,l,r; cin >> n >> l >> r; if (n == 0 && l == 0 && r == 0) break; int a[n+1]; fill(a,a+n+1,0); for(int i = 1; i < n+1; i++){ cin >> a[i...
Problem There are $ N $ streetlights on a two-dimensional square of $ W \ times H $. Gaccho wants to start with $ (1,1) $ and go to $ (W, H) $. Gaccho is afraid of dark places, so he only wants to walk in the squares that are brightened by the streetlights. Initially, all streetlights only brighten the squares with th...
// {{{ #include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #...
Your task is to write a program of a simple dictionary which implements the following instructions: * insert str: insert a string str in to the dictionary * find str: if the distionary contains str, then print 'yes', otherwise print 'no' Notes Template in C Constraints * A string consists of 'A', 'C', 'G', or 'T' ...
import java.util.HashSet; import java.util.Set; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Set<String> set = new HashSet<String>(); int n = sc.nextInt(); for (int i = 0; i < n; i++) { String cmd = sc.next(); String str = s...
Write a program which reads an integer and prints sum of its digits. Input The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000. The input ends with a line including single zero. Your program should not process for this terminal ...
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); while(true){ String s=sc.next(); if(s.equals("0")) break; int ans=0; for(int i=0;i<s.length();i++){ ans+=s.charAt(i...
Its Chef's Birthday and his friends are demanding him for treat. So he went to the shop to buy N gift packets (one for each friend). Each gift packet bought from shop contains some number of chocolates in it. Chef believes in equality i.e. all gift packets should contain equal number of chocolates in it. So Chef thou...
import sys for t in xrange(int(sys.stdin.readline())): n=int(sys.stdin.readline()) arr=map(int,sys.stdin.readline().split()) s=sum(arr) if s%n ==0: avg=s/n c=0 for i in xrange(n): c+=abs(avg-arr[i]) print c/2 else: print "No Treat"
Lira is now very keen on compiler development. :) She knows that one of the most important components of a compiler, is its parser. A parser is, in simple terms, a software component that processes text, and checks it's semantic correctness, or, if you prefer, if the text is properly built. As an example, in declaring...
import sys RL = sys.stdin.readline T = int(RL()) for i in xrange(T): inp = RL() stack = 0 strlen = len(inp) count = 0 for j in xrange(strlen): if inp[j] == '<': stack += 1 elif inp[j] == '>': if stack == 0: break stack -= 1 ...
Tuzik is a little dog. But despite the fact he is still a puppy he already knows about the pretty things that coins are. He knows that for every coin he can get very tasty bone from his master. He believes that some day he will find a treasure and have loads of bones. And finally he found something interesting. A woode...
# @author Kilari Teja # GDOG Possibles = [100, 50, 10, 5, 2, 1] for _ in xrange(int(raw_input().strip())): Bucks = map(int, raw_input().strip().split(" ")) MaxBucks = 0 for People in xrange(1, Bucks[1] + 1): if Bucks[0]%People > MaxBucks: MaxBucks = Bucks[0]%People print MaxBucks
The new season of the Bytelandian Premier League (BPL) has started! In the BPL, any two soccer teams play with each other exactly once. In each match, the winner earns 3 points and the loser earns no point. There is no draw (if the match is level after the two halves, two teams will take part in a penalty shootout to d...
#!/usr/bin/python # Richard Lee import os import sys def champion_possible(team_id, r_m, c_list): def team_sort(x, y): rx = r[x] ry = r[y] if rx == ry: return p[y] - p[x] return rx - ry def team_sort_r(x, y): rx = r[x] ry = r[y] if rx == ry: return ...
Problem Statement N knights were sitting at a round table and having a serious talk. The knights are so tired, that they can’t even rotate their neck to talk to talk to the knights sitting on their sides. So, a knight can only talk to the knight sitting diametrically opposite to him on the table. Given the number of kn...
#chiragjn t=int(raw_input()) for i in xrange(t): n,m=map(int,raw_input().split()) print m+(n>>1) if m<=n/2 else m-(n>>1)
Did you know that there are over 40,000 varieties of Rice in the world ? There are so many dishes that can be prepared with Rice too. A famous chef from Mumbai, Tid Gusto prepared a new dish and named it 'Tid Rice'. He posted the recipe in his newly designed blog for community voting, where a user can plus (+) or minus...
t=int(raw_input()) for _ in range(0,t): n=int(raw_input()) d= dict(raw_input().split() for _ in range(n)) k=[] for value in d: k.append(d[value]) sum=0 for item in k: if item=='+': sum+=1 elif item=="-": sum-=1 print sum
There is a beautiful garden of stones in Innopolis. Its most beautiful place is the n piles with stones numbered from 1 to n. EJOI participants have visited this place twice. When they first visited it, the number of stones in piles was x_1, x_2, …, x_n, correspondingly. One of the participants wrote down this sequ...
n=int(input()) p=input().split(' ') c=input().split(' ') t=z=0 for k in range(n): t+=int(p[k]) z+=int(c[k]) if (t<z): print('No') else: print('Yes')
Alice and Bob are playing a game on strings. Initially, they have some string t. In one move the first player selects the character c present in t and erases all it's occurrences in t, thus splitting t into many smaller strings. The game then goes independently with each of the strings — to make the move player select...
#include <bits/stdc++.h> using namespace std; struct pat { int x, y; pat(int x = 0, int y = 0) : x(x), y(y) {} bool operator<(const pat &p) const { return x == p.x ? y < p.y : x < p.x; } }; namespace RKK { const int N = 100011; int n, qaq; char str[N]; int s[N]; int nxt[N][26], pre[N][26]; int f[N][26], g[N]; int...
You are given two arrays a and b of positive integers, with length n and m respectively. Let c be an n × m matrix, where c_{i,j} = a_i ⋅ b_j. You need to find a subrectangle of the matrix c such that the sum of its elements is at most x, and its area (the total number of elements) is the largest possible. Formally...
#include <bits/stdc++.h> using ll = long long; const int maxn = 2018; const ll inf = 10000000000000; int main(int argc, char *argv[]) { std::ios::sync_with_stdio(false); std::cin.tie(0); ll n, m, x, a[maxn], b[maxn], pa[maxn], pb[maxn], ma[maxn], mb[maxn]; std::cin >> n >> m; pa[0] = pb[0] = 0; for (int i =...
Vasya is reading a e-book. The file of the book consists of n pages, numbered from 1 to n. The screen is currently displaying the contents of page x, and Vasya wants to read the page y. There are two buttons on the book which allow Vasya to scroll d pages forwards or backwards (but he cannot scroll outside the book). F...
#include <bits/stdc++.h> using namespace std; inline void boost() { ios_base::sync_with_stdio(); cin.tie(0); cout.tie(0); } const long long maxn = 1e5 + 123; const long long inf = 1e9 + 123; const long long mod = 1e9 + 7; const double pi = acos(-1); int main() { boost(); int t; cin >> t; for (int i = 1; i...
There are n segments [l_i, r_i] for 1 ≤ i ≤ n. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group. To optimize testing pr...
#include <bits/stdc++.h> using namespace std; int main() { int q = 0; cin >> q; vector<pair<pair<int, int>, int>> intervals; for (int i = 0; i < q; i++) { int n; cin >> n; intervals.resize(n); for (int j = 0; j < n; j++) { cin >> intervals[j].first.first >> intervals[j].first.second; ...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
a=input();b=input() A=a.lower();B=b.lower() if A==B: print(0) elif A>B: print(1) elif A<B: print(-1)
When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members eff...
#include <bits/stdc++.h> using namespace std; long long int MOD = (1e9) + 7; inline void fastIO() { ios_base::sync_with_stdio(0); cin.tie(0); } int main() { fastIO(); int n, k, ans = 0; cin >> n >> k; map<pair<string, string>, int> has; vector<string> fin(n); vector<string> input(n); for (int i = 0; i...
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k. Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p. Input The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime. The se...
#include <bits/stdc++.h> using namespace std; vector<long long int> v; map<long long int, long long int> m1; set<long long int> st; long long int fep(long long int x, long long int y, long long int mod) { long long int res = 1; while (y > 0) { if (y & 1) res = (res * x) % mod; y = y >> 1; x = (x * x) % ...
You are given an array a of n integers. You need to find the maximum value of a_{i} | ( a_{j} \& a_{k} ) over all triplets (i,j,k) such that i < j < k. Here \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and | denotes the [bitwise OR operation](https://en.wikipedia.org/wi...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e6 + 5; int n; int a[maxn]; int f[maxn]; int read() { int x; scanf("%d", &x); return x; } int lowbit(int x) { return x & -x; } int insert(int x, int y) { if (f[x | y] > 1) return 0; f[x | y]++; for (int nx = x, ny = 0; nx; nx ^= lowbit(nx)) { ...
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events. A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n × m rectangle map which represents the damaged part of the Forest...
#include <bits/stdc++.h> using namespace std; template <typename T> bool MinPlace(T &a, const T &b) { if (a > b) { a = b; return true; } return false; } template <typename T> bool MaxPlace(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } int dr[8] = {0, -1, -1, -1, 0, 1...
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the t...
#include <bits/stdc++.h> using namespace std; string s; void comp_z(vector<long> &z) { long n = z.size(); z[0] = n; long L = -1, R = -1; for (int i = 1; i < n; i++) { if (R < i) { L = R = i; while (R < n && s[R] == s[R - L]) R++; z[i] = R - L; R--; } else { long k = i - L; ...
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak) [Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive) NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO...
#include <bits/stdc++.h> using namespace std; bool op[3][100002]; int t; bool check(int c) { if (!op[1][c] && (!op[2][c] || !op[2][c - 1] || !op[2][c + 1])) { return false; } else if (!op[2][c] && (!op[1][c] || !op[1][c - 1] || !op[1][c + 1])) { return false; } return true; } int main() { memset(op, t...
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, ...
#include <bits/stdc++.h> using namespace std; long long int mod = 1000000007; vector<long long int> initializeDiffArray(vector<long long int>& A); void update(vector<long long int>& D, long long int l, long long int r, long long int x); void getArray(vector<long long int>& A, vector<long long int>& D); long...
Let's denote the following function f. This function takes an array a of length n and returns an array. Initially the result is an empty array. For each integer i from 1 to n we add element a_i to the end of the resulting array if it is greater than all previous elements (more formally, if a_i > max_{1 ≤ j < i}a_j). So...
#include <bits/stdc++.h> using namespace std; const int N = 5e5 + 7; long long t[4 * N]; long long mod[4 * N]; const long long Inf = 1e18; void update(int v, long long x) { t[v] += x; mod[v] += x; } void push(int v) { if (mod[v]) { update(2 * v + 1, mod[v]); update(2 * v + 2, mod[v]); mod[v] = 0; } ...
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
ans = [] for h in range(int(input())): a, k = map(int, input().strip().split()) temp = a a = str(a) for i in range(k-1): maxi = int(max(a)); mini = int(min(a)) a = str(temp + maxi*mini) if '0' in a: break temp = int(a) ans.append(a) print('\n'.join(a...
You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no m...
#include <bits/stdc++.h> using namespace std; int v[505]; vector<int> rasp; void mov(int poz) { rasp.push_back(poz + 1); swap(v[poz], v[poz + 1]); swap(v[poz], v[poz + 2]); } int main() { int t, i1, n, i, j; scanf("%d", &t); for (i1 = 1; i1 <= t; i1++) { scanf("%d", &n); for (i = 0; i < n; i++) scan...
You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1...
from collections import defaultdict as dd # d=dd(lambda:0) from sys import stdin stdin.readline def mp(): return list(map(int, stdin.readline().strip().split())) def it():return int(stdin.readline().strip()) for _ in range(it()): n=it() l=input() v=[] for i in l: v.append(int(i)) # for i in range(n): # v[i]-...
Lindsey Buckingham told Stevie Nicks ["Go your own way"](https://www.youtube.com/watch?v=6ul-cZyuYq4). Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world. Consider a hexagonal tiling of the plane as on the picture below. <image> Nicks wishes to go from the cell marked...
import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) #import sys #input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(...
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simple...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; ...
Getting so far in this contest is not an easy feat. By solving all the previous problems, you have impressed the gods greatly. Thus, they decided to spare you the story for this problem and grant a formal statement instead. Consider n agents. Each one of them initially has exactly one item, i-th agent has the item num...
#include <bits/stdc++.h> using namespace std; const int maxn = 41, P = 1000000007; int n, p[maxn], base[maxn], f[5100]; int fact[maxn], C[maxn][maxn], pw[maxn][maxn], vis[maxn]; vector<int> len, cnt, sub[5100]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &p[i]), p[i]--; ...
There is a graph of n rows and 10^6 + 2 columns, where rows are numbered from 1 to n and columns from 0 to 10^6 + 1: <image> Let's denote the node in the row i and column j by (i, j). Initially for each i the i-th row has exactly one obstacle — at node (i, a_i). You want to move some obstacles so that you can reach ...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); while((q--)!=0) { int n = sc.nextInt(); int u = sc.nextInt(); int v = sc.nextInt(); String s=sc.nextLine(); String[] a = sc.nextLine().split(" "); int z=Integ...
An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, an...
#include <iostream> #include <vector> #include <string> #include <array> #include <functional> #include <algorithm> #include <stack> #include <map> #include <set> #include <climits> #include <queue> #include <bitset> #include <cassert> #include <math.h> #include <complex> #include <iomanip> #include <unordered_map> usi...
You were playing with permutation p of length n, but you lost it in Blair, Alabama! Luckily, you remember some information about the permutation. More specifically, you remember an array b of length n, where b_i is the number of indices j such that j < i and p_j > p_i. You have the array b, and you want to find the p...
#include <bits/stdc++.h> #ifdef ALGO #include "el_psy_congroo.hpp" #else #define DUMP(...) 1145141919810 #define CHECK(...) (__VA_ARGS__) #endif int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::istream& reader = std::cin; const int BIT = 10; int n; reader >> n; std::vector<st...
In some country live wizards. They love to ride trolleybuses. A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it lea...
#include <bits/stdc++.h> using namespace std; using ll = long long; int n, a, d; int t[100005], v[100005]; double ans[100005]; int main() { cin.tie(0); cin >> n >> a >> d; for (int i = 1; i <= n; i++) cin >> t[i] >> v[i]; ans[0] = 0; for (int i = 1; i <= n; i++) { double tt = 1.0 * v[i] / a; double dd...
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces ...
from math import *; lineup=[int(x) for x in input().split()] a,b,c=sorted(lineup[1:4]) n=lineup[0] value=0 if a==1: print(n) exit() for i in range(0,n+1,a): for j in range(0,n+1,b): z=(n-i-j)/c if ceil(z)==floor(z) and int(z)>=0: x=i//a y=j//b z=int(z) value=max(value,x+y+z) print(int(value))
There is a developed network of flights between Berland and Beerland. All of them belong to the Berland state company BerAvia. Each flight connects some Berland city with some Beerland city. For each flight airplanes fly in both directions. Changes are coming to Berland — the state decided to privatize BerAvia, namely...
#include <bits/stdc++.h> using namespace std; const int N = 605, X = 90005, M = 200005; int n, m, p, S, T, nA, nB, cnt, du[N], le[X], ri[X], ans[X]; int tot, lnk[N], son[M], w[M], v[M], nxt[M]; int q[N], dst[N], pre[N]; bool bo[N], vis[N]; int read() { int x = 0; char ch = getchar(); while (ch < '0' || ch > '9') ...
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
a = set(list(raw_input())) if len(a) % 2 == 1: print 'IGNORE HIM!' else: print 'CHAT WITH HER!'
The board has got a painted tree graph, consisting of n nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles. Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.TreeMap; public class BlackWhiteTree { public...
Farmer John has just given the cows a program to play with! The program contains two integer variables, x and y, and performs the following operations on a sequence a1, a2, ..., an of positive integers: 1. Initially, x = 1 and y = 0. If, after any step, x ≤ 0 or x > n, the program immediately terminates. 2. The p...
#include <bits/stdc++.h> using namespace std; using namespace std; int n, a[300001], was[300001][3]; long long d[300001][3]; long long calc(int v, int bit) { if (v <= 0 || v > n) return 0ll; if (v == 1) return -1; if (was[v][bit] == 2) return d[v][bit] = -1; if (was[v][bit] == 1) return d[v][bit]; was[v][bit]...
Professional sport is more than hard work. It also is the equipment, designed by top engineers. As an example, let's take tennis. Not only should you be in great shape, you also need an excellent racket! In this problem your task is to contribute to the development of tennis and to help to design a revolutionary new co...
#include <bits/stdc++.h> using namespace std; int n, m; long long ans; int main() { scanf("%d%d", &n, &m); for (int i = m + 1; i <= (n + 1) / 2; i++) { int p = n + 1 - i; int q = 2 * i; for (int j = m + 1; j <= n - m; j++) { int tmp = (p * (q - j) - 1) / (i + j); int now = (((tmp) < (n - m))...
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed. This time mr. Boosch plans to sign 2k l...
#include <bits/stdc++.h> using namespace std; int main() { int n, k, temp, idx = 0; long long sum = 0; cin >> n >> k; vector<long long> s; vector<long long> v; for (int i = 0; i < n; i++) { cin >> temp; v.push_back(temp); sum += temp; if ((i + 1) >= k) { s.push_back(sum); sum -= ...
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m. Public transport is not free. There are 4 types of tickets: 1. A ticket for one r...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0), cin.tie(NULL), cout.tie(NULL); ; int arr[4]; for (int i = 0; i < 4; ++i) { cin >> arr[i]; } int n, m; cin >> n >> m; vector<int> b(n), t(m); for (int i = 0; i < n; ++i) { cin >> b[i]; } for (int i = 0;...
One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors. There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai ratin...
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.text.ParseException; import java.util.*; import java.util.List; import static java.lang.Math.max; public class Main implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != nu...
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he d...
#!/usr/bin/python import os import sys import itertools import collections import string def solve(f): s1 = f.read_str() s2 = f.read_str() n = len(s1) c1 = collections.Counter(s1) c2 = collections.Counter(s2) ans1 = None for i in xrange(n-1): if s1[i] != s2[i]: ans1 =...
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and n water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that...
import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(), s = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) s -= a[i] = in.nextInt(); Arra...
In a far away galaxy there are n inhabited planets, numbered with numbers from 1 to n. They are located at large distances from each other, that's why the communication between them was very difficult until on the planet number 1 a hyperdrive was invented. As soon as this significant event took place, n - 1 spaceships ...
#include <bits/stdc++.h> using namespace std; const int N = 5010; int x[N], y[N], z[N]; double sqr(double x) { return x * x; } double dis(int i, int j) { return sqrt(sqr(x[i] - x[j]) + sqr(y[i] - y[j]) + sqr(z[i] - z[j])); } int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d%d%d",...
Malek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each ...
from sys import stdin def nb_good_numbers(n): by_digit = { "0": 2, "1": 7, "2": 2, "3": 3, "4": 3, "5": 4, "6": 2, "7": 5, "8": 1, "9": 2, } result = 1 for digit in n: result *= by_digit[digit] return result ...
A and B are preparing themselves for programming contests. After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes. A likes lowercase letters of the Latin alphabet. He has assigned to each letter a ...
#include <bits/stdc++.h> using namespace std; int val[26]; unordered_map<long long, int> ht[26]; int main() { ios::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL); for (int i = 0; i < 26; ++i) cin >> val[i]; string str; cin >> str; long long cm = 0, ans = 0; for (int i = 0; i < ((int)(str).size()); ...
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows. Let's assume that we are given a c...
#include <bits/stdc++.h> using namespace std; const long long maxn = 3e5 + 10, Maxn = 1e5 + 10, SQ = 360, lg = 22; const long long mod = 1e9 + 7; const long long inf = 1e18 + 10; vector<pair<long long, long long>> adj[maxn]; long long d[maxn], p[maxn], n, m; map<pair<long long, long long>, pair<long long, long long>> m...
In this task you need to process a set of stock exchange orders and use them to create order book. An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell...
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.ut...
Gosha's universe is a table consisting of n rows and m columns. Both the rows and columns are numbered with consecutive integers starting with 1. We will use (r, c) to denote a cell located in the row r and column c. Gosha is often invited somewhere. Every time he gets an invitation, he first calculates the number of ...
#include <bits/stdc++.h> using namespace std; const int N = 22; int n, m, q, last, vi[N][N]; int dx[5] = {0, -1, 1, 0, 0}; int dy[5] = {0, 0, 0, -1, 1}; inline void add(int &a, int b) { a = ((a + b >= 1000000007) ? a + b - 1000000007 : a + b); } inline void del(int &a, int b) { a = ((a - b < 0) ? a - b + 1000000007...
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art. First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the tra...
#include <bits/stdc++.h> using namespace std; const int INF = 2e9; const int N = 2105; int dp[N], lcp[N][N], lcpr[N][N], lmatch[N]; pair<int, int> subs[N]; int par[N]; string s, t; int n, m; void print(int idx) { if (idx != 0) print(par[idx]); cout << subs[idx].first + 1 << " " << subs[idx].second + 1 << "\n"; } in...
For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree. Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to ...
#include <bits/stdc++.h> using namespace std; const int maxn = 200005; int in[maxn], in1[maxn]; int dp[maxn]; int dp1[maxn]; int dp2[maxn]; int s[maxn]; int vis[maxn]; int dp3[maxn]; vector<int> g[maxn]; int a[maxn]; int k; int flag; void dfs(int u, int pa) { int p = g[u].size(); dp1[u] = 1; vis[u] = 1; for (in...
You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edge...
#include <bits/stdc++.h> using namespace std; int INT_MAX_VAL = (int)0x3F3F3F3F; int INT_MIN_VAL = (int)-0x3F3F3F3F; long long LONG_MAX_VAL = (long long)0x3F3F3F3F3F3F3F3F; long long LONG_MIN_VAL = (long long)-0x3F3F3F3F3F3F3F3F; int colors[500006]; vector<pair<int, char> > graph[500006]; int n, m; int dfs(int v, char ...
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya...
import math from typing import Iterable, List def solve(arr:Iterable[str], n: int) -> int: curr = 0 res = 0 for v in arr: if v == '1'*n: curr = 0 else : curr += 1 res = max(res , curr) return res def main(): n,d = map(int, input().split(' ')) arr = [] for i in...
Thought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal. The...
#include <bits/stdc++.h> using namespace std; int n, c; int a[205]; vector<int> e[205]; int d[205][205], f[205][205], p[205], b[205]; void dfs(int k, int fa) { for (int i = 0; i < n; ++i) { f[k][i] = a[d[k][i]] + c; } for (int i = 0; i < e[k].size(); ++i) { int u = e[k][i]; if (fa == u) continue; ...
A simplified arithmetic expression (SAE) is an arithmetic expression defined by the following grammar: * <SAE> ::= <Number> | <SAE>+<SAE> | <SAE>*<SAE> | (<SAE>) * <Number> ::= <Digit> | <Digit><Number> * <Digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 In other words it's a correct arithmetic expression tha...
#include <bits/stdc++.h> using namespace std; int n, q, l, r, st[400500], ct, bel[400500], pw[400500], su[400500], lb[400500], rb[400500], as[400500], v1[400500], sl[400500], sr[400500], tp[400500], vl[400500]; char s[400500]; struct qu1 { int l, r, id; }; vector<qu1> qu[400500]; int calc(int l, int r) { re...
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses. You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, i...
import sys input = sys.stdin.readline n, m = input().split() n = int(n) m = int(m) polW = [] eneW = [] turnsP = 0 turnsE = 0 same = 0 for i in range(n): polW.append(input()) turnsP+=1 for i in range(m): word = input() if word in polW: turnsP-=1 same+=1 else: turnsE...
Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai. Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affectio...
#include <bits/stdc++.h> using namespace std; double esp = 1e-8; const long double PI = acos((long double)-1); const long long int INF = 0x3f3f3f3fll; const int MOD = 1e9 + 7ll; const int maxn = 110100; set<long long int> q; vector<long long int> tq; long long int A[maxn]; map<long long int, int> qu; int main() { lon...
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length <image> are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome. Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba...
#include <bits/stdc++.h> using namespace std; const long long INF = 1e14 + 9; vector<long long> hash_valuen(5000009, 0); vector<long long> hash_valuer(5000009, 0); long long ans[5000009]; long long inv[5000009]; const long long p = 317; const long long m = 104000717; long long gcd(long long a, long long tri) { long l...
Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In o...
def good(lab): for i, line in enumerate(lab): for j, item in enumerate(line): if item == 1: continue flag = False for k, x in enumerate(line): if j==k: continue col = [l[j] for l in lab] f...
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each eleme...
n=input() l=[0] r=[0] for i in range(n): a=map(int,raw_input().split()) l=l+[a[0]] r=r+[a[1]] b=[] c=[1]*(n+1) e=[] for i in range(1,1+n): if c[i]!=0: j=l[i] c[j]=0 d=[i] while j!=0: c[j]=0 d=[j]+d j=l[j] k=r[i] ...
Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset. k experienced teams are participating in the contest. Some of these teams already know some of the problems...
#include <bits/stdc++.h> using namespace std; int main() { int n, k; cin >> n >> k; vector<int> count(16); for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < k; j++) { int x; cin >> x; sum = sum * 2 + x; } count[sum] += 1; } int ans = 0; if (count[0] > 0) ...
You are given a rooted tree consisting of n vertices. Each vertex has a number written on it; number ai is written on vertex i. Let's denote d(i, j) as the distance between vertices i and j in the tree (that is, the number of edges in the shortest path from i to j). Also let's denote the k-blocked subtree of vertex x ...
import java.io.*; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class EduF implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { ...
You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0. It is allowed to leave a as it is. Input The first line contains integer a (1 ≤ a ≤ 1018). The second line contains i...
import copy Num1, Num2 = sorted(list(input())), list(input()) Num1.reverse() Temp1, Temp2, i, j, Result= copy.copy(Num1), copy.copy(Num2), 0, 0, [] if len(Temp1) < len(Temp2): print(''.join(Temp1)) exit() while True: if i + 1 > len(Temp1): Temp1.append(Result[len(Result) - 1]) Temp1.sort()...
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from c...
from __future__ import division, print_function import os import sys import io class FastI(): """ FastIO for PyPy3 by Pajenegod """ stream = io.BytesIO() newlines = 0 def read1(self): b, ptr = os.read(0, (1 << 13) + os.fstat(0).st_size), self.stream.tell() self.stream.seek(0, 2) ...
You are given a string s. You should answer n queries. The i-th query consists of integer k_i and string m_i. The answer for this query is the minimum length of such a string t that t is a substring of s and m_i has at least k_i occurrences as a substring in t. A substring of a string is a continuous segment of charac...
#include <bits/stdc++.h> using namespace std; const int MAXCHAR = 26; struct STATE { int next[MAXCHAR]; int suf_state; int out_state; int id_of_pattern; int isLeaf; STATE() { for (int i = 0; i < MAXCHAR; i++) { next[i] = -1; } suf_state = out_state = id_of_pattern = isLeaf = -1; } }; voi...
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i. Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). For ...
#include <bits/stdc++.h> using namespace std; const int MaxN = 200000 + 5; const int MaxA = 200000 + 5; int N; int A[MaxN], U[MaxN], V[MaxN]; bool not_prime[MaxA]; int prs[MaxA], cntp, mu[MaxA]; int par[MaxA], siz[MaxA]; bool vis[MaxA]; long long f[MaxA], g[MaxA]; vector<int> E[MaxA]; void Linear_sieve(int n) { not_p...
You are given a string S and Q query strings (q1, q2, ... , qQ). For each query string, report whether or not it is a subsequence of S. Input : The first line contains a string S. The next line contains a single integer, Q. The following Q lines each contain 1 query string qi. Output : Output Q lines. On the i^th...
ind=0 z="" f=0 x=raw_input() for _ in xrange(input()): f=0 z=x y=raw_input() for i in xrange(len(y)): if y[i] in z: ind=z.index(y[i]) z=z[ind+1:] else: f=1 break if f==1: print "No" else: p...
Little chandu is very fond of playing games. Recently, He found a few straws each of length 1 inches in the store room. He took all of them and decided to mark a rectangular area on the floor with straws and warn rest of the family members to not to enter that area so that he can play in peace. He wants to maximize tha...
import sys import math t=input() for i in range(0,t): m = input(); if m%2 == 1 : m=m-1; b=m/4; a=m/2-b; n= a*b; print n;
N boys are sitting in a circle. Each of them have some apples in their hand. You find that the total number of the apples can be divided by N. So you want to divide the apples equally among all the boys. But they are so lazy that each one of them only wants to give one apple to one of the neighbors at one step. Calcula...
n = int(raw_input()) a = map(long,raw_input().split(' ')) avg = sum(a)/n p = a[0]-avg b = [p] for x in a[1:]: p = p + x -avg b.append(p) b.sort() mid = b[len(b)/2] total = sum(map(lambda x:abs(x-mid),b)) print total
You are given non-negative integer N. Find N pairwise different points on the Euclidean plane with integer coordinates in the corresponding order and the following properties: 1) the distance between any two consecutive points in the order is equal for the all pairs of consecutive points 2) the angle created by any t...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' test=1 for i in range(test): a=int(raw_input()) if a != 1 and a !=2 and a != 4: print "NO" break; else: print "YES" print "0 0" if a == 1: break; if a == 4: print "...
“Can you answer this million dollar question ?” said the presenter to Little Achraf. “Yes”, he responded. “Ok … here is the question”. We define a sequence A of strings of order L as follows: A[n] = \sum\limits_{i = 0}^{L-1} A[n-L+i]; n ≥ L+1; where addition refers to string concatenation A[n] ∈ [a-z A-Z 0-9]; ...
import sys L,C= map(int,raw_input().split()) f = [1]*(L+1) f[0] = 0 ind = L while f[ind] <= 10**20: ind+=1 x = 0 for i in range(ind-L,ind): x+=f[i] f.append(x) for i in range(0,L): x = 0 for i in range(len(f)-L,len(f)): x += f[i] f.append(x) def fun(a,n): if a <= L:...
Our monk loves food. Hence,he took up position of a manager at Sagar,a restaurant that serves people with delicious food packages. It is a very famous place and people are always queuing up to have one of those packages. Each package has a cost associated with it. The packages are kept as a pile. The job of a manager...
stack=[] for _ in range(input()): n = map(int, raw_input().split()) if len(n) == 1: if stack == []: print "No Food" else: print stack[-1] stack = stack[:-1] elif len(n) == 2: stack.append(n[1])