input
stringlengths
29
13k
output
stringlengths
9
73.4k
You will be given an integer a and a string s consisting of lowercase English letters as input. Write a program that prints s if a is not less than 3200 and prints `red` if a is less than 3200. Constraints * 2800 \leq a < 5000 * s is a string of length between 1 and 10 (inclusive). * Each character of s is a lowerca...
a,s = int(input()),input() print(s if a>=3200 else "red")
There are N stones arranged in a row. Every stone is painted white or black. A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is `.`, and the stone is black if the character is `#`. Takahashi wants to change the colors of some stones to black or white so t...
#include "bits/stdc++.h" using namespace std; int main() { int N; string S; cin >> N >> S; int cnt1 = 0, cnt2 = 0; for (int i = 0; i < N; i++) { if (S[i] == '.') cnt2++; } int ans = cnt2; for (int i = 0; i < N; i++) { if (S[i] == '#') cnt1++; else cnt2--; ...
You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there? Here, a Shichi-Go-San number is a positive integer that satisfies the following condition: * When the number is written in base ten, each of the digits `7`, `5` ...
import java.util.*; import java.util.Map.Entry; class Main { // static int mod = (int) (Math.pow(10,9)+7); static int mod = 2019; static List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); public static void main(String[] args) { Scanner sc = new Scanner(System...
We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j). Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, ...
#include <iostream> using namespace std; int h, w, fl=1, a[55][55]; string s; int main() { int i, j; cin>>h>>w; for(i=1; i<=h; i++) { cin>>s; for(j=1; j<=w; j++) a[i][j] = s[j-1]=='.' ? 0:1; } for(i=1; i<=h; i++) for(j=1; j<=w; j++) { if(a[i][j]==1 && a[i-1][j] + a[i+1][j] + a[i][j-1] + a[i][j+1] == 0) fl=0;...
You are given two sequences a and b, both of length 2N. The i-th elements in a and b are a_i and b_i, respectively. Using these sequences, Snuke is doing the job of calculating the beauty of pairs of balanced sequences of parentheses (defined below) of length 2N. The beauty of a pair (s,t) is calculated as follows: * ...
#include<bits/stdc++.h> using namespace std; #define int long long #define rep(i,n) for(int i=0;i<(n);i++) #define pb push_back #define all(v) (v).begin(),(v).end() #define fi first #define se second typedef vector<int>vint; typedef pair<int,int>pint; typedef vector<pint>vpint; template<typename A,typename B>inline ...
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of road...
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float...
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b...
#include <iostream> #include <string.h> #include <algorithm> #include <vector> #include <queue> using namespace std; typedef long long ll; const int INF=1000000; int main() { int dp[101][101]={}; for(int i=0;i<101;++i){ for(int j=0;j<101;++j){ dp[i][j]=INF; } } int n,m,a[1001],b[1001],c[1001]; cin>>n>>m; ...
Alice, Bob and Charlie are playing Card Game for Three, as below: * At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the d...
#include<bits/stdc++.h> using namespace std ; #define Next( i, x ) for( register int i = head[x]; i; i = e[i].next ) #define rep( i, s, t ) for( register int i = (s); i <= (t); ++ i ) #define drep( i, s, t ) for( register int i = (t); i >= (s); -- i ) #define re register #define int long long int gi() { char cc = getc...
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami p...
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <complex> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(...
A set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number. Of the four prime numbers that make up a quadruplet prime, the largest number is called the size of the quadruplet prime. For example, the smallest prime quadruplet is a set of (5, 7, 11, 13), which is 13 in size. Th...
#include <cstdio> int prim[10000000]; int main() { int n, i, j; for( i = 2; i < 10000000 / 2; i++ ){ for( j = 2; j < 10000000 / 2; j++ ){ if( i * j > 10000000 || prim[i] == 1 ) break; prim[i*j] = 1; } } while( 1 ){ scanf( "%d", &n ); if( n == 0 ) break; for( i = n; n >= 0; i-- ){ ...
Bob is playing a game called "Dungeon 2" which is the sequel to the popular "Dungeon" released last year. The game is played on a map consisting of $N$ rooms and $N-1$ roads connecting them. The roads allow bidirectional traffic and the player can start his tour from any room and reach any other room by way of multiple...
#include "bits/stdc++.h" #pragma warning(disable:4996) using namespace std; using ld = long double; ld eps=1e-9; int answer=-1e9; vector<int> dfs(const vector<vector<int>>&edges, const vector<int>&scores, const int now, const int from) { vector<int>ans(3,-1e9); ans[0]=scores[now]; for (auto e : edges[now]) { ...
The Aizu Wakamatsu city office decided to lay a hot water pipeline covering the whole area of the city to heat houses. The pipeline starts from some hot springs and connects every district in the city. The pipeline can fork at a hot spring or a district, but no cycle is allowed. The city office wants to minimize the le...
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception{ BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String line; while(true){ /* input from here */ line = r.readLine(); //s: num of hot springs, d: num of districts ...
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively. Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+...
#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...
Despite urging requests of the townspeople, the municipal office cannot afford to improve many of the apparently deficient city amenities under this recession. The city swimming pool is one of the typical examples. It has only two swimming lanes. The Municipal Fitness Agency, under this circumstances, settled usage rul...
#include <iostream> #include <algorithm> #include <vector> #include <map> #include <cmath> using namespace std; const int N = 50; const double EPS = 1e-8; int n; vector<pair<double, int> > data; bool equals(double a, double b){ return abs(a - b) < EPS; } int solve(){ pair<double, double> dist[N]; int round[N],...
Problem Create a program that performs the following types of operations on an n × n matrix whose elements are 1 and 0. <image> Given the submatrix and the angle (0,90,180,270,360), rotate it clockwise by that amount. <image> Since a submatrix is ​​given, the values ​​are inverted. <image> Since a line is given, shif...
#include <iostream> #include <string> #include <vector> #include <cstring> #include <climits> #include <algorithm> #include <map> #include <queue> #include <cassert> using namespace std; int arr[15][15]; int t[15][15]; int main() { int n, m; cin >> n >> m; for (int i=0; i<n; ++i) { for (int j=0; j<n; ++j) { a...
Surrounding Area Land fence English text is not available in this practice contest. Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passen...
#include <bits/stdc++.h> #define rep(i,n) for(int i=0;i<n;++i) #define rep1(i,n) for(int i=1;i<=n;++i) using namespace std; int a[52][52]={}; int dx[4]={0,0,-1,1}; int dy[4]={-1,1,0,0}; int h,w; //color 0=. 1=B -1=W 2=b -2=w 10=* void paint(int y,int x,int color){ if((fabs(a[y][x])!=2 && a[y][x]!=0) || a[y][x]==c...
Some of you know an old story of Voronoi Island. There were N liege lords and they are always involved in territorial disputes. The residents of the island were despaired of the disputes. One day, a clever lord proposed to stop the disputes and divide the island fairly. His idea was to divide the island such that any ...
#include <bits/stdc++.h> using namespace std; #define int long long #define FR first #define SC second #define all(v) (v).begin(), (v).end() #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define reps(i, f, n) for(int i = (int)(f); i < (int)(n); i++) #define each(a, b) for(auto& a : b) typedef pair<int, int> P;...
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea. However, many of my friends are shy. They would hate it if they knew that too many people would come with them. Besides, many of my friends want to stand out. They will probably hate it if they know tha...
// AOJ 2331 import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] m = new int[100001]; for(int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); ...
Problem G: Nezumi's Treasure There were a mouse and a cat living in a field. The mouse stole a dried fish the cat had loved. The theft was found soon later. The mouse started running as chased by the cat for the dried fish. There were a number of rectangular obstacles in the field. The mouse always went straight ahea...
#include<queue> #include<cstdio> #include<algorithm> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; const int INF=1<<29; struct point{ int x,y; point(){} point(int x,int y):x(x),y(y){} bool operator==(const point &a)const{ return x==a.x && y==a.y; } }; bool cmp_point_1(const point &a,const point &...
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days. He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your h...
#include <iostream> #include <fstream> #include <cassert> #include <typeinfo> #include <vector> #include <stack> #include <cmath> #include <set> #include <map> #include <string> #include <algorithm> #include <cstdio> #include <queue> #include <iomanip> #include <cctype> #include <random> #include <time.h> #define syosu...
This issue is the same configuration issue as G: DAG Trio (Hard), with only the constraints being different. input $ N \ M $ $ a_1 \ b_1 $ $ a_2 \ b_2 $ $ \ vdots $ $ a_M \ b_M $ output Print "YES" or "NO" on the $ 1 $ line. Example Input 3 3 1 2 2 3 3 1 Output YES
#include<bits/stdc++.h> using namespace std; #define int long long 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 reps(i,f,n) for(int i=(f);i<(n);i++) #define all(v) (v).begin(),(v).end() #define each(it,v) for(__typeof((v).begin()) it=(v)...
B: Parentheses Number problem Define the correct parenthesis string as follows: * The empty string is the correct parenthesis string * For the correct parenthesis string S, `(` S `)` is the correct parenthesis string * For correct parentheses S, T ST is the correct parentheses Here, the permutations are associate...
/* -*- coding: utf-8 -*- * * 2931.cc: */ #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> #include<utility> #inc...
Problem Define a function $ f $ that starts with $ 1 $ and takes a sequence of finite lengths as an argument as follows. $ \ displaystyle f (\\ {a_1, a_2, \ ldots, a_n \\}) = \ sum_ {i = 1} ^ n {a_i} ^ i $ Given a sequence of length $ N $, $ X = \\ {x_1, x_2, \ ldots, x_N \\} $, $ f (X) for all subsequences $ X'$ ex...
#include <bits/stdc++.h> using namespace std; using ll = long long; const int mod = 998244353; const int inf = (1 << 30) - 1; const ll infll = (1LL << 61) - 1; #define fast() cin.tie(0), ios::sync_with_stdio(false) using ll = long long; ll mod_pow(ll x, ll n, ll mod) { ll res = 1; while(n > 0) { if(n & 1) (res...
For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A. An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik. Constraints * 1 ≤ n ≤ 100000 * 0 ≤ ai ≤ 109 Input n a0 a1 : ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MOD = 1e9 + 7; const int inf = 1e9; const ll INF = 1e18; const double pi = 3.14159265358979323846; int main(){ int n;cin>>n; int a[n];for(int i=0;i<n;i++) cin>>a[i]; int dp[n];fill(dp,dp+n,inf); for(int i=0;i<n;i++){ *lower_bound(dp,d...
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that multiple elements can have equivalent keys. * insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. * get($key$): Print all values with th...
# -*- coding: utf-8 -*- """ Dictionary - Multi-Map http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP2_8_D&lang=jp """ from bisect import insort, bisect_right, bisect_left class Multi_map: def __init__(self): self.mm = dict() self.lr = [] def insert(self, x, y): if x in self...
Problem description. In Bytelandian University, everyone has to enter his/her name on a computer when entering or leaving the library. The names are stored in a file on that computer. Assume that everyone adheres to this rule. Given the file, find out how many people are there in the library. There will not be spaces i...
for _ in xrange(int(input())): n=int(input()) dic={} for i in xrange(n): s=raw_input() if s not in dic: dic[s]=1 else: dic[s]+=1 count=0 for i in dic: if(dic[i]%2!=0): count+=1 print count
Chef loves to play games. Now he plays very interesting game called "Segment". At the beginning Chef has segment [0, X] and no points on it. On each step Chef chooses the subsegment of maximal length possible such as it contains no points on it. If there are more than one such subsegment Chef chooses the one with the m...
import math; t=int(input()); while t>0: t=t-1; inp=raw_input(); x=int(inp.split()[0]); k=int(inp.split()[1]); roun=int(math.log(k,2))+1; deno=pow(2,roun-1); points=0; if roun==1: points=0; else: points=pow(2,roun-1)-1; pos=k-points; print format(((x*1.0)/(deno*1.0))*(pos-1)+(1.0*x)/(2.0*deno),'0.30f');
There are N doors of a palace, all of which are operated by a set of buttons. One day, Alice, who is just 8 years old, gets access to these buttons. Having recently learnt the multiplication tables, she decides to press buttons in a particular order. First, she presses all the buttons that are multiples of 1. Next, she...
t=int(raw_input()) for i in xrange(t): n=int(raw_input()) print int(n**0.5)
Johnny needs to make a rectangular box for his physics class project. He has bought P cm of wire and S cm^2 of special paper. He would like to use all the wire (for the 12 edges) and paper (for the 6 sides) to make the box. What is the largest volume of the box that Johnny can make? Input The first line contains t, th...
#!/usr/bin/python import math def main(): num_times = int(raw_input()) for i in xrange(0, num_times): P, S = map(int, raw_input().split()) l1 = ((P/2) + math.sqrt(math.pow(P/2, 2) - 6*S))/6 l2 = ((P/2) - math.sqrt(math.pow(P/2, 2) - 6*S))/6 h1 = P/4 - 2*l1 h2 = P/4 - 2*...
You have N (3 ≤ N ≤ 2,000) wooden sticks, which are labeled from 1 to N. The i-th stick has a length of Li (1 ≤ Li ≤ 1,000,000). Your friend has challenged you to a simple game: you will pick three sticks at random, and if your friend can form a triangle with them (degenerate triangles included), he wins; otherwise, yo...
def sum_pair_less_than(v, S): i,j,pair_count = 0,len(v)-1,0 while i < j: if v[i]+v[j] < S : pair_count += j-i i+=1 else: j-=1 return pair_count def not_a_triangle_count(v): non_tri_count = 0 v.sort() i=len(v)-1 while i >= 2 : non_tri_count += sum_pair_less_than(v[0:i],v[i]) i-=1 return non_tri...
The number of submissions of CodeChef from Students of Graphic Era University had been growing since the day the CodeChef campus chapter, GEU_Coders had been formed here. This rise in user submissions alerted the staff members at CodeChef. They started to track user activities of students from Graphic Era University. T...
for i in xrange(input()): N=input() c=1 S=2 while c<N: if c%2!=0: S=(S*2)-1 else: S=(S*2)+1 c+=1 print S
You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path...
#include <bits/stdc++.h> int n, d, k, x, z; std::vector<int> V1, V2; void add(int u, int v) { V1.push_back(u); V2.push_back(v); } void dfs(int u, int dd, int p) { if (p) while (dd--) { if (x >= n) return; add(u, ++x); dfs(x, k - 1, p - 1); } } int main() { std::cin >> n >> d >> k; z ...
Polycarp studies in Berland State University. Soon he will have to take his exam. He has to pass exactly n exams. For the each exam i there are known two days: a_i — day of the first opportunity to pass the exam, b_i — day of the second opportunity to pass the exam (a_i < b_i). Polycarp can pass at most one exam durin...
//created by Whiplash99 import java.io.*; import java.util.Arrays; import java.util.HashMap; public class F { static class DSU { int parent[], vertices[], edges[], max[], nextMax[]; DSU(int N) { nextMax=new int[N]; parent=new int[N]; max=new int[N]; v...
On the surface of a newly discovered planet, which we model by a plane, explorers found remains of two different civilizations in various locations. They would like to learn more about those civilizations and to explore the area they need to build roads between some of locations. But as always, there are some restricti...
#include <bits/stdc++.h> using namespace std; struct point { int x, y, op, id; } p[1100]; int multi(point p1, point p2, point p0) { int x1, y1, x2, y2; x1 = p1.x - p0.x; y1 = p1.y - p0.y; x2 = p2.x - p0.x; y2 = p2.y - p0.y; return x1 * y2 - x2 * y1; } bool cmp(point p1, point p2) { return multi(p1, p2, p[...
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it. For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be dis...
#include <bits/stdc++.h> using namespace std; int main() { long long k; int n; int i; while (cin >> n >> k) { int d = n + 1; long long ara[d]; long long t1 = 0, c = 0, t, temp = 0, is = 1; for (i = 1; i <= n; i++) cin >> ara[i]; for (i = 1; i <= n; i++) { ara[i] = temp + ara[i]; ...
Alice and Bob play a game on a grid with n rows and infinitely many columns. In each row, there are three tokens, blue, white and red one. Before the game starts and after every move, the following two conditions must hold: * Any two tokens are not in the same cell. * In each row, the blue token is to the left o...
#include <bits/stdc++.h> #pragma GCC optimize("O2,unroll-loops,no-stack-protector,fast-math") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; namespace io { const int L = (1 << 20) + 1; char buf[L], *S, *T, c; char getchar() { if (__builtin_expect(S == T, 0)) { T...
Let's define the Eulerian traversal of a tree (a connected undirected graph without cycles) as follows: consider a depth-first search algorithm which traverses vertices of the tree and enumerates them in the order of visiting (only the first visit of each vertex counts). This function starts from the vertex number 1 an...
#include <bits/stdc++.h> using namespace std; const long long INF = 1ll << 60; long long n, m, Max[500010], d[500010], L[500010], R[500010], ans[500010]; long long ver[1000010], edge[1000010], Next[1000010], head[500010], tot; vector<long long> q[500010]; struct SegmentTree { long long l, r, Min, lazy; } tree[500010 ...
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to...
import heapq n,k=map(int,input().split()) b_l=[] for _ in range(n): t,b=map(int,input().split()) b_l.append([b,t]) b_l.sort(reverse=True) ans=0 sum_fg=0 h=[] heapq.heapify(h) for i in range(n): sum_fg+=b_l[i][1] heapq.heappush(h,b_l[i][1]) while(len(h)>k): g=heapq.heappop(h) sum_fg-=...
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile. You are given n operations which Vasya has made. Find the minimal possible number of stones that can b...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int TESTS = 1; while (TESTS--) { long long n; cin >> n; string s; cin >> s; long long ans = 0; for (long long i = 0; i < n; i++) { if (s[i] == '-') ans--;...
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now. Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per cocon...
#include <bits/stdc++.h> using namespace std; int main() { long long int x, y, z; while (~scanf("%lld%lld%lld", &x, &y, &z)) { long long n1 = x / z; long long m1 = x % z; long long n2 = y / z; long long m2 = y % z; long long sum = n1 + n2; long long k = 0; if (m1 + m2 >= z) { long ...
There is a square grid of size n × n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs max(h, w) to color a rectangle of size h × w. You are to make all cells white for minimum total cost. Input The first line c...
#include <bits/stdc++.h> using namespace std; int n; char s[51][51]; int ans[51][51][51][51]; int solve(int r1, int c1, int r2, int c2) { if (r1 == r2 && c1 == c2) ans[r1][c1][r2][c2] = (s[r1][c1] == '#'); if (ans[r1][c1][r2][c2] != -1) return ans[r1][c1][r2][c2]; ans[r1][c1][r2][c2] = max(r2 - r1 + 1, c2 - c1 + ...
The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2...
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.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Input...
I'm the Map, I'm the Map! I'm the MAP!!! Map In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan...
#include <bits/stdc++.h> using namespace std; const int N = 500 * 1000 + 10; int t, n, m, par[N], deg[N], st, en, h[N], mn, comp[N], sv[2][N]; vector<int> adj[N]; bool vis[N], ans[N]; void gclear() { for (int i = 0; i < n; i++) { for (int j = 0; j < 2; j++) sv[j][i] = -1; adj[i].clear(); comp[i] = ans[i] ...
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches. You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The re...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Solution { static PrintWriter bw; static BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); p...
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i. There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning: * If ℓ = 0, then the cursor...
#include <bits/stdc++.h> using namespace std; const int N = 5e6 + 5; const long long mod = 1e9 + 7; long long t, n, x, a[N]; string s; int main() { cin >> t; while (t--) { cin >> x >> s; for (int i = 1; i <= s.length(); i++) { a[i] = s[i - 1] - 48; } long long len = s.length(), kt = 0; for...
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1". More formally, f(s) is equal to the ...
'''input 5 3 1 3 2 3 3 4 0 5 2 ''' import sys read = lambda: list(map(int,sys.stdin.readline().strip().split())) # try: sigma = lambda x:x*(x+1)//2 for _ in range(int(input())): n,m = read() k = n-m total = sigma(n) # if m==0 or m==n: # print(total) # continue if k>m: e,f =...
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as ...
n = int(input()) occ = [0 for i in range(n)] graph = [[0,0] for i in range(n-1)] for i in range(n-1): x, y = map(int,input().split()) occ[x-1]+=1 occ[y-1]+=1 graph[i][0] = x-1 graph[i][1] = y-1 fin = [-1 for i in range(n-1)] for i in range(n): if occ[i] >= 3 : var = 0 for j ...
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowe...
#include <bits/stdc++.h> using namespace std; const int maxn = 1005; const int inf = 0x3f3f3f3f; int m1[maxn][maxn], m2[maxn][maxn]; bool hang[maxn], lie[maxn], have; int ans, n, m; int dxy[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; pair<int, int> p; char ch; inline bool ju1() { bool b1 = 0, b2 = 0; for (int i = 1;...
You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is poss...
from __future__ import division, print_function # import threading # threading.stack_size(2**27) # import sys # sys.setrecursionlimit(10**7) # sys.stdin = open('inpy.txt', 'r') # sys.stdout = open('outpy.txt', 'w') from sys import stdin, stdout import bisect #c++ upperbound import math import heapq i_m=92233...
Serge, the chef of the famous restaurant "Salt, Pepper & Garlic" is trying to obtain his first Michelin star. He has been informed that a secret expert plans to visit his restaurant this evening. Even though the expert's name hasn't been disclosed, Serge is certain he knows which dish from the menu will be ordered as ...
#include <bits/stdc++.h> using namespace std; const int N = 100005; int v[5], w[5], id[5]; long long p1[N], p2[N]; long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; } namespace N1 { int sum; void insert(int x, int fl) { if (!p1[x] && !p2[x]) fl ? ++sum : --sum; } bool check() { return sum != 0; ...
You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j}...
import sys as _sys def main(): t = int(input()) for i_t in range(t): n, k = _read_ints() a = tuple(_read_ints()) try: result = find_min_m(a, k) except ValueError: result = -1 print(result) def _read_line(): result = _sys.stdin.readline() ...
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots...
#include <bits/stdc++.h> struct Split { int totSz; int pcs; }; using LL = long long; LL cost(Split s) { int q = s.totSz / s.pcs; int r = s.totSz % s.pcs; return 1LL * q * q * (s.pcs - r) + 1LL * (q + 1) * (q + 1) * r; } LL valNext(Split s) { LL pc = cost(s); ++s.pcs; assert(pc - cost(s) >= 0); return ...
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following ac...
#include <iostream> #include <algorithm> #include <cstring> #include <cmath> using namespace std; using ll = long long; const int N = 1e6 + 10; int a[200]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--) { memset(a, 0, sizeof(a)); int n...
Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course...
import math def c (k, n): return (math.factorial(n) // (math.factorial(k) * math.factorial(n - k))) % (10**9 + 7) def solve(): n, k = map(int, input().split()) a = [] for i in input().split(): a.append(int(i)) a.sort() m = dict() for i in a: if(m.get(i, 0) == 0): m[i]...
You are given two tables A and B of size n × m. We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, thei...
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; vector<vector<int>> a(n, vector<int>(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) cin >> a[i][j]; } vector<vector<int>> b(n, vector<i...
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monum...
#include<bits/stdc++.h> using namespace std; const int nn =5100; const int inff = 0x3fffffff; const double eps = 1e-8; typedef long long LL; const double pi = acos(-1.0); const LL mod = 998244353; int n,m; LL POW(LL x,LL y) { LL ret=1; while(y) { if(y&1) ret=(ret*x)%mod; x=(x*x)...
One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides,...
n=int(input()) s=0 X=[int(x) for x in input().split(" ")] X.sort(reverse=True) for i in range(n): s=s+(-1)**(i)*X[i]*X[i] print(3.1415926536*s)
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequenc...
import java.io.*; public class A { final int MOD = 1000000007; final double eps = 1e-12; public A () throws IOException { int N = sc.nextInt(); long [] A = sc.nextLongs(); start(); long res = 0; for (int k = 0; k < N-1; ++k) { int t = 0; while ((k+1) + (1 << t) <= N) ++t; --t; A[k + (1...
Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length x is such a substring of length 2x, that its first half coin...
#include <bits/stdc++.h> int nums[100000] = {0}; int main() { int n = 0; std::cin >> n; std::unordered_map<int, std::vector<int> > nhz(n); for (int i = 0; i < n; ++i) { std::cin >> nums[i]; nhz[nums[i]].push_back(i); } int index = 0; for (int i = 0, next = 0; i < n; i = next) { std::unordered_...
A plane contains a not necessarily convex polygon without self-intersections, consisting of n vertexes, numbered from 1 to n. There is a spider sitting on the border of the polygon, the spider can move like that: 1. Transfer. The spider moves from the point p1 with coordinates (x1, y1), lying on the polygon border, ...
#include <bits/stdc++.h> using namespace std; const int MAX = 800000 + 10; const double INF = 1e30; const double EPS = 0.02; struct point { double x, y; point(double a, double b) { x = a; y = b; } point() {} void print() { printf("%lf %lf\n", x, y); } }; double sqr(double x) { return x * x; } double d...
Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them. Chilly Willy wants to find the minimum number of length n, such that it is simultaneously...
def main(n): K = 10 ** (n - 1) if (n < 3): print -1 else: K += 210 - K % 210 print K main(int(raw_input()))
Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 ≤ a1 ≤ a2 ≤ ... ≤ an). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws eac...
#! /Library/Frameworks/Python.framework/Versions/2.6/bin/python n = int(raw_input()) inp = raw_input().split() a = [int(inp[i]) for i in range(n)] m = int(raw_input()) box_top = 0 for i in range(m): inp = raw_input().split() w = int(inp[0]) h = int(inp[1]) box_bottom = max(a[w-1],box_top) box_top = box_botto...
Yaroslav has n points that lie on the Ox axis. The coordinate of the first point is x1, the coordinate of the second point is x2, ..., the coordinate of the n-th point is — xn. Now Yaroslav wants to execute m queries, each of them is of one of the two following types: 1. Move the pj-th point from position xpj to pos...
#include <bits/stdc++.h> using namespace std; struct T { long long sum; int len; long long sol; }; T unite(T a, T b) { long long sum = a.sum + b.sum; int len = a.len + b.len; long long sol = a.sol + b.sol + b.sum * a.len - a.sum * b.len; return {sum, len, sol}; } const int N = (int)1e5 + 7; int n; int a[N...
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...
import java.util.*; import java.math.*; import java.io.*; public class CF320E { class CHT { class Line { long m, b; double left = Long.MIN_VALUE; public Line(long mm, long x, long y) { m = mm; b = -m * x + y; } public Line(long mm, long bb) { m = mm; b = bb; } long eval(long x) { return...
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel. When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the...
#include <bits/stdc++.h> using namespace std; template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } const int oo = 0x3f3f3f3f; const int __buffsize = 100000; char __buff[__buffsize]; cha...
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret...
#include <bits/stdc++.h> using namespace std; int dist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } int const N = 2000, K = 10; int vis[K]; pair<int, int> sla[K][4]; vector<vector<int>> tans = vector<vector<int>>(K, vector<int>(K)); void solvetask() { int n, m, k...
Once Vasya played bricks. All the bricks in the set had regular cubical shape. Vasya vas a talented architect, however the tower he built kept falling apart. Let us consider the building process. Vasya takes a brick and puts it on top of the already built tower so that the sides of the brick are parallel to the sides ...
#include <bits/stdc++.h> using namespace std; void solve(); int main() { ios::sync_with_stdio(0); solve(); return 0; } pair<pair<double, double>, pair<double, double> > rects[100]; void solve() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> rects[i].first.first >> rects[i].first.second >> ...
Last year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1, 2, ..., K and the center i...
#include <bits/stdc++.h> using namespace std; const int iinf = 1e9 + 7; const long long linf = 1ll << 60; const double dinf = 1e10; void scf(int &x) { bool f = 0; x = 0; char c = getchar(); while ((c < '0' || c > '9') && c != '-') c = getchar(); if (c == '-') { f = 1; c = getchar(); } while (c >= ...
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads....
import java.util.*; import java.io.*; public class Main { BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ while (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() thr...
Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost — a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of poin...
import sys input=sys.stdin.readline n=int(input()) s=list(map(int,input().split())) s.sort() s.reverse() num_manfi=0 num_sefr=0 flag=0 for i in s: if i>0: print(i,end=' ') flag=1 elif i==0: num_sefr+=1 else: num_manfi+=1 num_manfi-=(num_manfi%2) s.reverse() for i in ...
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn. Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d...
#include <bits/stdc++.h> using namespace std; const int INF = 1000000007; const int N = 100100; int n, k; bool used[N]; int main() { cin >> n >> k; int last = 1 + k; for (int i = 1; i < k; i++) { if (used[i]) continue; printf("%d ", i); used[i] = true; if (used[last - i + 1]) continue; printf(...
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to ...
import sys def main(): rdl = list(map(int,input().split())) obx(rdl[0],rdl[1],0,1) def obx(lvl, ind, kl, current): if lvl ==0: print(int(kl)) sys.exit() all = 0 for i in range(lvl+1): all += 2**i all -= 1 if ind > (2**(lvl))/2: if current == 1: kl...
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: ...
import java.util.*; public class Main { public static class Bridge implements Comparable<Bridge> { int nomber; long length; public Bridge(int nomber, long length) { this.nomber = nomber; this.length = length; } @Override public int compareTo...
You are given an array of positive integers a1, a2, ..., an × T of length n × T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array. Input The first line contains two space-separated integers: n, T (1 ≤ n ≤ 100, 1 ≤ T ≤ 107). The second li...
#include <bits/stdc++.h> using namespace std; int dp[1000000], arr[1000000], arr2[300], n, t, maxn = 1, mx = 1; int main() { cin >> n; cin >> t; for (int i = 0; i < n; ++i) { cin >> arr[i]; arr2[arr[i]]++; mx = max(mx, arr2[arr[i]]); dp[i] = 1; } int k = min(n, t); for (int i = n; i < n * k;...
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Comparator; import java.util.PriorityQueue; public class Ltower { private long[] Heap; private int size; private int maxsize; private static final int FRONT = 1; ...
Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of n (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness. The mean of a collection is the average of its elements. The median of a colle...
import java.util.*; import java.io.*; public class E { FastScanner in; PrintWriter out; long[] a; long[] p; long getSum(int l, int r) { return p[r + 1] - p[l]; } class Frac implements Comparable<Frac> { long num; long den; public Frac(long num, long den) ...
Little Petya is now fond of data compression algorithms. He has already studied gz, bz, zip algorithms and many others. Inspired by the new knowledge, Petya is now developing the new compression algorithm which he wants to name dis. Petya decided to compress tables. He is given a table a consisting of n rows and m col...
#include <bits/stdc++.h> using namespace std; struct yts { int x, t, l, ne; } e[4000010]; struct yts2 { int x, t, ne; } E[4000010]; struct PP { int x, id; }; vector<PP> vec1[1000010], vec2[1000010]; int v[2000010], V[2000010], scc[2000010], dfn[2000010], low[2000010], st[2000010], q[2000010], du[2000010], f[2...
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
#include <bits/stdc++.h> using namespace std; int main() { int arr[101], n, imin = 0, imax = 0; cin >> n; for (int i = 1; i <= n; i++) { cin >> arr[i]; if (arr[i] == 1) imin = i; else if (arr[i] == n) imax = i; } int a; if (imax < imin) swap(imax, imin); int rsp = abs(imin - imax) ...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
sum1,sum2,sum3 = 0,0,0 n = int(input()) while n: n-=1 l = list(map(int, input().split())) sum1 += l[0] sum2 += l[1] sum3 += l[2] if sum1==0 and sum2 ==0 and sum3 ==0: print("YES") else: print("NO")
Little girl Masha likes winter sports, today she's planning to take part in slalom skiing. The track is represented as a grid composed of n × m squares. There are rectangular obstacles at the track, composed of grid squares. Masha must get from the square (1, 1) to the square (n, m). She can move from a square to adja...
#include <bits/stdc++.h> using namespace std; const long long MAXN = 1e6 + 10; const long long INF = 1e9 + 10; const long long Mod = 1e9 + 7; struct node { long long val, lazy; bool zero; node() { val = 0; lazy = 0; zero = false; } }; node segt_2[4 * MAXN]; vector<pair<int, pair<int, int> > > query[...
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n. <image> Mehrdad has become quite confused and wants you to help him. Please hel...
#include <bits/stdc++.h> using namespace std; int n; int ksm(int x) { int tt = 1378, rtn = 1; while (x) { if (x & 1) rtn = (rtn * tt) % 10; x >>= 1; tt = (tt * tt) % 10; } return rtn; } int main() { scanf("%d", &n); printf("%d\n", ksm(n) % 10); return 0; }
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent verti...
#include <bits/stdc++.h> using namespace std; int N; int x, y, root = -1; vector<int> g[200100]; int len[200100], viz[3][200100]; int dmax = 0, ind; int stacky[200100], l = 0; void dfs(int x) { viz[0][x] = 1; if (g[x].size() == 1) { len[x] = 1; } else { int okk = 1; int kiddo = -1, kiddo2 = -1; fo...
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise. You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i > 1 the respective term satisfies the condition bi = ...
#include <bits/stdc++.h> using namespace std; long long int b, q, l; int m; long long int a[100001]; int p, n; int c; long long int abso(long long int x) { if (x >= 0) return x; return -x; } int main() { c = 0; scanf("%lld %lld %lld %d", &b, &q, &l, &m); for (int i = 0; i < m; i++) scanf("%lld", &a[i]); n =...
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who ...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Formatter; import java.util.HashMap; import java.util.Locale; /** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 4/19/11 * Time: 6:04 PM * To change this template use File | Settings | File...
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers c...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.StringBuilder; import java.util.*; import java.lang.Math; public class CF427B { public static void main(String[] args) throws Exception { Scanner scanner = new...
Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOExcept...
Two best friends Serozha and Gena play a game. Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak =...
#include <bits/stdc++.h> using namespace std; int dp[100005], ans[100005]; void solve(int num) { if (dp[num] != -1) return; ans[num] = -1; dp[num] = 0; int i, n = 2, a, sum; set<int> myset; myset.clear(); while (2 * num - n * (n - 1) > 0) { if ((2 * num - n * (n - 1)) % (2 * n) == 0) { a = (2 * ...
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string). You are gi...
#include <bits/stdc++.h> using namespace std; const long long int N = 5005; const long long int mod = 1e17 + 7; long long int k, n; string s[N]; long long int high, idx; long long int cnt[26]; bool satisfy(long long int x) { long long int ret = 0; for (long long int i = 0; i < n; i++) { if (s[x][i] != s[idx][i]...
Vova has recently learned what a circulaton in a graph is. Recall the definition: let G = (V, E) be a directed graph. A circulation f is such a collection of non-negative real numbers f_e (e ∈ E), that for each vertex v ∈ V the following conservation condition holds: $$$∑_{e ∈ \delta^{-}(v)} f_e = ∑_{e ∈ \delta^{+}(v)...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } long double d[1001 + 5]...
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the...
#include <bits/stdc++.h> using namespace std; int dx[] = {0, 0, 1, -1, -1, -1, 1, 1}; int dy[] = {1, -1, 0, 0, -1, 1, 1, -1}; template <class T> inline T biton(T n, T pos) { return n | ((T)1 << pos); } template <class T> inline T bitoff(T n, T pos) { return n & ~((T)1 << pos); } template <class T> inline T ison(T n...
You are given a special connected undirected graph where each vertex belongs to at most one simple cycle. Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles). For each node, independently, output the maximum distance between it and a leaf in the resulting...
#include <bits/stdc++.h> using namespace std; const int inf = (int)1e9; const long long linf = (long long)1e18; const int mod = (int)1e9 + 7; const long double eps = (long double)1e-8; const int maxn = (int)5e5 + 5; const long double pi = acos(-1); int n, m, cnt_cyc; int t[maxn], cyc[maxn], tup[maxn]; int ans[maxn], an...
Raj and simran are in love. but thakur baldev singh doesnt want them to be together. But baldev Singh cares for her daughter too. He wants raj to prove his love for her daughter and family. So Baldev singh being a great lover of strings sets up problem for raj. he screams out a string and asks simran to choose her ...
t = input(); while(t > 0): s = raw_input().split(); print s[0].count(s[1]); t -= 1;
** Problem Statement is Updated ** Xenny had N colors with him, all arranged in a straight line. He was interested in picking up a particular subarray of colors. A pre-set is a set that contains all subarrays of colors that start from the first color and do not contain the last color. An end-set is a set that contai...
def returnAnswer(a): n = len(a) length = 0 arr = [] for i in range(0, n): arr.append(0) i = 1 while(i<n): if(a[i] == a[length]): length += 1 arr[i] = length i += 1 else: if(length != 0): length = arr[length-1] else: arr[i] = 0 i += 1 retu...
A cell phone company is trying out its new model of cell phone. Here's how its structure is: The keypad has 11 buttons corresponding to digits from 0 to 9 and one additional button called Add. After pressing any button from 0 to 9, the corresponding digit appears on the screen. The Add button replaces the last two di...
for _ in range(input()): total_cost = map(int, raw_input().split()) for i in range(10): for j in range(1, 10): for k in range(j, 10): total_cost[(j + k) % 10] = min(total_cost[(j + k) % 10], total_cost[j]+total_cost[k]) input() Result = 0 inputs = raw...
There is a new magician in town. His trick is known as "Find the Ring". He puts 3 glasses at 3 spots on the table, labeling them as 0, 1 and 2. Now, he hides a ring under one of the glasses. The glasses are opaque and placed upside down, so that the ring is not visible to the audience. Now, he begins to make certain ...
n=int(raw_input()) while n: t=(raw_input()) t=t.split(' ') t[0]=int(t[0]) t[1]=int(t[1]) if t[1]==0: print t[0] elif t[1]%2==0: if t[0]==1: print "1" else : print '0' else : if t[0]==1: print "0" else : print '1' n-=1
You have a polygon described by coordinates of its vertices. Can you find how many points with integer coordinates lay strictly inside it? Input The first line contains an integer N - number of vertices. Next N lines contain 2 space-separated integers each and describe polygon vertices in clockwise order. Note that po...
from fractions import gcd n = input() vertices = [] for i in range(n): vertices.append(map(int, raw_input().split())) vertices.append(vertices[0]) b = 0 for i in range(n): dx = abs(vertices[i + 1][0] - vertices[i][0]) dy = abs(vertices[i + 1][1] - vertices[i][1]) b += gcd(dx, dy) b = max(0, b) area = 0...
Maxi and Dumpy are playing with numbers. Maxi throws a ball up in the air and shouts a random number. Dumpy notes down this number on a piece of paper. They repeat this N times. But Dumpy just found out that there are many repetitive numbers in the list. He doesn't like it. He asks you to filter the list, remove the re...
n=input() num=raw_input() num=num.split(" ") num=map(int, num) dum=[] for i in num: if(i not in dum): dum.append(i) for i in dum: print(i),
Little Raju recently learnt about binary numbers. After spending some time with it, he decided to count in how many ways he can make N digit numbers that is formed by ones and zeroes. But zeroes can not be next to each other. Help him finding in how many different numbers can he make? Example: There 5 possible ways o...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name print 'Hello World!' ''' t=int(input()) for i in range(t): n=int(input()) if n==1: print(2) else: a=1 b=2 for i in range(2,n+1): a,b=b,a+b print(b)
Manu is a very bright student and had learned c++ Programming on her own.She has covered loops and if/else.She is a very inquisitive child and always love to discover new things.Same applies to programming she learns various syntax.One day while reading the documentation of a cstdlib library she came across a function ...
t=input() while t>0: k,n=map(int,raw_input().split()) if k>n: print "1.000000000" else: f=1.0 for i in range(n,n-k,-1): f=(f*i)/n f=1-f print "%.9f"%(f) t-=1
Given an array A. Delete an single element from the array such that sum of the differences of adjacent elements should be minimum. For more clarification Sum for an array A having N element is defined as : abs( A[0] - A[1] ) + abs( A[1] - A[2] ) + abs( A[2] - A[3] ) +............ + abs( A[N-2] - A[N-1] ) Inp...
t=int(raw_input()) for qq in xrange(t): n=int(raw_input()) l=map(int,raw_input().split()) s=sum(l) minval=9999999999999999999 ret=0 if n==1: print 0 continue for i in xrange(n): tmp=0 cp=s if i>0 and i<n-1: tmp = abs(l[i]-l[i-1]) + abs(l[i]-l[i+1]) cp-=tmp cp+=abs(l[i+1]-l[i-1]) if cp < min...