input
stringlengths
29
13k
output
stringlengths
9
73.4k
Time Limit: 8 sec / Memory Limit: 64 MB Example Input 2 4 2 4 0.4000000 3 0.5000000 4 1 5 0.3333333 5 3 5 0.7777777 4 0.1111111 2 0.0001111 Output YES
#include <bits/stdc++.h> using namespace std; #define FOR(i,k,n) for(int i = (k); i < (n); i++) #define REP(i,n) FOR(i,0,n) #define ALL(a) a.begin(), a.end() #define MS(m,v) memset(m,v,sizeof(m)) #define D10 fixed<<setprecision(10) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<str...
Mr. B loves Brainf * ck and submits all the assignments given at school using Brainf * ck. Recently, I was brainwashed by Mr. B, and the teacher limited the language to solve the problem to Brainf * ck. At this rate, everyone will lose credit. You decide to help rescue everyone's units by creating a program that will ...
#include<iostream> using namespace std; int main(){string s,u="[<++++++++++>-]>",c=">+++++[<++++++>-]>+++++[<++++++++>-]>+++++"+u+"++++++"+u+"+++++++"+u+"++++++++"+u+"+++++++++"+u+"++++++++++"+u+"+++++++++++"+u+"++++++++++++"+u+"<<<<<<<<<<<"; int p=0,i,j,a,b,d;for(cin>>s,i=0;i<s.length();++i){a=s[i]/10-3,b=a-p,p=a,d=s[...
Example Input 3 2 1 2 1 2 3 2 1 10 100 Output 320
#include<bits/stdc++.h> using namespace std; #define MAX 2005 typedef long long ll; struct edge{ll to,cost;}; vector<ll> ans; vector<edge> G[MAX]; ll A[MAX]; int n,m; ll a,b,c; ll dfs(int pos,int prev,int root,ll cost){ vector<ll> res; for(int i=0;i<(int)G[pos].size();i++){ edge e=G[pos][i]; if(e.to==prev)...
Convex polygon pillar industrial city The Industrial Convex Pillar City (ICPC) is a city of buildings in the shape of several convex polygonal columns. You are about to walk through this city from your current location S to your destination T. The sun is strong today, so I want to go to my destination without passing ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vint; typedef pair<int,int> pint; typedef vector<pint> vpint; #define rep(i,n) for(int i=0;i<(n);i++) #define REP(i,n) for(int i=n-1;i>=(0);i--) #define reps(i,f,n) for(int i=(f);i<(n);i++) #define each(it,v) for(__typeof((v).begin(...
F: Grid number problem Ebi-chan is trying to write exactly one integer from 1 to 2 \ times n in a grid with n columns horizontally and 2 rows vertically. Only one integer can be written to each cell in the grid. It's not fun just to write normally, so I set the following rules. * The absolute value of the differen...
#include <iostream> using namespace std; typedef long long int ll; ll mod; ll dp[2][201][11][(1<<11)]; int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); int N,K; cin >> N >> K >> mod; dp[0][0][1][1]=1; int kk=(1<<(1+K)); for(int _=0;_<N;_++){ for(int i=0;i<=2*N;i++){ ...
Earthquakes E869120 You are not good at earthquakes. Specifically, if an earthquake with a seismic intensity of $ p $ occurs while you are doing a task, the performance of that task will be reduced by $ 10 \ times p $ percent. Yesterday, there were $ N $ earthquakes. More specifically, yesterday's i-th earthquake oc...
#include <bits/stdc++.h> #define rep(i,n)for(int i=0;i<(n);i++) using namespace std; typedef long long ll; typedef pair<int,int>P; const int INF=0x3f3f3f3f; const ll INFL=0x3f3f3f3f3f3f3f3f; const int MOD=1000000007; int t[200000],a[200000]; ll s[8][200000]; int main(){ int n;cin>>n; vector<int>xs; rep(i,n){ sc...
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path). Constraints * 1 ≤ |V| ≤ 100000 * 0 ≤ di ≤ 10000 * 0 ≤ |E| ≤ 500000 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E) and th...
from heapq import heappush, heappop INF = 10**10 a,b,c = map(int,input().split()) d = [[] for i in range(a)] for i in range(b): ta,tb,tc = map(int,input().split()) d[ta].append((tb,tc)) def dijkstra(N, G, s): dist = [INF] * N que = [(0, s)] dist[s] = 0 while que: c, v = heappop(que) ...
At last, we have successfully neutralized all the cyber weapons of mass destruction, saved our university along the way and lay to waste another evil scheme in the process. All that separates that hacker from us now is his last lair of security, his ultimate firewall. It is imperative for us to break through this last ...
for i in xrange(input()): x=input() s=0 y=x while x>0: s+=x%10 x/=10 print y*pow(2,s)
AND gates and OR gates are basic components used in building digital circuits. Both gates have two input lines and one output line. The output of an AND gate is 1 if both inputs are 1, otherwise the output is 0. The output of an OR gate is 1 if at least one input is 1, otherwise the output is 0. You are given a digit...
def circuits(): t=int(raw_input()) for i in range(t): n=raw_input() n=int(raw_input()) inp=[] in1=[] in2=[] for j in range(n): x=raw_input().split() inp.append(int(x[0])) if x[0]=='0': in1.append(0) in2.append(0) else: in1.append(int(x[1])) in2.append(int(x[2])) lowp=0 h...
Problem Description An online quiz is going to be held at NIT Hamirpur. Each student will be given a system which is connected to internet. Although all the systems are connected to same network, there is still varying data transfer speed among them. This can cause pages to load slower on one system than the other. The...
l=[int(i) for i in raw_input().split()]; n=l[0]; m=l[1]; l=[int(i) for i in raw_input().split()]; l.sort(); l=l[::-1]; print l[m-1];
Once N boys and M girls attended a party. You are given a matrix A of N rows and M columns where Aij is 1 if the i-th boy likes the j-th girl, otherwise it will be 0. Note that it is not necessary that if a boy x likes girl y, then girl y should like boy x. You know that if there are two different boys x and y, who bot...
# @author Kilari Teja # LCOLLIS for Indx in range(0, int(raw_input())): Collisions = 0 Dims = [int(Dim) for Dim in (raw_input()).split(" ")] Cols = [[] for CIndx in range(0, Dims[1])] for RIndx in range(0, Dims[0]): Row = raw_input() for Chr in range(0, Dims[1]): Cols[Chr].append(Row[Chr]) for Col in Co...
Recently, Chef got obsessed with piano. He is a just a rookie in this stuff and can not move his fingers from one key to other fast enough. He discovered that the best way to train finger speed is to play scales. There are different kinds of scales which are divided on the basis of their interval patterns. For instance...
for _ in range(input()): s=raw_input() n=input() t,sum=0,0 for i in s: if i=='T': sum+=2 #print t else: sum+=1 #sum=t+st #print sum temp=12*n j,i,c=temp,1,0 while i<=temp: j=temp-i while j: j-=sum if j>=0: c+=1 if j-sum<0: break i+=1 if temp-i<sum: break print c
John's barn has a fence consisting of N consecutive parts numbered from left to right starting from 1 to N. Each part is initially painted in one of two colors: red or green, whose information is provided you by a string C. The color of i-th part Ci will be equal to 'R' if the color of the part is red and 'G' if it is ...
t = int(raw_input()) for i in range(t): n,k = [int(j) for j in raw_input().split()] c = raw_input() l = list(c) q = [] qf,qb = 0,0 j,co = 0,0 while j < n: if (qb-qf)%2 == 0: if l[j] == 'R': co += 1 q.append(min(n,j+k)) qb += 1 else: if l[j] == 'G': co += 1 q.append(min(n,j+k)) ...
Alice got an array of length n as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice. Bob has chosen m changes of the following form. For some integer...
import java.util.Scanner; public class Code { public static long distSum(int n) { long sum=0; int i,j=n/2; for(i=0;i<n;i++) { sum=sum+ Math.abs(i-j); } return sum; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=in.nextInt(); ...
You are given two positive integers a and b. There are two possible operations: 1. multiply one of the numbers by some prime p; 2. divide one of the numbers on its prime factor p. What is the minimum number of operations required to obtain two integers having the same number of divisors? You are given severa...
#include <bits/stdc++.h> using namespace std; struct block { int id; vector<int> factors_vector; int divisor; }; block different_blocks[1000]; int no_of_different_blocks = 0; int no_of_different_divisors = 0; bool v[1000009]; long long primes[1000009]; int n_primes; int tmp[1000]; void pre_process(); int sieve();...
Pasha is a young technician, nevertheless, he has already got a huge goal: to assemble a PC. The first task he has to become familiar with is to assemble an electric scheme. The scheme Pasha assembled yesterday consists of several wires. Each wire is a segment that connects two points on a plane with integer coordinat...
#include <bits/stdc++.h> using namespace std; struct VerSeg { int x, y_1, y_2; VerSeg(int x_, int y_1_, int y_2_) : x(x_), y_1(y_1_), y_2(y_2_) {} VerSeg() {} }; struct HorSeg { int y, x_1, x_2; HorSeg(int y_, int x_1_, int x_2_) : y(y_), x_1(x_1_), x_2(x_2_) {} HorSeg() {} }; vector<VerSeg> ver, versAns; v...
Vova has taken his summer practice this year and now he should write a report on how it went. Vova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exactly n pages and the i-th page will include x_i tables and y_i formulas. The pages are...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); long long n, k; cin >> n >> k; vector<int> x(n), y(n); for (int& xi : x) cin >> xi; for (int& yi : y) cin >> yi; for (long long i = 0, px = 0, py = 0, qx, qy; i < n; ++i, px = qx, py = qy) { qx = max...
Alex decided to try his luck in TV shows. He once went to the quiz named "What's That Word?!". After perfectly answering the questions "How is a pseudonym commonly referred to in the Internet?" ("Um... a nick?"), "After which famous inventor we name the unit of the magnetic field strength?" ("Um... Nikola Tesla?") and ...
#include <bits/stdc++.h> using namespace std; constexpr int kMaxN = 100000; constexpr int kMaxValue = 7000; constexpr int kBitSetSize = (kMaxValue + 1) / 64 + 1; typedef long long BitSet[kBitSetSize]; void Add(BitSet a, BitSet b, BitSet c) { for (int i = 0; i < kBitSetSize; ++i) { c[i] = a[i] ^ b[i]; } } void M...
You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Le...
#include <bits/stdc++.h> using namespace std; void DEB(istream_iterator<string> it) {} template <typename T, typename... Args> void DEB(istream_iterator<string> it, T a, Args... args) { cout << *it << " = " << a << '\n'; DEB(++it, args...); } const int N = 3e5 + 5, mod = 1e9 + 7, inf = 1e9 + 7; int f[N][3]; int n, ...
<image> Input The input contains a single integer a (0 ≤ a ≤ 15). Output Output a single integer. Example Input 3 Output 13
print([15,14,12,13,8,9,10,11,0,1,2,3,4,5,6,7][input()])
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that n⋅ m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each...
N = int(input()) def make_vowels(N): ans = ["aeiou", "eioua", "iouae", "ouaei", "uaeio"] vowels = "aeiou" m = 5 while m < N: if N % m == 0 and N // m >= 5: break m += 1 else: return print(-1) n = N // m for i in range(n): if i <= 4: ...
With your help, Heidi has prepared a plan of trap placement and defence. Yet suddenly, the Doctor popped out of the TARDIS and told her that he had spied on the Daleks' preparations, and there is more of them than ever. Desperate times require desperate measures, so Heidi is going to risk meeting with the Daleks and sh...
#include <bits/stdc++.h> #pragma GCC optimize(2) #pragma GCC optimize(3) using namespace std; template <typename _T> inline void read(_T &f) { f = 0; _T fu = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') fu = -1; c = getchar(); } while (c >= '0' && c <= '9') { f = (f << 3) + ...
The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without chang...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.Input...
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i ⋅ a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hoolig...
import java.util.Scanner; //*1300 public class Multiplication_Table { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { solve(); } protected static void solve() { int n = sc.nextInt(); long a[][] = new long[n][n]; for(i...
Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i ≠ j. S...
#include <bits/stdc++.h> using namespace std; const int DIM = 2005; pair<int, int> pts[DIM]; long long dp[DIM]; bool oki[DIM]; int cst1[DIM], cst2[DIM], fth[DIM]; long long dist(int a, int b) { if (a > b) swap(a, b); if (a == 0) return cst1[b]; else return (cst2[a] + cst2[b]) * 1LL * (abs(pts[a...
You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≤ m ≤ n) beautiful, if there exists two indices l, r (1 ≤ l ≤ r ≤ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numb...
#include <bits/stdc++.h> using namespace std; const int base = 100003; const long long MM = 1ll * 1000000007 * 1000000007; int n, p[1000005]; void Solve() { cin >> n; int l = 2e9; int r = -1; for (int i = 1; i <= n; ++i) { int x; cin >> x; p[x] = i; } for (int i = 1; i <= n; ++i) { r = max(r...
An infinitely long Line Chillland Collider (LCC) was built in Chillland. There are n pipes with coordinates x_i that are connected to LCC. When the experiment starts at time 0, i-th proton flies from the i-th pipe with speed v_i. It flies to the right with probability p_i and flies to the left with probability (1 - p_i...
#include <bits/stdc++.h> using namespace std; int read() { int X = 0, w = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') w = -1; c = getchar(); } while (c >= '0' && c <= '9') X = X * 10 + c - '0', c = getchar(); return X * w; } const int N = 100000 + 10; const int mod = 998244353;...
Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem: You have an array a consisting of n positive integers. An operation consists of choosing an element and either adding 1 to it or subtracting 1 from it, such that the element remains posit...
#include <bits/stdc++.h> using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); class FKuroniAndThePunishment { vector<long long> primes; void sieve() { int N = 1E6; vector<bool> p(N, true); for (long long i = 2; i < N; i++) { if (p[i]) { primes.push_b...
A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward"). You are given a list of commands that will be given to the turtle. You have to change exactly n commands from the lis...
import java.io.Closeable; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.AbstractList; import java.io.Writer; import java.util.Collection; import java.util.List; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.u...
You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one). Input The first line contains the integer n (2 ≤ n ≤ 2·105). The second line contains elements of the sequence a1, ...
import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class T1{ public T1(){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = 0; long sum = 0; int arr[] = new int[n]; int ans[] = new int[n]; for(int i = 0; i < n; ...
Let's consider all integers in the range from 1 to n (inclusive). Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≤ a < b ≤ n. The greatest common divisor, gcd(a, b), of two positive integ...
n = int(input()) for i in range(n): print(int(input())//2)
Omkar is standing at the foot of Celeste mountain. The summit is n meters away from him, and he can see all of the mountains up to the summit, so for all 1 ≤ j ≤ n he knows that the height of the mountain at the point j meters away from himself is h_j meters. It turns out that for all j satisfying 1 ≤ j ≤ n - 1, h_j < ...
import java.io.*; import java.util.*; public class Main{ static void bruteForce(long[]in,int n) { while(true) { boolean modified=false; long[]newin=in.clone(); for(int i=0;i<n-1;i++) { if(in[i]+2<=in[i+1]) { newin[i]++; newin[i+1]--; modified=true; } } in=newin; if(!modi...
RedDreamer has an array a consisting of n non-negative integers, and an unlucky integer T. Let's denote the misfortune of array b having length m as f(b) — the number of pairs of integers (i, j) such that 1 ≤ i < j ≤ m and b_i + b_j = T. RedDreamer has to paint each element of a into one of two colors, white and black...
for I in range(int(input())): n,t = map(int,input().split()) a = list(map(int,input().split())) d = [] if t % 2 != 0: for i in range(n): if a[i] <= t // 2: d.append(1) else: d.append(0) else: p = 0 for i in range(n): ...
You are a mayor of Berlyatov. There are n districts and m two-way roads between them. The i-th road connects districts x_i and y_i. The cost of travelling along this road is w_i. There is some path between each pair of districts, so the city is connected. There are k delivery routes in Berlyatov. The i-th route is goi...
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC optimize("Ofast") using namespace std; const int inf = 0x3f3f3f3f; const int N = 1100, M = 1e5 + 10; int g[N], nxt[M], v[M], w[M], ed; void add(int x, int y, int z) { v[++ed] = y, nxt[ed] = g[x], g[x] = ed, w[ed] = z; } priority_queue<pair<int, int>, vec...
You are given a tree with n vertices numbered 1, …, n. A tree is a connected simple graph without cycles. Let dist(u, v) be the number of edges in the unique simple path connecting vertices u and v. Let diam(l, r) = max dist(u, v) over all pairs u, v such that l ≤ u, v ≤ r. Compute ∑_{1 ≤ l ≤ r ≤ n} diam(l, r). Inp...
#include<bits/stdc++.h> #define rd(x) x=read() #define N 200005 #define int long long using namespace std; int n,k; vector<int>e[N]; int vis[N],mn,rt; int s[N],dep[N],p[N][21],faa[N],f[21][N]; int b[N],c[N],w[N],g[N],suf[N]; inline int read() { int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0'){if(ch=='-...
Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd. <image> The problem is: You are given a connected tree rooted at node 1. You sho...
#include<cstdio> #include<algorithm> #include<cmath> #include<cstring> #include<vector> #include<map> #include<queue> #include<array> #include<queue> #include<set> using namespace std; #define imax(a,b) (((a)>(b))?(a):(b)) #define imin(a,b) (((a)<(b))?(a):(b)) #define mp make_pair typedef long long ll; const int N =...
Sayaka Saeki is a member of the student council, which has n other members (excluding Sayaka). The i-th member has a height of a_i millimeters. It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wa...
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ sc=new MScanner(System.in); pw = new PrintWriter(System.out); int tc=sc.nextInt(); for(int j=1;j<=tc;j++) { int l=sc.nextInt(); List<Integer> even=new Arr...
Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament. It is known that in a match between two players, the o...
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.Collections; import java.util.StringTokenizer; public class Solve { static int mod = 1000000000 + 7; static long INF = 1000_0...
Vasya lagged behind at the University and got to the battlefield. Just joking! He's simply playing some computer game. The field is a flat platform with n trenches dug on it. The trenches are segments on a plane parallel to the coordinate axes. No two trenches intersect. There is a huge enemy laser far away from Vasya...
#include <bits/stdc++.h> using namespace std; struct point { int x, y; }; struct segment { point a, b; }; double G[1002][1002]; vector<segment> S; int a, b; int N; double mins[1002]; bool used[1002]; double getLength(point a, point b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); } bool so...
The Little Elephant very much loves sums on intervals. This time he has a pair of integers l and r (l ≤ r). The Little Elephant has to find the number of such integers x (l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be inclu...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class LittleElephantAndInterval { static long calc(long x) { if (x < 10) r...
Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room n × m meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that it...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, m; cin >> n >> m; char mat[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> mat[i][j]; int peri = 0; for (int i = 0; i < n; i++) for (int j = ...
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times. Greg now only does three types of exercises: "chest" exercises,...
n=int(input()) l=list(map(int,input().split())) chest=back=biceps=0 for i in range(0,n,3): chest+=l[i] for i in range(1,n,3): biceps+=l[i] for i in range(2,n,3): back+=l[i] if chest>biceps and chest>back: print("chest") elif biceps>chest and biceps>back: print("biceps") else: print("back")
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, t...
import java.util.Arrays; import java.util.Scanner; public class A { public static boolean between(int x, int st, int end) { return x <= Math.max(st,end) && x >= Math.min(st,end); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt();...
In a far away galaxy there is war again. The treacherous Republic made k precision strikes of power ai on the Empire possessions. To cope with the republican threat, the Supreme Council decided to deal a decisive blow to the enemy forces. To successfully complete the conflict, the confrontation balance after the blow...
#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; } template <typename S, typename T...
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros. Now Iahub wants to count the number of ways...
#include <bits/stdc++.h> using namespace std; string s; int n; long long inverse(long long a, long long b, long long *X, long long *Y) { if (b == 0) { *X = 1; *Y = 0; return a; } else { long long xx, yy; long long ret = inverse(b, a % b, &xx, &yy); *X = yy; *Y = xx - (a / b) * yy; re...
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf. A tree is b...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:256000000") using namespace std; const int INF = (1 << 29) + 5; const long long int LLINF = (1ll << 59) + 5; const int MOD = 1000 * 1000 * 1000 + 7; const int MAX_N = 1000 * 100 + 5; int n; vector<int> graph[MAX_N]; long long int cnt[MAX_N]; long long int dp[MAX_...
There are a set of points S on the plane. This set doesn't contain the origin O(0, 0), and for each two distinct points in the set A and B, the triangle OAB has strictly positive area. Consider a set of pairs of points (P1, P2), (P3, P4), ..., (P2k - 1, P2k). We'll call the set good if and only if: * k ≥ 2. * Al...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-9; const int MOD = 1000000007; int n, pot[1000100]; pair<double, double> a[1010]; bool cmp(const pair<double, double> &A, const pair<double, double> &B) { if (abs(A.first - B.first) > eps) return A.first < B.first; if (abs(A.second - B.second) > ep...
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office. The teacher remembers that the "very beau...
#include <bits/stdc++.h> using namespace std; void fast() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); } long long int gcd(long long int x, long long int y) { if (y == 0) return x; return gcd(y, x % y); } long long int lcm(long long int a, long long int b) { return (a * b) / gcd(a, b);...
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once. The appointed Judge was the most experienced member — Pavel. But since he was the wi...
#include <bits/stdc++.h> using namespace std; int n, k; int main() { cin >> n >> k; int total = (n * (n - 1)) / 2; if (total >= n * k) { total = n * k; cout << total << "\n"; int nod1 = 1; int nod2 = nod1 + 1; int cate = 0; while (total > 0) { cate++; if (nod2 > n) nod2 = 1; ...
DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a ...
#include <bits/stdc++.h> using namespace std; const int MX = 1000 + 100; vector<pair<int, int> > G[MX]; bitset<MX> bs; struct data { int v, f, t; bool operator<(const data& in) const { return v < in.v; } }; int val[MX]; int main() { srand(time(0)); int n, e; cin >> n >> e; if (e == 0) { cout << "0.00000...
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a × b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is,...
n,a,b = map(int, input().split(' ')) A = 6*n if a*b >= 6*n : print(a*b) print(a,b) else : R = [] temp = float("INF") for i in range(1, int(A**0.5)+2) : j = A//i if i*j < A : j+=1 x = max([a,b,i,j]) y = max(min(a,b) , min(i,j)) if temp > x*y : temp ...
An n × n square matrix is special, if: * it is binary, that is, each cell contains either a 0, or a 1; * the number of ones in each row and column equals 2. You are given n and the first m rows of the matrix. Print the number of special n × n matrices, such that the first m rows coincide with the given ones. ...
#include <bits/stdc++.h> using namespace std; const int N = 505; long long dp[N][N]; int mod, n, m, sum[N]; long long C(int a) { return (long long)a * (a - 1) / 2; } long long dfs(int a, int b) { if (a < 0 || b < 0) return 0; if (a == 0 && b == 0) return 1; if (~dp[a][b]) return dp[a][b]; dp[a][b] = 0; dp[a][...
You need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:60777216") using namespace std; int n, c; set<int> sl[1111111]; set<int> sr[1111111]; int LN[1111111]; int RN[1111111]; void print_tree(int pos) { if (LN[pos] != -1) print_tree(LN[pos]); printf("%d ", pos); if (RN[pos] != -1) print_tree(RN[pos]); } int STAR...
Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment. The teacher gave Andrew an array of n numbers a1, ..., an. After that he asked Andrew for each k from 1 to n - 1 to build a k-ary...
#include <bits/stdc++.h> using namespace std; const int MAXN = 210000; int fenw[MAXN]; int a[MAXN], ans[MAXN]; int sum(int x) { int sum = 0; for (; x >= 0; x &= x + 1, --x) sum += fenw[x]; return sum; } void add(int x, int z) { for (; x < MAXN; x |= x + 1) fenw[x] += z; } int main(int argc, const char *argv[]) ...
Two kittens, Max and Min, play with a pair of non-negative integers x and y. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, x and y became negative at the same time, and kitten Max tries to prevent him from...
#include <bits/stdc++.h> using namespace std; set<pair<int, int> > a; vector<pair<int, int> > v, w; bool f(pair<int, int> a, pair<int, int> b, pair<int, int> c) { return 1LL * (-c.second + a.second) * (b.first - a.first) > 1LL * (-b.second + a.second) * (c.first - a.first); } int main() { int n, m, x, y; ...
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. <image> Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g...
import math #n,k = map(int, input().strip().split(' ')) n=int(input()) #lst = list(map(int, input().strip().split(' '))) if n==1 or n==2 or n==3: print(n) else: p=math.sqrt(n) l=[1,n] c=1 for j in range(2,int(p)+1): if n%j==0: l.insert(c,j) if n//j!=j: ...
Misha decided to help Pasha and Akim be friends again. He had a cunning plan — to destroy all the laughy mushrooms. He knows that the laughy mushrooms can easily burst when they laugh. Mushrooms grow on the lawns. There are a[t] mushrooms on the t-th lawn. Misha knows that the lawns where the mushrooms grow have a uni...
import java.io.IOException; import java.util.Arrays; import java.io.FilterInputStream; import java.util.HashMap; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeSet; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at...
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes. The parking lot before the office consists of one line of (2n - 2) parking spaces. Unfortunately the total number of cars...
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayL...
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent. Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direct...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL); int n, a, b; cin >> n >> a >> b; cout << 1 + (((n * 500) + a + b - 1) % n); return 0; }
Petya has recently learned data structure named "Binary heap". The heap he is now operating with allows the following operations: * put the given number into the heap; * get the value of the minimum element in the heap; * extract the minimum element from the heap; Thus, at any moment of time the heap con...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.StringTokenizer; public class C357 { public static void main(String[] args) { MyScanner scan = new MyScanner(); Prin...
Scott Lang is at war with Darren Cross. There are n chairs in a hall where they are, numbered with 1, 2, ..., n from left to right. The i-th chair is located at coordinate xi. Scott is on chair number s and Cross is on chair number e. Scott can jump to all other chairs (not only neighboring chairs). He wants to start a...
#include <bits/stdc++.h> long long f[5010][5010]; int a[5010], b[5010], c[5010], d[5010], x[5010]; int main() { int n, s, e; scanf("%d%d%d", &n, &s, &e); for (int i = 1; i <= n; i++) scanf("%d", &x[i]); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), a[i] += x[i]; for (int i = 1; i <= n; i++) scanf("%d", &b[...
Alice and Bob are well-known for sending messages to each other. This time you have a rooted tree with Bob standing in the root node and copies of Alice standing in each of the other vertices. The root node has number 0, the rest are numbered 1 through n. At some moments of time some copies of Alice want to send a mes...
#include <bits/stdc++.h> using namespace std; const int maxn = 8e5 + 5; const int inf = 1 << 28; vector<int> adj[maxn]; int siz[maxn], top[maxn], par[maxn], mson[maxn]; int ans[maxn], n, m, ord[maxn], x[maxn], t[maxn]; int dfn[maxn], edfn[maxn], idx, pos[maxn], dep[maxn]; int maxd[maxn], rst[maxn], eff[maxn]; void buil...
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are n lanes of m desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to n from the left to the right, the desks in a lane are numb...
#include <bits/stdc++.h> using namespace std; bool s_end(size_t c) { return (c == string ::npos) ? true : false; } int main() { int n, m, k; cin >> n >> m >> k; int lane = (k + 2 * m - 1) / (2 * m); k -= (lane - 1) * 2 * m; int desk = (k + 1) / 2; char side = (k % 2) ? 'L' : 'R'; cout << lane << " " << de...
A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular. Draw the given sequence using a minimalistic pseud...
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(nullptr); ios_base::sync_with_stdio(false); cout.setf(ios_base::fixed); cout.precision(24); int n; cin >> n; vector<int> deep(n, 0); string s; cin >> s; int cnt = 0, mx = 0; for (int i = 0; i < n; ++i) { if (s[i] == '[') { ...
Igor the analyst is at work. He learned about a feature in his text editor called "Replace All". Igor is too bored at work and thus he came up with the following problem: Given two strings x and y which consist of the English letters 'A' and 'B' only, a pair of strings (s, t) is called good if: * s and t consist of...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
Karen is getting ready for a new school day! <image> It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time i...
h, m = map(int, input().split(':')) for i in range(999): if h == 10 * (m % 10) + m // 10: print(i) break h, m = (h, m + 1) if m < 59 else ((h + 1) % 24, 0)
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ...
from collections import Counter n , k = map(int , input().split()) s = input() s = list(s) cnt = Counter(s) r = 0 for i in cnt: if cnt[i] > k: r = 1 break print('YES' if r == 0 else 'NO')
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees. A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and ...
from collections import defaultdict n = int(input()) degree = [0 for i in range(n+1)] def BFS(d,x,visited): visited[x] = 1 queue = [(x,1)] l1 = set() l2 = set() while len(queue): temp,j = queue.pop() visited[temp] = 1 if j%2 == 1: l1.add(temp) else: l2.add(temp) for i in d[temp]: if visite...
During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it. Like many other creative people, Izabella has a specific sense of beaut...
#include <bits/stdc++.h> using namespace std; int a[500010], n, k, suf[500010]; int l_bad, r_bad; int mi[500010 << 2], mi_pos[500010 << 2]; vector<int> v[500010]; void push_up(int o) { mi[o] = min(mi[o << 1], mi[o << 1 | 1]); mi_pos[o] = (mi[o << 1] < mi[o << 1 | 1]) ? mi_pos[o << 1] : mi_pos[o << 1 | 1]; } v...
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d. For each point from 1 to n is known if there is...
n , d =map(int, input().split()) s= str(input()) ans = -1 i=1 count = 0 while i<len(s): temp = s[i:i+d] if '1' in temp: x = temp.rfind('1') i = i+ x +1 count = count +1 else: print(ans) count=0 break if count!=0: print(count)
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows: <image> Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists. For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B. Input...
#include <bits/stdc++.h> using namespace std; void print(int p, int q) { for (int i = 1; i < q; i++) cout << p + i << " "; cout << p << " "; } int main() { int n, a, b; cin >> n >> a >> b; if (a < b) { int c = a; a = b; b = c; } int na, nb = -1; for (na = n / a; na >= 0; na--) { if ((n -...
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that: * b is lexicographically greater than or equal to a. * bi ≥ 2. * b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest com...
#include <bits/stdc++.h> using namespace std; set<int> prims; vector<bool> used; vector<int> divisors; vector<bool> skip; vector<int> nxt; vector<int> prv; void init_prims(int ub) { divisors.resize(ub, 0); for (int i = 0; i < ub; ++i) { divisors[i] = i; } for (int i = 2; i < ub; ++i) { if (divisors[i] =...
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tr...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 10; int a[maxn]; bool used[maxn]; void dfs(int v) { used[v] = 1; if (!used[a[v]]) dfs(a[v]); } int main() { ios_base::sync_with_stdio(0); cin.tie(nullptr); int n; cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i]; int x = n; for (in...
Chandan is a horrendous murderer and he wants to kill Arjit just because he's lazy. Chandan is following the trail of Arjit's shoes. The trail is in the form of a k-ary tree. Arjit is lazy, sure, but he's smart. So, he magically moves away from Chandan as far as he can go. Chandan doesn't know the way out, but he kno...
t=int(raw_input()) def bfs(x): b=[False]*(n+1)# an array of false flags to keep track of vertices visited memo=["p"]*(n+1) l=0 c=0 q=[] q.append(x) memo[x]=0 while len(q)!=0: #t=s[-1] top=q.pop(0) #l=t b[top]=True #q.pop(0) for j in G[top]:...
Bosky and Menot are two friends who participated in GSF Hacks Prelims on HackerEarth, and both of them easily qualified for the on-site round. Bosky wants to team up with Menot for the on-site round but Menot has a date with his girlfriend the same day. Bosky thus plans to spoil Menot’s date and trigger their breakup. ...
days = [0]*31 for i in xrange(input()): string = raw_input().split() if string[0] == 'G:': choice = [int(x) for x in string if x.isdigit()] for gval in choice: days[gval] += 2*(choice.count(gval)) else: choice = [int(x) for x in string if x.isdigit()] for gval in choice: days[gval] += 1*(choice.cou...
As we know , Professor Dalton is teaching Compiler Design. During his first class, he found that the students are very talkative. so,he decided to divide the class into two sections, A & B such that the difference between the strength of two sections is minimum. Print the strength of two sections in non decreasing o...
testcases = raw_input() for i in range(int(testcases)): tot = raw_input() tot = int(tot) if(tot%2==0): a=tot/2 print a,a else: a=tot/2 print a,a+1
Gajodhar is travelling from one city to another city. Let starting city be the source and city at which his journey ends be destination. There are many intermediate cities between source and destination. Gajodhar has weak memory, so he remembers names of cities by their first character. If there are more than one inter...
t = int(raw_input()) while t: t-=1 n = int(raw_input()) a = [] c = 0 for i in xrange(n): b = str(raw_input()) a.append(b[0]) for i in a: if a.count(i) == 1: c+=1 print c
You are given N positive integers A1, A2, ... AN. Find the number of ways to distribute them in 2 groups in such a way that sum of numbers in each group is greater or equal K. The answer can be large so output it modulo 10^9 + 7. Input The first line contains two space-separated integers N and K. The second line conta...
MOD=1000000007 N,K=map(int,raw_input().split()) A=map(int,raw_input().split()) found=[0]*K found[0]=1 Kplus=0 if sum(A)<2*K: print 0 exit() for a in A: Kplus=Kplus*2 for j in range(max(0,K-a),K): Kplus+=found[j] Kplus%=MOD for j in range(K-1,a-1,-1): found[j]=(found[j]+found[j-a])%MOD print (MOD+Kplus-sum(f...
Given a binary tree in a two dimensional plane which has both side covered by mirrors. As this is a 2D dimensional image, we define our print function to print only those nodes whose reflection is showing on one of the mirrors, first we print the value of the nodes with reflections appearing on the right mirror and th...
import math def findReflection(tree,ansL,ansR,start,end): l = end - start; lRef = ''; rRef = ''; for v in range(0,l+1): if tree[start+v] != '0': lRef = v+start; break; for v in range(0,l+1): if tree[end-v] != '0': rRef = end-v; break;...
Given A and B, count the numbers N such that A ≤ N ≤ B and N is a palindrome. Examples: Palindromes: 121, 11 , 11411 Not Palindromes: 122, 10 Input: First line contains T, the number of testcases. Each testcase consists of two integers A and B in one line. Output: For each testcase, print the required answer ...
n = input() def check_palindromic(x): if str(x) == str(x)[::-1]: return True return False kq = [] for i in range(n): dem = 0 nhap = list(map(lambda x: int(x), raw_input().split())) for j in range(nhap[0], nhap[1]+1): if check_palindromic(j) == True: dem += 1 kq.appen...
King Tle4Ever just appointed Moron as the new Engineer for his country Time Limit Exceeded. In the country of Time Limit Exceeded there are n cities and there is a direct road between each pair of cities. Now cleaning up these roads costs Tle4Ever a lot of money so he wants to demolish some of the roads but not all for...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' for _ in range(input()): n,q = map(int,raw_input().split()) q=q-1 ans = n*n - (n%q)*((n+q-1)/q)*((n+q-1)/q) - (q - n%q)*(n/q)*(n/q) ans/=2 ans1 =(n*(n-1))/2 -ans ...
Jack and Jill are sitting at the bottom of their tree house and debating in how many ways then can jump up the stairs on the tree and reach the tree house .Because Jack is older than Jill, He can jump one, two or three stairs in one step while Jill can jump just one or two stairs in one step . For example, Jack can cov...
a = 0; b = 1; c = 1; d = 0; e = 1; n = int(raw_input()); if n <= 0: print "ERROR"; else: n -= 1; while (n): c = a + b + c; b = c - a - b; a = c - b - a; e = d + e; d = e - d; n -= 1; e = d + e; d = e - d; print "Jack-"+str(c)+"\nJill-"+str(e);
A Puzzle is a game, problem, or toy that tests a person's ingenuity. In a puzzle, one is required to put pieces together, in a logical way, in order to arrive at the correct solution of the puzzle. There are different types of puzzles for different ages.Puzzles are often devised as a form of entertainment but they can ...
(N, K) = map (int, str(raw_input()).split()) nums = sorted (map (int, str(raw_input()).split())) count = 0 for i in range(N-2): j = i+1 k = N-1 while True: while nums[i] * nums[j] * nums[k] > K: k -= 1 if k == j: break count += k-j j += 1 if j >= k: break print count
We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is `S`, it means it was sunny on the i-th day; if that character is `R`, it means it was rainy on that day. Find the maximum number of consecutive rainy days in this period. ...
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main(){ string s;cin>>s; int an=0,cur=0; for(char x:s){ if(x=='R') cur++; else cur=0; an=max(an,cur); }cout<<an<<"\n"; }
Find \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}. Here \gcd(a,b,c) denotes the greatest common divisor of a, b, and c. Constraints * 1 \leq K \leq 200 * K is an integer. Input Input is given from Standard Input in the following format: K Output Print the value of \displaystyle{\sum_{...
import math K=int(input()) ans=0 for i in range(1,K+1): for j in range(1,K+1): for k in range(1,K+1): ans+=math.gcd(math.gcd(i,j),k) print(ans)
Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it. The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer)....
n = int(input()) m = 1 while int(m*1.08) < n: m += 1 print(m) if int(m*1.08) == n else print(":(")
There is a blackboard on which all integers from -10^{18} through 10^{18} are written, each of them appearing once. Takahashi will repeat the following sequence of operations any number of times he likes, possibly zero: * Choose an integer between 1 and N (inclusive) that is written on the blackboard. Let x be the cho...
#include <bits/stdc++.h> using namespace std; #define ll long long #define f(i, x, n) for(int i = x; i < (int)(n); ++i) int const N = 150, M = N >> 1; int dp[N + 1][N + 1][N + 1], md, dp0[M + 1][M + 1]; inline void ad(int &x, int y) { if ((x += y) >= md)x -= md; } inline void up(int i, int a, int b, int y) { ad(dp[i]...
Snuke participated in a magic show. A magician prepared N identical-looking boxes. He put a treasure in one of the boxes, closed the boxes, shuffled them, and numbered them 1 through N. Since the boxes are shuffled, now Snuke has no idea which box contains the treasure. Snuke wins the game if he opens a box containin...
#include <bits/stdc++.h> using namespace std; typedef long long LL; int main(){ int n, k; cin >> n >> k; vector<int> a(n); for(int i = 0; i < n; i++){ cin >> a[i]; } k++; // should get all numbers to at least k+1; int asum = 0; int amax = 0; for(int i = 0; i < n; i++){ a[i] = k - a[i]; if(a[i] < 0) a[...
There are N cities on a number line. The i-th city is located at coordinate x_i. Your objective is to visit all these cities at least once. In order to do so, you will first set a positive integer D. Then, you will depart from coordinate X and perform Move 1 and Move 2 below, as many times as you like: * Move 1: tr...
import math n,x=map(int,input().split());l=[abs(x-i) for i in list(map(int,input().split()))];r=0 for i in range(len(l)): r=math.gcd(r,l[i]) print(r)
Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten. He remembers that the remainder of a divided by b was greater than or equal to K. Find the number of possible pairs that he may have had. Constraints * 1 \leq N \leq 10^5 * 0 \leq K \leq N-1 * All input values are integers. ...
n, k = map(int, input().split()) ans = 0 for i in range(1,n+1): ans += (n//i)*max(0,i-k)+max(0,n%i-k+1) if k==0: ans -= n print(ans)
Rng is preparing a problem set for a qualification round of CODEFESTIVAL. He has N candidates of problems. The difficulty of the i-th candidate is D_i. There must be M problems in the problem set, and the difficulty of the i-th problem must be T_i. Here, one candidate of a problem cannot be used as multiple problems....
#!/usr/bin/env python import sys line = sys.stdin.readline().strip() n = int(line) parts = sys.stdin.readline().strip().split() nvals = map(int,parts) nhash = {} for item in nvals: if nhash.has_key(item): nhash[item] += 1 else: nhash[item] = 1 line = sys.stdin.readline().strip() m = int(line...
There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively. For each of these bags, you will paint one of the balls red, and paint the other blue. Afterwards, the 2N balls will be classified according to color. Then, we will define the f...
import sys from operator import itemgetter inf = 1 << 30 def solve(): n = int(sys.stdin.readline()) # r_max = MAX, b_min = MIN にしたとき r_max = b_max = 0 r_min = b_min = inf p = [] for i in range(n): xi, yi = map(int, sys.stdin.readline().split()) if xi > yi: ...
We have an N×N checkerboard. From the square at the upper left corner, a square that is i squares to the right and j squares below is denoted as (i, j). Particularly, the square at the upper left corner is denoted as (0, 0). Each square (i, j) such that i+j is even, is colored black, and the other squares are colored...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define each(itr,v) for(auto itr:v) #define pb push_back #define all(x) (x).be...
Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so. Constraints * 1 ≤ length of the side ≤ 1,000 * N ≤ 1,000 Input Input consists of several data sets. In the first line, the number of data set, N is...
N = int(input()) for i in range(N): num = sorted(map(int, input().split())) if num[0] ** 2 + num[1] ** 2 == num[2] ** 2: print("YES") else: print("NO")
A mischievous notice has arrived from the primitive slow-life organization "Akaruda". Akaruda is famous for mischief such as throwing a pie at the face of a VIP, but recently it has become more radical, such as using gunpowder to sprinkle rat fireworks at the reception venue. The notice is the following text. --- Per...
#include<iostream> #include<cstdlib> #include<algorithm> using namespace std; int main(){ int n; cin>>n; for(int i=0;i<n;i++){ int h,m; char _; cin>>h>>_>>m; int d=min(abs(h*60+m-12*m) , 720-max(h*60+m,12*m)+min(h*60+m,12*m)); if(d<30*2){ cout<<"alert\n"; }else if(d<90*2){ cout<<"warning\n"; }el...
There was a big old mansion in one place, and one cat settled in. As shown in the figure, the mansion has a convex polygonal shape when viewed from above, and is made up of several rooms surrounded by straight walls. One wall is supported by pillars at both ends. The mansion is so old that every wall has one hole that ...
#include <bits/stdc++.h> #define _overload(_1,_2,_3,name,...) name #define _rep(i,n) _range(i,0,n) #define _range(i,a,b) for(int i=int(a);i<int(b);++i) #define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__) #define _all(arg) begin(arg),end(arg) template<class T>bool chmax(T &a, const T &b) { return (a<b)?(...
problem JOI Shoji manages the time spent at work by employees with a time card. When an employee arrives at the office, he / she uses a dedicated device to stamp the arrival time on the time card. When leaving the office after work, the time of leaving the office is stamped on the time card. The time is handled in a 2...
#include <cstdio> int main (int argc, char const* argv[]) { int a,b,c,d,e,f,t,i; for(i=0;i<3;i++){ scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f); t=d*60*60+e*60+f-a*60*60-b*60-c; printf("%d %d %d\n",t/3600%60,t/60%60,t%60); } return 0; }
Since I got tired to write long problem statements, I decided to make this problem statement short. For given positive integer L, how many pairs of positive integers a, b (a ≤ b) such that LCM(a, b) = L are there? Here, LCM(a, b) stands for the least common multiple of a and b. Constraints * 1 ≤ L ≤ 1012 Input For ...
#include<cstdio> #include<vector> #define pb push_back using namespace std; typedef vector<int> vi; int main(){ static bool era[1000000]; for(int i=2;i<100;i++){ if(!era[i]) for(int j=i*i;j<1000000;j+=i) era[j]=true; } vi pr; for(int i=2;i<1000000;i++) if(!era[i]) pr.pb(i); int n=pr.size(); for(long long...
Life is not easy. Sometimes it is beyond your control. Now, as contestants of ACM ICPC, you might be just tasting the bitter of life. But don't worry! Do not look only on the dark side of life, but look also on the bright side. Life may be an enjoyable game of chance, like throwing dice. Do or die! Then, at last, you m...
#include<iostream> #include<string> using namespace std; void Run(int&, int&, int&, int&); int main(){ int i, n, top, bottom, north, south, west, east; string str; while(1){ cin >> n; if(n == 0) break; top = 1; bottom = 6; north = 2; south = 5; west = 3; east = 4; for(i=0...
Consider a binary tree whose leaves are assigned integer weights. Such a tree is called balanced if, for every non-leaf node, the sum of the weights in its left subtree is equal to that in the right subtree. For instance, the tree in the following figure is balanced. <image> Figure I.1. A balanced tree A balanced tr...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #defi...