input
stringlengths
29
13k
output
stringlengths
9
73.4k
You generate real numbers s1, s2, ..., sn as follows: * s0 = 0; * si = si - 1 + ti, where ti is a real number chosen independently uniformly at random between 0 and 1, inclusive. You are given real numbers x1, x2, ..., xn. You are interested in the probability that si ≤ xi is true for all i simultaneously. ...
#include <bits/stdc++.h> using namespace std; const int md = 998244353; inline void add(int &a, int b) { a += b; if (a >= md) a -= md; } inline void sub(int &a, int b) { a -= b; if (a < 0) a += md; } inline int mul(int a, int b) { return (int)((long long)a * b % md); } inline int power(int a, long long b) { i...
Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't m...
#include <bits/stdc++.h> using namespace std; enum estados { INDEF = 0, GANA = 1, PIERDE = 2 }; const int N = 1e5 + 1; int main() { int n; scanf("%d %*d", &n); int sig[2 * N] = {}; int siguientes[2 * N] = {}; vector<int> anteriores[2 * N]; vector<estados> estado(2 * n + 1, INDEF); for (int i = 1; i <= n; ...
You are given a set of n elements indexed from 1 to n. The weight of i-th element is wi. The weight of some subset of a given set is denoted as <image>. The weight of some partition R of a given set into k subsets is <image> (recall that a partition of a given set is a set of its subsets such that every element of the ...
#include <bits/stdc++.h> using namespace std; const int maxn = 202020; const int mod = 1000000007; int a[maxn], s; int fac[maxn], ifac[maxn]; int qpow(int a, int n) { int ans = 1; for (; n; n >>= 1, a = (long long)a * a % mod) if (n & 1) ans = (long long)ans * a % mod; return ans; } int gets(int n, int m) { ...
Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that. The box's lock is constructed...
#include <bits/stdc++.h> using namespace std; struct neighbours { char face; char mas[4]; }; struct answer { neighbours mas[6]; }; vector<answer> answers; answer currentAnswer; char colors[6]; char faces[6]; bool used[6]; int matrix[6][4]; void mySort(char mas[4]) { char var[4]; for (int i = 0; i < 4; i++) va...
Arnab is a robber and he has managed to rob N different strings from Akash. Now he decides to sell these strings in the market to make some profit. But, of all the strings he has, he wants to find the size of the largest anagram group so that he can easily sell that one first and make maximum profit initially. Help him...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' n = int(raw_input()) d = dict() for i in range(n): s = raw_input() x = ''.join(sorted(s)) if not d.has_key(x): d[x]=1 else: d[x]+=1 max = -1 for j in d.values(): if j > max: ...
You are studying a swarm of N fireflies. Each firefly is moving in a straight line at a constant speed. You are standing at the center of the universe, at position (0, 0, 0). Each firefly has the same mass, and you want to know how close the center of the swarm will get to your location (the origin). You know the posi...
import math def cross(a, b): c = [float(a[1])*float(b[2]) - float(a[2])*float(b[1]), float(a[2])*float(b[0]) - float(a[0])*float(b[2]), float(a[0])*float(b[1]) - float(a[1])*float(b[0])] return c def modulo(a): b=float(a[0])*float(a[0])+float(a[1])*float(a[1])+float(a[2])*float(a[2]) b=mat...
You have an unbiased dice which you want to keep rolling until you get N consecutive even numbers. You've rolled the dice M times and surprisingly, all rolls resulted in even numbers. What is the expected number of additional rolls needed until you get N consecutive even numbers? Input: The first line contains the n...
t = input() while t > 0: a = raw_input() c,d = a.split() ans = 0 c = int(c) d = int(d) y = 1 z = 1 for i in range (c): y = y*2 for i in range (d): z = z*2 ans=y-z ans=2*ans print(str(ans)+'.00') t = t-1
Anmol likes gems very much. He has N packets of gems, here the ith packet contains Pi gems. You need to find the minimal number of packets Anmol needs to take to his trip to Market, if he wants to eat there at least M gems. Note that gems are already packed, i.e. he cannot change the amount of gems in any packet. Inpu...
def find_min(t,sum1,items): items.sort() i = t-1 sumz = 0 m = sum1 count = 0 while i>=0: sumz += items[i] count += 1 if(sumz>=m): return (count) break i -= 1 if i == -1: return (-1) if __name__=='__main__': ...
Verma has got 2 arrays of integer numbers. He wished to find the sum of product of all numbers in first array with all the numbers in second array. i.e suppose 1st array A[] contains N numbers and 2nd array B[] contains m numbers. He wished to calculate for all 1 ≤ i ≤ N and for all 1 ≤ j ≤ M.. sum(Ai*Bi). As he is ...
line=raw_input().split(' ') a=int(line[0]) b=int(line[1]) line1 = raw_input().split(' ') line2 = raw_input().split(' ') sum1=0 sum2=0 for i in range(0,a): sum1 = sum1 + int( line1[i]) for j in range(0,b): sum2 += int(line2[j]) print sum1*sum2
Our Code Monk recently learnt about Graphs and is very excited! He went over to the Graph-making factory to watch some freshly prepared graphs. Incidentally, one of the workers at the factory was ill today, so Monk decided to step in and do her job. The Monk's Job is to Identify whether the incoming graph is a tr...
print "Yes" if (2*(input()-1)-sum(list(map(int,raw_input().split())))==0) else "No"
Kevin has a permutation P of N integers 1, 2, ..., N, but he doesn't like it. Kevin wants to get a permutation Q. Also he believes that there are M good pairs of integers (ai , bi). Kevin can perform following operation with his permutation: Swap Px and Py only if (x, y) is a good pair. Help him and tell if Kevin can...
def dfs(v): global mark,c_c q=[] q.append(v) while q: top=q.pop() mark[top]=c_c for j in G[top]: if mark[j]==-1: q.append(j) mark[j]=mark[top] #d[c_c]=s t=input() while t!=0: n,m=map(int,raw_input().split()...
Its Diwali time and little Roy thought of an interesting design for Rangoli. He created an N x N grid. Roy fills some of the cells of grid with red color. Cell located at ith row and jth column is colored if i+j is prime. Consider Zero-based numbering of grid. (See Sample Test Case Explanation for clarification) Roy ...
def sieve(n): is_prime = [True] * (n+1) is_prime[0] = is_prime[1] = False for i in range(2, n+1): if is_prime[i]: for j in range(i+i, n+1, i): is_prime[j] = False return is_prime n = int(raw_input()) is_prime = sieve(n+n) total = 0 for i in range(n): if is_prime[...
Subly found a set of Numbers in his Dad's table. Subly examines that set and wants to know how many numbers in that set are not divisible by his favourite number. He asked his brother for help. His brother told him that the numbers were in some row of the Pascals Triangle. But since he was busy, he couldn't solve Sub...
from sys import stdin n,m = map(int,stdin.readline().split()) tot = 0 cur = n ans = 0 while cur: tot += cur/m cur/=m for i in xrange(n+1): fir = n-i sec = i u = 0 v = 0 while fir: u += fir/m fir/=m while sec: v += sec/m sec/=m #print i,n-i,u,v if u+v >= tot: ans+=1 print ans
Vivek and Sita are in a relationship. Both of them love playing with numbers and treat each other with puzzles every now and then. When Sita visits her class she comes to see that there is a gift packed in a wooden box which has a lock in it which can only be unlocked by solving the puzzle written on the paper note w...
import math def powmod(x, y, md): if x==0: return 0 if y==0: return 1 ans = powmod(x, y//2, md) ans = (ans*ans)%md if y%2==1: ans = (x*ans)%md return ans def Rn(N): if N<=10: return R[N] n4 = int(math.ceil(N/4.0)) n5 = int(math.ceil(N/5.0)) n10= in...
New AtCoder City has an infinite grid of streets, as follows: * At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point. * A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coor...
import sys input = sys.stdin.readline def main(): n = int(input()) l = [list(map(int,input().split())) for i in range(n)] xcal = [[0]*n for i in range(1<<n)] ycal = [[0]*n for i in range(1<<n)] for i in range(1<<n): for j in range(n): xcal[i][j] = abs(l[j][0]) ycal[...
Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left. Each square is painted black or white. The grid is said to be good if and only if the following condition is satisfied: * From (1, 1), we can reach (H, W) by moving one sq...
h, w = map(int, input().split()) s = [list(input()) for _ in range(h)] dp = [[h * w] * w for _ in range(h)] dp[0][0] = 0 if s[0][0] == "." else 1 for x0 in range(w): for y0 in range(h): for i, j in [(0, 1), (1, 0)]: x = x0 + i y = y0 + j if x < w and y < h: ...
Given are positive integers N and K. Determine if the 3N integers K, K+1, ..., K+3N-1 can be partitioned into N triples (a_1,b_1,c_1), ..., (a_N,b_N,c_N) so that the condition below is satisfied. Any of the integers K, K+1, ..., K+3N-1 must appear in exactly one of those triples. * For every integer i from 1 to N, a_...
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<algorithm> #include<vector> #include<queue> #define ll long long #define maxn 200010 inline ll read() { ll x=0; char c=getchar(),f=1; for(;c<'0'||'9'<c;c=getchar())if(c=='-')f=-1; for(;'0'<=c&&c<='9';c=getchar())x=x*10+c-'0'; return x*f; ...
There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:...
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5 + 5, mod = 1e9 + 7; const double inf = 1e18; struct e{ int x, y; double nx, ny; char p; }a[maxn]; int n; double F(double mid) { double maxx = -inf, minx = inf, maxy = -inf, miny = inf; for (int i = 0; i < n; ++i)...
There are N jewels, numbered 1 to N. The color of these jewels are represented by integers between 1 and K (inclusive), and the color of Jewel i is C_i. Also, these jewels have specified values, and the value of Jewel i is V_i. Snuke would like to choose some of these jewels to exhibit. Here, the set of the chosen jew...
//https://atcoder.jp/contests/nikkei2019-qual/tasks/nikkei2019_qual_f #include<bits/stdc++.h> using namespace std; typedef long long LL; #ifdef BTK #define DEBUG if(1) #else #define CIN_ONLY if(1) struct cww {cww() {CIN_ONLY{ios::sync_with_stdio(false); cin.tie(0);}}}star; #define DEBUG if(0) #endif #define ALL(v) (v)....
A programming competition site AtCode regularly holds programming contests. The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200. The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800. The contest after the ARC is called AG...
#include <iostream> using namespace std; int main(){ int a; cin>>a; if (a>=0&&a<1200){cout<<"ABC";} else if(a>=1200&&a<2800){cout<<"ARC";} else {cout<<"AGC";} }
You are given a rooted tree with N vertices. The vertices are numbered 0, 1, ..., N-1. The root is Vertex 0, and the parent of Vertex i (i = 1, 2, ..., N-1) is Vertex p_i. Initially, an integer a_i is written in Vertex i. Here, (a_0, a_1, ..., a_{N-1}) is a permutation of (0, 1, ..., N-1). You can execute the followi...
#include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef complex<double> point; #define xx real() #define yy imag() #define REP(i, a, b) for(int i = (a); i < (int)(b); i++) #define REPN(i, a, b) for(int i ...
There are 2N balls in the xy-plane. The coordinates of the i-th of them is (x_i, y_i). Here, x_i and y_i are integers between 1 and N (inclusive) for all i, and no two balls occupy the same coordinates. In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B. Then, he placed the type-A r...
//little jump frog txdy #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #define rep(i,l,r) for(int i=(l);i<=(r);++i) #define per(i,r,l) for(int i=(r);i>=(l);--i) #define pb...
Let us consider the following operations on a string consisting of `A` and `B`: 1. Select a character in a string. If it is `A`, replace it with `BB`. If it is `B`, replace with `AA`. 2. Select a substring that is equal to either `AAA` or `BBB`, and delete it from the string. For example, if the first operation is ...
#include <bits/stdc++.h> using namespace std; const int N = (int) 1e5 + 5; char s[N], t[N]; int q; int sus[N], sut[N]; int main() { ios_base :: sync_with_stdio(false); cin.tie(NULL); cin >> s + 1; cin >> t + 1; int ls = strlen(s + 1), lt = strlen(t + 1); for (int i = 1; i <= ls; i++) sus[i] = sus[i - 1] + s[i] ...
Input The input is given from Standard Input in the following format: > $N \ K$ Output * Please output the $K$-th triangle area. * Print a floating number denoting the answer. The relative or absolute error of your answer should not be higher than $10^{−9}$. Constraints * $3 \le N \le 200,000$ * $1 \le K \le \...
#include <bits/stdc++.h> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; using lint=long long; const double PI=acos(-1); double SIN[200000]; double area(int i,int j){if(j-i<0) printf("!! i = %d, j = %d\n",i,j); return 2*SIN[i]*SIN[j]*SIN[j-i]; } int main(){ int n; lint k; scanf("%d%lld",&n,&k); r...
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system. We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as sho...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[][][] ink = { { {0,0,0,0,0}, {0,0,1,0,0}, {0,1,1,1,0}, {0,0,1,0,0}, {0,0,0,0,0} }, { {0,0,0,0,0}, {0,1,1,1,0}, {0,1,1,1,0}, ...
<image> Matryoshka is a wooden doll in the shape of a female figure and is a typical Russian folk craft. Matryoshka has a nested structure in which smaller dolls are contained inside a large doll, and is composed of multiple dolls of different sizes. In order to have such a nested structure, the body of each doll has ...
import java.util.*; public class Main{ void solve(){ Scanner sc = new Scanner(System.in); while(true){ int n = sc.nextInt(); if(n==0) break; ArrayList<int[]> hr = new ArrayList<int[]>(); for(int i=0; i<n; i++) hr.add(new int[]{...
A programming contest will be held at White Tiger University this year as well. There are several questions in the contest, each of which is assigned a score according to the difficulty level. The executive committee decided to calculate the score for each team based on the following rules, taking into account both th...
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <string> #include <sstream> #include <complex> #include <vector> #include <list> #include <queue> #include <deque> #include <stack> #include <map> #include <set> #include <iomanip> #define rep(i, n) for (int i = 0;...
There is a long-established secondhand bookstore called JOI secondhand bookstore in your town, and you often use the JOI secondhand bookstore. Each book has a standard price, and you can buy it at that price if you go to the JOI secondhand bookstore. At the JOI secondhand bookstore, books are classified into 10 genres...
#include<bits/stdc++.h> using namespace std; int main(){ int n,k,c,g; vector<int> book[11]; cin >> n >> k; for(int i=0;i<n;i++){ cin >> c >> g; book[g].push_back(c); } int dp[11][2001]={}; for(int i=1;i<=10;i++){ sort(book[i].begin(),book[i].end(),greater<int>()); for(int j=1;j<book[i].siz...
There are n wizards. They are numbered from 1 to n, and the i-th wizard has the magical power ri (1 ≤ i ≤ n). Now they are confronting a powerful wizard, whose enemy's magical power is S. n Wizards are good at fighting together, especially two people. When two wizards cooperate, the magical power is simply the sum, and...
#include <iostream> using namespace std; int main () { int n, s; while (cin >> n >> s, n || s) { int r[n]; for (int i = 0; i < n; i++) { cin >> r[i]; } int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (r[i] + r[j] > s) { count++; } } } cout << coun...
Following FIFA World Cup, a larger competition called ``GIGA Universe Cup'' is taking place somewhere in our universe. Both FIFA World Cup and GIGA Universe Cup are two rounds competitions that consist of the first round, also known as ``group league,'' and the second called ``final tournament.'' In the first round, pa...
#include <bits/stdc++.h> #define rep(i,n) for(int i = 0; i < n; i++) #define MAX_N 40 #define INF 1000000 #define MOD 1000000007 using namespace std; typedef long long ll; typedef pair<int,int> P; int p[4][4]; int pp[4][4]; int me; bool y[4]; int po[4], gd[4], go[4]; string str; int comp(int z){ if(po[me] > po[z]...
Example Input 8 8 1 2 1 3 2 4 2 5 2 8 3 5 3 6 4 7 1000 100 100 10 10 10 1 1 3 2 8 6 2 4 7 2 7 8 Output 1000 10 100
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <cassert> #include <cctype> #include <stack> #include <queue> using namespace std; typedef long long LL; const int N = 50005; const int M = 405; typedef unsigned long long ULL; int cnt, n; bool times; struct Bit...
Problem There is a puzzle game where you move curling stones and stack them exactly on the goal square. The detailed rules are as follows. The field consists of H × W squares, with stones placed in some squares at the beginning. There is only one goal square, and no stone is placed on the goal square from the beginni...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; bool solve(vector<string>ini_field,int gx,int gy) { set<vector<string>>memo; memo.emplace(ini_field); queue<vector<string>>que; que.push(ini_field); int dx[] = { -1,0,1,0 }; int dy[] = { 0,...
Some of you might have seen instruments like the figure below. <image> Figure 1: Spirograph There are a fixed circle (indicated by A in the figure) and a smaller interior circle with some pinholes (indicated by B). By putting a pen point through one of the pinholes and then rolling the circle B without slipping arou...
import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class Main { int INF = 1 << 28; int p, q, r; final int DIV = 1000000; double s, t; void run() { Scanner sc = new Scanner(System.in); for(;;) { p = sc.nextInt(); q = sc.nextInt(); r = sc.nextInt(); if( (p...
A video game company called ICPC (International Company for Playing and Competing) is now developing a new arcade game. The new game features a lot of branches. This makes the game enjoyable for everyone, since players can choose their routes in the game depending on their skills. Rookie players can choose an easy rout...
#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<(int)(n);++i) #define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i) #define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i) #define each(a,b) for(auto& (a): (b)) #define all(v) (v).begi...
Problem statement Mr. K, a student of the magic department of a certain university, lives in a vast mansion. There was a forest behind the mansion, but there were places where no trees were growing. I felt that it would look bad from the mansion as it was, so Mr. K decided to plant a tree in a place where no trees wer...
#include<iostream> #include<cstdio> using namespace std; int main(){ int h,w,imap[1010][1010],H[1010],W[1010]; for(int i=0;i<1010;i++)H[i] = W[i] = 0; cin >> h >> w; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> imap[i][j]; if(imap[i][j] == 0)H[i]++,W[j]++; } } for(int i=0;i...
Problem Statement You have a rectangular board with square cells arranged in $H$ rows and $W$ columns. The rows are numbered $1$ through $H$ from top to bottom, and the columns are numbered $1$ through $W$ from left to right. The cell at the row $i$ and the column $j$ is denoted by $(i, j)$. Each cell on the board is ...
#include <cmath> #include <cstdio> #include <cstring> #include <algorithm> const int MAXN = 555; const int MAXS = 101111; const int MAXH = 555; const int MAXL = 555; const long double eps = 1e-15; int n, m, cnt, c[MAXN], l[MAXS], graph[MAXN][MAXN]; char a[MAXN][MAXN], b[MAXN][MAXN]; namespace Gaussian_Elimination{ ...
Example Input 201 Output 701
/* -*- coding: utf-8 -*- * * 2728.cc: Change a Password */ #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<string> #include<vector> #include<map> #include<set> #include<stack> #include<list> #include<queue> #include<deque> #include<algorithm> #include<numeric> #incl...
Mr. Endo wanted to write the code that performs breadth-first search (BFS), which is a search algorithm to explore all vertices on a directed graph. An example of pseudo code of BFS is as follows: 1: $current \leftarrow \{start\_vertex\}$ 2: $visited \leftarrow current$ 3: while $visited \ne$ the set of all the verti...
#include<bits/stdc++.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define HUGE_NUM 99999999999999999 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; #define SIZE 505 int V,E; int root = 0; int POW[20],pow_max = 0; bool can_visit[20][SIZE][SIZE],chec...
Problem Gaccho has his favorite watch. One day the minute hand of the clock came off and I lost it somewhere. However, Gaccho wants to keep using the watch and wants to read the time with only the short hand. Output the time (hour h, minute m) for the information θ of the short hand. A clock is a so-called analog clo...
#include <cassert> #include <cctype> #include <cerrno> #include <cfloat> #include <ciso646> #include <climits> #include <clocale> #include <cmath> #include <csetjmp> #include <csignal> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <ccomplex> #in...
You want to make change for $ n $ cents. Assuming that you have infinite supply of coins of 1, 5, 10 and / or 25 cents coins respectively, find the minimum number of coins you need. Constraints * $ 1 \ le n \ le 10 ^ 9 $ Input $ n $ The integer $ n $ is given in a line. output Print the minimum number of coins...
#include <iostream> using namespace std; int main() { int n; cin >> n; int r = n; const int c25 = r / 25; r -= 25 * c25; const int c10 = r / 10; r -= 10 * c10; const int c5 = r / 5; r -= 5 * c5; cout << c25 + c10 + c5 + r << endl; }
Write a program which reads two integers a and b, and calculates the following values: * a ÷ b: d (in integer) * remainder of a ÷ b: r (in integer) * a ÷ b: f (in real number) Constraints * 1 ≤ a, b ≤ 109 Input Two integers a and b are given in a line. Output Print d, r and f separated by a space in a line. For ...
a,b=map(int,raw_input().split()) print "%d %d %.8f"%(a/b,a%b,float(a)/b)
Virat Kohli and Rohit Sharma are warming up for the World Cup at the Brisbane Cricket Ground, commonly known as "The Gabba". Their coach has asked them to go to the ground at the crack of dawn, and then jog around the stadium in laps. The Cricket Ground has poles spaced equally apart and numbered sequentially from 1 to...
# your code goes here i_num = int(raw_input()) Nvar, Mvar = 0,0 def step_calc(pos_var, step): pos_var += step if pos_var <= Mvar: return pos_var pos_var -= Mvar return Mvar + (pos_var%(Nvar - Mvar + 1)) for i_var in xrange(i_num): i_line = raw_input().split(' ') i_line = [int(item) for item in i_line] ...
Chef is studying Rotational Motion in physics. Here is preparing for Engineering Entrance exam. He's stuck in a problem. Which states that "Two fans, each with a single blade are rotating one above the other, about the same axis of rotation and both blades have the same length. Consider the blade as a rod. Both the fan...
problem='https://www.codechef.com/problems/CHFANS' __author__='Ravindra Singh' def gcd(a,b): if a%b==0: return b else: return gcd(b,a%b) T=int(raw_input()) for i in range(T): a,b=map(int,raw_input().split()) if a>b: print abs(abs((a-b))//gcd(a,b)) else: print abs(ab...
You are given a permutation A of the first N positive integers. You are also given Q queries to perform one-by-one, the i-th is defined by a pair Xi Yi and has the meaning that you swap the Xi-th number in the permutation with the Yi-th one. After performing each query you should output the number of inversions in the ...
def SortCount(A): l = len(A) if l > 1: n = l//2 C = A[:n] D = A[n:] C, c = SortCount(A[:n]) D, d = SortCount(A[n:]) B, b = MergeCount(C,D) return B, b+c+d else: return A, 0 def MergeCount(A,B): count = 0 M = [] i=0 j=0 while i<len(A) and j<len(B)...
Liliputs are holding a drawing competition for K kids, but with K human-sized pencils stolen from humans. In order to make life easier for the kids, the organizers want to give a pencil to each kid in a way such that the sum of the absolute differences of the height of a kid and the length of the pencil assigned to him...
for num in range(input()): n =input() arr1 = map(int,raw_input().split()) arr1.sort() arr2 = map(int,raw_input().split()) arr2.sort() m=0 for i in range(n): m+=abs(arr1[i]-arr2[i]) # m=min(m,abs(arr1[i]-arr2[i])) print "Case "+str(num+1)+": "+str(m)
Leha is playing a very interesting game. The game will be played on a rectangular grid consisting of N rows and M columns. Initially all the cells of the grid are uncolored. Leha's initial score is zero. At each turn, he chooses some cell that is yet not colored, and colors that cell. The score obtained in this step w...
T=int(raw_input()) while T: n,m=map(int,raw_input().split()) ans = 2*n*m-n-m print(ans) T-=1
A number is called palindromic if its decimal representation is a palindrome. You are given a range, described by a pair of integers L and R. Find the sum of all palindromic numbers lying in the range [L, R], inclusive of both the extrema. Input The first line of the input contains an integer T denoting the number of ...
for tests in xrange(int(raw_input())): a, z = map(int, raw_input().split()) str_range = map(str, xrange(a, z + 1)) print sum([int(str_num) for str_num in str_range if str_num == str_num[::-1]])
You are given a permutation p_1, p_2, ..., p_n. A permutation of length n is a sequence such that each integer between 1 and n occurs exactly once in the sequence. Find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m. The ...
import java.io.*; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; public class Main { static long mod=(long)(1e+9) + 7; static int[] sieve; stat...
You are given n segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. The intersection of a sequence of segments is such a maximal set of points (not necesserily having...
#include <bits/stdc++.h> using namespace std; struct re { long long x, y; }; re r[300005]; re f[300005], b[300005]; re ti(re a, re b) { re c; c.x = max(a.x, b.x); c.y = min(a.y, b.y); return c; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; int n; cin >> n; int i; for ...
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to ...
import java.util.Scanner; public class P103A { public static void main(String[] args) { Scanner inScanner = new Scanner(System.in); int n = inScanner.nextInt(); long sum = 0; for (long i = 0; i < n; i++) sum += (i + 1) * inScanner.nextLong() - i; System.out.prin...
You are given an array a of length n that consists of zeros and ones. You can perform the following operation multiple times. The operation consists of two steps: 1. Choose three integers 1 ≤ x < y < z ≤ n, that form an arithmetic progression (y - x = z - y). 2. Flip the values a_x, a_y, a_z (i.e. change 1 to 0...
#include <bits/stdc++.h> using namespace std; const int maxn = 100010; int n; int a[maxn]; struct Ans { int x, y, z; } ans[maxn]; int nnm; int que[maxn]; void fan(int x, int y, int z) { if (x > z) swap(x, z); nnm++; ans[nnm].x = x; ans[nnm].y = y; ans[nnm].z = z; a[x] ^= 1; a[y] ^= 1; a[z] ^= 1; } int...
You are given two permutations a and b, both consisting of n elements. Permutation of n elements is such a integer sequence that each value from 1 to n appears exactly once in it. You are asked to perform two types of queries with them: * 1~l_a~r_a~l_b~r_b — calculate the number of values which appear in both segme...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target("sse4.2,sse4.1,ssse3,sse3,sse2,sse") #pragma GCC target("avx") #pragma GCC target("avx2") using namespace std; const int maxn = (int)2e5; alignas(32) int a[maxn]; alignas(32) int b[maxn]; alignas(32) int posA[maxn]; alignas(32) int posB[maxn]; al...
Fedya and Sasha are friends, that's why Sasha knows everything about Fedya. Fedya keeps his patience in an infinitely large bowl. But, unlike the bowl, Fedya's patience isn't infinite, that is why let v be the number of liters of Fedya's patience, and, as soon as v becomes equal to 0, the bowl will burst immediately. ...
#include <bits/stdc++.h> using namespace std; mt19937 gen(200); struct node { pair<int, int> f, s; node *le, *ri; long long mn, res; int tl, tr; node() { mn = 228; } node(int l, int r) { tl = l; tr = r; mn = 228; if (l == r) return; le = new node(l, (l + r) / 2); ri = new node((l + r...
Treeland consists of n cities and n-1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree. There are some private road companies in Treeland. The government decided to sell roads to t...
import java.util.*; import java.lang.*; import java.io.*; import java.awt.*; // U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................ //JUst keep faith in ur strengths .................................................. // ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 ...
You are given two n × m matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; int a[n][m], b[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> a[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> b[i][j]; } } for (int i...
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4. ...
def fun(x): s=0 org=x while(x): s+=x%10 x=x//10 temp=s%4 if temp : org+=1 return fun(org) else : return org x=int(input()) print(fun(x))
Gildong is playing a video game called Block Adventure. In Block Adventure, there are n columns of blocks in a row, and the columns are numbered from 1 to n. All blocks have equal heights. The height of the i-th column is represented as h_i, which is the number of blocks stacked in the i-th column. Gildong plays the g...
t = int(input()) for _ in range(t): n, m, k = map(int, input().split()) h = list(map(int, input().split())) for i in range(n - 1): m += h[i] - max(0, (h[i + 1] - k)) if m < 0: print("NO") break if(m >= 0): print("YES")
In the galaxy far far away is the ancient interplanetary republic of Bubbleland, consisting of N planets. Between them, there are M bidirectional wormholes, each connecting a pair of planets. Bubbleland is a very centralized republic, having a capital planet Whiteplanet, from which any another planet can be reached usi...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int mod1 = 998244353; const int N = 1 << 17; int weight[N], in[N], parent[N]; vector<pair<int, int> > edge[N]; int a[N], b[N], c[N], d[N]; long long qpow(long long a, long long b, long long mod) { long long res = 1; while (b) { if (b &...
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit...
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Random; import java.io.PrintWriter; /* Solution Created: 04:36:52 14/11/2019 Custom Compet...
This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily...
#include <bits/stdc++.h> using namespace std; bool cmp(pair<int, int> a, pair<int, int> b) { return (a.first > b.first || (a.first == b.first && a.second < b.second)); } int main() { int n; cin >> n; vector<int> a(n); vector<pair<int, int> > c; for (int i = 0; i < n; i++) { cin >> a[i]; c.push_back(...
There are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself. For each friend the value f_i is known: it is either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import javax.swing.JInternalFrame; public class Main { public static void main(String[] args) throws IOException { S...
Let's call a graph with n vertices, each of which has it's own point A_i = (x_i, y_i) with integer coordinates, a planar tree if: * All points A_1, A_2, …, A_n are different and no three points lie on the same line. * The graph is a tree, i.e. there are exactly n-1 edges there exists a path between any pair of ve...
#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...
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem. You are given an array a of n integers (the given array can contain equal elements). You can perform the following operations on array element...
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 7; int T; int n, a[MAXN], f[MAXN][3], vis[MAXN]; vector<int> v; inline int getid(int x) { return lower_bound(v.begin(), v.end(), x) - v.begin() + 1; } inline void solve() { sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); ...
You are given an array a_1, a_2, ..., a_n, consisting of n positive integers. Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves: 1. move right — go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n. 2. mo...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { long long n, k, z; cin >> n >> k >> z; long long a[n + 7]; for (int i = 0; i < n; i++) cin >> a[i]; long long ans = 0; for (int i = 0; i <= (z); i++) { long long r = (k - (2 * i)), sum = 0, mx =...
There are n points on a plane. The i-th point has coordinates (x_i, y_i). You have two horizontal platforms, both of length k. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same y-coordinate) and have integer borders. If the left border of the platform is (x, y) then the r...
from bisect import bisect,bisect_left for _ in range(int(input())): n,k=map(int,input().split()) x=list(map(int,input().split())) y=input() x.sort() a=[] b=[] i=0 while i<n: b.append(bisect(x,x[i]+k)-i) a.append(i-bisect_left(x,x[i]-k)+1) i+=1 b.reverse() ...
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead. You should perform the given operation n - 1 times and make the resulting number that will be left on the board as s...
import java.util.Scanner; import java.util.Arrays; import java.util.ArrayList; public class contest11103{ static Scanner scan = new Scanner(System.in); static long ceil(long x, long y){ if((x+y)%2==0){ return (x+y)/2; }else{ return (x+y)/2+(long)1; } } static int t = scan.nextInt(); public static void ...
Gildong is playing with his dog, Badugi. They're at a park that has n intersections and n-1 bidirectional roads, each 1 meter in length and connecting two intersections with each other. The intersections are numbered from 1 to n, and for every a and b (1 ≤ a, b ≤ n), it is possible to get to the b-th intersection from ...
#include<bits/stdc++.h> #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> #include<stack> #include<queue> #define INF 0x3f3f3f3f #define lowbit(x) x & -x #define lson root<<1,l,mid #define rson root<<1|1,mid+1,r using namespace std; typedef long long ll; const int mod=1e9+7; con...
Nezzar loves the game osu!. osu! is played on beatmaps, which can be seen as an array consisting of distinct points on a plane. A beatmap is called nice if for any three consecutive points A,B,C listed in order, the angle between these three points, centered at B, is strictly less than 90 degrees. <image> Points A,B,...
#include<bits/stdc++.h> #define pb push_back #define fi first #define se second #define all(v) (v).begin(), (v).end() using namespace std; typedef long long LL; typedef pair<int, int> pii; typedef pair<LL, LL> pil; const int MAX_N = 5005; const LL MOD = 1000000007LL; const int inf = 0x3fffffff; int n; bool chk[MAX_N]; ...
A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu. There is a string s. You must insert exactly one character 'a' somewhere in s. If it is poss...
def par(s): n = len(s) for i in range(n // 2): if s[i] != s[n - 1 - i]: return False return True def solve(s): if not par('a' + s): return 'YES\n' + 'a' + s if not par(s + 'a'): return 'YES\n' + s + 'a' return 'NO' t = int(input()) while t > 0: s = input() print(solve(s)) t -= 1
You are given an array a of n integers. Define the cost of some array t as follows: $$$cost(t) = ∑_{x ∈ set(t) } last(x) - first(x),$$$ where set(t) is the set of all values in t without repetitions, first(x), and last(x) are the indices of the first and last occurrence of x in t, respectively. In other words, we co...
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef double db; typedef pair<int, int> pii; typedef vector<int> vi; #define fi first #define se second #define mp make_pair #define pb push_back #define sz(x) ((int)(x.size())) #define all(x) (x).begin(), (x).end() #define rep(i, l, r) for(int i = (...
You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string. In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 ≤ a ≤ b < x ≤ y ≤ |s| and substrings s[a... b], s[x... y] are palindromes. A pal...
#include <bits/stdc++.h> using namespace std; string str; long long ans[2001], sum[2001], temp, pal[2001][2001], n; int main() { ios_base::sync_with_stdio(false); cin >> str; n = str.size(); for (int i = 0; i < n; i++) for (int j = 0; j < n - i; j++) { int x = j; int y = j + i; if (x == y)...
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem. You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the ...
import java.util.*; import java.io.*; public class Solution { FastScanner in; PrintWriter out; int N; int circles = 0; int boxes = 0; int [][] a; boolean [][] was; class point { int x; int y; point(int x, int y) { this.x = x; this.y = y; } } boolean ok (int x, int y) { if (x < 0 || x >...
A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!". The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west ...
#include <bits/stdc++.h> using namespace std; int fast_input(void) { int x = 0; char ch; ch = getchar(); while (ch < '0' && ch > '9') { ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x + x + x + x + x + x + x + x + x + x + ch - '0'; ch = getchar(); } return x; } int X[2], n[2], line[...
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!). The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the...
import java.io.*; import java.util.*; public class Test { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken(...
You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of N rows and M columns of cells. The robot is initially at some cell on the i-th row and the j-th column. Then at every step the robot c...
import java.io.BufferedReader; import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputStream inputStream = System.i...
Imagine an n × m grid with some blocked cells. The top left cell in the grid has coordinates (1, 1) and the bottom right cell has coordinates (n, m). There are k blocked cells in the grid and others are empty. You flash a laser beam from the center of an empty cell (xs, ys) in one of the diagonal directions (i.e. north...
#include <bits/stdc++.h> using namespace std; int a1234; char buf[1 << 18], *bufs = buf, *buft = buf; inline int gc() { return bufs == buft && (buft = (bufs = buf) + fread(buf, 1, 1 << 18, stdin)), bufs == buft ? -1 : *bufs++; } inline void xxx() { for (;;) ; } inline int rd(int l, int r) { return rand...
The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y). * If the wind blows to the east, the boat will move to (x + 1, y). ...
#include <bits/stdc++.h> const int maxn = 100005; using namespace std; char c[maxn]; int main() { int n, x, y, x1, y1, i; while (scanf("%d", &n) != EOF) { int flag = 0; int sum = 0; scanf("%d%d%d%d", &x, &y, &x1, &y1); scanf("%s", c); for (i = 0; c[i] != '\0'; i++) { if (c[i] == 'E') { ...
Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a1, a2, ..., an. They bought a chain saw from a shop. Each time they use the chain saw on the tree...
#include <bits/stdc++.h> using namespace std; const long long maxL = 20; long long mod = 1e9 + 7; long long mod1 = 1e9 + 7; long long inf = 1e12; long long linf = 1e18; const long long maxn = 1e5 + 100; const long long maxk = 210; const long long baze = 330; vector<pair<long long, long long> > vc; long long n, a[maxn],...
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually. After the contest was over, Valera ...
import math scann=input() numbers=scann.split() s=int(numbers[0]) s2=int(numbers[1]) min1=int(numbers[2]) max1=int(numbers[3]) total=int(numbers[4]) s2mp=int(numbers[5]) div=int(s2mp/s2) mod=s2mp%s2 students=[] for i in range(mod): students.append(div +1) #intentarlo solo con piso iter1=s2-mod for j in range(iter1...
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points. Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined,...
#include <bits/stdc++.h> using namespace std; const double eps = 1.0e-11; const double pi = acos(-1.0); const int INF = 1000000000; const int N = 110; vector<pair<int, int> > pe; int dp[N][N][N]; int n, k; int solve(int pt) { if (pt > n) return INF; for (long long i = 0; i < N; i++) for (long long j = 0; j < N;...
The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke. R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges mes...
#include <bits/stdc++.h> using namespace std; int main() { int a[20010][12]; int per[20010], chat[12]; int i, n, m, k, j, c, p; cin >> n >> m >> k; memset(per, 0, sizeof(per)); memset(chat, 0, sizeof(chat)); for (i = 1; i <= n; ++i) for (j = 1; j <= m; ++j) cin >> a[i][j]; for (i = 1; i <= k; ++i) {...
The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited ever...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; if (n == 1 && m == 2) { cout << 0 << "\n" << 1 << ' ' << 1 << "\n" << 1 << ' ' << 2 << "\n" << 1 << " " << 1; } else if (n == 2 && m == 1) { cout << 0 << "\n" << 1 << ' ' << 1 << "\n" ...
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him? Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of th...
n = int(raw_input()) a = [] for i in range(0,n+2): a.append([]); if i==0 or i==n+1: for j in range(0, n+2): a[i].append(0) if i!=0 and i!=n+1: line = raw_input() a[i].append(0) for c in line: if c == 'x': a[i].append(0) els...
How many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: d-sorting. This sorting is applied to the strings of length at least d, where d is some positive integer. The characters of the string are so...
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchEx...
When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title. Let's d...
#include <bits/stdc++.h> using namespace std; string s; long long int cnt[500005]; double avg = 0.0; bool check(char c) { if (c == 'I' || c == 'E' || c == 'A' || c == 'O' || c == 'U' || c == 'Y') return true; return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> s; int n = in...
An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sur...
n = int(input()) if n ==1: print(1) print(1) else: odd = [int(k) for k in range(n+1) if k % 2 != 0] odd.reverse() even = [int(k) for k in range(1,n+1) if k % 2 == 0] even.reverse() odd_len = len(odd) #even.reverse() if abs(odd[odd_len-1]-even[0]) == 1: even = even[1:] nu...
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it. ...
import java.util.*; public class sd { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int[] h = new int[6]; for(int i=0;i<6;i++){ h[i] = in.nextInt(); } int t=0,s=0; s = h[1] ...
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes. More formally, you are given an odd numer n. Find a set of numbers pi (1 ≤ i ≤ k), such that 1. 1 ≤ k ≤ 3 2. ...
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; import java.util.concurrent.ArrayBlockingQueue; public class Main { Scanner sc = new Scanner(System.in); public static void main(String[] args) { new Main(); ...
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following defin...
#include <bits/stdc++.h> using namespace std; const int MAXn = 100 * 1000; pair<pair<int, int>, int> w[MAXn + 5]; pair<int, int> ans[MAXn + 5]; int last[MAXn + 5]; bool cmp(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) { if (a.first.first < b.first.first) return true; else if (a.first.first == b.fir...
Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else. For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic...
#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 int read() { int x = 0; char ch = getchar(); bool positive = 1; for ...
Johnny is playing a well-known computer game. The game are in some country, where the player can freely travel, pass quests and gain an experience. In that country there are n islands and m bridges between them, so you can travel from any island to any other. In the middle of some bridges are lying ancient powerful ar...
#include <bits/stdc++.h> using namespace std; const int inf = 1e9; const int MOD = 1e9 + 7; const int N = 3e5 + 10; int n, m, st, en, w[N], v[N][2]; vector<int> e[N]; vector<pair<int, int> > v2[N]; int low[N], num[N], t[N], br[N]; queue<int> q; int good[N], t2[N]; void prepare() { scanf("%d%d", &n, &m); int x, y; ...
Little Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern. An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a a...
import math n, red, blue, red_cost, blue_cost = map(int, input().split()) reds = n//red - n//((red*blue)//math.gcd(red,blue)) blues = n//blue - n//((red*blue)//math.gcd(red,blue)) ans = reds*red_cost + blues*blue_cost + max(blue_cost, red_cost)*(n//((red*blue)//math.gcd(red,blue))) print(int(ans))
Again, there are hard times in Berland! Many towns have such tensions that even civil war is possible. There are n towns in Reberland, some pairs of which connected by two-way roads. It is not guaranteed that it is possible to reach one town from any other town using these roads. Towns s and t announce the final br...
#include <bits/stdc++.h> using namespace std; const int N = 1010, M = 30010; vector<pair<int, int> > g[N]; int cost[M]; int disc[N], low[N]; int p[N]; int n, m; int s, t; int asfasdf; int reach_t[N]; int traversed[M]; const int oo = 0x3f3f3f3f; int ret; int retb; void tarjan(int u, int ign) { disc[u] = low[u] = asfas...
Unfortunately, the formal description of the task turned out to be too long, so here is the legend. Research rover finally reached the surface of Mars and is ready to complete its mission. Unfortunately, due to the mistake in the navigation system design, the rover is located in the wrong place. The rover will operat...
#include <bits/stdc++.h> #pragma GCC optimize(3, "Ofast", "inline") #pragma GCC target("avx,avx2") using namespace std; template <class t> inline t read(t &x) { char c = getchar(); bool f = 0; x = 0; while (!isdigit(c)) f |= c == '-', c = getchar(); while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = g...
One day, Hongcow goes to the store and sees a brand new deck of n special cards. Each individual card is either red or blue. He decides he wants to buy them immediately. To do this, he needs to play a game with the owner of the store. This game takes some number of turns to complete. On a turn, Hongcow may do one of t...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); int N; cin >> N; vector<bool> color(N); vector<int> r(N), b(N); for (int i = 0; i < N; i++) { string t; cin >> t >> r[i] >> b[i]; color[i] ...
Student Arseny likes to plan his life for n days ahead. He visits a canteen every day and he has already decided what he will order in each of the following n days. Prices in the canteen do not change and that means Arseny will spend ci rubles during the i-th day. There are 1-ruble coins and 100-ruble notes in circula...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n, m, c[N], w[N]; pair<int, int> ans[N]; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); cin >> n >> m; for (int i = 0; i < n; i++) cin >> c[i]; for (int i = 0; i < n; i++) cin >> w[i]; set<pair<int, int> > s; long ...
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any verte...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class C implements Runnable { List<Integer>[] r; long[][] down; int ...
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane...
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); //String test = "A-large-practice"; //ConsoleIO io = new ConsoleIO(new...
You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisib...
#include <bits/stdc++.h> using namespace std; const int M = 2505; char S[M][M]; int n, m, sum[M][M]; int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) scanf("%s", S[i] + 1); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) sum[i][j] = (S[i][j] == '1') + sum[i][j - 1]; for (int j...
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct. There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for whi...
#include <bits/stdc++.h> using namespace std; const long long int N = 1e6 + 2, inf = 1e9 + 7; void _run(); void no() { cout << "-1\n", exit(0); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); _run(); return 0; } string rs[N]; void _run() { int n; cin >> n; string s[n + 1]; for (int i = 1; i <= ...