input
stringlengths
29
13k
output
stringlengths
9
73.4k
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not. You are given a string A consisting of lowerca...
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define REP(i,a) FOR(i,0,a) const int MAX_LEN=2e5,INF=1e6; string A; char dp[MAX_LEN+1]; int dp2[MAX_LEN+1]; map<char,int> mp[MAX_LEN+1]; int main(){ cin>>A; A.insert(A.begin(),'$'); dp[A.size()-1]='a'; dp2[A.size()-1]=1; ...
Takahashi has received an undirected graph with N vertices, numbered 1, 2, ..., N. The edges in this graph are represented by (u_i, v_i). There are no self-loops and multiple edges in this graph. Based on this graph, Takahashi is now constructing a new graph with N^2 vertices, where each vertex is labeled with a pair ...
#include <bits/stdc++.h> #define rep(i,n)for(int i=0;i<(n);i++) using namespace std; typedef long long ll; vector<int>E[200000]; int id[200000]; int d[200000]; void dfs(int v,int k){ id[v]=k; for(int u:E[v]){ if(id[u]==-1){ if(d[v]!=-1)d[u]=!d[v]; dfs(u,k); } else{ if(d[u]==d[v]){ d[u]=-1; } ...
We have a grid with 3 rows and N columns. The cell at the i-th row and j-th column is denoted (i, j). Initially, each cell (i, j) contains the integer i+3j-3. <image> A grid with N=5 columns Snuke can perform the following operation any number of times: * Choose a 3×3 subrectangle of the grid. The placement of inte...
#include<bits/stdc++.h> using namespace std; typedef long long LL; #define N 120000 int n,g[2],a[N][3],b[N],c[N],bit[2][N],f[2]; int qry(int k,int x){ int ret=0; for (;x;x-=x&(-x)) ret+=bit[k][x]; return ret; } void add(int k,int x){ for (;x<=n;x+=x&(-x)) ++bit[k][x]; } int main(){ scanf("%d",&n); for (int ...
Create a program that reads the sales unit price and sales quantity and outputs the total sales amount and the average sales quantity. Input The input is given in the following format: Sales unit price, sales quantity Sales unit price, sales quantity :: :: A comma-separated pair of unit price and quantity is gi...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); Array...
Create a program that calculates and outputs the surface distance by inputting the north latitude and east longitude of two cities on the earth. However, the earth is a sphere with a radius of 6,378.1 km, and the surface distance between two points is the shortest distance along this sphere. Also, in the southern hemis...
#include<iostream> #include<cmath> #define LEN 6378.1 #define PI 3.141592653589793238 using namespace std; double a, b, c, d, BC, CA, C; int main() { while (true) { cin >> a >> b >> c >> d; if (a == -1) { break; } BC = PI / 180 * (90.0 - a); CA = PI / 180 * (90.0 - c); C = PI*(d - b) / 180; cout << (int)(0...
In Aizu prefecture, we decided to create a new town to increase the population. To that end, we decided to cultivate a new rectangular land and divide this land into squares of the same size. The cost of developing this land is proportional to the number of plots, but the prefecture wants to minimize this cost. Create...
#include<bits/stdc++.h> using namespace std; long long gcd(long long a, long long b); int main(){ long long w, h, c; cin >> w >> h >> c; long long ky = gcd(w, h); long long ans1 = w / ky; long long ans2 = h / ky; long long ans = ans1 * ans2; cout << ans * c << '\n'; return 0; } l...
problem Five students, Taro, Jiro, Saburo, Shiro, and Hanako, participated in the JOI High School class. In this class, a final exam was conducted. All five people took the final exam. For students with a final exam score of 40 or higher, the final exam score was used as is. All students with a final exam score of le...
#include <bits/stdc++.h> typedef long long LL; using namespace std; int main(){ int sum = 0; for (int i = 0; i < 5; i ++) { int t; cin >> t; t = max(40, t); sum += t; } cout << sum/5 << endl; }
In the 17th century, Fermat wrote that he proved for any integer $n \geq 3$, there exist no positive integers $x$, $y$, $z$ such that $x^n + y^n = z^n$. However he never disclosed the proof. Later, this claim was named Fermat's Last Theorem or Fermat's Conjecture. If Fermat's Last Theorem holds in case of $n$, then it...
#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<vector> #include<algorithm> using namespace std; #define rep2(x,from,to) for(long long x=(from);(x)<(to);(x)++) #define rep(x,to) rep2(x,0,to) #define INF 1000000000 #define N 1111 long long dp[N+4]; long long n; long long ans; int main() { ...
Let’s try a dice puzzle. The rules of this puzzle are as follows. 1. Dice with six faces as shown in Figure 1 are used in the puzzle. <image> Figure 1: Faces of a die 2. With twenty seven such dice, a 3 × 3 × 3 cube is built as shown in Figure 2. <image> Figure 2: 3 × 3 × 3 cube 3. When building up a cube made o...
#include <bits/stdc++.h> using namespace std; class Dice{ private: void roll(int a,int b,int c,int d){ swap(x[a],x[b]); swap(x[b],x[d]); swap(x[c],x[d]); } public: int x[6]; Dice(){ for(int i = 0 ; i < 6 ; i++){ x[i] = i+1; } } void roll_N(){...
Problem G Rendezvous on a Tetrahedron One day, you found two worms $P$ and $Q$ crawling on the surface of a regular tetrahedron with four vertices $A$, $B$, $C$ and $D$. Both worms started from the vertex $A$, went straight ahead, and stopped crawling after a while. When a worm reached one of the edges of the tetrahe...
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <string> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <complex> #include <functional> #include <ca...
Daruma Otoshi You are playing a variant of a game called "Daruma Otoshi (Dharma Block Striking)". At the start of a game, several wooden blocks of the same size but with varying weights are stacked on top of each other, forming a tower. Another block symbolizing Dharma is placed atop. You have a wooden hammer with it...
import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; public class Main { Scanner sc = new Scanner(System.in); public static void main(String[] args){ new Main(); } public Main(){ new AOJ1611().doIt(); } class AOJ1611{ void doIt(){ while(true) { ...
Your friend's archaeologist was excavating the ruins. One day he found a large number of slate engraved with a series of dubious symbols. He was delighted with this great discovery and immediately began to decipher the symbols engraved on the slate. After weeks of his deciphering efforts, it was apparently found that t...
#include<iostream> #include<vector> #include<algorithm> using namespace std; const int OpeSize = 15; struct data{ char ope,dir; }; vector<data> V[OpeSize]; void input(){ for(int i = 0; i < OpeSize; i++) V[i].clear(); int n; cin >> n; for(int i = 0; i < n; i++){ char d; int num; cin >> d; ...
King Mercer is the king of ACM kingdom. There are one capital and some cities in his kingdom. Amazingly, there are no roads in the kingdom now. Recently, he planned to construct roads between the capital and the cities, but it turned out that the construction cost of his plan is much higher than expected. In order to ...
#include <iostream> #include <queue> #include <functional> #include <cstring> using namespace std; #define MAX_V 10240 // 从顶点from指向顶点to的权值为cost的边 typedef struct edge { int to, distance, cost; edge(){} edge(int to, int distance, int cost) : to(to), distance(distance), cost(cost){} bool operator > (const edge & b) ...
Idol --- It's the eternal longing of girls. However, only a handful stand at the top. You have decided to enter such a survival world as an idol producer. And today, I will take your idol and challenge an important audition. The three elements that determine the audition are visual, dance, and vocal. There are m appea...
#include<iostream> #include<sstream> #include<algorithm> #include<set> #include<map> #include<queue> #include<complex> #include<cstdio> #include<cstdlib> #include<cstring> #include<cassert> #define rep(i,n) for(int i=0;i<(int)n;i++) #define all(c) (c).begin(),(c).end() #define mp make_pair #define pb push_back #define...
Problem Statement We have planted $N$ flower seeds, all of which come into different flowers. We want to make all the flowers come out together. Each plant has a value called vitality, which is initially zero. Watering and spreading fertilizers cause changes on it, and the $i$-th plant will come into flower if its vi...
#include<bits/stdc++.h> using namespace std; int main(){ while(1){ int n; cin >> n; if(!n) break; double pw; cin >> pw; vector<double> vw(n); vector<double> pf(n); vector<double> vf(n); vector<double> th(n); for(int i = 0; i < n; i++){ ci...
Early morning in summer camp The morning of JAG summer training camp is early. To be exact, it is not so fast, but many participants feel that it is fast. At the facility that is the venue for the training camp every year, participants must collect and clean the sheets when they move out. If even one room is delayed,...
#include <bits/stdc++.h> #define ll long long #define INF 1000000005 #define MOD 1000000007 #define EPS 1e-10 #define rep(i,n) for(int i=0;i<n;++i) using namespace std; typedef pair<int,int>P; const int MAX_N = 102; double p[MAX_N]; vector<int> G[MAX_N]; vector<int> rG[MAX_N]; vector<int> vs; //??°?????????????????...
Number of tanka Wishing to die in the spring under the flowers This is one of the famous tanka poems that Saigyo Hoshi wrote. Tanka is a type of waka poem that has been popular in Japan for a long time, and most of it consists of five phrases and thirty-one sounds of 5, 7, 5, 7, and 7. By the way, the number 57577 c...
#include <bits/stdc++.h> #define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME #define pr(...) cerr<< GET_MACRO(__VA_ARGS__,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__) <<endl #define pr1(a) (#a)<<"="<<(a)<<" " #define pr2(a,b) pr1(a)<<pr1(b) #define pr3(a,b,c) pr1(a)<<pr2(b,c) #define pr4(a,b,c,d) pr1(a)<<pr3(b,c,...
Problem Given $ N $ a pair of non-negative integers $ (a_i, b_i) $ and non-negative integers $ A $, $ B $. I want to do as many of the following operations as possible. * $ | a_i --b_i | \ leq A $ or $ B \ leq | a_i --b_i | \ leq Take out and delete the element $ i $ that satisfies 2A $ * $ | (a_i + a_j)-(b_i + b_j)...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; const ld eps = 1e-9; ////フォード - ファルカーソン法 O(Flow|E|) typedef int Weight; const Weight INF = 1e9; const Weight ZERO = 0; struct Edge { int src, dst; Weight weight; int...
Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once. You are given the sequence A and q questions where each question contains Mi. Notes You can solve this problem by a Burte Force appro...
import java.util.Scanner; class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] c = new int[n]; for (int i = 0; i < n; i++) { c[i] = in.nextInt(); } int q = in.nextInt(); for (int i = 0; i < q; i++) { if(solve(c,0,in.nextInt()))...
Write a program which finds a pattern $p$ in a ring shaped text $s$. <image> Constraints * $1 \leq $ length of $p \leq $ length of $s \leq 100$ * $s$ and $p$ consists of lower-case letters Input In the first line, the text $s$ is given. In the second line, the pattern $p$ is given. Output If $p$ is in $s$, prin...
s = input() p = input() print("Yes" if p in (s + s) else "No")
A cricket team consists of 11 players and some are good at batting, others are good at bowling and some of them are good at both batting and bowling. The batting coach wants to select exactly K players having maximum possible sum of scores. Given the batting score of each of the 11 players, find the number of ways in w...
p = int(raw_input()) fact = []; fact.append(1); for i in range(1,12): t = fact[i-1]*i; fact.append(t); for q in range(p): arr = map(int,raw_input().split()); k = int(raw_input()); arr.sort(); arr.reverse(); n = 0; i = k-1; while i >= 0: if(arr[i] == arr[k-1]): n+=1; i-=1; r = 0; i = k; while i < len...
So, as you all know free WiFis are being installed in our institute. These are a special type of WiFi and they start to interfere when there is a signal coming from two different WiFis at a single location. The WiFi installation task is given to you. There are N suitable locations for the installation of WiFi. ...
def f(d, N, C, X): cows_placed = 1 last_pos = X[0] for i in xrange(1, N): if X[i] - last_pos >= d: cows_placed += 1 last_pos = X[i] if cows_placed == C: return 1 return 0 N, C = map(int, raw_input().split()) X = [] for i in xrange(N): X.append(input()) X.sort() start = 0 end = X[N-1] while st...
Chef is the head of commercial logging industry that recently bought a farm containing N trees. You are given initial height of the i-th tree by Hi and the rate of growth of height as Ri meters per month. For simplicity, you can assume that all the trees are perfect cylinders of equal radius. This allows us to consider...
def possible(x,l,w): sm=0 for i in range(n): if((ini[i]+rate[i]*x)>=l): sm=sm+ini[i]+rate[i]*x if sm>=w: return 1 else: return 0 n,w,l=map(int,raw_input().split()) ini=[] rate=[] for i in range(n): cur=map(int,raw_input().split()) ini.append(cur...
Stuart is obsessed to numbers. He like all type of numbers in fact he is having a great collection of numbers in his room. His collection includes N different large numbers. But today he is searching for a number which is having maximum frequency of digit X. Numbers are large so he can’t do the task on his own. Help hi...
for _ in range(input()): n=input() a=raw_input().split() x=raw_input() b=[0]*n #n=a[0].count(x) #print n for i in range(n): c=a[i].count(x) b[i]=c m=max(b) #print b for i in range(n): if b[i]==m: print a[i] break
Problem Statement You have a number N and you want to calculate how many divisors of N are special. A number is said to be special if it is possible to remove some digits from it to get a number having 3, 5 or 6 only.For exemple number 38597 is special since it is posible to remove digits 8, 9, 7 to get 35. You can...
from math import sqrt t=input() while t!=0: n=input() c=0 for i in range(2,int(sqrt(n))+1): if n%i==0: if str(i).find('5')!=-1 or str(i).find('3')!=-1 or str(i).find('6')!=-1: c+=1 # print i ...
Andy and Bob are the only two delivery men of Pizza-chef store. Today, the store received N orders. It's known that the amount of tips may be different when handled by different delivery man. More specifically, if Andy takes the i^th order, he would be tipped Ai dollars and if Bob takes this order, the tip would be Bi ...
n,x,y = map(int,raw_input().split()) n1 = [int(i) for i in raw_input().split()] n2 = [int(i) for i in raw_input().split()] num = [n1[i]-n2[i] for i in xrange(n) ] num.sort(reverse=True) mx = max(0,n-y) Mx = min(n,x) xy = sum(n2) for i in xrange(mx): xy += num[i] ans = xy for i in xrange(mx,Mx): xy += num[i] ...
Natasha was already going to fly back to Earth when she remembered that she needs to go to the Martian store to buy Martian souvenirs for her friends. It is known, that the Martian year lasts x_{max} months, month lasts y_{max} days, day lasts z_{max} seconds. Natasha also knows that this store works according to the ...
#include <bits/stdc++.h> using namespace std; inline char gc() { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } inline long long read() { long long x = 0; char ch = getchar(); bool positive...
Little C loves number «3» very much. He loves all things about it. Now he is interested in the following problem: There are two arrays of 2^n intergers a_0,a_1,...,a_{2^n-1} and b_0,b_1,...,b_{2^n-1}. The task is for each i (0 ≤ i ≤ 2^n-1), to calculate c_i=∑ a_j ⋅ b_k (j|k=i and j\&k=0, where "|" denotes [bitwise o...
#include <bits/stdc++.h> using namespace std; template <typename T> void maxtt(T& t1, T t2) { t1 = max(t1, t2); } template <typename T> void mintt(T& t1, T t2) { t1 = min(t1, t2); } bool debug = 0; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; string direc = "RDLU"; long long ln, lk, lm; void etp(b...
We get more and more news about DDoS-attacks of popular websites. Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment. Arseny knows statistics on the number of requests p...
#include <bits/stdc++.h> using namespace std; long long int index_sum[5001]; long long int n, varr[5001]; long long int summ(int i) { if (i < 0) return 0; return index_sum[i]; } int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> varr[i]; index_sum[i] = varr[i] + summ(i - 1); } long long int...
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(NULL); cin.tie(NULL); long long n, k; cin >> n >> k; long long ans = ceil(n * 2.0 / k) + ceil(n * 5.0 / k) + ceil(n * 8.0 / k); cout << ans; }
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya came across an interval of numbers [a, a + l - 1]. Let F(x) be the number of lucky dig...
#include <bits/stdc++.h> using namespace std; template <class A, class B> A convert(B x) { stringstream ss; ss << x; A ret; ss >> ret; return ret; } const int oo = ~0u >> 3; const double eps = 1e-10, pi = acos(-1); const int ml = 20, mo = 1000000007; const int fx[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, ...
A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x. Find out if what Baron told can be true. Input The only line co...
#include <bits/stdc++.h> using namespace std; int poss[1000][10], diff[1000][10]; pair<pair<int, int>, int> parent[1000][20000]; queue<pair<int, int> > Q; int main() { int a; cin >> a; int i, j; for (i = 0; i < a; i++) { for (j = 0; j < 10; j++) { int l = (a * j + i) % 10, c = (a * j + i) / 10; ...
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string. You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin...
#include <bits/stdc++.h> using namespace std; const long long INF = 0xacacaca; inline long long read() { long long x = 0, f = 0; char ch = 0; while (!isdigit(ch)) f |= (ch == '-'), ch = getchar(); while (isdigit(ch)) (x *= 10) += (ch ^ 48), ch = getchar(); return f ? -x : x; } long long a, b, c, ans; signed m...
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n. In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The i...
n, m = map(int, input().split()) a = list(map(int, input().split())) l, r = 0, m-1 while r > l: mid = (l + r) >> 1 p = 0 f = False for i in a: if i <= p <= i+mid or i <= p+m <= i+mid: continue if i < p: f = True break p = max(p, i) if f: ...
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree. Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black ...
#include <bits/stdc++.h> using namespace std; const int N = 200000 + 10; vector<int> g[N]; int n, sz[N]; long long up[N], down[N]; int rt1 = 1, rt2 = 0; void pre(int u, int p) { sz[u] = 1; for (auto v : g[u]) { if (v == p) continue; pre(v, u); sz[u] += sz[v]; down[u] += down[v] + sz[v]; } } void d...
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine th...
#include <bits/stdc++.h> using namespace std; const long long int mod = 1e9 + 7; const long long int N = 200; vector<long long int> gr[N]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long int i, j, tc; tc = 1; while (tc--) { long long int n; cin >> n; long long i...
Suppose you are stuck on a desert island. The only way to save yourself is to craft a wooden raft and go to the sea. Fortunately, you have a hand-made saw and a forest nearby. Moreover, you've already cut several trees and prepared it to the point that now you have n logs and the i-th log has length a_i. The wooden ra...
#include <bits/stdc++.h> #pragma GCC optimize("-O3") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") using namespace std; const int MAXN = 1123456; const int N = 5e5; const int inf = 1e9; template <typename T> void vout(T s) { cout << s << endl; exit(0); } int pref[MAXN], cnt[MAXN]; struct Set { ...
The only difference between easy and hard versions is the maximum value of n. You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n. The positive integer is called good if it can be represented as a sum of distinct powers of 3 (...
def ternary (n): if n == 0: return '0' nums = [] while n: n, r = divmod(n, 3) nums.append(str(r)) return ''.join(reversed(nums)) for xyz in range(0,int(input())): n=int(input()) s=ternary(n) f=0 for i in range(0,len(s)): if s[i]=='2': f=1 ...
BerPhone X is almost ready for release with n applications being preinstalled on the phone. A category of an application characterizes a genre or a theme of this application (like "game", "business", or "education"). The categories are given as integers between 1 and n, inclusive; the i-th application has category c_i....
#include <bits/stdc++.h> using namespace std; long long a[2000005]; long long p[2000005]; long long n, t; int main() { cin >> t; while (t--) { scanf("%lld", &n); for (int i = 0; i < n; i++) scanf("%lld", &a[i]); sort(a, a + n); int cnt = 0; p[cnt] = 1; for (int i = 1; i < n; i++) { if ...
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her youn...
#include <bits/stdc++.h> using namespace std; bool possible(map<int, int> &M) { map<int, int>::iterator it = M.begin(), jt = M.begin(); jt++; if (M.size() == 2) { return (jt->first == 1 + it->first) and (it->second == jt->second); } if (jt->second < 2) return false; it->second--; if (it->second == 0) ...
Alice has got addicted to a game called Sirtet recently. In Sirtet, player is given an n × m grid. Initially a_{i,j} cubes are stacked up in the cell (i,j). Two cells are called adjacent if they share a side. Player can perform the following operations: * stack up one cube in two adjacent cells; * stack up two ...
#include <bits/stdc++.h> using namespace std; using ul = unsigned long long; using ll = long long; using ld = long double; mt19937 rng( (unsigned int)chrono::steady_clock::now().time_since_epoch().count()); ll powmod(ll a, ll b) { a %= 998244353LL; ll res = 1; while (b) { if (b % 2 == 0) { a *= a; ...
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut...
t = int(input()) for i in range(t): n, m = map(int, input().split()) if n >= 3: print(2 * m) if n == 2: print(m) if n == 1: print(0)
Ray lost his array and needs to find it by asking Omkar. Omkar is willing to disclose that the array has the following qualities: 1. The array has n (1 ≤ n ≤ 2 ⋅ 10^5) elements. 2. Every element in the array a_i is an integer in the range 1 ≤ a_i ≤ 10^9. 3. The array is sorted in nondecreasing order. Ray i...
#include <bits/stdc++.h> using namespace std; long long mod = pow(10, 9) + 7; vector<long long> ans(2000000); pair<long long, long long> query(long long l, long long r) { cout << "? " << l << " " << r << endl; long long x; cin >> x; if (x == -1) { exit(0); } long long f; cin >> f; return {x, f}; } v...
Boboniu has a directed graph with n vertices and m edges. The out-degree of each vertex is at most k. Each edge has an integer weight between 1 and m. No two edges have equal weights. Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a v...
#include <bits/stdc++.h> using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); template <class T> void IN(T& x) { cin >> x; } template <class H, class... T> void IN(H& h, T&... t) { IN(h); IN(t...); } template <class T1, class T2> void OUT(const pair<T1, T2>& x); template <c...
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
a = input() b = input() n = list(a) + list(b) n = sorted(n) p = sorted(list(input())) if n == p: print("YES") else: print("NO")
Andre has very specific tastes. Recently he started falling in love with arrays. Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements — 6 — is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't div...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; for (int i = 0; i < n; i++) { std::cout << 1 << " "; } std: cout << "\n"; } }
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i — coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is go...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { Problem problem = new Problem(); problem.solve(); } } class Problem { Parser parser = ...
You have c_1 letters 'a', c_2 letters 'b', ..., c_{26} letters 'z'. You want to build a beautiful string of length n from them (obviously, you cannot use the i-th letter more than c_i times). Each c_i is greater than n/3. A string is called beautiful if there are no palindromic contiguous substrings of odd length grea...
#include <bits/stdc++.h> using namespace std; const int N = 405, mod = 998244353; int n, mx[26], ans = 26*26, f[N][N][2][2], g[2][N][N][3][3], cnt[3], cur; int main() { scanf("%d", &n); for (int i = 0; i < 26; i++) scanf("%d", &mx[i]); for (int i = 3; i <= n; i++) ans = 25ll*ans%mod; cnt[0] = 25, cnt[1] = 1;...
Let's define the cost of a string s as the number of index pairs i and j (1 ≤ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}. You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If...
#include<bits/stdc++.h> using namespace std; #define to(x) ((x)-'a'+1) typedef pair<int,int> pii; priority_queue<pii,vector<pii>,greater<pii> > q[27]; int main(){ int n,k; scanf("%d%d",&n,&k); for(int i=1;i<=k;++i){ for(int j=1;j<=k;++j){ q[i].push(pii(0,j)); } } int pre=k; for(int i=1;i<=n;++i){ pii t...
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this ...
#include<cmath> #include<iostream> #include<bits/stdc++.h> #include<string> using namespace std; int main() {int n;cin>>n;vector<char> v(n);int t;cin>>t; vector<int> g(n);long long s=0; for(int i=0;i<n;i++) {cin>>v[i]; s+=v[i]-96;g[i]=s;} while(t--){ int a,b;cin>>a>>b; if(a==1) cout<<g[b-1]<<" \n";...
Let's define a non-oriented connected graph of n vertices and n - 1 edges as a beard, if all of its vertices except, perhaps, one, have the degree of 2 or 1 (that is, there exists no more than one vertex, whose degree is more than two). Let us remind you that the degree of a vertex is the number of edges that connect t...
#include <bits/stdc++.h> using namespace std; int n, m, tot; int head[400010], dep[400010], dfn[400010]; struct edge { int fr, to, nxt; } e[400010 << 1]; int read() { int s = 0, w = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch...
The Fat Rat and his friend Сerealguy have had a bet whether at least a few oats are going to descend to them by some clever construction. The figure below shows the clever construction. <image> A more formal description of the clever construction is as follows. The clever construction consists of n rows with scales. ...
#include <bits/stdc++.h> const double pi = acos(-1); const int MOD = 1e9 + 7; const int INF = 1e9 + 7; const int MAXN = 5e1 + 5; const double eps = 1e-9; using namespace std; int a[MAXN], w[MAXN][MAXN], dp[MAXN][MAXN][MAXN][MAXN]; int dfs(int i, int j, int l, int r) { if (j > r || i + j - 1 < l || l > r) return dp[i]...
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its su...
#include <bits/stdc++.h> using namespace std; int n; int main() { cin >> n; if (n >= 34000) cout << 3; else cout << 2; }
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn. Nickolas adores permutations. He likes some permutations more than the o...
#include <bits/stdc++.h> using namespace std; int p[111], n; int main() { cin >> n; if (n == 1 || n % 2 == 1) { cout << -1; return 0; } for (int i = 1; i <= n; i++) p[i] = i; for (int i = 2; i <= n; i++) swap(p[i - 1], p[i]), i++; for (int i = 1; i <= n; i++) cout << p[i] << " "; cin.get(), cin.ge...
The Little Elephant loves trees very much, he especially loves root trees. He's got a tree consisting of n nodes (the nodes are numbered from 1 to n), with root at node number 1. Each node of the tree contains some list of numbers which initially is empty. The Little Elephant wants to apply m operations. On the i-th...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100000 + 86; vector<int> e[MAXN]; vector<pair<int, int> > s[MAXN]; int l[MAXN], r[MAXN]; int t, c[MAXN]; int n, q; struct seg_tree { int nz[MAXN << 2], x[MAXN << 2]; void init() { memset(nz, 0, sizeof(nz)); memset(x, 0, sizeof(x)); } void up...
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree. The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtre...
n = input() e = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, raw_input().split()) e[a - 1].append(b - 1) e[b - 1].append(a - 1) d = [0] * n d[0] = 1 q = [0] for u in q: for v in e[u]: if not d[v]: d[v] = d[u] + 1 q.append(v) print sum(1. / x for x in d)
You are given a rectangle grid. That grid's size is n × m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers (x, y) (0 ≤ x ≤ n, 0 ≤ y ≤ m). Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (...
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public...
I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself. I would like to create a new graph in such a way that: * The new graph consists of the same number o...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class problemE { static void solve() throws IOException { int n = n...
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: * choose indexes i and j (i ≠ j) that haven't been chosen yet; * round elemen...
#include <bits/stdc++.h> using namespace std; const int M = 4000 + 10; int a[M]; int b[M]; int main() { int n; cin >> n; int nn = 2 * n; int p1 = 0; int p2 = 0; int cnt0 = 0; for (int i = 0; i < nn; i++) { string s; cin >> s; int sz = s.length(); int idx = 0; while (idx < sz && s[idx] ...
You are given a matrix consisting of digits zero and one, its size is n × m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations? Let's assume that the rows of matrix a are numbered from 1 to n ...
#include <bits/stdc++.h> using namespace std; void time_start(clock_t *tt) { *tt = clock(); } void print_time(clock_t tt) { tt = clock() - tt; printf("executed in %.f ms\n", (float)tt / CLOCKS_PER_SEC * 1000); } template <typename T> inline T getnum() { T num = 0; char c; do { c = getchar(); } while (c ...
User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are n pages numbered by integers from 1 to n. Assume that somebody is on the p-th page now. The navigation will look like this: << p - k p - k + 1 ... p - 1 (p) p + 1 ... p + k - 1 p + k >> When someone clicks...
n, p, k = map(int, input().split()) x = 0 close_symbol = True pages = "" if((p-k) > 1): pages += "<< " if(k<=p): for x in range (k): if(p-k+x == 0): continue #means that p == k and need to ommit first navigation number pages += str(p-k+x) + " " else: for x in range(1,p): ...
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out...
def main(): s = input() print(("NO", "YES")[s == s[::-1] and all(c in "AHIMOTUVWXY" for c in s)]) if __name__ == '__main__': main()
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1 = 1; F2 = 1; Fn = Fn - 1 + Fn - 2 (n > 2). DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1, a2, ..., an. Moreover, there are m queries, each query has one of the two t...
#include <bits/stdc++.h> using namespace std; const long long INF = 1e18 + 5; const int mod = 1e9 + 9; const int N = 3 * 1e5 + 5; namespace FIB { struct Matrix { int a[3][3]; Matrix() { memset(a, 0, sizeof(a)); } Matrix operator*(const Matrix& M2) { Matrix result; for (int i = 0; i < 3; i++) for (in...
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is h...
import string import sys n = string.atoi(raw_input()) count = 1 for i in range(1, n): count = count + i if count != n: count = count % n sys.stdout.write(str(count) + ' ')
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ...
n,l=map(int,input().split()) a=list(map(int,input().split())) a.sort() max=0 for i in range(len(a)-1): if a[i+1]-a[i]>max: max=a[i+1]-a[i] if a[0]>=max/2 and a[0]>=l-a[len(a)-1]: print("%.10f"%(a[0])) elif l-a[len(a)-1]>=max/2 and l-a[len(a)-1]>=a[0]: print("%.10f"%(l-a[len(a)-1])) elif max/2>=l-a[l...
Drazil is playing a math game with Varda. Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>. First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th...
def add(x, i): if i == 1: pass if i == 2: x.append(2) if i == 3: x.append(3) if i == 4: x.append(2) x.append(2) x.append(3) if i == 5: x.append(5) if i == 6: x.append(5) x.append(3) if i == 7: x.append(7) if...
Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m...
#include <bits/stdc++.h> using namespace std; long long int mod; long long int a[550]; long long int dp[2][501][501]; int main() { long long int n, m, i, j, ans, b, z, k; memset(dp, 0, sizeof(dp)); scanf("%lld", &n); scanf("%lld", &m); scanf("%lld", &b); scanf("%lld", &mod); dp[0][0][0] = 1; for (i = 1;...
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name,...
import java.io.*; import java.util.*; public class C { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstrea...
Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int l = input.nextInt(); int p = input.nextInt(); int q = input.nextInt(); double collisionT = ((double)l)/(p+q); double harryDistance = collisionT*p; double collisionT2 = ((dou...
A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5,...
#include <bits/stdc++.h> using namespace std; const int inf = (int)1.01e9; const double eps = 1e-9; const int maxn = (int)1e6 + 10; int a[maxn]; int b[maxn]; int mem[maxn]; int used[maxn]; int total = 0; void make(vector<int> v) { total += ((int)(v).size()); int step = (((int)(v).size()) + 1) / 2; for (int i = 0;...
A thief made his way to a shop. As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai. The thief is greedy, so he will take exactly k products (it's possible fo...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const double eps = 1E-8; const int FFTSZ = 1 << 20; const double pi = acos(-1.); struct cp { double real, img; cp(double _r = 0.0, double _i = 0.0) : real(_r), img(_i) {} cp operator+(const cp &c) const { return cp(real + c.real, img + c.im...
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested ...
import java.io.*; import java.util.*; public class Main { private BufferedReader in; private StringTokenizer line; private PrintWriter out; private boolean isDebug; public Main(boolean isDebug) { this.isDebug = isDebug; } private static final int mm = 1000000007; private lon...
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' ...
/* * PDPM IIITDM Jabalpur * Asutosh Rana */ import java.util.*; import java.io.*; import java.math.*; public class Main { static long MOD = 1000000007; public static void main (String[] args) throws java.lang.Exception { InputReader in=new InputReader(System.in); BufferedReader br = new BufferedReader...
One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more par...
#include <bits/stdc++.h> using namespace std; class C_ {}; template <typename T> C_& operator<<(C_& __m, const T& __s) { if (!1) cerr << "\E[91m" << __s << "\E[0m"; return __m; } C_ merr; struct __s { __s() { if (1) { ios_base::Init i; cin.sync_with_stdio(0); cin.tie(0); } } ~__s() {...
Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters — its significance ci and width wi. Stepan decided to expose some of his cups on a shelf with width d in such a way, that: * there is at least one ...
import java.io.*; import java.util.*; import static java.lang.Math.max; public class Main { BufferedReader br; StringTokenizer in; PrintWriter pw; Random r; int INF = (int) (2 * 1e9) + 1; long LNF = (long) 1e18; long mod = (long) (1e9 + 7); int pp = 27; // you shall not hack!!!!!!...
A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers ...
n = int(input()) p = map(int,input().split()) a = map(int,input().split()) b = map(int,input().split()) m = int(input()) pos = map(int,input().split()) fut = zip(p,a,b) fut=list(fut) def sravni(elem): return elem[0] fut.sort(key=sravni) vz = [] for i in range(n): vz.append(False) lastc = [0,0,0] result = "" ...
Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation whi...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author pr...
You are given a tree with n vertices and you are allowed to perform no more than 2n transformations on it. Transformation is defined by three vertices x, y, y' and consists of deleting edge (x, y) and adding edge (x, y'). Transformation x, y, y' could be performed if all the following conditions are satisfied: 1. Th...
#include <bits/stdc++.h> using namespace std; namespace debug { void __(short x) { cout << x; } void __(int x) { cout << x; } void __(long long x) { cout << x; } void __(unsigned long long x) { cout << x; } void __(double x) { cout << x; } void __(long double x) { cout << x; } void __(char x) { cout << x; } void __(con...
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai ...
#include <bits/stdc++.h> struct St { int h, h1, h2, nom, type; }; bool operator<(St a, St b) { return a.h1 - a.h2 > b.h1 - b.h2; } St st[200000]; int k[100000]; int i, n, n2; long long s, npart, a, b, c, d, npitca, fa, fb, fc, fd; int cnt[100001]; long long sum(long long npi_1) { long long npi_2 = npitca - npi_1; ...
You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22)...
#include <bits/stdc++.h> using namespace std; int a[22 + 1], sortat[22 + 1]; int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { cin >> a[i]; sortat[i] = a[i]; } sort(sortat, sortat + n); for (int i = 0; i < n; ++i) { int k = 0; while (sortat[k] < a[i]) ++k; k = (k + 1) % n; ...
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) ...
#include <bits/stdc++.h> std::string E[300], T[300], F[300]; std::vector<int> EA, TA, FA; bool cmp(const std::string &a, const std::string &b) { if (a.size() > b.size()) return true; if (a.size() < b.size()) return false; if (a > b) return true; return false; } int main() { std::ios::sync_with_stdio(0); for...
Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression. An Ahmes arithmetic expression can be defined as: * "d" is an Ahmes arithmetic ...
#include <bits/stdc++.h> const int INF = std::numeric_limits<int>::max() / 2; const long long INFLL = std::numeric_limits<long long>::max() / 2; const int MAX_N = 10005; int n, p, m, cnt[MAX_N + 10]; std::unordered_map<int, int> min[MAX_N], max[MAX_N]; std::vector<int> adj[MAX_N]; std::string str; void build_tree() { ...
You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The firs...
#include <bits/stdc++.h> using namespace std; struct line { long long a, b, c; }; struct line calc(long long x1, long long y1, long long x2, long long y2) { struct line nw; nw.a = y2 - y1; nw.b = x1 - x2; nw.c = (nw.a) * x1 + (nw.b) * y1; return nw; } bool chk(struct line ln, pair<int, int> point) { if ((...
As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the ...
import sys A, B, C, D = map(int, sys.stdin.readline().split()) cols = 49 rows = 50 res = [['.' for i in range(cols)] for j in range (rows)] A -= 1 B -= 1 for r in range (rows // 2): for c in range (cols): if r % 2 == 0 or c % 2 == 0: res[r][c] = 'A' elif B > 0: res[r][c] = 'B' B -= 1 eli...
Amit Chahal has a pious love for all kind of fruit juices. Almost every day ,he buys One litre pack of juice. For past one month , Amit Chahal is having a very bad time. One day while he was on a date, he Reverse Peristalsis . Amit Chahal guessed it is probably due to juices he has been drinking for a while. Amit Chah...
def isprime(number): if number==2: return 1 if number%2==0: return 0 N=number**0.5 i=3 while i<=N: if number%i==0: return 0 i=i+2 return 1 def main(): for t in range(input()): number=long(raw_input()) summ=0 while number>0: summ=summ+number%10 number=number/10 if isprime(summ)==1: p...
You are looking for a place to park your car on a wall street. You can park at any position that meets the following requirements: 1. It is not directly in front of a private driveway. 2. It is not directly in front of a bus stop. 3. It is not 5 meters before a bus stop. 4. It is not 10 meters before a bus stop. 5....
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t=int(raw_input()) while t>0: s=raw_input() r=0 for i in range(len(s)): if s[i]=='-': p=0 try: if s[i+1]=='B' or s[i+1]=='S': p=1 #print("a "+str(i)) exc...
You have some boxes. All of them are assigned a unique positive integer. This number is written on them with a marker. Your task is simple that is to evaluate a number of queries. The description of a single query is given below: The query consists of 2 positive integers L and R. You have to report total number of bo...
import bisect; N=input(); A=map(int,raw_input().split()); A.sort(); for _ in xrange(int(raw_input())): L,R=map(int,raw_input().split()); print bisect.bisect_right(A,R) - bisect.bisect_left(A,L)
Life and death, win or lose - both have two sides to each other. And that's what Arjit and Chandu Don are fighting about. They are tired of gang-wars between each other, and thus decide to settle like men in a field, of Mathematics. But even while going to play the game of Mathematics, they have not given up on their ...
from sys import stdin from fractions import gcd # for result memoization registry = {} def get_result(a,b): if not registry.has_key((a,b)): if a== 1: registry[(a,b)] = 0 elif b == 1: registry[(a,b)] = 1 else: greatest_div =gcd(a,b) if greatest_div == 1: registry[(a,b)] = 1 ^ get_result(b-1,a) ...
Now our heroes - Maga and Alex are working for Oil Company as developers. Recently they have faced a great problem. They couldn’t find the correct solution. Could you help them? We are given r – radius of lower base and s – slant height. The figure can be cylinder or truncated cone. You have to find as largest volum...
import math r,s=map(int,raw_input().split()) max_V=0 R=r h=s while h>=0: t=s**2-(R-r)**2 if t<0: break h=t**.5 V=(math.pi*h)*(r**2+R**2+R*r)/3.0 if V>=max_V: max_V=V R=R+0.001 print"%0.2f" % max_V
Monk A loves to complete all his tasks just before the deadlines for introducing unwanted thrill in his life. But, there is another Monk D who hates this habit of Monk A and thinks it's risky. To test Monk A, Monk D provided him tasks for N days in the form of an array Array, where the elements of the array represen...
N=int(raw_input()) for i in xrange(0,N): n=raw_input() x={} line=raw_input().split() maxm=0 for j in line: lent=bin(int(j)).count("1") if(x.get(lent)==None): x[lent]=[j] if(lent>maxm): maxm=lent else: temp=x[lent] ...
Shreyan is appearing for CAT examination and is stuck at a problem to find minimum value needed to be added or subtracted to make a number perfect square.You as his friend and a good programmer agrees to help him find the answer. INPUT: First line will contain no of test cases T (1 < T < 10000) Next T lines will ha...
import math for j in range(input()): n = input() x = math.sqrt(n) a = int(x) ** 2 b = (int(x) + 1) ** 2 if a == n: print 'YES' elif b-n < n-a: print '+' + str(b-n) else: print '-' + str(n-a)
Roy has a matrix of size NxN. Rows and Columns are numbered from 0 to N-1. jth column of ith row contains absolute difference between i and j. In other words, Matrix[i][j] = abs(i-j) where 0 ≤ i, j < N. Your task is to find sum of this matrix i.e. sum = 0 for i=0 to N-1 for j=0 to N-1 sum += Matrix[i][...
t=input() for i in range(t): a=input() print (a*(a-1)*(a+1))/3
Vivek likes strings a lot but moreover he likes Awesome strings. Vivek calls a string str Awesome if zero or more letters of the string str can be rearranged to form the string "HackerEarth" (case insensitive). For eg : strings HackerEarth , Earthhacker , haeackerrth are all Awesome strings whereas strings HE, Mycareer...
p=[0]*500001 c=[0]*26 t=[0]*26 c[ord('h')-97]=c[ord('a')-97]=c[ord('e')-97]=c[ord('r')-97]=2 c[ord('c')-97]=c[ord('k')-97]=c[ord('t')-97]=1; s=raw_input().lower() k=len(s) if k>10: for i in range(11): t[ord(s[i])-97]+=1 if t==c: p[10]=1 for i in range(11,k): p[i]=p[i-1] if s[i]==s[i-11]: if p[i-1]==p[...
As we have seen our little Vaishanavi playing with the plywood, her brother Vaishnav was playing with numbers. Read about Factorial As we all know this kid always thinks in a different way than others think. He have some numbers with him. He wants to find out that if he finds the factorial of the numbers that he ha...
def calculate_factorial(number): isPrime = [True] * (number + 1) result = 1 for i in xrange(2, number + 1): if isPrime[i]: j = i + i while j <= number: isPrime[j] = False j += i sum = 0 t = i while t <= number: sum += number // t t *= i result *= i**sum return result i = i...
M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if...
a,b,c,k=map(int,open(0).read().split()) for i in' '*k: if a>=b:b*=2 elif b>=c:c*=2 print('NYoe s'[a<b<c::2])
We have N balls. The i-th ball has an integer A_i written on it. For each k=1, 2, ..., N, solve the following problem and print the answer. * Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal. Constraint...
#include<bits/stdc++.h> using namespace std; #define i64 long long int #define ran 202202 int n; int a[ran]; int s[ran]; int main() { scanf("%d", &n); for(int i=0;i<n;i++) { scanf("%d", &a[i]); s[a[i]]++; } i64 ans = 0; for(int i=0;i<ran;i++) ans += 1LL*s[i]*(s[i]-1)/2; for(int i=0;i<n;i++) { printf(...
How many ways are there to choose two distinct positive integers totaling N, disregarding the order? Constraints * 1 \leq N \leq 10^6 * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 4 Output 1 Input 999999 Output 499999
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; cout << ((n - 1) >> 1); return 0; }
A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}. How many times will the ball make a bounce where the coordinate is at most X? Constraints * 1 \leq N \leq 100 * 1 \leq L_i ...
n, x = map(int, input().split()) l = [int(i) for i in input().split()] d = 0 c = 0 for i in l: d += i if d <= x: c += 1 print(c+1)
There are N dishes of cuisine placed in front of Takahashi and Aoki. For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N. When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness. Starting from Takahashi, they alternately choose one dish and ...
N = int(input()) A, B = [], [] for i in range(N): a,b = map(int, input().split()) A.append(a) B.append(b) AB = sorted([s+t for s,t in zip(A,B)], reverse=True) su = sum(AB[::2]) print(su-sum(B))
La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each. Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes. Constraints * N is an integer between 1 and 10...
#include <iostream> using namespace std; int main() { int N; cin >> N; int n = 0; while(n <= N) { if((N-n) % 7 == 0) { cout << "Yes\n"; return 0; } n += 4; } cout << "No\n"; return 0; }