input
stringlengths
29
13k
output
stringlengths
9
73.4k
Chef has bought N robots to transport cakes for a large community wedding. He has assigned unique indices, from 1 to N, to each of them. How it will happen? Chef arranges the N robots in a row, in the (increasing) order of their indices. Then, he chooses the first M robots and moves them to the end of the queue. Now, C...
def GI(): return int(raw_input()) def GIS(): return map(int, raw_input().split()) def main(): # Trying for better than O(N) gcd = lambda a, b: gcd(b, a%b) if a%b else b for i in xrange(GI()): N, M = GIS() if M == 0: cakes_distributed = 1 else: g = gcd(N, M) ...
Chef is the new king of the country Chefland. As first and most important responsibility he wants to reconstruct the road system of Chefland. There are N (1 to N) cities in the country and each city i has a population Pi. Chef wants to build some bi-directional roads connecting different cities such that each city is c...
for _ in xrange(input()): n = input() p = map(int, raw_input().strip().split()) p.sort() min = p[0] print sum([min*p[i] for i in range(1,n)])
3:33 It's possible for all the digits displayed on a digital clock in the hours:minutes format to be identical. The time shown above (3:33) is an example of such a situation. Other examples are 2:2 and 1:11. Note that the digits of 33:33 are identical, but it is not a valid time on a usual digital clock. The above exam...
for _ in xrange(input()): H, M = map(int, raw_input().split()) count = 0 for i in range(1, H): if i < 10 or i % 11 == 0: start = str(i)[0] while int(start) in range(M): count += 1 start += str(i)[0] print count + 1
On Internet sites usually the registration form automatically checks and validate the passowrd's crypt resistance. If the user's password isn't complex enough a message is displayed. You have already implemented password validation in Web Programming class. Today your task is to implement password validation program. ...
import re t=raw_input() flag=1 if len(t)<5: flag=0 regex=re.compile('[a-z]') if len(regex.findall(t))==0: flag=0 regex2=re.compile('[A-Z]') if len(regex2.findall(t))==0: flag=0 regex3=re.compile('[0-9]') if len(regex3.findall(t))==0: flag=0 if flag==1: print "YES" else: print "NO"
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n. It is known that, from the capital (the city with the number 1), you can reach any o...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 100; int n, m, k; struct Edge { int u, v; Edge(int _u = 0, int _v = 0) : u(_u), v(_v) {} } road[maxn]; bool vis[maxn]; int dis[maxn]; int f[maxn]; vector<int> edge[maxn]; vector<int> p[maxn]; vector<string> path; void bfs() { queue<int> Q; Q.p...
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges. Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loo...
#include <bits/stdc++.h> using namespace std; int n, ans, d[200010], p[200010]; vector<vector<int> > gr; void dfs(int x, int par) { p[x] = par; if (par != -1) { d[x] = d[par] + 1; } for (auto j : gr[x]) { if (j == par) { continue; } dfs(j, x); } } set<pair<int, int> > pajestegreedy; int ...
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all. Sasha se...
import java.util.Scanner; public class D { public static void main(String[] args) { Scanner inp = new Scanner(System.in); long n=inp.nextLong(),k=inp.nextLong(); int p = inp.nextInt(); if(n%2 == 1){n--;k--;} for(int i = 0 ; i < p ; i++) { long a = ...
A lot of people dream of convertibles (also often called cabriolets). Some of convertibles, however, don't have roof at all, and are vulnerable to rain. This is why Melon Ask, the famous inventor, decided to create a rain protection mechanism for convertibles. The workplace of the mechanism is a part of plane just abo...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; const long double eps1 = 1e-4; const long double eps2 = 1e-10; int gi() { int x = 0, o = 1; char ch = getchar(); while (!isdigit(ch) && ch != '-') ch = getchar(); if (ch == '-') o = -1, ch = getchar(); while (isdigit(ch)) x = x * 10 + ch - ...
You are given an array a of n points in k-dimensional space. Let the distance between two points a_x and a_y be ∑ _{i = 1}^{k} |a_{x, i} - a_{y, i}| (it is also known as Manhattan distance). You have to process q queries of the following two types: * 1 i b_1 b_2 ... b_k — set i-th element of a to the point (b_1, b_...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelp...
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q) For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes. Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi...
# -*- coding: utf-8 -*- """ Created on Sun Feb 17 15:00:31 2019 @author: avina """ x,y,z = map(int, input().strip().split()) a,b,c = map(int,input().strip().split()) k=0 if a+b+c >= x+y+z: if a+b >= x+y: if a>=x: k+=1 if k != 0: print("YES") else: print("NO")
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n. Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the ...
#include <bits/stdc++.h> using namespace std; const int N = 1 << 18; int a[N], pre[N], p[N], pos[N]; int fa[N][20], dp[N][20]; int rmq(int l, int r) { int k = 31 - __builtin_clz(r - l + 1); return max(dp[l][k], dp[r - (1 << k) + 1][k]); } int main() { int n, m, q; scanf("%d%d%d", &n, &m, &q); for (int i = 1; ...
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1. There are m straight segments on the disc, the endpoints of which are all among the aforementioned ...
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; using vi = vector<int>; using ll = long long; int n, m; vector<pii> a; unordered_set<ll> s; bool f(int r) { for (int i = int(0); i < int(m); i++) { ll x = a[i].first + r, y = a[i].second + r; if (x >= n) x -= n; if (y >= n) y -= n; ...
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k. During each turn Vova can choose what to do: * If the current charge of his laptop battery is strictly gre...
n=int(input()) for i in range(0,n): p=input().rstrip().split(' ') k=int(p[0]) K=k; n=int(p[1]) CC=n; a=int(p[2]) b=int(p[3]) T=min(a,b); if (k%T==0): H=(k//T)-1; else: H=(k//T) if n>H: print(-1) else: if k%a==0: A=(k//a)-1; ...
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is r...
import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.Comparator.*; public class Main { FastScanner in; PrintWriter out; ArrayList<Integer>[] graph; ArrayList<GraphPair>...
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in ...
import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') ...
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers. There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct. Ujan is lazy, so he will do the following reordering of the numbe...
#include <bits/stdc++.h> using namespace std; const int maxn = 15 * 5000 + 5; int k, v[20], vis[maxn]; long long a[20][5050], ss[20], tot, sum; struct node { int val, bel; } x[maxn]; map<long long, int> mp; vector<int> g[maxn], rec[1 << 15 + 5], tmp; int pre[1 << 15 + 5], dp[1 << 15 + 5], ok[1 << 15 + 5], l[20], r[20...
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events. A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n × m rectangle map which represents the damaged part of the Forest...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Q...
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year... n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate ...
#include <bits/stdc++.h> using namespace std; const long long MOD = 998244353; long long mpow(long long a, long long b, long long p = MOD) { a = a % p; long long res = 1; while (b > 0) { if (b & 1) res = (res * a) % p; a = (a * a) % p; b = b >> 1; } return res % p; } const long long N = 2e5 + 100;...
You are given a string s. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may eras...
n=int(input()) for i in range(n): x=input() if '1' in x: a=x.index('1') c=0 for j in range(a+1,len(x)): if x[j]=='1': c+=x.count('0',a,j) a=j print(c) else: print(0)
The King of Berland Polycarp LXXXIV has n daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are n other kingdoms as well. So Polycarp LXXXIV has enumerated his daughters from 1 to n and the kingdoms from 1 to n....
t = int(input()) setups = [] for _ in range(t): n = int(input()) setup = [] for _ in range(n): count_and_list = input().split(" ") if len(count_and_list) == 1: husbands = tuple() else: husbands = tuple(int(x) for x in count_and_list[1:]) setup.append(h...
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ...
k = int(input()) cur = 10**18 best = [] for p in range(1, 41): for q in range(1, 41): for i in range(1, 10): res = (p**i)*(q**(10-i)) if res >= k: temp = p*i+q*(10-i)-10 if temp <= cur: cur = temp best = (p, q, ...
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n]. Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2]. In one step, you can choose one segment (either from the first or fro...
from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import...
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the ta...
//package round100; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), R = ni(), r = ni(); if(r > R){ out.printl...
You are given a string s. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the str...
#include <bits/stdc++.h> using namespace std; inline long long read() { long long sum = 0, ff = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') ff = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') sum = sum * 10 + ch - '0', ch = getchar(); return sum * ff; } const long lon...
You are given one integer n (n > 1). Recall that a permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation of length 5, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (...
def lip(): return list(map(int,input().split())) def splip(): return map(int,input().split()) def intip(): return int(input()) for _ in range(intip()): n = intip() l = [i for i in range(1,n+1)] l = l[::-1] mid = n//2 if n==2: print(*l) elif n%2!=0: l[mid] , l[mid-1] = l[mid-1],...
In the famous Oh-Suit-United tournament, two teams are playing against each other for the grand prize of precious pepper points. The first team consists of n players, and the second team consists of m players. Each player has a potential: the potential of the i-th player in the first team is a_i, and the potential of ...
//zxggtxdy! #include<bits/stdc++.h> using namespace std; #define LL long long const int N=1e6,Q=1e6+7; int n,m,k,q,a[Q],b[Q],pos[Q]; multiset<int>f1,f2; struct Seg{ LL f1[Q<<2],f2[Q<<2]; inline void covex(int u,LL A,LL B){ u=pos[u],f1[u]+=A,f2[u]+=B,u=u>>1; while(u>0) f1[u]=f1[u<<1]+f1[u<<1|1],f2[u]=f2[u<<1]+f2[u...
Interaction This is an interactive problem. You need to read participants' queries from standard input and print your responses to standard output. You don't know the number of queries upfront, so you'll need to process them as you get them; you'll know you're done once you reach the end of the file. In each query,...
#include<bits/stdc++.h> using namespace std; #define MOD 1000000007 using ll = long long; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); string d; while ( getline(cin, d) ) { cout << "NO" << endl; cout.flush(); } return 0; }
Kavi has 2n points lying on the OX axis, i-th of which is located at x = i. Kavi considers all ways to split these 2n points into n pairs. Among those, he is interested in good pairings, which are defined as follows: Consider n segments with ends at the points in correspondent pairs. The pairing is called good, if fo...
import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop #from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(...
A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other. The architect bureau, where Pe...
#include <bits/stdc++.h> using namespace std; int main() { int n, t; cin >> n >> t; map<double, int> m; for (int i = 0; i < n; i++) { double xi, ai; cin >> xi >> ai; m[xi - ai / 2.0]++; m[xi + ai / 2.0]--; } vector<pair<double, int> > v; int res = 2; for (__typeof(m.begin()) it = m.begin...
The Smart Beaver from ABBYY has a long history of cooperating with the "Institute of Cytology and Genetics". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows. There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercas...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 2000 + 10; const int MAX_K = 500 + 10; string Arr[MAX_N]; pair<long long, long long> T[2 * MAX_N][12]; long long Dist(const string &a, const string &b) { long long sz = (int)min(a.size(), b.size()); int i; for (i = 0; i < sz; i++) if (a[i] != b[i...
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's probl...
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner r = new Scanner(System.in); int N = r.nextInt(); char[][] a = new char[N][]; for(int i = 0; i < N; i++) a[...
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations. Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of number...
#include <bits/stdc++.h> using namespace std; long long MOD, L, R, d, k, ans; map<long long, long long> F; long long fib(long long x) { if (x < 2) return 1 % MOD; if (F.count(x)) return F[x]; long long k = x / 2; if (x % 2) return F[x] = (fib(k) * fib(k + 1) % MOD + fib(k) * fib(k - 1) % MOD) % MOD; retur...
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is n...
import java.io.*; import java.util.*; public class minFolder { public static void main(String[] args) throws IOException { PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out)); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.rea...
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the pa...
#include <bits/stdc++.h> using namespace std; const int INF_MAX = 0x7FFFFFFF; const int INF_MIN = -(1 << 30); const double eps = 1e-10; const double pi = acos(-1.0); int toInt(string s) { istringstream sin(s); int t; sin >> t; return t; } template <class T> string toString(T x) { ostringstream sout; sout <<...
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds. Polar bears Alice and Bob each have caught some fish, and they are g...
//package com.congli.codeforces; import java.io.*; import java.util.*; public class C180Div2D_FishWeight { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { C180Div2D_FishWeight test = new C180Div2D_FishWeight(); test.start(); } pu...
Fox Ciel is playing a card game with her friend Jiro. Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack. Now is Ciel's battle phase, Ciel can do the following ope...
#include <bits/stdc++.h> using namespace std; int adj[222][222], deg[222], flow[222][222], cost[222][222], dis[222], pre[222]; int N, M, fl; void add_edge(int u, int v, int w, int c = 0) { adj[u][deg[u]++] = v; adj[v][deg[v]++] = u; flow[u][v] = w; flow[v][u] = 0; cost[u][v] = c; cost[v][u] = -c; } queue<in...
One fine morning, n fools lined up in a row. After that, they numbered each other with numbers from 1 to n, inclusive. Each fool got a unique number. The fools decided not to change their numbers before the end of the fun. Every fool has exactly k bullets and a pistol. In addition, the fool number i has probability of...
#include <bits/stdc++.h> using namespace std; using ll = long long; using vvi = vector<vector<int>>; using vi = vector<int>; using vvll = vector<vector<long long>>; using vll = vector<long long>; using vd = vector<double>; using vvd = vector<vector<double>>; using pii = pair<int, int>; using vpii = vector<pair<int, int...
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 int N = 200005; pair<int, int> a[N]; int n, k; vector<int> w; long long calc(int v) { int l = lower_bound(a + 1, a + n + 1, pair<int, int>(v - 1, 0)) - a; int r = lower_bound(a + 1, a + n + 1, pair<int, int>(v + 1, 0)) - a - 1; int must = k - l + 1; if (must >...
The programmers from the R2 company love playing 2048. One day, they decided to invent their own simplified version of this game — 2k on a stripe. Imagine an infinite in one direction stripe, consisting of unit squares (the side of each square is equal to the height of the stripe). Each square can either be empty or c...
#include <bits/stdc++.h> using namespace std; template <class T, class L> bool smax(T &x, L y) { return x < y ? (x = y, 1) : 0; } template <class T, class L> bool smin(T &x, L y) { return y < x ? (x = y, 1) : 0; } const int maxn = 2e3 + 17, mod = 1e9 + 7; int n, dp[maxn][2048], ans, s[maxn], a[maxn], k; void go(int...
Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n. Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which epi...
import sys input=sys.stdin.buffer.readline n=int(input()) arr=list(map(int,input().split())) arr.sort() z=0 for i in range(0,n-1): if arr[i]==i+1: continue else: print(i+1) z=1 break if z==0: print(n)
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: * Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. * Each time Applema...
import java.io.*; import java.util.*; public class Toastman { public static void main(String[]args)throws IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String s[]=br.readLine().split(" "); long a[]=ne...
Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: <image> where <image> is equal to 1 if some ...
#B problem X = raw_input() X = X.split() #print X m = int(X[0]) n = int(X[1]) A = [[0]*n for i in range(m)] #print A B = [[0]*n for i in range(m)] for i in range(m): temp = raw_input() for j in range(n): B[i][j] = int(temp[2*j]) temp1 = [] temp2 = [] for i in range(m): if (sum(B[i]) == n): t...
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
#domino piling M,N=map(int,input().split()) d=(M*N)//2 print(d)
Polycarp has n dice d1, d2, ..., dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1, d2, ..., dn. However, she finds it enough to make a series of statements of...
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public static void main(String[] xa) throws IOException { InputReader sc = new InputReader(new BufferedInputStream(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter( ...
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of gia...
#include <bits/stdc++.h> using namespace std; const int maxN = 2000 + 10; const int maxM = 1000 * 100 * 4; const int mod = 1e9 + 7; inline int bpow(int a, int b) { int res = 1; for (; b; b /= 2) { if (b & 1) res = res * 1ll * a % mod; a = a * 1ll * a % mod; } return res; } int fact[maxM]; inline int ch(...
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office. All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with...
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.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; imp...
There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will acti...
import sys input = sys.stdin.readline from bisect import * n = int(input()) ab = [tuple(map(int, input().split())) for _ in range(n)] ab.sort(key=lambda k: k[0]) a = [-10**18]+[ai for ai, _ in ab] dp = [0]*(n+1) for i in range(1, n+1): j = bisect_left(a, ab[i-1][0]-ab[i-1][1])-1 dp[i] = dp[j]+i-j-1 ans = 10*...
Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve. It's a well-known fact that Limak, as e...
#include <bits/stdc++.h> int read() { int ans = 0, c, f = 1; while (!isdigit(c = getchar())) if (c == '-') f *= -1; do ans = ans * 10 + c - '0'; while (isdigit(c = getchar())); return ans * f; } const int N = 10050; const int K = 5; inline int query(int l, int r, int t) { return (r + K - t) / K - (l - 1...
Limak is a little polar bear. He has n balls, the i-th ball has size ti. Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy: * No two friends can get balls of the same size. * No two friends can get balls of sizes that di...
n = int(input()) s = map(int, input().split()) l = [] a = 'NO' for i in s: if i not in l: l += [i] l = sorted(l) if len(l) >= 3: for i in range(len(l) - 2): if l[i] + 2 == l[i + 1] + 1 == l[i + 2]: a = 'YES' print(a)
The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each b...
#include <bits/stdc++.h> using namespace std; int main() { int n, i, j, k, h, t1, t2, index, t = 2; scanf("%d", &n); double a[n][n], p1 = 0, ans = 0, ans2 = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { scanf("%lf", &a[i][j]); if (i == 0 && a[i][j] > p1) { p1 = a[i][j]; ...
Bomboslav set up a branding agency and now helps companies to create new logos and advertising slogans. In term of this problems, slogan of the company should be a non-empty substring of its name. For example, if the company name is "hornsandhoofs", then substrings "sand" and "hor" could be its slogans, while strings "...
#include <bits/stdc++.h> const int MAX_N = 2e5 + 10, SIGMA = 26; int N, ans; char S[MAX_N]; struct SegTree { int l, r, m; SegTree *cl, *cr; SegTree(int l, int r) : l(l), r(r), m((l + r) / 2), cl(nullptr), cr(nullptr) {} }; SegTree *touch(int l, int r, int x) { SegTree *res = new SegTree(l, r); if (l != ...
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to...
def GetDistance(x1,x2,x3,z): return abs(z-x1) + abs(z-x2) + abs(z-x3) friends= raw_input().split() x1=int(friends[0]) x2=int(friends[1]) x3=int(friends[2]) frnds=[x1,x2,x3] dist=[] for i in range(min(frnds),max(frnds)+1): dist.append(GetDistance(x1,x2,x3,i)) print min(dist)
Hongcow's teacher heard that Hongcow had learned about the cyclic shift, and decided to set the following problem for him. You are given a list of n strings s1, s2, ..., sn contained in the list A. A list X of strings is called stable if the following condition holds. First, a message is defined as a concatenation o...
#include <bits/stdc++.h> using namespace std; const int MAXN = 35; const int MAXS = 100005; long long n, b1 = 31337, b2 = 1299721, p1 = 1000000007, p2 = 1000000011, sol; string s[MAXN]; int len[MAXN], bio[MAXS]; long long h1[MAXN][MAXS], h2[MAXN][MAXS]; long long pot1[MAXS], pot2[MAXS]; vector<int> c[MAXN], v[MAXS]; lo...
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s...
''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College Date:08/06/2020 ''' from os import path import sys from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right ...
There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to bui...
n = int(input()) array = list(map(int, input().split())) array = sorted(array) mink = array[-1] - array[0] count = 0 for i in range(1, len(array)): if mink > array[i] - array[i-1]: mink = array[i] - array[i-1] count = 1 elif mink == array[i] - array[i-1]: count += 1 print(mink, count)
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost ...
n,m1=map(int,input().split()) lp=list(map(int,input().split())) l=0 r=n while l<r : m=(l+r+1)//2 l1=lp[::] for i in range(n) : l1[i]=lp[i]+((i+1)*m) l1=sorted(l1) s=sum(l1[:m]) if s>m1 : r=m-1 else : l=m l1=lp[::] for i in range(n) : l1[i]=lp[i]+((i+1)*l) l1=sorte...
Alice and Bob are playing a game with a string of characters, with Alice going first. The string consists n characters, each of which is one of the first k letters of the alphabet. On a player’s turn, they can either arbitrarily permute the characters in the words, or delete exactly one character in the word (if there ...
#include <bits/stdc++.h> using namespace std; const int logMax = 20; const int NMax = 250005; int DP[logMax][NMax]; int MOD, N, K; int supra[NMax], cnt; int Inv[NMax], Fact[NMax]; int power(int n, int p) { int sol = 1; while (p) { if (p & 1) sol = (1LL * sol * n) % MOD; p /= 2; n = (1LL * n * n) % MOD; ...
All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland! It is well-known that there are n cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that th...
#include <bits/stdc++.h> using namespace std; const long long maxn = 2e5 + 7; long long n, m, a[maxn], par[maxn], delp[maxn], cnt; long long num[maxn], delpar[maxn]; vector<long long> cac[maxn]; vector<long long> vt[maxn]; long long ans1[maxn], ans2[maxn], ans3[maxn], cnt2; void DFS(long long u, long long p) { par[u]...
Berland.Taxi is a new taxi company with k cars which started operating in the capital of Berland just recently. The capital has n houses on a straight line numbered from 1 (leftmost) to n (rightmost), and the distance between any two neighboring houses is the same. You have to help the company schedule all the taxi ri...
#include <bits/stdc++.h> using namespace std; multiset<int> W; set<pair<long long, long long> > S[200020]; struct str { str() {} str(long long tm, int c, int b) : tm(tm), c(c), b(b) {} long long tm; int c, b; bool operator>(const str &rhs) const { return tm > rhs.tm; } }; priority_queue<str, vector<str>, grea...
Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a car...
s = list(input()) d = {'a', 'u', 'o', 'e', 'i', '1', '3', '5', '7', '9'} ans = 0 for i in s: if i in d: ans += 1 print(ans)
Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-e...
import java.io.*; public class D { static PrintStream out = System.out; static BufferedReader br; static Node root = new Node(null); static Node current = root; static int counter; static boolean pressEnter = false; static int skipped = 0; static { root.trans = new Node[26]; ...
The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Tw...
n=int(input()) a=[] b=[] for i in range(n): a.append(input()) for i in range(n): b.append(input()) def h(d): c=[] for i in range(n): c.append(d[n-i-1]) return c def r(d): c=[] for i in range(n): temp="" for j in range(n): temp+=d[j][n-i-1] c.appen...
Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping. Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two in...
#include <bits/stdc++.h> using namespace std; const int maxn = 111111; const int INF = 0x3f3f3f3f; int vis[maxn]; bool selected[maxn]; int n, m; vector<int> adj[maxn]; bool test[maxn]; double elapsed() { return clock() / (double)CLOCKS_PER_SEC; } bool dfs(int v) { if (selected[v] == true) return false; vis[v] = -1;...
Our hacker, Little Stuart lately has been fascinated by ancient puzzles. One day going through some really old books he finds something scribbled on the corner of a page. Now Little Stuart believes that the scribbled text is more mysterious than it originally looks, so he decides to find every occurrence of all the per...
t=int(raw_input()) while(t>0): s=raw_input() str=raw_input() s2=s[::-1] if s in str or s2 in str: print "YES" else: print "NO" t-=1
My flatmate, Sayan, once invited all his relatives and friends from all over the city to join him on his birthday party. He is also famous for boasting that all his friends and relatives belong to "proper" families. Now, he appointed a gaurd to allow only his relatives and friends into the party. It is gauranteed that ...
from collections import Counter as C t=int(raw_input()) def positiveSubsetSum( A, x ): # preliminary if x < 0 or x > sum( A ): # T = sum(A) return 0 # algorithm sub_sum = [0] * ( x + 1 ) sub_sum[0] = 1 p = 0 while not sub_sum[x] and p < len( A ): a = A[p] q = x wh...
Little Jhool is a world renowned kangaroo trainer. He's now living in Australia, and is training kangaroos for his research project on mobile soccer. (We don't know the connection, too.) Anyway, for the project to be completed he observes kangaroos for a lot of time - because he wants to figure out the hop count for v...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' count = int(raw_input()) for i in range(count): val = map(int, raw_input().split(" ")) B = val[1] A = val[0] M = val[2] print (B/M)-(A-1)/M
Deepak like strings which are in flip flop in nature. For example, he likes XYXYX, while he doesn't like XXYX. Now he want to convert every string into a string which he likes. for this, he only delete the character in the string. Now find the minimum number of delete operation which is required to covert a string tha...
n=input() for nn in range(n): s=raw_input() last=s[0] cnt=0 for c in s[1:]: if c==last: cnt+=1 last=c print cnt
Jal Mahal Lake is famous tourist place in Jaipur. The lake has floating planks in a straight line. The planks are currently not attached to each other, and there may be gaps between some of them. You have to push them all together and connect them into a single long plank. You are given the positions and lengths. For ...
for _ in xrange(input()): n=input() pos=map(int,raw_input().split()) sz=map(int,raw_input().split()) a=[] for i in xrange(n): a.append([pos[i],sz[i]]) a.sort() tmp=a[0][0]+a[0][1] ans=0 for i in xrange(1,n): ans+=a[i][0]-tmp tmp+=a[i][1] for z in xrange(1,n): t=0 tmp=a[z][0]+a[z][1] for i in xrang...
Micro is a big fan of the famous competitive programmer Gennady Korotkevich, known by his handle tourist. He wants to be like him. He has been practising hard but is not reaching anywhere. So he has left his fate to one game he has, called MinMax. The game consists of an array A of N integers. If the difference between...
t=input() while t>0: t=t-1 o=input() n=map(int ,raw_input().split()) if (max(n)-min(n))%2==0: print 'No' else: print 'Yes'
A:It is a natural number greater than 1 that has no positive divisors other than 1 and itself. B: It is a number that remains the same when its digits are reversed. It is "symmetrical". Patrik lives in Palestine. He loves everything starting with P and so numbers also. His friend gave him a number X and asked him t...
p=[1 , 1 , 2 , 3 , 5 , 7 , 11 , 101 , 131 , 151 , 181 , 191 , 313 , 353 , 373 , 383 , 727 , 757 , 787 , 797 , 919 , 929 , 10301 , 10501 , 10601 , 11311 , 11411 , 12421 , 12721 , 12821 , 13331 , 13831 , 13931 , 14341 , 14741 , 15451 , 15551 , 16061 , 16361 , 16561 , 16661 , 17471 , 17971 , 18181 , 18481 , 19391 , 19891 ...
Little Bear has received a home assignment to find the sum of all digits in a number N. Following his affinity towards single digit number, he intends to repeatedly compute the sum of all digits until the sum itself becomes a single digit number. Can you write a program to compute the final single-digit sum? As the n...
__author__ = 'pjha' def main(): N=input() for i in range(0,N): M=input() sum=0 for j in range(0,M): a=map(int,raw_input().split()) sum=sum+a[1]*a[0] while(sum>9): fsum=0 while(sum>0): fsum=fsum+sum%10 ...
DM of Bareilly wants to make Bareilly a smart city. So, one point amongst his management points is to arrange shops. He starts by arranging the bakery shops linearly, each at a unit distance apart and assigns them a number depending on its owner. Momu loves pastries of shops with same number so he wants to find the ...
noOfTestCases = int(raw_input()) def minDistance(n): structureCount = {} curIndex = 0 for digit in n: if(structureCount.has_key(digit) == False): structureCount[digit] = [curIndex,-1] else: newDistance = curIndex - structureCount[digit][0] if(structureCount[digit][1] == -1 or newDistance < structureCou...
Singh is getting bored at work. He has a lot of ideas (N) to work on (as side projects) but is unable to choose one. He chooses a random number (R) and lines up his ideas in a circle. He starts counting from first and removes the R^th idea in the circle until only one remains. Help him choose an idea to work on. Inpu...
n, k = list(map(int, raw_input().strip().split())) l = [i for i in range(n)] ind = 0 while len(l) != 1: ind = ( ind + k - 1 ) % len(l) l = l[0:ind] + l[ind+1:] print(l[0]+1)
You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input...
#Convolution_998244353 MOD = 998244353 ROOT = 3 sum_e = (911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601, 842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 0, 0, 0, 0, 0, 0, 0, 0, 0) sum_...
Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank. The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.) Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or abo...
#include <iostream> int main() { unsigned long long N=100, X; std::cin >> X; int i=0; while (N < X) { N *= 1.01; i++; } std::cout << i; }
2N players are running a competitive table tennis training on N tables numbered from 1 to N. The training consists of rounds. In each round, the players form N pairs, one pair per table. In each pair, competitors play a match against each other. As a result, one of them wins and the other one loses. The winner of the...
N,A,B=map(int,input().split()) if (A+B)%2==0: ans=(B-A)//2 else: ans=min(A-1,N-B)+1+(B-A-1)//2 print(ans)
There are N+1 towns. The i-th town is being attacked by A_i monsters. We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters. What is the maximum total number of monsters the heroes can cooperate to defeat? Constraints * All values in input are i...
#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> P; const int INF = pow(10, 7); int main(){ int n;cin>>n; ll ans=0; vector<int> a(n+1); for(int i=0;i<=n;i++){ cin>>a[i]; } for(int i=0;i<n;i++){ int b, d;cin>>b; d=min(a[i], b); ans+=d;a[i]-= d;b -= ...
You are given a string S of length N. Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings. Here, a subsequence of a string is a conca...
#include<bits/stdc++.h> using namespace std; using ll = long long; const ll mod = 1e9 + 7; int main() { int n; string s; cin >> n >> s; map<char, int> mp; for(auto i : s)mp[i]++; ll res = 1; for(auto i : mp) { res *= (1 + i.second); res %= mod; } cout << ((res - 1) + mod ) % mod<< endl; }
You are given integers N and M. Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N. Constraints * All values in input are integers. * 1 \leq N \leq 10^5 * N \leq M \leq 10^9 Input...
import itertools import math import copy N,M=map(int, raw_input().split()) M2=copy.deepcopy(M) A={} a=int( math.sqrt(M) )+2 for i in range(2,a): while M%i==0: if i not in A: A[i]=1 else: A[i]+=1 M/=i else: A[M]=1 B=[] for x in A.values(): B.append( range(x+1) ) L=list(itertools.product(*B)) ...
Nagase is a top student in high school. One day, she's analyzing some properties of special sets of positive integers. She thinks that a set S = \\{a_{1}, a_{2}, ..., a_{N}\\} of distinct positive integers is called special if for all 1 \leq i \leq N, the gcd (greatest common divisor) of a_{i} and the sum of the remai...
N=input() if N==3: print "2 5 63" quit() elif N==4: print "2 5 20 63" quit() #N>=5 #For 2 and 3 S=[2,3,4] N-=3 x=N/4 # N=4x+b b=N%4 for i in range(1,x+1): S.append(6*i) S.append(6*i+2) S.append(6*i+3) S.append(6*i+4) if x%2==0: if b==0: S.remove(6*x+3) S.append(6*x+6) elif b==1: S.append(6*(x+1)+...
Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K. Constraints * 2 \leq K \leq 10^5 * K is an integer. Input Input is given from Standard Input in the following format: K Output Print the smallest possible sum of the digits in the decimal notation of a positive mu...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pr...
You are given a image with a height of H pixels and a width of W pixels. Each pixel is represented by a lowercase English letter. The pixel at the i-th row from the top and j-th column from the left is a_{ij}. Put a box around this image and output the result. The box should consist of `#` and have a thickness of 1. ...
#include <stdio.h> int main(void) { int i, j, h, w; scanf("%d%d", &h, &w); char s[w + 10]; for(i = 0; i < w + 2; ++i) printf("#"); printf("\n"); for(i = 0; i < h; ++i) { scanf("%s", s); printf("#%s#\n", s); } for(i = 0; i < w + 2; ++i) printf("#"); return 0; }
There are two (6-sided) dice: a red die and a blue die. When a red die is rolled, it shows i with probability p_i percents, and when a blue die is rolled, it shows j with probability q_j percents. Petr and tourist are playing the following game. Both players know the probabilistic distributions of the two dice. First,...
#include <bits/stdc++.h> using namespace std; typedef long long LL; double p[6]; double q[6]; double ans = 1.0; void test(double prob){ double cur = 0; for(int i = 0; i < 6; i++){ cur += max(prob*p[i],(1.0-prob)*q[i]); } ans = min(ans,cur); } int main(){ for(int i = 0; i < 6; i++) cin >> p[i]; for(int i = 0; i...
We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball. Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i. Find the number of boxes that may ...
n,m=map(int,input().split()) cnt=[1]*n res=[0]*n res[0]=1 for i in range(m): x,y=map(int,input().split()) if res[x-1]==1: res[y-1]=1 if cnt[x-1]==1: res[x-1]=0 cnt[x-1]-=1 cnt[y-1]+=1 print(sum(res))
There are a total of W x H squares, with H rows vertically and W columns horizontally. Some squares are marked. Create a program that reads the marked state of each square and outputs the maximum rectangular area consisting of only the unmarked squares. The input data consists of one line of W characters, given H line...
import java.util.*; public class Main { public static void main(String[] args) { new Main().run(); } String table[]; void run() { Scanner sc = new Scanner(System.in); for (;;) { int R = sc.nextInt(); int C = sc.nextInt(); if (R == 0 && C == 0) break; table = new String[R]; for (int r = 0...
Gaku decided to observe the ant's nest as a free study during the summer vacation. The transparent observation case that his grandpa prepared for his grandchildren is very unique and looks like Figure 1. Ant nest Figure 1 This case consists of two congruent convex polygons s1 and s2 and some rectangles. Place one o...
#include<iostream> #include<vector> #include<complex> #include<algorithm> using namespace std; typedef double R; typedef complex<R> P; typedef vector<P> G; #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 X real() #define Y imag() const R EPS = 1e-8; const R INF = 1...
There are n sheets of square paper of the same size. Align the bottom of these papers horizontally and arrange them in several rows. However, adjacent rows must be arranged so that the left side is not lower than the right side. For example, n When = 5, the following 7 ways of arranging are possible. <image> We wil...
#include <iostream> #include <stack> using namespace std; stack<int> s; int a[31]; int f(int n){ if(n){ for(int i=n;i>0;--i){ if(s.empty()||s.top()>=i){ s.push(i);f(n-i);s.pop(); } } } else{ if(!s.empty()){ stack<int> t(s); int b=t.size(); for(int i=b-1;i>=0;--i){ a[i...
Taro loves chocolate and when he returns from school he eats his favorite chocolate bar with a heart symbol on it. A recent pleasure is to eat all the heart symbol blocks to the end. Taro , Try to eat as many heartless blocks as possible, with all heartmark blocks connected. <image> However, Taro is still young, and ...
#include<iostream> #include<vector> #include<algorithm> using namespace std; const int INF = 1000000000; int main() { int H, W; while(cin >> H >> W, H | W) { int n = H * W; vector<vector<int>> A(n, vector<int>(n, INF)); vector<int> heart; for(int i = 0; i < n; ++i) A[i][i] = 0;...
Prime Caves An international expedition discovered abandoned Buddhist cave temples in a giant cliff standing on the middle of a desert. There were many small caves dug into halfway down the vertical cliff, which were aligned on square grids. The archaeologists in the expedition were excited by Buddha's statues in thos...
import java.util.Arrays; import java.util.Scanner; public class Main { Scanner sc; int n, m; int MAX = 1000; int ofs = MAX / 2; int[][] dp, cave, pr; int LIM = 1000000; int[] tx = new int[] { 1, 0, -1, 0 }; int[] ty = new int[] { 0, -1, 0, 1 }; void run() { while (true) { m = ni(); ...
Mathematical expressions appearing in old papers and old technical articles are printed with typewriter in several lines, where a fixed-width or monospaced font is required to print characters (digits, symbols and spaces). Let us consider the following mathematical expression. <image> It is printed in the following f...
#include <iostream> #include <cstdio> #include <vector> #include <complex> #include <algorithm> #include <set> #include <map> #include <queue> #include <string> #include <cstring> #include <stack> #include <cmath> #include <iomanip> #include <sstream> #include <cassert> using namespace std; typedef long long ll; type...
Background The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves drawing as much as programming. So far, Yu-kun has drawn many pictures with circles and arrows. The arrows are always drawn to connect the circles. On...
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> edge; #define to first #define cost second int main() { cin.tie(NULL); ios::sync_with_stdio(false); int n, m, w; cin >> n >> m >> w; vector<int> in(n, 0); vector<vector<edge>> G(n); for(int i = 0; i < m; ++i) { int s, t, c; c...
You have moved to a new town. As starting a new life, you have made up your mind to do one thing: lying about your age. Since no person in this town knows your history, you don’t have to worry about immediate exposure. Also, in order to ease your conscience somewhat, you have decided to claim ages that represent your r...
#include<stdio.h> #include<algorithm> using namespace std; char str[20]; char s[20]; int main(){ int a,b,c; while(scanf("%d%d%d",&a,&b,&c),~a){ bool ok=false; sprintf(str,"%d",b); for(int i=2;i<17;i++){ long long tmp=0; for(int j=0;str[j];j++){ tmp*=i; tmp+=str[j]-'0'; } bool OK=true; for...
Heiankyo is known as a town with a grid of roads. Hokusai, a cat who lives in Heiankyo, has to go from his home to a secret place on the outskirts of town every day for patrol. However, I get tired of following the same path every day, and there is a risk of being followed, so Hokusai wants to use a different route ev...
//Name: Heian-Kyo Walking //Level: 2 //Category: 動的計画法,DP //Note: /* * 通れないパターンを覚えておき、グリッドグラフの最短経路数え上げをする。 * * オーダーは O(XY log P)。 */ #include <iostream> #include <set> #include <utility> #include <vector> using namespace std; typedef pair<int,int> Pt; void solve() { int X, Y; cin >> X >> Y; int P; ...
Problem statement Given the string $ S $. Find the number of all anagrams in $ S $ that are palindromic. An anagram of the string $ X $ is an anagram of $ Y $, which means that $ X $ is equal to $ Y $, or that the rearranged characters of $ X $ are equal to $ Y $. For example, for the string abcd, abcd and cbda are a...
import java.util.Scanner; //Palindromic Anagram public class Main{ void run(){ Scanner sc = new Scanner(System.in); long[] f = new long[21]; f[0] = 1; for(int i=1;i<21;i++)f[i]=f[i-1]*i; char[] s = sc.next().toCharArray(); int N = s.length; int[] c = new int[26]; for(char r:s)c[r-'a']++; int odd = ...
Problem Statement Mr. Hagiwara, a witch, has a very negative personality. When she feels depressed, she uses the magic of digging to make holes and cry and fill them. The magic of digging is as follows. She first draws N line segments on the ground. And when she casts the spell, a hole is created in the area surround...
#include <cassert>// c #include <ctime> #include <iostream>// io #include <iomanip> #include <fstream> #include <sstream> #include <vector>// container #include <map> #include <set> #include <queue> #include <bitset> #include <stack> #include <algorithm>// other #include <complex> #include <numeric> #include <functiona...
Example Input 8 0 2 0 0 2 0 2 1 3 1 3 3 1 3 1 2 Output 1
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> P; typedef pair<int,P> P1; typedef pair<P,P> P2; typedef long long ll; #define pu push #define pb push_back #define mp make_pair #define rep(i,x) for(int i=0;i<x;i++) typedef complex<double> pt; typedef pair<pt,pt> L; typedef vector<P> poly; const doub...
E: Binary Sequence-Binary Sequence- story I love binaries Bonald.Brvin.Bnuth! He is known as Uncle Bnuth, who is studying the nature of binary sequences at Offtunford University! By the way, if my name "Bonald.Brvin.Bnuth" is binarized from ASCII code, it will be "1000010 1101111 1101110 1100001 1101100 1100100 10111...
#include <bits/stdc++.h> using namespace std; class LazySegT{ private: int NN; struct Node{ int f, g, l, r; int lazy; }; Node segT[2*(1<<17)-1]; // =131072 public: LazySegT(int n){ NN = 1; while(NN < n) NN <<= 1; for(int i=0;i<2*NN-1;++i){ segT[i].f = segT[i].g = segT[i].l = segT[i].r = 0; segT...
G: Tree problem Given a tree consisting of N vertices. Each vertex of the tree is numbered from 1 to N. Of the N-1 edges, the i \ (= 1, 2, ..., N-1) edge connects the vertex u_i and the vertex v_i. Write a program to find the number of K non-empty subgraph sets of this tree, each of which is concatenated and no two ...
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <algorithm> #include <utility> #include <functional> #include <cstring> #include <queue> #include <stack> #include <math.h> #include <iterator> #include <vector> #include <string> #include <set> #include <math.h> #include <iostream> #include <random> #include...
Today's Random Number E869120 You ran a campaign called "Today's Random Numbers" for N days. This is a project to generate a random number once a day and post the value on Twitter. The "random numbers of the day" on day $ 1, 2, 3, \ dots, N $ were $ A_1, A_2, A_3, \ dots, A_N $, respectively. E869120 You would be ha...
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <iomanip> using namespace std; int main() { int n; cin >> n; int a; cin >> a; int ret = 0; for (int i = 0; i < n - 1; i++) { int x; cin >> x; if (a < x)ret++; a = x; } ...
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $S$, find the smallest sub-array size (smallest window length) where the sum of the sub-array is greater than or equal to $S$. If there is not such sub-array, report 0. Constraints * $1 \leq N \leq 10^5$ * $1 \leq S \leq 10^9$ * $1 \leq a_i \...
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 100000...