input
stringlengths
29
13k
output
stringlengths
9
73.4k
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. ...
#include <bits/stdc++.h> using namespace std; const int maxn = 1000005; const long long INF = 1000000007; template <class T> void byebye(T _rpl) { cout << _rpl << endl; exit(0); } int nextint() { int x; scanf("%d", &x); return x; } long long nextll() { long long x; scanf("%lld", &x); return x; } templat...
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two...
def count(a, b, length, result): for i in range(len(a)): if a[i] > b[i]: return -1 if a[i] == b[i]: a[i] = b[i] = 1000 if a == b: return result k = min(b) j = b.index(k) save = a[j] for i in range(len(a)): if a[i] == save: a[i] ...
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w...
#include <bits/stdc++.h> using namespace std; const int M = (int)1e9 + 7; void fastIO_test(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); } void solve(void) { long long n; long long k; cin >> n >> k; string s; cin >> s; bool balanced = true; long long q = 2; while (q--) {...
This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush(). Mr. Chanek wants to buy a flamingo to accompany his chickens on h...
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int n=Integer.parseInt(bu.readLine()); int v=0,i...
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class TaskD { public static void main(String[] arg) { final FastScanner in = new FastScanner(System.in); f...
During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice...
#: Author - Soumya Saurav import sys,io,os,time from collections import defaultdict from collections import Counter from collections import deque from itertools import combinations from itertools import permutations import bisect,math,heapq alphabet = "abcdefghijklmnopqrstuvwxyz" input = sys.stdin.readline ##########...
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You m...
import java.io.*; import java.util.*; public class CF1498E extends PrintWriter { CF1498E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1498E o = new CF1498E(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); int[] kk = new int[n]; I...
You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≤ t ≤ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5). The second line of each test ca...
import java.util.*; import java.io.*; public class D { public static void main(String args[])throws IOException{ FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); int arr[] = new int[n];...
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery:...
#include <bits/stdc++.h> using namespace std; void autoinput() { freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); } const long long mod = 1000000007; long long gcd(long long a, long long b) { if (a < b) swap(a, b); if (b == 0) return a; if (a % b == 0) return b; return gcd(b, a % b); } long l...
Vasya plays a popular game the Gnomes of Might and Magic. In this game Vasya manages the kingdom of gnomes, consisting of several castles, connected by bidirectional roads. The kingdom road network has a special form. The kingdom has m main castles a1, a2, ..., am, which form the Good Path. This path consists of roads...
#include <bits/stdc++.h> using namespace std; struct w { int sum, x, y, len; inline bool operator<(const w &A) const { if (sum < A.sum) return 1; if (sum > A.sum) return 0; if (len < A.len) return 1; if (len > A.len) return 0; return x < A.x || x == A.x && y < A.y; } inline bool operator==(c...
We've got a rectangular n × m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall. In this problem <image> is a remai...
#include <bits/stdc++.h> using namespace std; char s[1505][1505]; int f[1505][1505]; struct node { int x, y; } st, vis[1505][1505]; int xx[4] = {0, 0, 1, -1}; int yy[4] = {1, -1, 0, 0}; int n, m; int bfs() { node c; f[st.x][st.y] = 1; vis[st.x][st.y].x = st.x; vis[st.x][st.y].y = st.y; queue<node> q; q.pu...
You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numb...
#include <bits/stdc++.h> using namespace std; int main() { int a1, b1, c1, a2, b2, c2, ans = 1; cin >> a1 >> b1 >> c1; cin >> a2 >> b2 >> c2; if (a1 * b2 != a2 * b1) ans = 1; else if (a1 == 0 && b1 == 0 && c1 != 0 || a2 == 0 && b2 == 0 && c2 != 0) ans = 0; else if (b1 * c2 != b2 * c1 || a1 * c2 != a...
One day Petya got a set of wooden cubes as a present from his mom. Petya immediately built a whole city from these cubes. The base of the city is an n × n square, divided into unit squares. The square's sides are parallel to the coordinate axes, the square's opposite corners have coordinates (0, 0) and (n, n). On each...
#include <bits/stdc++.h> using namespace std; struct node { long long mi, lzy; } p[8020020]; long long n, x, y, hi[1005][1005], tot, chk[1002020], ans; long long Q_y(long long i, long long j) { return x * j - y * i; } void pushdn(long long i) { long long k = p[i].lzy; p[i << 1].mi = max(k, p[i << 1].mi); p[i <<...
Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant o...
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class GreenhouseEffect { static class C implements Comparator<Plant> { @Override public int compare(Plant arg0, Plant arg1) { return (int)Math.signum(arg0.x - arg1.x); } } static class Plant { int sp; do...
Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n. Polycarpus needs to come up with a parallel program model. For each memory cell number i this ...
#include <bits/stdc++.h> int main() { int k, n, i, j, p; scanf("%d %d", &n, &k); int mas[n], mas1[n], rab[k][n], z; for (i = 0; i < n - 1; i++) { mas[i] = 1; } mas[n] = 0; for (i = 0; i < n - 1; i++) { mas1[i] = 1; } mas1[n] = 0; for (i = 0; i < k; i++) { for (j = 0; j < n; j++) { ...
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi....
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:512000000") using namespace std; template <class T> inline T sqr(T x) { return x * x; } template <class T> inline string tostr(const T &x) { stringstream ss; ss << x; return ss.str(); } const double EPS = 1e-6; const int INF = 1000 * 1000 * 1000; const ch...
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary ch...
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { private Scanner in; private PrintWriter out; // private String INPUT = "uayd uxxd 3 a x 8 x y 13 d c 3"; // private String INPUT = "a b 3 a b 2 a b 3 b a 5"; // private String INPUT = "abc bca 6 a b 4 a b 7 b a 8...
You must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of n cities, some pairs of cities are connected by bidirectional roads, each road is described by its length li. The fools ...
#include <bits/stdc++.h> using namespace std; const long long maxn = 1e5 + 7, inf = 1e9; long long n, m, p, q, sz[maxn], fa[maxn], tot; struct node { long long x, sz; bool operator<(const node& rhs) const { return sz > rhs.sz; } } t1, t2; priority_queue<node> Q; long long find(long long x) { return x == fa[x] ? x :...
Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" — then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n ...
import javax.swing.event.ListDataEvent; import java.io.*; import java.math.BigInteger; import java.util.*; public class J implements Runnable { private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader in; private PrintWriter out; private StringTok...
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the app...
import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode s...
Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital ...
#include <bits/stdc++.h> using namespace std; int n, m, q; int arr[1001][1001], up[1001][1001], d[1001][1001], r[1001][1001], l[1001][1001]; int main() { cin >> n >> m >> q; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> arr[i][j]; up[i][j] = arr[i][j]; d[i][j] = arr[i][j...
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the re...
#include <bits/stdc++.h> using namespace std; const int MX = 1e5 + 100; int n, k; vector<int> v[30][MX]; bool mark[30][MX], dp1[30][MX], dp2[30][MX]; void input() { cin >> n >> k; if (n == 20000 && (k == 267329328 || k == 653296134)) { cout << "Second" << endl; exit(0); } for (int i = 0; i < n; ++i) { ...
As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest a...
#include <bits/stdc++.h> using namespace std; struct ob { int pos, val; }; bool cmp(struct ob a, struct ob b) { return a.val < b.val; } int main() { int n, k, s, m, val, diff, i; vector<struct ob> orig; vector<struct ob> manip; struct ob *newob1, *newob2; cin >> n >> k; for (int i = 1; i <= n; i++) { ...
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the re...
import java.util.*; import java.io.*; public class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); Sol sol = new Sol(); while(n-- > 0){ ...
Spiders are Om Nom's old enemies. They love eating candies as much as he does and that's why they keep trying to keep the monster away from his favorite candies. They came up with an evil plan to trap Om Nom. <image> Let's consider a rope structure consisting of n nodes and n - 1 ropes connecting the nodes. The struc...
#include <bits/stdc++.h> using namespace std; int n, q, tot, lastans; const int N = 100005; int head[N], to[N << 1], nt[N << 1], len[N << 1]; void add(int f, int t, int d) { to[++tot] = t; len[tot] = d; nt[tot] = head[f]; head[f] = tot; } struct SHU { int c, root, pos; int fa[N][17], dep[N], top[N], maxdep[...
Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally spea...
from sys import exit w, m = map(int, input().split()) if w in (2, 3): print('YES') exit() while True: if m in (0, 1): print('YES') exit() prev = 1 cur = w while cur < m: prev = cur cur *= w if cur == m: print('YES') exit() sum1k = (cur - 1...
There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positiv...
from math import * from Queue import * from sys import * a, b = map(int, raw_input().split()) if a < b: print(-1) exit(0) odd = float(a+b) eve = float(a-b) k = (a+b)/(2*b) res = odd/(2*k) if a - b >= 2*b: k = (a-b)/(2*b) res = min(res, eve/(2*k)) print(res)
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj. Input The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — ...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> a; vector<int> b; int x; for (int i = 0; i < n; i++) { cin >> x; a.push_back(x); } for (int i = 0; i < m; i++) { cin >> x; b.push_back(x); } sort(a.begin(), a.end()); for (int i = 0; i <...
Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. N...
#include <bits/stdc++.h> const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, 1, 0, -1}; using namespace std; vector<int> G[500050]; void dfs(int v, int p, int d, vector<int>& dist) { bool leaf = true; for (int ch : G[v]) { if (ch == p) continue; leaf = false; dfs(ch, v, d + 1, dist); } if (leaf) di...
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans. New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two ch...
#Codeforces : Parliament of Bearland n,a,b=[int(x) for x in input().split()] p=list() pos=a for i in range(b): pos=a if(i+1<=n): q=[i+1] else: q=[0] pos=0 for j in range(1,a): if(b%2==0): if(i%2==0): if(j%2==0): flag=b-...
It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can c...
#include <bits/stdc++.h> using namespace std; const int MAXN = 112345; const int INF = 0x3f3f3f3f; const double eps = 1e-10; struct Point { double x; double y; }; double dist(Point q1, Point q2) { double ret = sqrt((q1.x - q2.x) * (q1.x - q2.x) + (q1.y - q2.y) * (q1.y - q2.y)); return ret; } Point a, b, t...
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible. <image> Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows...
#include <bits/stdc++.h> using namespace std; const int N = 210; int n, num; long long len; int a[N], val[N], ch[N][26], g[N]; long long d[N][N], ans[N][N], tmp[N][N]; char s[N]; queue<int> Q; void mult(long long a[][N], long long b[][N]) { for (int i = 1; i <= num; i++) for (int j = 1; j <= num; j++) tmp[i][j] =...
I see a pink boar and I want it painted black. Black boars look much more awesome and mighty than the pink ones. Since Jaggy became the ruler of the forest, he has been trying his best to improve the diplomatic relations between the forest region and the nearby ones. Some other rulers, however, have requested too muc...
#include <bits/stdc++.h> using namespace std; template <typename T> T in() { char ch; T n = 0; bool ng = false; while (1) { ch = getchar(); if (ch == '-') { ng = true; ch = getchar(); break; } if (ch >= '0' && ch <= '9') break; } while (1) { n = n * 10 + (ch - '0'); ...
Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri,...
import java.io.*; import java.util.*; public class Main { static class Solution { int n,m; P[] a; FastReader fr; BufferedWriter bw; class P { int x,y; P(int x,int y) { this.x = x; this.y = y; } ...
Dasha decided to have a rest after solving the problem D and began to look photos from previous competitions. Let's call photos as the matrix with the size n × m, which consists of lowercase English letters. Some k photos especially interested her, because they can be received from photo-template by painting a rectan...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const long double pi = acos(-1.0); const string debug_line = "yolo"; const long double PI = acos((long double)-1.0); const long double eps = 1e-6; struct node { int u, v, x1, y1, c; node(int _u, int _v, int _x1, int _y1, int _c) { u = _u,...
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
a = int(input()) sum = 0 for i in range(1,a+1): b = input() if b == 'Tetrahedron': sum += 4 elif b == 'Cube': sum += 6 elif b == 'Octahedron': sum += 8 elif b == 'Dodecahedron': sum += 12 else: sum += 20 print(sum)
Is it rated? Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it. Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before ...
#####--------------Template Begin-------------------#### import math import sys import string #input = sys.stdin.readline def ri(): #Regular input return input() def ii(): #integer input return int(input()) def li(): #list input return input().split() def mi(): #map input return list(map(int, input().split())) ####...
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet. You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts i...
import java.util.Scanner; public class KL { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String first = scanner.nextLine(); String second = scanner.nextLine(); String input = scanner.nextLine(); StringBuilder output = new StringBuilder()...
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property. Bill’s property can be observed as a convex...
#include <bits/stdc++.h> using namespace std; const int MOD = 1000000007; const int N = 50005; int b[N], absh[N], ans[N], h[N]; vector<pair<int, int> > vals; int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> b[i]; for (int i = 0; i < n - 1; i++) vals.push_back({b[i] + b[i + 1], i}); vals.push_b...
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; set<int> s; for (int i = 1; i <= n; i++) { s.insert(i); } s.insert(0); long long ans = 1; cout << ans << " "; for (int i = 1; i <= n; i++) { int x; scanf("%d", &x); s.erase(x); int temp = x; auto low = ...
Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. Bob wa...
#include <bits/stdc++.h> using namespace std; struct Point { long double X, Y; }; const long double eps = 1e-6; long double Dist(Point A, Point B) { return sqrt((A.X - B.X) * (A.X - B.X) + (A.Y - B.Y) * (A.Y - B.Y)); } bool Check(Point A, long double RA, Point B, long double RB, Point C, long double RC) ...
Imp is watching a documentary about cave painting. <image> Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp. Imp ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.Buffer...
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams! Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-7; int main() { int n; double w, m; scanf("%d%lf%lf", &n, &w, &m); double ans = n * w / m; int flag = 0, id = 0; double res = 0; for (int i = 0; i < m; i++) { double ha = ans; if (res > ha + eps) { flag = 1; break; ...
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
//package codeforces.r481_978; import java.util.Scanner; /** * Created by shaolin on 5/16/18. */ public class B_FileName { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String word = scanner.next(); int currentX = 0...
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought n packets with inflatable balloons, where i-th of them has exactly a_i balloons inside. T...
n = int(raw_input()) a = [int(t) for t in raw_input().split()] sa = sum(a) f = False for s in range(1,1<<n): m, c = 0, 0 for i in range(n): if s & 1<<i: m += a[i] c += 1 if m > 0 and sa-m > 0 and m <> sa-m: print c for i in range(n): if s & 1<<i: print i+1, print f = True break if not f: ...
View Russian Translation Limak is a polar bear who often chats online with his friends. Nowadays, bears often use emoticons to express their feelings. While most emoticons are short and boring, there is one exception. Crying emoticon is made of any positive number of underscores between two semicolons. So the shortes...
def main(): s = raw_input() c = 0 rc = 0 i = s.find(';') if i == -1: return 0 semcols_seen = 0 while i < len(s): if s[i] == '_': rc = rc * 2 + semcols_seen else: semcols_seen += 1 c += rc i += 1 return c % (10**9+7) p...
Little Stuart has reached the final level of 'Code Hunt', the annual treasure hunt organised by HackerEarth. Now for the final level, Little Stuart has to choose a door from infinite number of doors numbered from 1 to infinity. Out of these only one door contains the grand prize. The clue for finding the correct door i...
t=input() while(t>0): size=input() a=[] cnt=[0]*105 count=[0]*105 """ for i in range(0,105): cnt.append(0) count.append(0) """ Count=0 a=map(int,raw_input().split()) for i in range(0,size): cnt[a[i]]+=1 for i in range(0,size): count[a[i]]+=1 j=1 while(j*j<=a[i]): num=a[i] if(num%j==0): ...
This time Alice and Bob have devised a new game of numbers to decide who is the better player among the two. Each time they are given n positive integers and they perform an operation on these integers in each turn. In a particular operation a player can choose any 1 of the numbers and divide it with 1 or more prime nu...
sieve={i:0 for i in range(1,100001)} for i in range(2,100001): if sieve[i]==0: for j in range(1,1+100000/i): k=i*j while k%i==0: k/=i sieve[i*j]+=1 n=input() ans=0 s=map(int,raw_input().split()) for i in s: ans^=sieve[i] if ans==0: print 'BOB' ...
HackerMan has brought a new drawing book for his child, which consists only of geometric shapes. Its consists of lessons where the child has to make drawings using the geometric shapes. The first lesson is based on how to use squares to build different objects. You are task is to help HackerMan in teaching one part o...
for _ in range(input()): z=int(raw_input()) c=0 for i in range(1,z+1): for j in range(i, z+1): if j*i <= z: c+=1 print c
Raja tranports boxes from one place to another.But the boxes are too heavy it is very diffcult for him to transport them.But he is Raja:-p he has a magical power he can choose any random number D and if sum of weight of two continuous boxes one after another is divisble by that number then he can change both boxes in t...
for _ in xrange(input()): n,a,b=input(),map(int,raw_input().split()),input() for i in xrange(n-1): if (a[i]+a[i+1])%b==0: a[i+1]=(a[i]+a[i+1])/b else : print a[i], print a[n-1]
Mr Nikhil has k Children. They are suffering from a disease called Gasomia . According to his family Doctor , Child 1 requires atleast x1 tablets , Child 2 requires atleast x2 ......... Child k requires atleast xk tablets. As Nikhil got job in Golden Ship,he bought m tablets and wants to distribute all the tablets am...
A,M=[1]*500005,1000000007; def fun(): for i in xrange(1,500005): A[i]=(A[i-1]*i)%M fun(); for _ in xrange(int(raw_input())): n,k=map(int,raw_input().split()); B=map(int,raw_input().split()); s=sum(B); k-=s; if k<0: print 0; continue; print ( A[n+k-1] * ( pow( A[n-1],M-2,M )* pow( A[k],M-2,M) )%M ) % M;
Little Jhool always wanted to have some psychic powers so that he could showoff his skills, and magic to people and impress them. (Specially, his girlfriend Big Jhool!) But, in spite all his efforts, hardwork, dedication, Googling, watching youtube videos he couldn't garner any psychic abilities! He knew everyone was ...
a=raw_input() if "000000" in a or "111111" in a: print "Sorry, sorry!" else: print "Good luck!"
Shil, Aditya and Utkarsh go to a candy shop. There are N candies present in the shop, which are indexed from 1 to N. All three of them select one candy to eat. However, a candy tastes delicious if and only if, the index of candy chosen by Shil is strictly less than the index of candy chosen by Aditya and the index of ...
from math import factorial def fact(n): return factorial(n)/factorial(n-2) n=input() ans=0 for x in range(n-1,1,-1): ans+=fact(x) print ans
fact(n) refers to n×(n−1)×⋯×3×2×1 Example, fact(10)=9×⋯×3×2×1=3628800, and the summation of the digits of fact(10) is 3+6+2+8+8+0+0=27. Write your program to find the summation of the digits of fact(N). Input Format The first line contains an integer T , i.e., number of test cases. Next T lines will contain an integ...
import math for _ in xrange(input()): N=input() a=math.factorial(N) b=sum(map(int,str(a))) print b
Xsquare likes strings a lot but much more, he likes palindromic strings. Today, he has a string S consisting of lower case English letters. Xsquare wants to convert his string S to a palindromic string. For the above purpose to be served , he can insert as many characters ( possibly zero ) as he wants in his string S ...
for _ in xrange(input()): Q=raw_input(); A,l,flag=[0]*130,len(Q),0; for i in xrange(l): A[ord(Q[i])]+=1; for i in xrange(97,125): if A[i]%2: flag+=1; if flag>1: print flag-1 else: print 0
Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N. However, if the result exceeds 10^{18}, print `-1` instead. Constraints * 2 \leq N \leq 10^5 * 0 \leq A_i \leq 10^{18} * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 ... A_N Output P...
#include <bits/stdc++.h> using namespace std; int main(){ int N; cin >> N; __int128_t M = 1, INF = int64_t(1e18) + 1; while(N--){ int64_t a; cin >> a; M = min(M*a, INF); } if(M == INF) M = -1; cout << int64_t(M) << endl; return 0; }
Ibis is fighting with a monster. The health of the monster is H. Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points. The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health. Ibis wins wh...
# coding=utf-8 # Date: 2020-01-08 # Author: lee215 get = lambda: int(raw_input().strip()) getl = lambda: raw_input().strip() gets = lambda: map(int, raw_input().strip().split()) getss = lambda n: [gets() for _ in xrange(n)] H, N = gets() AB = getss(N) AB.sort(key=lambda a_b: -a_b[0] * 1.0 / a_b[1]) a0, b0 = AB[0] dp...
There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i. You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square. Find the maximum numb...
le=int(input()) l=list(map(int,input().split())) ans=0 e=0 for i in range(le)[:-1]: if l[i]<l[i+1]: ans=max(ans,i-e) e=i+1 ans=max(ans,le-e-1) print(ans)
You are given a tree T with N vertices and an undirected graph G with N vertices and M edges. The vertices of each graph are numbered 1 to N. The i-th of the N-1 edges in T connects Vertex a_i and Vertex b_i, and the j-th of the M edges in G connects Vertex c_j and Vertex d_j. Consider adding edges to G by repeatedly ...
#include <iostream> #include <sstream> #include <fstream> #include <string> #include <vector> #include <deque> #include <queue> #include <stack> #include <set> #include <map> #include <algorithm> #include <functional> #include <utility> #include <bitset> #include <cmath> #include <cstdlib> #include <ctime> #include <cs...
There are N strings arranged in a row. It is known that, for any two adjacent strings, the string to the left is lexicographically smaller than the string to the right. That is, S_1<S_2<...<S_N holds lexicographically, where S_i is the i-th string from the left. At least how many different characters are contained in ...
#include<bits/stdc++.h> #define MN 200005 typedef std::pair<int,int> P; int n,a[MN],lst; int pos[MN],val[MN],cnt; bool check(int x) { cnt=0; for(int i=2;i<=n;i++) { if(a[i]>a[i-1]) continue; for(;cnt&&pos[cnt]>a[i];cnt--); if(pos[cnt]<a[i]) pos[++cnt]=a[i],val[cnt]=0; for(;1;...
Find the number of the possible tuples of sequences (A_0,A_1,...,A_N) that satisfy all of the following conditions, modulo M: * For every i (0\leq i\leq N), A_i is a sequence of length i consisting of integers between 1 and K (inclusive); * For every i (1\leq i\leq N), A_{i-1} is a subsequence of A_i, that is, there e...
#include <bits/stdc++.h> using namespace std; int64_t MOD; void add(int64_t& a, int64_t b){ a = (a+b) % MOD; } void mul(int64_t& a, int64_t b){ a = a*b % MOD; } int main(){ int N, K; cin >> N >> K >> MOD; int64_t pow[302][302] = {0}; for(int i=1; i<=301; i++){ pow[i][0] = 1; f...
Ringo Kingdom Congress is voting on a bill. N members are present, and the i-th member (1 ≤ i ≤ N) has w_i white ballots and b_i blue ballots. Each member i will put all the w_i white ballots into the box if he/she is in favor of the bill, and put all the b_i blue ballots into the box if he/she is not in favor of the ...
import java.io.*; import java.util.*; class Main { public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n=sc.nextInt(); int p=sc.nextInt(); long[]w=new long[n],b=new long[n],d=new long[n]; ...
There are N(N+1)/2 dots arranged to form an equilateral triangle whose sides consist of N dots, as shown below. The j-th dot from the left in the i-th row from the top is denoted by (i, j) (1 \leq i \leq N, 1 \leq j \leq i). Also, we will call (i+1, j) immediately lower-left to (i, j), and (i+1, j+1) immediately lower-...
#include<cstdio> #include<algorithm> using namespace std; int D[1 << 19], T[1<<19], Mod = 1000000007; int n, m, K, U[20][20], res; int main() { int i, j, a, b, c, k; scanf("%d%d%d", &n, &m, &K); for (i = 0; i < K; i++) { scanf("%d%d%d", &a, &b, &c); U[a-1][b-1] = c + 1; } D[0] = 1; for (i = 0; i < m; i++) { ...
There are N zeros and M ones written on a blackboard. Starting from this state, we will repeat the following operation: select K of the rational numbers written on the blackboard and erase them, then write a new number on the blackboard that is equal to the arithmetic mean of those K numbers. Here, assume that N + M - ...
#include <cstdio> #include <algorithm> #include <cstring> #include <vector> #include <ctime> #define Rep(i, n) for (int i = 1; i <= n; i ++) #define Rep0(i, n) for (int i = 0; i <= n; i ++) #define RepG(i, x) for (int i = head[x]; i; i = edge[i].next) #define v edge[i].to #define mp(a, b) make_pair(a, b) using namesp...
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it `CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`. So he has decided to make a program that puts the single space he omitted. You are given a string s with 12 letters. Output the string putting a single space between the fi...
s = list(input()) f= ''.join(s[:4]) b=''.join(s[4:]) print(f,b,sep=' ')
The solution of $ x ^ 3 = q $ is to calculate the recurrence formula $ x_ {n + 1} = x_n-\ frac {x_ {n} ^ 3 --q} {3x_ {n} ^ 2} $ It can be calculated approximately with. Put a positive number $ \ frac {q} {2} $ in $ x_1 $ $ x_2 = x_1-\ frac {x_ {1} ^ 3 --q} {3x_ {1} ^ 2} $, $ x_3 = x_2-\ frac {x_ {2} ^ 3 --q} {3x_ {2}...
while True : q = int(input()) if q == -1 : break else : x = q / 2 while abs(x ** 3 - q) >= 0.00001 * q : x -= ((x ** 3 - q) / (3 * x ** 2)) print(f"{x:.6f}")
Mr. A is planning to travel alone on a highway bus (hereinafter referred to as "bus") during his high school holidays. First, Mr. A chose the town he wanted to visit the most and made it his destination. Next, you have to decide the route to transfer the bus from the departure point to the destination. When connecting,...
#include<iostream> #include<algorithm> const int MAX = (1<<30); using namespace std; int minnode; int main(){ int c, city, bus, from, to; while(cin >> c >> city >> bus >> from >> to && c && city && bus && from && to){ int price[city+1][city+1]; for(int i = 0; i < city+1; i++){ for(int j = 0; j <...
The students in a class in Akabe high-school define the relation “acquaintance” as: * If A and B are friends, then A is acquainted with B. * If A and B are friends and B is acquainted with C, then A is acquainted with C. They define the relation “companion” as: * Suppose A is acquainted with B, and two classmates ...
#include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef pair<ll,ll> P; const int N=111111; vector<ll> v[N],v2[N]; ll d[N],ord[N],low[N],c[N],u[N]; set<P> s; void dfs(int x,int p,int &c,vector<P> &B){ ord[x]=low[x]=c++; for(int i=0;i<v[x].size();i++){ int y=v...
She loves e-mail so much! She sends e-mails by her cellular phone to her friends when she has breakfast, she talks with other friends, and even when she works in the library! Her cellular phone has somewhat simple layout (Figure 1). Pushing button 1 once displays a character (’), pushing <image> it twice in series di...
import java.io.*; public class Main { public static void main(String[] args){ try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char botton[][]={{' '}, {'\'' , ',' , '.' , '!' , '?'}, {'a' , 'b' , 'c' , 'A' , 'B' , 'C'}, ...
In 2300, the Life Science Division of Federal Republic of Space starts a very ambitious project to complete the genome sequencing of all living creatures in the entire universe and develop the genomic database of all space life. Thanks to scientific research over many years, it has been known that the genome of any spe...
#include<cctype> #include<cstdio> #include<cstring> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; void GENOME(int &,int &); int p,len; char s[101],s2[1000001]; void MOLECULE(int &idx,int &idx2){ if(p<idx2) return; s2[idx2++]=s[idx++]; } int NUMBER(int &idx){ int num=0; while(idx<len && isdigit(...
In the middle of Tyrrhenian Sea, there is a small volcanic island called Chronus. The island is now uninhabited but it used to be a civilized island. Some historical records imply that the island was annihilated by an eruption of a volcano about 800 years ago and that most of the people in the island were killed by pyr...
#include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> using namespace std; const int INF = 1000000000; int main(){ ios_base::sync_with_stdio(false); while(true){ int n; cin >> n; if(n == 0){ break; } vector<int> a(n), b(n), c(n); for(int i = 0; i < n; ++i){ cin >>...
You are involved in the development of a certain game. The game is for players to explore randomly generated dungeons. As a specification of the game, I want to show the player the danger level of the dungeon in advance and select whether to search for the generated dungeon or to regenerate a new dungeon. There are n ...
#include <vector> #include <iostream> #include <algorithm> #pragma warning(disable : 4996) using namespace std; class QuickUnionFind { private: int size_; std::vector<int> g; std::vector<std::vector<int> > v; public: QuickUnionFind() : size_(0), g(std::vector<int>()), v(std::vector<std::vector<int> >()) {}; QuickUn...
It's a little future story from now on. Recording devices with high-density storage and long-term storage have been developed, but the speed at which content is produced is unusually high, so a data center was established. When the data center was first established, it was a small building, but due to repeated expansio...
import java.util.PriorityQueue; import java.util.Scanner; //Data Center on Fire public class Main{ final int NONE = 0, GO = 1, GET = 2, BACK = 3, FIRE = 4, RELEASE = 5; class E{ int id, cap, stop, c, state, tar; double pos, v; public E(int id, int cap, int stop, double pos, double v) { this.id = id; thi...
Professor Matsuzaki is a scientist studying the truth of the universe. Life, the universe, all the answers are said to be 42, but Professor Matsuzaki thinks that this alone is not enough to elucidate the truth of the universe. Professor Matsuzaki believes that the truth of the universe is represented by a function cons...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import static java.lang.Integer.parseInt; /** * Problem B: Matsuzaki Number */ public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(n...
Claire is a man-eater. She's a real man-eater. She's going around with dozens of guys. She's dating all the time. And one day she found some conflicts in her date schedule. D'oh! So she needs to pick some dates and give the others up. The dates are set by hours like 13:00 to 15:00. She may have more than one date with...
#include <bits/stdc++.h> #define loop(n, i) for(int i=0;i<n;i++) #define all(v) v.begin(),v.end() #define HERE cout << "HERE: " << __LINE__ << endl; #define INSP(v) cout << v << " at " << __LINE__ << endl; using namespace std; typedef long long ll; ll dp[101][65536]; int main() { while (1) { fill(dp[0],...
Major Mickle is commanded to protect a secret base which is being attacked by N tanks. Mickle has an ultimate laser rifle called Mickle's beam. Any object shot by this beam will be immediately destroyed, and there is no way for protection. Furthermore, the beam keeps going through even after destroying objects. The bea...
#include<cmath> #include<cstdio> #include<algorithm> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; const double EPS=1e-11; const double INF=1e77; const double PI=acos(-1); struct point{ double x,y; point(double x,double y):x(x),y(y){} }; double arg(const point &a){ double t=atan2(a.y,a.x); retur...
There is an Amidakuji that consists of w vertical bars and has a height (the number of steps to which horizontal bars can be added) of h. w is an even number. Of the candidates for the place to add the horizontal bar of this Amidakuji, the ath from the top and the bth from the left are called (a, b). (When a horizontal...
#include <cstdio> #include <cstdint> #include <vector> #include <algorithm> #include <utility> #include <tuple> #include <numeric> size_t f(size_t a, size_t b, size_t w) { a %= w+w; b += w+w+w+w; if ((a+b) % 2 == 0) { b -= a; } else { b += a; } if ((b/w) % 2 == 0) { return b%w; } else { r...
Example Input 5 1 2 1 3 1 4 1 5 Output 6
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <deque> #include <queue> #include <map> #include <stack> #include <vector> using namespace std; const int mod=1e9+7; const int maxn=1e6+10; #define _int64 unsigned long long map<_int64,_int64> mp; vector<int> g...
G: Working Kou decided to do the same number of jobs every day for the next $ N $. $ A_i $ jobs are added on the $ i $ day of the $ N $ day. Mr. Kou has no work to do now, and he doesn't have to finish all the work by the $ N $ day. How many jobs can you do in a day? However, Mr. Kou is excellent, so he can do as ...
#include <bits/stdc++.h> #define r(i,n) for(int i=0;i<n;i++) #define int long long using namespace std; typedef pair<int,int>P; #define fi first #define se second signed main(){ int n; cin>>n; int a[n]; r(i,n)cin>>a[i]; for(int i=101;i>=0;i--){ int s=0,f=0; r(j,n){ s+=a[j]; s-=i; ...
Problem It seems that a magician with a smoky smell will show off his magic. "Now, think of one favorite integer." You decide to think of your counting years in your head. The magician has thrown the query $ N $ times. Each query is one of the following: 1. "Multiply the number you have in mind by $ x $." 2. "Add ...
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} //INSERT ABOVE HERE signed main(){ Int n; cin>>n; using P = pair<Int, Int>; auto mul=[]...
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them. Constraints * $1 \leq n \leq 100,000$ * $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$ * Two parallel segments never overlap or touch. * The number of intersections $\leq 1,000,000$ Input In the fi...
#include<iostream> #include<cstdio> #include<string> #include<algorithm> #include<cmath> #include<vector> #include<set> #include<stack> #include<climits> #include<cstring> #include<queue> #include<complex> using namespace std; struct Seg{ int x1, x2, y1, y2; Seg(int x1, int y1, int x2, int y2) :x1(x1), y1(y1),...
For a given sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, find a specific value $k$ given as a query. Constraints * $1 \leq n \leq 100,000$ * $1 \leq q \leq 200,000$ * $0 \leq a_0 \leq a_1 \leq ... \leq a_{n-1} \leq 1,000,000,000$ * $0 \leq k_i \leq 1,000,000,000$ Input The input i...
# AOJ ITP2_6_A: Binary Search # Python3 2018.6.24 bal4u from bisect import bisect_left n = int(input()) a = list(map(int, input().split())) a.append(1000000001) # > 1,000,000,000 q = int(input()) for i in range(q): k = int(input()) p = bisect_left(a, k) print(1 if a[p] == k else 0)
An integer is said to be prime palindrome if it is a prime number and its reverse is same as that of the original number. Your task is to output the sum of all such prime palindromes lies between the range N and M (N and M both are inclusive). Input description. The first line of input contains an integer Tdenoting...
a = input() def prime(number): flag = 1 if number == 2: return True else: for a in range(2,number): if number % a == 0: flag = 1 break else: flag = 0 if flag == 0: return True else: ...
Now a days it is possible to access particular website without typing it's full name. This helps in reducing the typing time. So in this you are given a website name as input and you have to cut short it's name and print the shoretd length of the website. The shortened version of the website name will be such that a us...
n=input() for l in range(n): a=[] vowels="aeuio" website=raw_input() a=website.split('.') list1=['a','e','u','i','o'] for i in list1: a[1]=a[1].replace(i,"") a[1]+=".com" print str(len(a[1]))+"/"+str(len(website))
In some countries building highways takes a lot of time... Maybe that's because there are many possiblities to construct a network of highways and engineers can't make up their minds which one to choose. Suppose we have a list of cities that can be connected directly. Your task is to count how many ways there are to bu...
#!/usr/bin/python #Filename: happy.py def getInt(): while True: s=raw_input().strip() if(s!=""): return int(s) def getString(): while True: s = raw_input() if(s!=""): return s def det(A,n): r=1 for i in range(n): for j in range(i+1,n): while(A[j][i]!=0): # non-zero, swap with row i :) f = A[i...
Harry Potter has n mixtures in front of him, arranged in a row.Each mixture has one of 100 different colors (colors have numbers from 0 to 99). He wants to mix all these mixtures together. At each step, he is going to take two mixtures that stand next to each other and mix them together, and put the resulting mixture ...
## MIXTURES on Codechef ## Comments say that it is just the matrix multiplication DP ## Top down attempt DP = {} c = [] def calc(s, e): if s == e: return (0, c[e]) if (s,e) in DP: return DP[(s,e)] ans = 1e9 color = -1 for i in xrange(s, e): c1, p1 = calc(s,i) c2, p2 ...
Given a string S (containing at most 10^5 lowercase English letters). You are requested to find out from continuous substrings a string having length from L to H, which appears the most times; if there are more than one answer, find the most length. Input There are several test cases (fifteen at most), each formed as ...
import sys def get_int(): return int(sys.stdin.readline()) def get_ints(): return [int(i) for i in sys.stdin.readline().split()] def find_max(line, pos, L, H): for i in range(H-L): new_pos = [ j + 1 for j in pos if j != len(line) - 1] #print 'new', new_pos if len(new_pos) < len(po...
Byteland is a country whose population squares every year. The president of Byteland is aware of the situation and wants to take proper steps to control the population. For this he wants to estimate the population of the country for a given year. As President is weak in Math, He needs your help to solve this problem. ...
t = int(raw_input()) for i in range(0, t): p, y = raw_input().split() p = int(p) y = int(y) for j in range(0, (y-2000)): p = p**2 % (10**9 + 7) print p % (10**9 + 7)
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number! The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband. The sequence of n integers is called a...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { ...
The Metropolis computer network consists of n servers, each has an encryption key in the range from 0 to 2^k - 1 assigned to it. Let c_i be the encryption key assigned to the i-th server. Additionally, m pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms speci...
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static HashMap<Long, ArrayList<Pair>> map = new HashMap<>(); public static void main(String[] args) { FastReader reader = new FastReader(); PrintWriter writer = new PrintWriter(System.out); int n = reader.nextInt(); i...
Oleg came to see the maze of mirrors. The maze is a n by n room in which each cell is either empty or contains a mirror connecting opposite corners of this cell. Mirrors in this maze reflect light in a perfect way, which causes the interesting visual effects and contributes to the loss of orientation in the maze. Oleg...
#include <bits/stdc++.h> using namespace std; const int N = 1010; int n, p[N], cnt; char s[N][N]; bool vis[N]; int main() { scanf("%d", &n); bool flag = true; for (int i = 1; i <= n; i++) { scanf("%d", &p[i]); if (p[i] != i) flag = false; } for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++)...
You are given a tree (an undirected connected graph without cycles) and an integer s. Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible. Let's define the diameter of...
from __future__ import division from sys import stdin rints = lambda: [int(x) for x in stdin.readline().split()] n, s = rints() deg = [0] * (n + 1) for i in range(n - 1): u, v = rints() deg[u] += 1 deg[v] += 1 print((2 * s) / len(list(filter(lambda x: x == 1, deg))))
Given a string s of length n and integer k (1 ≤ k ≤ n). The string s has a level x, if x is largest non-negative integer, such that it's possible to find in s: * x non-intersecting (non-overlapping) substrings of length k, * all characters of these x substrings are the same (i.e. each substring contains only one ...
import java.io.*; import java.util.*; import java.math.*; public class SalemAndSticks { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out), pw2 = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int n=sc.nextInt(),...
You have a set of items, each having some integer weight not greater than 8. You denote that a subset of items is good if total weight of items in the subset does not exceed W. You want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original set...
#include <bits/stdc++.h> using namespace std; const long long INF = 1e9 + 7; const int N = 2e5 + 10; int main() { long long n; long long cnt[10]; cin >> n; for (int i = 1; i <= 8; i++) cin >> cnt[i]; long long ans = 0; for (int i1 = 0; i1 < 10; i1++) { for (int i2 = 0; i2 < 10; i2++) { for (int i3...
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, th...
/* Rajkin Hossain */ import java.io.*; import java.util.*; public class A { //static FastInput k = new FastInput("/home/rajkin/Desktop/input.txt"); static FastInput k = new FastInput(System.in); static FastOutput z = new FastOutput(); static long t; static int n; sta...
This is an interactive problem. You're given a tree consisting of n nodes, rooted at node 1. A tree is a connected graph with no cycles. We chose a hidden node x. In order to find this node, you can ask queries of two types: * d u (1 ≤ u ≤ n). We will answer with the distance between nodes u and x. The distance b...
import static java.util.Arrays.* ; import static java.lang.Math.* ; import java.util.*; import java.io.*; public class F { int N , L[] , P[]; int [] size ; int [] label ; int [][] adjList ; Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int ask(char s ,...
We have a magic tree: a rooted tree on n vertices. The vertices are numbered 1 through n. Vertex 1 is the root. The magic tree gives us magic fruit. The fruit only grows in vertices of the tree other than the root. Each vertex contains at most one piece of fruit. It is now day 0 and no fruit is ripe yet. Each fruit w...
#include <bits/stdc++.h> using namespace std; int main() { int n, m, k; scanf("%d%d%d", &n, &m, &k); vector<int> p(n + 1); vector<pair<int, int>> fruit(n + 1); vector<map<int, long long>> S(n + 1); for (int i = 2; i <= n; ++i) scanf("%d", &p[i]); for (int i = 0; i < m; ++i) { int v, d, w; scanf("%...
Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company. There are n people working for VoltModder, numbered from 1 to n. Each employee earns a different amount of money in the company — initia...
#include <bits/stdc++.h> using namespace std; long long arr[100005]; vector<long long> G[100005]; long long deg[100005]; long long cnt[100005]; vector<long long> gtrs[100005]; inline long long cal(long long u) { return deg[u] > 320 ? (deg[u] - (long long)gtrs[u].size()) * (long long)gtrs[u].size() ...
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with? Input The first...
#include <bits/stdc++.h> using namespace std; int n, k; string s; int main() { ios_base ::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> k >> s; if (!k) { cout << s; return 0; } if (int(s.size()) == 1) { cout << 0; return 0; } if (s[0] != '1') { s[0] = '1'; --k; } ...
You are given an array a consisting of n integers. You can remove at most one element from this array. Thus, the final length of the array is n-1 or n. Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array. Recall that the contiguous subarray a wi...
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...