input
stringlengths
29
13k
output
stringlengths
9
73.4k
Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert. There are n_1 different types of first courses Ivan can buy (the i-th of them costs a_i coins), n_2 different types of second courses (the i-th of them costs b_i coins), n_3 different types of dri...
MAX_VAL = 2 ** 31 def prepare_values(vals): zipped_vals = list(zip(vals, range(1, len(vals) + 1))) zipped_vals.sort() pairs = [(old_i, i) for i, (val, old_i) in enumerate(zipped_vals, 1)] return zipped_vals, dict(pairs) def renumber_ids(dic, l): return [dic[x] for x in l] def get_first_absent(...
You are given three integers a, b and c. Find two positive integers x and y (x > 0, y > 0) such that: * the decimal representation of x without leading zeroes consists of a digits; * the decimal representation of y without leading zeroes consists of b digits; * the decimal representation of gcd(x, y) without...
from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range; from future_builtins import ascii, filter, hex, map, oct, zip BUFSIZE = 8192; class FastIO(IOBase): newlines = 0 def __init__(self, ...
Polycarp has x of red and y of blue candies. Using them, he wants to make gift sets. Each gift set contains either a red candies and b blue candies, or a blue candies and b red candies. Any candy can belong to at most one gift set. Help Polycarp to find the largest number of gift sets he can create. For example, if x...
import java.util.*; import java.io.*; public class Main2 { static class FastReader{ BufferedReader br;StringTokenizer st;public FastReader(){br = new BufferedReader(new InputStreamReader(System.in));}String next(){while (st == null || !st.hasMoreElements()){try{st = new StringTokenizer(br.readLine());}catch (IOExcep...
One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as <image> lines, drinks another cup of tea, then he writes <...
import sys import math def is_enough(num_v, teh, total_lines) : rem_lines = total_lines pownth = 0 now = 0 while (True) : now = num_v / math.pow(teh, pownth) pownth += 1 rem_lines -= int(now) if rem_lines <= 0 : return True if now < 1 : break return False ''' Main Program ''' lines, teh = map...
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide...
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author lwc62...
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its su...
#include <bits/stdc++.h> using namespace std; const long long N = 1e5 + 10; int main() { cout << 2; return 0; }
John Doe has a crooked fence, consisting of n rectangular planks, lined up from the left to the right: the plank that goes i-th (1 ≤ i ≤ n) (from left to right) has width 1 and height hi. We will assume that the plank that goes i-th (1 ≤ i ≤ n) (from left to right) has index i. A piece of the fence from l to r (1 ≤ l ...
#include <bits/stdc++.h> using namespace std; int n, a[111111], s[222222], k, sa[222222], rnk[222222], tmp[222222], lcp[222222], sz, x, y, l, r, mid, m, len, lb, rb, ans, sn; struct hjt { int rt[222222], l[11111111], r[11111111], tree[11111111], szz; int build(int lp, int rp) { int pos = ++szz; if (lp =...
The Little Elephant loves the LCM (least common multiple) operation of a non-empty set of positive integers. The result of the LCM operation of k positive integers x1, x2, ..., xk is the minimum positive integer that is divisible by each of numbers xi. Let's assume that there is a sequence of integers b1, b2, ..., bn....
#include <bits/stdc++.h> using namespace std; int a[100010]; vector<int> f[100010]; long long mypow(long long x, long long y) { long long res = 1; while (y) { if (y & 1) { res *= x; res %= 1000000007; } x *= x; x %= 1000000007; y >>= 1; } return res; } int main() { int i, j, k,...
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side tha...
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); double w = in.nextLong(); double h = in.nextLong(); double a = in.nextDouble(); if (a > 90) a = 180 - a; if (a == 0) { Sy...
Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year...
import sys import datetime y1, m1, d1 = map(int, input().split(':')) y2, m2, d2 = map(int, input().split(':')) print(abs((datetime.date(y1, m1, d1) - datetime.date(y2, m2, d2)).days))
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the ro...
#include <bits/stdc++.h> using namespace std; int cnt = 0; bool dfs(const vector<vector<bool> >& a, vector<pair<int, int> >& res) { for (int i = 0; i < a.size(); ++i) { bool foo = true; for (int j = 0; j < a.size(); ++j) { if (!a[i][j]) { foo = false; res.push_back(make_pair(i, j)); ...
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number ...
n = int(raw_input()) a = [int(x) for x in raw_input().split()] zeros = len([x for x in a if x == 0]) five = len([x for x in a if x == 5]) if zeros == 0: print -1 exit(0) ret = ["5"]*((five / 9)*9) if len(ret) == 0: ret = "0" else: ret += ["0"]*zeros print "".join(ret)
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The...
#include <bits/stdc++.h> using namespace std; int main() { int n, m, frm, to, mon, ret = 0; scanf("%d%d", &n, &m); vector<int> peop(n, 0); for (int i = 0; i < m; i++) { scanf("%d%d%d", &frm, &to, &mon); peop[frm - 1] += mon, peop[to - 1] -= mon; } for (int i = 0; i < n; i++) { mon = peop[i]; ...
User ainta decided to make a new instant messenger called "aintalk". With aintalk, each user can chat with other people. User ainta made the prototype of some functions to implement this thing. 1. login(u): User u logins into aintalk and becomes online. 2. logout(u): User u logouts and becomes offline. 3. add_...
#include <bits/stdc++.h> using namespace std; const int MAX = 50000 + 10; int n, m, q; int in[MAX], du[MAX], f[MAX]; set<int> ne[MAX]; int cmp(int a, int b) { return (du[a] != du[b]) ? (du[a] < du[b]) : (a < b); } void add(int a, int b) { ++du[a]; ++du[b]; if (cmp(b, a)) swap(a, b); ne[a].insert(b); f[b] += i...
A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game. Let's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who...
#include <bits/stdc++.h> using namespace std; struct Fenwick { vector<int> t; int n; void init(int nn) { n = nn; t.assign(n, 0); } int sum(int r) { int result = 0; for (; r >= 0; r = (r & (r + 1)) - 1) result += t[r]; return result; } void inc(int i, int delta) { for (; i < n; i = ...
DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one numb...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; ++i) cin >> v[i]; vector<pair<int, int> > vp(n); int ans = min(2, n); int count = 1; int l = 0; for (int i = 1; i < n; ++i) { if (v[i] > v[i - 1]) ++count; else { in...
Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Hel...
#include <bits/stdc++.h> const int N = 100500; int n, a, b, p[N], arr[N]; int answer[N]; int find(int x) { int a = std::lower_bound(arr, arr + n, x) - arr; if (a >= n || arr[a] != x) return -1; return a; } void fail() { printf("NO\n"); exit(0); } void start() { for (int i = 0; i < n; ++i) { if (answer[i...
One day Maria Ivanovna found a Sasha's piece of paper with a message dedicated to Olya. Maria Ivanovna wants to know what is there in a message, but unfortunately the message is ciphered. Maria Ivanovna knows that her students usually cipher their messages by replacing each letter of an original message by some another...
#include <bits/stdc++.h> int32_t char_ind(char ch) { if (ch >= 'a' && ch <= 'z') return ch - 'a'; return ch - 'A' + 26; } char ind_to_char(int32_t ind) { if (ind < 26) return 'a' + ind; return 'A' + (ind - 26); } void spfa(int32_t n, int32_t source, int64_t* distances, int32_t* parents, int32_t* statu...
Drazil created a following problem about putting 1 × 2 tiles into an n × m grid: "There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it." But Draz...
#include <bits/stdc++.h> using namespace std; const int N = 2000 + 20; int n, m, cnt, cntp, deg[N][N], vis[N][N]; int dir[4][2] = {1, 0, 0, -1, -1, 0, 0, 1}; char money[4] = {'v', '<', '^', '>'}; char a[N][N]; struct node { int deg; int x, y; node(int a, int b, int t) { x = a, y = b, deg = t; } bool operator<(s...
Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a res...
#include <bits/stdc++.h> using namespace std; int n; int m; vector<int> v[1002]; bool vis[1002]; bool col[1002]; vector<int> node; inline bool dfs(int b) { vis[b] = true; node.push_back(b); for (int i = 0; i < v[b].size(); i++) { int go = v[b][i]; if (vis[go]) { if (col[go] == col[b]) { puts...
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check ...
n=input() count=0 l=['ABSINTH','BEER','BRANDY','CHAMPAGNE','GIN','RUM','SAKE','TEQUILA','VODKA','WHISKEY','WINE'] for i in range(0,n): s=raw_input() if s.isdigit(): if int(s)<18: count+=1 else: if s in l: count+=1 print count
A top-secret military base under the command of Colonel Zuev is expecting an inspection from the Ministry of Defence. According to the charter, each top-secret military base must include a top-secret troop that should... well, we cannot tell you exactly what it should do, it is a top secret troop at the end. The proble...
#include <bits/stdc++.h> using namespace std; int n, k, s, ar[1 << 20]; int dp[3][200][200 * 200]; int main() { ios_base::sync_with_stdio(0); cin >> n >> k >> s; for (int i = 1; i <= n; i++) cin >> ar[i]; if (s > n * n / 2 + 10) s = n * n / 2 + 10; for (int done = 0; done <= s; done++) for (int pref = 0; ...
You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a...
#include <bits/stdc++.h> using namespace std; char ch[1000000 + 10]; stack<int> s; int main() { int i; while (~scanf("%s", ch)) { int l = strlen(ch); int flag = 1; int ans = 0; while (!s.empty()) s.pop(); for (i = 0; i < l; i++) { if (ch[i] == '[' || ch[i] == '<' || ch[i] == '(' || ch[i] =...
You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n — the number of strings (...
#include <bits/stdc++.h> using namespace std; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " : " << arg1 << '\n'; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cerr.write(nam...
Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record! For rolling a ball one gets a score — an integer (maybe negative) number of points. Score for the i-th roll is multiplied by i and scores are summed up. So, for k rolls with scores s1, s2, ....
// package codeforces.educational.ecf011; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class F { public static void main(String[] args) { InputReader in = new InputReader(System.in); Pri...
Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified. After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcas...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100005, MAXM = 1005; bitset<MAXM> All, P[MAXM]; int n, m, Q; int start[MAXN], cnt = 0; int Ans[MAXN]; struct Node { int op, x, y, id; } T[MAXN]; struct Edge { int next, to; } edge[MAXN]; void add(int from, int to) { cnt++; edge[cnt].to = to; edge[...
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the N...
#include <bits/stdc++.h> using namespace std; int main() { std::ios::sync_with_stdio(false); int n, x = 0; cin >> n; for (int i = 0; i < n; ++i) { int t; string s; cin >> t >> s; if (s[0] == 'N') x -= t; else if (s[0] == 'S') x += t; else if (x == 0 || x == 20000) { cou...
Test data generation is not an easy task! Often, generating big random test cases is not enough to ensure thorough testing of solutions for correctness. For example, consider a problem from an old Codeforces round. Its input format looks roughly as follows: The first line contains a single integer n (1 ≤ n ≤ maxn) — ...
#include <bits/stdc++.h> const int N = 70000; const long double pi = atan(1.0) * 4; struct comake_pair { long double r, i; comake_pair() {} comake_pair(long double r_, long double i_) : r(r_), i(i_) {} comake_pair operator+(const comake_pair &B) { return comake_pair(r + B.r, i + B.i); } comake_pair oper...
Mike has discovered a new way to encode permutations. If he has a permutation P = [p1, p2, ..., pn], he will encode it in the following way: Denote by A = [a1, a2, ..., an] a sequence of length n which will represent the code of the permutation. For each i from 1 to n sequentially, he will choose the smallest unmarked...
#include <bits/stdc++.h> int n; int a[500009], ans[500009], p[500009], b[500009], tot; int num[2000009]; inline void build(int u, int l, int r) { if (l == r) { num[u] = b[l]; return; } register int mid(l + r >> 1); build(u << 1, l, mid); build(u << 1 | 1, mid + 1, r); num[u] = (num[u << 1] > num[u <...
Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This t...
#include <bits/stdc++.h> using namespace std; const int N = 6010, M = N * 20, INF = 1e9; int n, a[N], h[N], tot, e[M], nxt[M], fl[M], co[M], f[N], vis[N], calc, now[N], D[N], ans, In[N], Out[N], T; bool bz[N]; void Add(int x, int y, int f, int c) { e[++tot] = y; nxt[tot] = h[x]; fl[tot] = f; co[tot] = c; ...
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is...
import java.io.*; import java.util.*; public class C { public static void main(String[] args) { int n; int[] a = null, sorted = null, mark = null; List<List> outputs = null; try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) { String line = in.readLine(); n = ...
There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y. A path from city s to city t is a sequence of cit...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.function.IntConsumer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStrea...
Two best friends Serozha and Gena play a game. Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak =...
#include <bits/stdc++.h> using namespace std; signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); long long n; cin >> n; long long f[n + 1]; f[0] = 0; long long ans[n + 1]; long long pref[n + 1]; pref[0] = 0; ans[0] = -1; for (long long i = 1; i < n + 1; ++i) {...
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity. Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci r...
def getcost(litres,indices,l,c): minicost=1000000000000000000000000 cost=100000000000000000000000000 for x in indices: if l[x]<=litres: cost=(litres/l[x])*c[x] litres=litres%l[x] if litres==0: break else: cost+= getcost(...
Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by...
import math i,x1,y1,x2,y2=input().split() R=int(i) x=int(x1) y=int(y1) xx=int(x2) yy=int(y2) a=(x-xx)*(x-xx) b=(y-yy)*(y-yy) d=math.sqrt(a+b) flag=0 if a+b >= R*R: print(x,end=" ") print(y,end=" ") print(R) flag=1 elif flag!=1 and d!=0: r=(d+R)/2 t=xx + r*(x-xx)/d u=yy + r*(y-yy)/d print...
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute. Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th m...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class Test { public static void main(String[] args) { MyScanner sc = new MyScanner(); int n = sc.nextInt(); int k...
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead. "What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone." "But these blends are at their best, aren't they?" ...
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner in = new Scanner(System.in); String ls = in.next(); for(...
Amit is very fond of cookies, so he wants to buy some. There are N different cookies lying in front of him, with their prices, but he has only K Rs. He wants to maximize the number of cookies he buys with this money. Now, you are Amit's best friend and have to help him buy as many cookies as possible. Input Format ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' n,m=map(int,raw_input().split()) l=[int(i) for i in raw_input().split()] l.sort() p=0 c=0 for i in l: p+=i if m>p: c+=1 print c
HackerMan loves playing Age of Empire. A few days ago, he discovered a variant of that game which is equally adventurous. Here, he has to capture a castle before his enemy. The map consists of several interconnected paths in a grid pattern. He starts at top left intersection (1,1), and then proceeds towards the castle...
test=input() for n in range(0,test): size=map(int, raw_input().split()) x=size[0] y=size[1] G=[] for i in range(0,x): G.append(map(int, raw_input().split())) s=[0,0] e=map(int, raw_input().split()) G1=[] P=[] C=[] for i in range(0,x): G1.append([10000]*y) ...
Anshu's father is a billionaire but he wants Anshu to learn the value of money. So, his father gives him his pocket money in a different manner. He gives 1Rs. on first day, 2 Rs. on second, 3 Rs. on third and so on. So, Anshu gets n Rs. on any nth day. Anshu's father asks Anshu how much money he has received in tota...
for t in range(input()): x=long(raw_input()) print x*(x+1)/2
In this problem you will be given an integer array A of size N, your task is find whether given array is sorted or not (in ascending order) , if print "YES" else print "NO". Array a[n] is sorted if a[0] ≤ a[1] ≤ ... a[n - 1]. Input First line of input contains contains integer T denoting number of test cases. For...
aa = int(raw_input()) outt=[] for x in range(aa): a=int(raw_input()) b=map(int,raw_input().split()) c=b s=sorted(c) if s==b: outt.append("YES") else: outt.append("NO") for k in outt: print k
Little Lalit is an extremely good competitive coder. But recently, he was challenged by another fellow competitive programmer called Little Kundu. Lalit decides to challenge Kundu to prove that he's better than him. After a tough grueling competitive fight, Lalit manages to beat Kundu. Let us give you some statist...
t = int(raw_input()) for _ in range(t): prob = 0.0; lis = [] lis = map(int,raw_input().split()) prob = float(lis[0]-lis[1])/float(lis[0]+lis[1]) print format(prob,".12f")
The Monk is trying to explain to its users that even a single unit of time can be extremely important and to demonstrate this particular fact he gives them a challenging task. There are N processes to be completed by you, the chosen one, since you're Monk's favorite student. All the processes have a unique number as...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t=int(raw_input()) c=raw_input().split() i=raw_input().split() x=0 z=0 while x<t: if c[x]==i[x]: x+=1 else: temp=c[x] for j in range(x+1,t): c[j-1]=c[j] c[t-1]=temp z+=1 p...
There are M males and F females arranged in a circle. Starting from a given point, you count clockwise and remove the K'th person from the circle (where K=1 is the person at the current point, K=2 is the next person in the clockwise direction, etc...). After removing that person, the next person in the clockwise direct...
def rate(p, m, f): return (p+1)%(m + f ); for _ in range(input()): m, f, k = map(int, raw_input().split()) ret = ["M"] * (m + f) pos = len(ret) - 1 for i in range(f): j = 0 while j < k: pos = (pos+1) % len(ret) if ret[pos] == 'M': j+=1 ...
Its Diwali time and there are LED series lights everywhere. Little Roy got curious about how LED lights work. He noticed that in one single LED Bulb there are 3 LED lights, namely Red, Green and Blue. State of the bulb at any moment is the sum of Red, Green and Blue LED light. Bulb works as follows: Roy took out al...
(T, Rs, Gs, Bs) = map(int, raw_input().split(' ')) R = 0 G = 0 B = 0 Y = 0 C = 0 M = 0 W = 0 Bk = 0 (tR, tG, tB) = (0, 0, 0) (rcount, gcount, bcount) = (Rs, Gs, Bs) for x in xrange(T): # set values of LEDs if rcount == 0: rcount = Rs tR = 1 if tR == 0 else 0 if gcount == 0: gcount = Gs tG = 1 if tG =...
Prof. M went to unknown world where words are considered to be powerful according to their weights. But Prof. M doesn't know how to calculate weight of words. He will tell you a word and you have to tell its weight. You know that weight of a word is equal to sum weight of individual characters. But as Prof. M is too o...
#!/usr/bin/env python import string t = int(raw_input()) letters = string.ascii_letters let_list = {} for x in range(26): let_list[letters[x]] = x + 1 for _ in range(t): text = raw_input() m = int(raw_input()) missed = raw_input().split() weight = 0 for i in range(len(text)): if text[i...
Siddharth is a math geek. His only work in free time is to think of a new math problem and keep working on that. Siddharth's latest problem is to sum up digits of a number till the result is a single digit. It goes this way.. Ex: for number 123     it is 1+2+3 = 6 and for number 12345     it is 1+2+3+4+5 = 15 => 1+5 ...
k=input() for i in range(0,k): p=raw_input() a=int(p,3) a=list(str(a)) while(len(a)!=1): a=sum(map(int,a)) a=list(str(a)) print a[0]
We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i. You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have? Constraints * 1\leq N,Q \leq 5 \times 10^5 * 1\leq c_i \leq N * 1\leq ...
import java.io.*; import java.util.*; import java.math.BigDecimal; @SuppressWarnings("unused") public class Main { FastScanner in; PrintWriter out; final static int MOD = (int)1e9+7; void solve(){ int N = in.nextInt(), Q = in.nextInt(); int[] c = in.nextIntArray1Index(N); i...
A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied: * S is a palindrome. * Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome. * The string consisting of the (N+3)/2-st through N-th charact...
s=input() n=len(s) s1=s[:n//2] s2=s[n//2+1:] if s1==s2 and s1==s1[::-1]: print("Yes") else: print("No")
Takahashi is at an all-you-can-eat restaurant. The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i. The restaurant has the following rules: * You can only order one dish at a time. The dish ordered will be immediately served and ready to eat. * You cannot or...
import java.util.*; public class Main { static Dish[] dishes; static int[][] dp; public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); dishes = new Dish[n]; dp = new int[n][t + 1]; for (int i = 0; i < n; i++) { dishes[i] = ...
There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i). We will repeat the following operation as long as possible: * Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at...
import sys input = sys.stdin.readline M = 10**5 n = int(input()) G = [[] for _ in range(2*M+1)] for _ in range(n): x, y = map(int, input().split()) G[x].append(y+M) G[y+M].append(x) seen = [False]*(2*M+1) def dfs(v): stack = [v] seen[v] = True cnt_x, cnt_y = 0, 0 while stack: v = stack.pop() if v...
We conducted a survey on newspaper subscriptions. More specifically, we asked each of the N respondents the following two questions: * Question 1: Are you subscribing to Newspaper X? * Question 2: Are you subscribing to Newspaper Y? As the result, A respondents answered "yes" to Question 1, and B respondents answer...
#include <iostream> using namespace std; int main() { int n, a, b; cin >> n >> a >> b; cout << min(a, b) << " " << max(a + b - n, 0) << "\n"; return 0; }
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters: * The ...
n,m,q=map(int,input().split()) a=[[0 for _ in range(n)] for _ in range(n)] for i in range(m): x,y=map(int,input().split()) a[x-1][y-1]+=1 for j in range(n): for k in range(1,n): a[j][k]=a[j][k]+a[j][k-1] for l in range(q): ans=0 L,R=map(int,input().split()) for g in range(L-1,R): ans+=a[g][...
You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N. Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal. Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two ac...
#include <bits/stdc++.h> using namespace std; #define ll long long const int N = (int)1e4 + 7; int a[N], b[N]; int main() { int n; scanf("%d", &n); ll sum = 0, sum1 = 0, c = 0; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); sum += a[i]; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); sum...
We have an N \times N square grid. We will paint each square in the grid either black or white. If we paint exactly A squares white, how many squares will be painted black? Constraints * 1 \leq N \leq 100 * 0 \leq A \leq N^2 Inputs Input is given from Standard Input in the following format: N A Outputs Print...
s = input() b = input() a = s * s print a - b
Input Format Let the i-th query query_i, the input format is following: N Q p_0 a_0 p_1 a_1 : : p_{N - 1} a_{N - 1} query_0 query_1 : : query_{Q - 1} THe format of query_i is one of the three format: 1 v_i d_i x_i 2 v_i d_i 3 pr_i ar_i Output Format Print the result in one line for each query 2. ...
#include <algorithm> #include <iostream> #include <sstream> #include <string> #include <cstring> #include <vector> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> #include <list> #include <cassert> #include <ctime> #include...
Snuke has a board with an N \times N grid, and N \times N tiles. Each side of a square that is part of the perimeter of the grid is attached with a socket. That is, each side of the grid is attached with N sockets, for the total of 4 \times N sockets. These sockets are labeled as follows: * The sockets on the top sid...
#include <bits/stdc++.h> using namespace std; const int MAXN=3e2+7; const int inf=1e9+7; struct po { int from,to,w,nxt; } edge[MAXN*MAXN*15]; int head[MAXN*MAXN+MAXN*6],num=-1,n,m,s,t,b[MAXN],dep[MAXN*MAXN+MAXN*6],cur[MAXN*MAXN+MAXN*6]; int U[MAXN],L[MAXN],R[MAXN],D[MAXN],id[MAXN][MAXN],I; int us[MAXN][MAXN],vis[MAXN]...
There are four points: $A(x_1, y_1)$, $B(x_2, y_2)$, $C(x_3, y_3)$, and $D(x_4, y_4)$. Write a program which determines whether the line $AB$ and the line $CD$ are parallel. If those two lines are parallel, your program should prints "YES" and if not prints "NO". Input Input consists of several datasets. In the fir...
num=int(input()) for i in range (num): info=list(map(float,input().split())) info=list(map(lambda x:int(x*10**6),info)) if info[2]==info[0]: if info[6]==info[4]: print("YES") else: print("NO") elif info[6]==info[4]: if info[2]==info[0]: print("...
I decided to do bowling as a recreation of the class. Create a program that inputs the pitching information for each participant and outputs the grade information in descending order of score. If there is a tie, output in ascending order of student ID number. However, it is assumed that the number of participants is 3 ...
#include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <cmath> #include <stack> #include <vector> #include <map> #include <set> #include <queue> #include <list> #include <iostream> #include <sstream> #include <climits> #include <cfloat> #include <complex> typedef long long ll; const doub...
The King of Akabeko has two princes. The king decided to divide the country into two when he abdicated, and let each prince rule the country one by one. The names of the new countries are Aka and Beko. There are N towns and M roads connecting the two towns in Akabeko. The King decided to allocate the town of Akabeko an...
#include<unordered_map> #include<utility> template<typename T> class UnionFind { public: void unite(const T& a, const T& b) { T x = find(a), y = find(b); if(size_[x] < size_[y]) std::swap(x, y); if(x != y) parent_[y] = x, size_[x] += size_[y]; } const T find(const T& x) { if(!parent_.count(x)) { ...
problem There is one bar-shaped candy with a length of N mm (where N is an even number). Two JOI officials decided to cut this candy into multiple pieces and divide them into a total of N / 2 mm. did. For unknown reasons, this candy has different ease of cutting depending on the location. The two examined the candy e...
#include <cstdio> #include <algorithm> using namespace std; #define x 10001 int dp[x][2],num[x]; int main() { int n; scanf("%d",&n); for(int i=1;i<n;i++) { scanf("%d",&num[i]); } for(int i=0;i<x;i++) { dp[i][0]=x*x; dp[i][1]=x*x; } dp[1][0]=0; for(int i=1;i<n;i++) { ...
There is the word heuristics. It's a relatively simple approach that usually works, although there is no guarantee that it will work. The world is full of heuristics because it is simple and powerful. Some examples of heuristics include: In an anime program, the popularity of a character is proportional to the total a...
#include <iostream> #include <algorithm> #include <utility> #include <vector> #include <list> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <stack> #include <string> #include <sstream> #include <cstring> #include <cstdlib> using namespace std; #define ALL(c)...
Ken and Keiko are young, poor and busy. Short explanation: they are students, and ridden with part-time jobs. To make things worse, Ken lives in Hakodate and Keiko in Tokyo. They want to meet, but since they have neither time nor money, they have to go back to their respective jobs immediately after, and must be carefu...
import java.util.*; public class Main { final int INF = 1 << 24; HashMap<String, Integer> tonum; HashMap<Integer, Integer> timetable; ArrayList<D> toT, fromT, toH,fromH; ArrayList<ArrayList<C>> pass; int Tnum, Hnum, citysize, timesize; class C implements Comparable<C>{ int from, to, begin, end, fare; public...
Example Input 20 Output 4
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #defi...
Problem Gaccho owns a field separated by W horizontal x H vertical squares. The cell in the x-th column and the y-th row is called the cell (x, y). Only one plant with a height of 0 cm is planted on the land of some trout, and nothing is planted on the land of other trout. Gaccho sprinkles fertilizer on the field at ...
#include <fstream> #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <sstream> #include <map> #include <set> #include <vector> #include <cmath> #include <queue> #include <random> using namespace std; #define min(a,b) ((a)<(b) ? (a):(b)) #def...
A dam construction project was designed around an area called Black Force. The area is surrounded by mountains and its rugged terrain is said to be very suitable for constructing a dam. However, the project is now almost pushed into cancellation by a strong protest campaign started by the local residents. Your task is...
#include<iostream> #include<algorithm> #include<vector> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) #define ALL(C) (C).begin(),(C).end() #define pb push_back const int W = 20,H = 20; int vol; bool vis[H][W]; bool liv[H][W]; int h[H][W]; int dx[]={0,0,1,-1};...
In 2337, people are bored at daily life and have crazy desire of having extraordinary experience. These days,“Dungeon Adventure” is one of the hottest attractions, where brave adventurers risk their lives to kill the evil monsters and save the world. You are a manager of one of such dungeons. Recently you have been re...
#include <bits/stdc++.h> using namespace std; #define LOG(...) fprintf(stderr,__VA_ARGS__) //#define LOG(...) #define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);++i) #define REP(i,n) for(int i=0;i<(int)(n);++i) #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(),(a).rend() #define EXIST(s,e) ((s).find(e)!...
One sunny day, Dick T. Mustang found an ancient personal computer in the closet. He brought it back to his room and turned it on with a sense of nostalgia, seeing a message coming on the screen: READY? Yes. BASIC. BASIC is a programming language designed for beginners, and was widely used from 1980's to 1990's. Th...
#include <bits/stdc++.h> using namespace std; const int N = 100005; const int INF = 0x3f3f3f3f; inline int get_note(int O, char ch, int f) { if (ch == 'C') return (O - 1) * 12 + 1 + f; else if (ch == 'D') return (O - 1) * 12 + 3 + f; else if (ch == 'E') return (O - 1) * 12 + 5 + f; else if (ch == 'F') return (O - 1...
Problem Statement "Everlasting -One-" is an award-winning online game launched this year. This game has rapidly become famous for its large number of characters you can play. In this game, a character is characterized by attributes. There are $N$ attributes in this game, numbered $1$ through $N$. Each attribute takes...
#include <algorithm> #include <cstdlib> #include <iostream> #include <vector> using namespace std; class union_find { private: vector<int> uf; int find(int x) { return uf[x] < 0 ? x : uf[x] = find(uf[x]); } public: explicit union_find(int n):uf(n, -1) {} void unite(int x, int y) { x = find(x); y = find(y...
Example Input 2 2 2 1 0 0 0 Output 24
#include <bits/stdc++.h> using namespace std; vector<int> dx = {1, -1, 0, 0, 0, 0}; vector<int> dy = {0, 0, 1, -1, 0, 0}; vector<int> dz = {0, 0, 0, 0, 1, -1}; int main(){ int A, B, C, N; cin >> A >> B >> C >> N; set<tuple<int, int, int>> st; for (int i = 0; i < N; i++){ int x, y, z; cin >> x >> y >> z;...
The JAG Kingdom consists of $N$ cities and $M$ bidirectional roads. The $i$-th road ($u_i, v_i, c_i$) connects the city $u_i$ and the city $v_i$ with the length $c_i$. One day, you, a citizen of the JAG Kingdom, decided to go to the city $T$ from the city $S$. However, you know that one of the roads in the JAG Kingdom ...
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> #define maxn 100010 #define maxm 800010 typedef long long ll; struct Edge { Edge *next; int to, w; } *last[maxn], e[maxm], *ecnt = e; inline void link(int a, int b, int w) { *++ecnt = (Edge) {last[a], b, w}; last[a] = ecnt; *++ecnt = (Edge)...
Problem You bought a tree-shaped lighting fixture called a tree light. This luminaire has n contacts, each numbered from 0 to n-1. Each contact consists of a light bulb that can express 10 levels of brightness and a device for switching the state of the light bulb. Initially, the brightness of the bulbs at all contac...
#include<bits/stdc++.h> using namespace std; typedef unsigned long long int ull; typedef long long int ll; typedef pair<ll,ll> pll; typedef long double D; typedef complex<D> P; #define F first #define S second const ll E=1e18+7; const ll MOD=1000000007; template<typename T,typename U>istream & operator >> (istream &i,...
The goal of the 15 puzzle problem is to complete pieces on $4 \times 4$ cells where one of the cells is empty space. In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 15 as shown below. 1 2 3 4 6 7 8 0 5 10 11 12 9 13 14 15 You can move a piece toward the empty space a...
#include <algorithm> #include <cstdio> #include <cstdlib> #include <iostream> #include <string> using namespace std; #define N 4 #define N2 16 #define LIMIT 45 const int dx[4] { -1, 0, 1, 0 }; const int dy[4] { 0, -1, 0, 1 }; const char dir[4] { 'u', 'l', 'd', 'r' }; int MDT[N2][N2]; struct Puzzle { int f[N2], spa...
Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No". Constraints * 0 ≤ a, b, c ≤ 100 Input Three integers a, b and c separated by a single space are given in a line. Output Print "Yes" or "No" in a line. Examples Input 1 3 8 Output Yes Input 3 8 1 Output...
import java.util.Scanner; class Main{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); if((a < b) && (b < c)){ System.out.println("Yes"); }else{ System.out.println("No"); } } }
Chef loves to prepare delicious dishes. This time, Chef has decided to prepare a special dish for you, and needs to gather several apples to do so. Chef has N apple trees in his home garden. Each tree has a certain (non-zero) number of apples on it. In order to create his dish, Chef wants to pluck every apple from ever...
t=int(raw_input()) for asd in range(t): n=int(raw_input()) a=map(int,raw_input().split()) a=sorted(a) c=1 for i in range(1,n): if a[i]!=a[i-1]: c+=1 print c
Aman has a hardware store in Una. One day when he went down to the store room to fetch a box of nails. He found that the price tag had faded out. The first and the last digits of the price were not readable. Although, the number of nails in the box could be read clearly. The box read, 72 nails, Rs. _679_ What were ...
import sys test=int(input()) while(test>0): N=int(input()) xyz=sys.stdin.readline().split() i=99999 flag='true' while(flag=='true'): mid_3=int(i%100)/10 #print '1',mid_3 if(mid_3==int(xyz[2])): mid_3=int((i%1000)/100) #print '2', mid_3 if(mid_3==int(xyz[1])): mid_3=int((i%10000)/1000) #print...
The Government of Greedistan has just found out that there is a lot of gold beneath some land area in their country. They quickly surveyed the land area and found that some people are living there, and surprisingly the houses are organized in a M x N grid, each cell having exactly one house. To acquire all the gold ben...
t=int(raw_input()) while(t): t-=1 m,n=map(int,raw_input().split(" ")) if(m and n): print m/2+n/2+1 else: print 0
You are given two integer arrays A and B each of size N. Let us define interaction of arrays A and B to be the sum of A[i] * B[i] for each i from 1 to N. You want to maximize the value of interaction of the arrays. You are allowed to make at most K (possibly zero) operations of following kind. In a single operation,...
# /cc/2016/March/Long/MAXISUM for tc in xrange(input()): n_nums, n_ops = map(long, raw_input().strip().split()) nums1 = map(long, raw_input().strip().split()) nums2 = map(long, raw_input().strip().split()) print sum(num1 * num2 for num1, num2 in zip(nums1, nums2)) + (n_ops * max(map(abs, nums2)))
In a museum there is an empty wall. We can imagine this wall as a triangle on a coordinate plane with vertices (0; 0), (N; 0), (N; N * A / B), where N, A, B are some positive integers. The space has been allotted to a photographer who wants his masterpiece on that wall. He is confused with the size of the photo frame ...
from re import findall count = int(raw_input()) def test(p): x,y = p global m if eval(str(y)+".0")/x <= m: return True return False for i in range(count): n,a,b = [int(x) for x in findall("\d+",raw_input())] m,net = eval(str(a) + ".0")/b,0 xx,yr = xrange(1,n+1),int(eval(str(n)+"*"+st...
Sridhar was a seasoned traveler. He liked to visit new places. More than all he was a meticulous planner. This time he was planning to visit Europe. He wrote down his travel itinerary like as follows: If he wanted to visit Madrid, Paris, Munich, Warsaw and Kiev in this order, he would write it down like as: Madrid P...
from sys import stdin t=input() for i in range(0,t): d={} src=[] dest=[] n=input() for j in range(0,n-1): b = stdin.readline().split() d[b[0]]=b[1]+"%"+b[2] dest.append(b[1]) tmp=list(set(d)-set(dest)) s=tmp[0] cost=0 for j in range(0,n-1): ch=d[s...
You are given a bracket sequence s (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of...
#include <bits/stdc++.h> using namespace std; const int maxn = 205; const int base = 1e9 + 7; int n, m; char s[maxn], t[maxn]; int nxt[maxn][2]; int f[maxn][maxn][maxn]; void Input() { cin >> n; cin >> (s + 1); m = strlen(s + 1); } int CalcNxt(char *P, char *B, int len) { bool bl; for (int i = (len); i >= (0)...
While some people enjoy spending their time solving programming contests, Dina prefers taking beautiful pictures. As soon as Byteland Botanical Garden announced Summer Oenothera Exhibition she decided to test her new camera there. The exhibition consists of l = 10^{100} Oenothera species arranged in a row and consecut...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,abm,mmx,avx,avx2") #pragma GCC optimize("unroll-loops") using namespace std; const unsigned _mod = 998244353; const unsigned mod = 1e9 + 7; const long long infi = 0x3f3f3f3f3f3f3f3fll; const int inf = 0x3f3f3f3f; char bu...
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 ≤ a_1 < a_2 < … < a_n ≤ 10^3, and then went to the bathroom. JATC decided to prank his friend by erasing some consecutive elements in the array. Since he...
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; const long long MOD = (long long)1e9 + 7; const long long MOD2 = 1007681537; const long long LINF = (long long)1e18; const long double PI = acos((long double)-1); const long double EPS = 1e-12; inline long long gcd(long long a, long long b) { long lon...
The Fair Nut has two arrays a and b, consisting of n numbers. He found them so long ago that no one knows when they came to him. The Fair Nut often changes numbers in his arrays. He also is interested in how similar a and b are after every modification. Let's denote similarity of two arrays as the minimum number of o...
#include <bits/stdc++.h> using namespace std; using vint = vector<int>; using pint = pair<int, int>; using vpint = vector<pint>; template <typename A, typename B> inline void chmin(A& a, B b) { if (a > b) a = b; } template <typename A, typename B> inline void chmax(A& a, B b) { if (a < b) a = b; } template <class A...
This is an interactive problem. Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him: * "x", if (x mod a) ≥ (y mod a). ...
import java.util.*; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; public class B { FastScanner in; PrintWriter out; boolean systemIO = true; public static void quickSort(int[] a, int from, int to) { if (to - from <= 1) { return; } int i = from; int j = to - 1; int x ...
You still have partial information about the score during the historic football match. You are given a set of pairs (a_i, b_i), indicating that at some point during the match the score was "a_i: b_i". It is known that if the current score is «x:y», then after the goal it will change to "x+1:y" or "x:y+1". What is the l...
#include <bits/stdc++.h> using namespace std; const int N = 10005; int a[N], b[N]; int main() { int n; cin >> n; a[0] = 0, b[0] = 0; for (int i = 1; i <= n; i++) { cin >> a[i] >> b[i]; } int ans = 1; for (int i = 1; i <= n; i++) { if (a[i - 1] == b[i - 1]) ans += min(a[i], b[i]) - a[i - 1]; ...
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of n high school students numbered from 1 to n. Initially, each student i is on position i. Each student i is characterized by two numbers — a_i and b_i. Dissatisfaction of the person i equals the product of a_i b...
import java.io.*; import java.nio.CharBuffer; import java.util.Arrays; import java.util.Comparator; import java.util.NoSuchElementException; public class P1152D { public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(Sys...
Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n...
#include <bits/stdc++.h> using namespace std; long long mod = 1e9 + 7; long long nop = 100; vector<int> primes(nop, 1); long long cnt = 0; void sieve() { primes[1] = primes[0] = 0; for (long long i = 2; i * i <= nop; i++) { if (primes[i]) { for (long long j = i * i; j <= nop; j += i) { primes[j] =...
Tokitsukaze is playing a room escape game designed by SkywalkerT. In this game, she needs to find out hidden clues in the room to reveal a way to escape. After a while, she realizes that the only way to run away is to open the digital door lock since she accidentally went into a secret compartment and found some clues...
#include <bits/stdc++.h> template <typename T> inline T max(T a, T b) { return a > b ? a : b; } template <typename T> inline T min(T a, T b) { return a < b ? a : b; } template <typename T> inline T abs(T a) { return a > 0 ? a : -a; } template <typename T> inline bool repr(T &a, T b) { return a < b ? a = b, 1 : ...
Airports often use moving walkways to help you walking big distances faster. Each such walkway has some speed that effectively increases your speed. You can stand on such a walkway and let it move you, or you could also walk and then your effective speed is your walking speed plus walkway's speed. Limak wants to get f...
#include <bits/stdc++.h> using namespace std; int const N = 200000; long double const eps = 1e-10; int n, L; long double an, fr, v; set<pair<long double, int> > st; void sc(long double &x) { double t; scanf("%lf", &t); x = t; } struct S { int l, r, d; long double os, cs; void sc() { scanf("%d%d", &l, &r...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what i...
import java.io.BufferedReader; import java.io.FileInputStream; 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.Collections; import java.util.HashSet; import java.util.Scanner; impo...
A palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i ∈ [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes. You have n binary strings s_1, s_2, ..., s_n (each s_i consists of zeroes and/or ones). You ca...
#include <bits/stdc++.h> using namespace std; bool is_pal(int n, int a, int b) { if (a < 0 || b < 0) return false; bool a_even = a % 2 == 0; bool b_even = b % 2 == 0; if (n % 2 == 0) { if (!a_even || !b_even) return false; return true; } else { if (a_even || b_even) return true; if (a == 0 || ...
There is given an integer k and a grid 2^k × 2^k with some numbers written in its cells, cell (i, j) initially contains number a_{ij}. Grid is considered to be a torus, that is, the cell to the right of (i, 2^k) is (i, 1), the cell below the (2^k, i) is (1, i) There is also given a lattice figure F, consisting of t cel...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(nullptr); int k; cin >> k; int n = 1 << k; vector<vector<long long>> a(n, vector<long long>(n)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> a[i][j]; int t; cin >> t; vector<pair<i...
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins. He wants to distribute all these n coins between his sisters in such a way that ...
import sys T = int(sys.stdin.readline()) for _ in range(T): a, b, c, n = map(int , sys.stdin.readline().split()) if not (a+b+c+n)%3 and max(a, b, c)<=(a+b+c+n)//3: print('YES') else: print('NO')
Screen resolution of Polycarp's monitor is a × b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x, y) (0 ≤ x < a, 0 ≤ y < b). You can consider columns of pixels to be numbered from 0 to a-1, and rows — from 0 to b-1. Polycarp wants to open a rectangular window of maximal size, which ...
t=int(input()) for _ in range(t): a,b,x,y=map(int,input().split()) print(max(max(a-1-x,x)*b,max(b-1-y,y)*a))
This is an interactive problem. Yui is a girl who enjoys playing Mahjong. <image> She has a mysterious set which consists of tiles (this set can be empty). Each tile has an integer value between 1 and n, and at most n tiles in the set have the same value. So the set can contain at most n^2 tiles. You want to figure...
#include <bits/stdc++.h> using namespace std; pair<int, int> ask(int x) { printf("+ %d\n", x); fflush(stdout); int a, b; scanf("%d%d", &a, &b); return {a, b}; } int qw(int x) { int q = 0; while (q * (q - 1) / 2 < x) q++; return q; } int n, A, B, res[111]; int main() { scanf("%d", &n); scanf("%d%d", ...
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k). At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he...
def main_function(): from sys import stdin from sys import stdout from math import ceil input = stdin.readline print = stdout.write for _ in range(int(input())): n, m, k = map(int, input().split()) if m <= n//k: print(f'{m}\n') else: print(f'{n//k...
Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly n flowers. Vladimir went to a flower shop, and he was amazed to see that there are m types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers ...
// package codeforces.round.n657; import java.util.*; /** * @Author: nayix * @Date: 7/20/20 10:13 AM */ public class ChoosingFlowers { static class Flower { private long happiness; private long continueHappiness; public Flower(Scanner in) { this.happiness = in.nextLong(); ...
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som...
n=int(input()) l=list(map(int,input().split())) i=0 while(n>0): if i==7: i=0 n -= l[i] if n>0: i+=1 print(i+1)
After making a strategic plan with carriers for expansion of mobile network throughout the whole country, the government decided to cover rural areas with the last generation of 5G network. Since 5G antenna towers will be built in the area of mainly private properties, the government needs an easy way to find informat...
#include <bits/stdc++.h> #pragma warning(disable : 4996) template <typename T> T min(T x, T y) { return x < y ? x : y; } template <typename T> T max(T x, T y) { return x > y ? x : y; }; const int INF = 2000000005; const long long mod = 1000000007; const long long MAXN = 1000005; const double eps = 1e-6; int sgn(dou...