input
stringlengths
29
13k
output
stringlengths
9
73.4k
Once upon a time DravDe, an outstanding person famous for his professional achievements (as you must remember, he works in a warehouse storing Ogudar-Olok, a magical but non-alcoholic drink) came home after a hard day. That day he had to drink 9875 boxes of the drink and, having come home, he went to bed at once. Drav...
//package d; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception{ Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); int n = in.nextInt(); int m = in.nextInt(); int a[] = new int[n]; ...
Iahub got lost in a very big desert. The desert can be represented as a n × n square matrix, where each cell is a zone of the desert. The cell (i, j) represents the cell at row i and column j (1 ≤ i, j ≤ n). Iahub can go from one cell (i, j) only down or right, that is to cells (i + 1, j) or (i, j + 1). Also, there a...
#include <bits/stdc++.h> using namespace std; const int maxm = 100004; int n, m, mx[maxm]; pair<int, int> a[maxm], b[maxm], p[maxm]; int an, bn; int Find1(int x, int y) { int l(1), r(an), mid; while (l < r) { mid = (l + r) >> 1; if (a[mid].second >= x) r = mid; else l = mid + 1; } if (x ...
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the...
import java.util.*; public class A_237 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int lines = sc.nextInt(); char pos = ' ', neg = ' '; boolean error=false; for(int i=0;i<lines;++i){ String line = sc.next(); if(i==0...
Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks. There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory...
#include <bits/stdc++.h> using namespace std; int main() { int b, c[10][10], i, mx = 0, h, j, k, l, r; int a[10] = {1, 2, 3, 4, 5}; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { cin >> c[i][j]; } } for (h = 0; h < 5; h++) { for (i = 0; i < 5; i++) { if (i == h) continue; fo...
The Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with n vertices labeled from 0 to n - 1, where n is a power of two, equal to 2m. <image> The ener...
#include <bits/stdc++.h> using namespace std; const int N = 1100000; int a[N], b[N], c[N], f[N]; unsigned long long p[100]; int n, m; long long T; int mod, phi, cnt; int mod1, mod2; long long k1, k2; int ans; struct FWT1 { int a[N], b[N]; int power(int x, long long y) { int ret = 1; for (; y; y >>= 1, x = 1...
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them. Each command is one of the following two types: 1. Go 1 unit towards the positive direction, denoted as '+' 2. Go 1 unit towards the negative direction, ...
import math s1=input() s2=input() c1=0 c2=0 c3=0 for items in s1: if items=="+": c1+=1 if items=="-": c2+=1 for items in s2: if items=="+": c1-=1 if items=="-": c2-=1 if items=="?": c3+=1 if (c2<0): print(0.000) elif (c2>c3): print(0.000) else: ...
Vasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors — the positive integers i such that for at least one...
#include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); long long n; cin >> n; cout << n << " "; for (long long i = 2; i <= n; i++) cout << i - 1 << " "; cout << "\n"; }
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bi...
#include <bits/stdc++.h> using namespace std; int n, q, k, a[60005], p, P; bool u[20000005]; int main() { scanf("%d%d", &n, &k); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); u[a[i]] = 1; } scanf("%d", &q); while (q--) { int c, ans = 100; scanf("%d", &c); for (int x = 0; x <= k; ++x) ...
In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law). Having read about it on Codeforces, the Hedgeho...
// package CodeForces; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; public class Round50C { public static void solve() { int n = s.nextInt(); long[] rl = new long[n]; long[] rr = new long[n]; ...
In the country there are exactly n cities numbered with positive integers from 1 to n. In each city there is an airport is located. Also, there is the only one airline, which makes m flights. Unfortunately, to use them, you need to be a regular customer of this company, namely, you have the opportunity to enjoy flight...
#include <bits/stdc++.h> using namespace std; int n, m; int dis[10010]; struct M { bitset<210> s[210]; } Ye; bitset<210> ans; struct edge { int a, b, v; } e[1010]; M operator*(const M &x, const M &y) { M now; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (x.s[i][j]) now.s[i] |= y.s[j]; ...
While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1, a2, ..., am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1, f2, ..., fn of length n an...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> b, sol; map<int, vector<int> > f; int a; for (int i = 0; i < n; i++) { cin >> a; f[a].push_back(i); } for (int i = 0; i < m; i++) { cin >> a; b.push_back(a); } int flag = 1; for (int i =...
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps...
import java.util.Scanner; public class Ishu { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int x1,x2,y1,y2,sum=0,d1,d2,sd; char c='a'; x1=scan.nextInt(); y1=scan.nextInt(); x2=scan.nextInt(); y2=scan.nextInt(); d1=x2-x1; d2=y2-y1; if(d1<0...
Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake a...
#include <bits/stdc++.h> const int N = 20; bool dp[1 << N]; std::vector<std::vector<int>> vec = { {0, 1, 2}, {3, 4, 5, 6}, {7, 8, 9, 10, 11}, {12, 13, 14, 15}, {16, 17, 18}, {0, 3, 7}, {1, 4, 8, 12}, {2, 5, 9, 13, 16}, {6, 10, 14, 17}, {11, 15, 18}, {7, 12, 16}, {3, 8, 13, ...
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it. That element can store information about the matrix of integers size n × m. There a...
#include <bits/stdc++.h> using namespace std; vector<int> row, col, A; vector<pair<pair<int, int>, int> > mat; int grid[111][111]; void shift_up(int c, int n, int m) { int i, temp; temp = grid[n][c]; for (i = n; i > 1; i--) grid[i][c] = grid[i - 1][c]; grid[1][c] = temp; } void shift_left(int r, int n, int m) {...
So many wall designs to choose from! Even modulo 106 + 3, it's an enormous number. Given that recently Heidi acquired an unlimited supply of bricks, her choices are endless! She really needs to do something to narrow them down. Heidi is quick to come up with criteria for a useful wall: * In a useful wall, at least ...
#include <bits/stdc++.h> using namespace std; template <typename S, typename T> ostream& operator<<(ostream& out, pair<S, T> const& p) { out << '(' << p.first << ", " << p.second << ')'; return out; } template <typename T> ostream& operator<<(ostream& out, vector<T> const& v) { int l = v.size(); for (int i = 0;...
Sonya was unable to think of a story for this problem, so here comes the formal description. You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operati...
#include <bits/stdc++.h> using namespace std; int main() { size_t n; cin >> n; vector<int64_t> a; copy_n(istream_iterator<int64_t>(cin), n, back_inserter(a)); set<int64_t> values_set; for (size_t i = 0; i != n; ++i) { values_set.insert(a[i] - i); } vector<int64_t> values(values_set.begin(), values_s...
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 peo...
n, n1, n2 = [int(x) for x in input().split()] d = [int(x) for x in input().split()] d.sort(reverse=True) s1 = 0 s2 = 0 n1, n2 = min(n1, n2), max(n1, n2) for i in range(n1): s1 += d[i] for i in range(n1, n1 + n2): s2 += d[i] ans = s1 / n1 + s2 / n2 print(ans)
Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described). This priority factor will be affected by three types of actions: * 1. "X posted on Y's wall" (...
#include <bits/stdc++.h> using namespace std; const int MAXN = 110; string me; map<string, int> M; string word[MAXN]; struct node { string name; int v; node() { name = ""; v = 0; } } relate[MAXN]; bool operator<(const node &a, const node &b) { if (a.v == b.v) return a.name < b.name; else ret...
Andryusha is an orderly boy and likes to keep things in their place. Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the sock...
#include <bits/stdc++.h> using namespace std; int main() { int n, tmp; cin >> n; vector<int> a(100001, 0); int counter = 0; int max_count = 0; n = n * 2; while (n--) { cin >> tmp; if (a[tmp] == 0) { ++counter; ++a[tmp]; } else if (a[tmp] == 1) { --counter; ++a[tmp]; ...
Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser. Last evening Roma started to play poker. He decided to spend no more than k virtual bourl...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1005; bool dp[MAX_N][2 * MAX_N]; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, k; cin >> n >> k; string s; cin >> s; dp[0][k] = true; for (int i = 0; i < (int)(n); ++i) { for (int j = (int)(1); j < (int)(2 * k); ++j) { ...
Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more...
#include <bits/stdc++.h> using namespace std; char c[2000100]; int p[2000100]; int get(int a) { if (p[a] == a) return a; return p[a] = get(p[a]); } void unite(int a, int b) { p[a] = b; } void add(string &s, int a) { int k = get(a); while (true) { if (k - a + 1 > s.size()) break; c[k] = s[k - a]; uni...
There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-8; const double pi = acos(-1.0); vector<pair<long long, long long> > V; vector<long long> ans; struct TE { long long a, b; } E[101000]; long long n, m, st[101000], sum; bool cmp(TE a, TE b) { if (a.a == b.a) return a.b < b.b; return a.a < b.a; } ...
Luba has to do n chores today. i-th chore takes ai units of time to complete. It is guaranteed that for every <image> the condition ai ≥ ai - 1 is met, so the sequence is sorted. Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a...
import java.lang.reflect.Array; import java.util.*; import java.math.*; import java.io.*; import java.text.*; public class A { static class Node implements Comparable<Node>{ int x; double d; public Node(int x,double d){ this.x=x; this.d=d; } public ...
A correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so tha...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.util.Random; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream...
A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new...
import java.io.*; import java.util.*; import static java.lang.Math.*; public class BetaRound75_Div1_A implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws IOException...
You are given a binary string s (each character of this string is either 0 or 1). Let's denote the cost of string t as the number of occurences of s in t. For example, if s is 11 and t is 111011, then the cost of t is 3. Let's also denote the Fibonacci strings sequence as follows: * F(0) is 0; * F(1) is 1; * F...
#include <bits/stdc++.h> using namespace std; const int N = 100, yzh = 1e9 + 7; void read(int &x) { char ch; bool flag = 0; for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar()) ; for (x = 0; isdigit(ch); x = (x << 1) + (x << 3) + ch - 48, ch = getchar()) ; x *= 1 -...
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way. There are n ghosts in the universe, they move in the OXY plane, each one of them has its own velocity that does not change in time: \overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarr...
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; import java.util.Objects; public class D478Div2 { public static void main(String[] args) { new D478Di...
For a vector \vec{v} = (x, y), define |v| = √{x^2 + y^2}. Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, ⋅⋅⋅, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_...
#include <bits/stdc++.h> using namespace std; template <class T> using min_queue = priority_queue<T, vector<T>, greater<T>>; template <typename Args> void kill(Args args) { cout << args << "\n"; exit(0); } mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const double PI = acos(-1); const long lo...
Bajirao's city has N X N police stations P(i,j) (1 ≤ i ≤ N, 1 ≤ j ≤ N) arranged in an N X N square matrix format. Bajirao is a really hardworking police officer and wants to solve all the pending cases of all the police stations in his city. However, the Police Commissioner (his senior) is not allowing him to do so due...
n=input() casearray=[] for i in range(n): casearray.append(map(int,raw_input().split())) maxcase=[] maxcaseperlevel=[] directconnect=[] for i in range(n): directconnect.append(-1) maxcase.append([]) maxcaseperlevel.append([]) for j in range(n): maxcase[i].append(0) maxcaseperlevel[i]...
Chris always struggle in converting angles from degree to radian or vice-verse. You being his best friend whom he trusts so much, decided to help him out. Sam has T angles you need to convert them in radian and represent them in fraction(i.e P/Q) and simplest form. [Note]: be careful with sign convention here π=$. Inp...
from fractions import gcd t=int(raw_input()) while(t): angle=int(raw_input()) if angle>=360: angle=angle-360*(angle//360) g=gcd(angle,180) rad=180 while(g!=1): angle=angle/g rad/=g g=gcd(angle,rad) if angle==1 and rad!=1: print "$"+"/"+str(rad) elif angle!=1 and rad==1: print str(angle)+"$" ...
You are given 'k' eggs and a 'n' storey building. The eggs MIGHT break if thrown down from a specific height (Note: It is NOT necessary that the eggs have to break; they might not even break from the topmost floor). What is the minimum number of steps in which you can find (using 'k' eggs) the minimum height of the flo...
ht = {} def floors(e, s): if e == 0 or s == 0: return 0 elif e == 1: return s elif s == 1: return 1 elif e > s: return floors(s, s) if not ht.has_key((e, s)): ht[(e, s)] = floors(e-1, s-1) + floors(e, s-1) + 1 return ht[(e, s)] noc = input() while noc: ...
A fashion show rates participants according to their level of hotness. Two different fashion shows were organized, one for men and the other for women. A date for the third is yet to be decided ;) . Now the results of both fashion shows are out. The participants of both the fashion shows have decided to date each othe...
T=input() while(T): T-=1 N=input() H=map(int,raw_input().split()) M=map(int,raw_input().split()) H.sort() M.sort() s=0 for x in xrange(N): s+=H[x]*M[x] print s
It’s well know fact among kitties that digits 4 and 7 are lucky digits. Today, N boxes of fish bites arrived. Each box has a unique integer label on it, ranged between 1 and N, inclusive. The boxes are going to be given away to the kitties in increasing order of their labels. That is, the first box given away will be t...
k = input() n = input() i=1 a=0 b=0 cnt=0 while(i<=n): a+=str(i).count('4') b+=str(i).count('7') if(a+b>k): cnt+=1 a=0 b=0 i+=1 print cnt
Description: Name string is a string consisting of letters "R","K" and "V". Today Oz wants to design a name string in a beautiful manner. Actually Oz cannot insert these three letters arbitrary anywhere ,he has to follow some rules to make the name string look beautiful. First thing is that the name string should consi...
for _ in xrange(input()): r,k,v=sorted(map(int,raw_input().split())) if k==v: print k+v else: print 2*k+1
The main building of the nation is developing complex patterns as each day progresses. The task is to find the number of three sided closed figures on the nth day. (Input – n Output – number of triangles) SAMPLE INPUT 2 SAMPLE OUTPUT 5
n=int(raw_input()) print n*n+(n-1)**2
Kancha wants to participate in a new event of Technobyte. Event says that you have to write a number in seven segment display using matchsticks. Please refer to the diagram below for how many sticks are used for each digit !! Now, event coordinator gave kancha a long string. your task is to tell how many matchsticks w...
A=[6,2,5,5,4,5,6,3,7,6] t=input() for i in range(0,t): s=raw_input() S=0 for j in range(0,len(s)): ch=ord(s[j])-48 S=S+A[ch] print(S)
Fatal Eagle has finally teamed up with Arjit to take on this weird army of zombies and vampires. And they are coming up with strategies to beat these guys on a roll. The simple thing they figured out is that these creatures attack everything by the method of brute force - i.e., the total power they have while attacking...
# Awesome Recursion Problem. # TODO(hapie): Learn iterative permutation generation algorithms. # 2^n recursions. doors = [0, 0] powers_sum = 0 arrangement_sum = 0 def recurse(item, idx): if idx == len(item): global arrangement_sum arrangement_sum += 1 return for i in range(2): if i == 0 and doors[0] + it...
Let f(x) represent the number of set bits (i.e. bit = 1) in the binary representation of non-negative integer x. For e.g. f(3) = 2, since 3 is represented as '11' in binary. Xenny's friend Xynazog gave him the following task: Given two non-negative integers A and B, find the sum of f(x) for all x in range [A, B] (A a...
from math import floor,log def f(n): if n<1:return 0 x=floor(log(n)/log(2)) return int(x*pow(2,x-1)+f(n-pow(2,x))+n-pow(2,x)+1) t=input() for _ in xrange(t): a,b=map(int,raw_input().split()) print f(b)-f(a-1)
Given is a number sequence A of length N. Find the number of integers i \left(1 \leq i \leq N\right) with the following property: * For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i. Constraints * All values in input are integers. * 1 \leq N \leq 2 \times 10^5 * 1 \leq A_...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.next()); int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = Integer.parseInt(sc.next()); } Array...
You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria. According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a; boolean result = true; for (int i=0; i<n; i++) { a = sc.nextInt(); if (a % 2 == 0) { if (!(a % 3 == 0 || a % 5 == 0)) { result = false; bre...
Snuke found a random number generator. It generates an integer between 0 and N-1 (inclusive). An integer sequence A_0, A_1, \cdots, A_{N-1} represents the probability that each of these integers is generated. The integer i (0 \leq i \leq N-1) is generated with probability A_i / S, where S = \sum_{i=0}^{N-1} A_i. The pr...
#include <bits/stdc++.h> typedef long long LL; typedef unsigned long long ULL; #define debug printf("fuck %d\n", __LINE__); inline LL read() { LL res = 0, bo = 1; char ch = getchar(); while(ch < '0' || ch > '9') { if (ch == '-') bo = -1; ch = getchar(); } while(ch >= '0' && ch <= '9') { res = (res << 1) + (res <<...
You have a digit sequence S of length 4. You are wondering which of the following formats S is in: * YYMM format: the last two digits of the year and the two-digit representation of the month (example: `01` for January), concatenated in this order * MMYY format: the two-digit representation of the month and the last t...
S = int(input()) b=S%100 a=S//100 if 1<=a<=12 and 1<=b<=12: print('AMBIGUOUS') elif 1<=a<=12: print('MMYY') elif 1<=b<=12: print('YYMM') else: print('NA')
There is a grid with H horizontal rows and W vertical columns. Let (i, j) denote the square at the i-th row from the top and the j-th column from the left. In the grid, N Squares (r_1, c_1), (r_2, c_2), \ldots, (r_N, c_N) are wall squares, and the others are all empty squares. It is guaranteed that Squares (1, 1) and ...
//In the name of God #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair <int , int> pii; const int N = 2e5+10 , mod = 1e9+7; vector <pii> v; int dp[N] , fac[N] , rev[N]; inline int power(int x , int y){ int ret = 1; for( ; y ; y /= 2){ if(y & 1) ret = 1ll * ret * ...
Takahashi has two positive integers A and B. It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10). Constraints * 2 ≤ N ≤ 10^5 * N is an integer. Input Input is given from Standard Input in the following format: N Outp...
N = sum([int(i) for i in input()]) print('10' if N == 1 else N)
A robot is put at the origin in a two-dimensional plane. Initially, the robot is facing in the positive x-axis direction. This robot will be given an instruction sequence s. s consists of the following two kinds of letters, and will be executed in order from front to back. * `F` : Move in the current direction by dis...
import os import sys if os.getenv("LOCAL"): sys.stdin = open("_in.txt", "r") sys.setrecursionlimit(10 ** 9) INF = float("inf") IINF = 10 ** 18 MOD = 10 ** 9 + 7 # MOD = 998244353 S = sys.stdin.buffer.readline().decode().rstrip() X, Y = list(map(int, sys.stdin.buffer.readline().split())) # X 軸と Y 軸は独立に考えられる。 d =...
Takahashi is hosting an sports meet. There are N people who will participate. These people are conveniently numbered 1 through N. Also, there are M options of sports for this event. These sports are numbered 1 through M. Among these options, Takahashi will select one or more sports (possibly all) to be played in the ev...
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter ...
There are N boxes arranged in a circle. The i-th box contains A_i stones. Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation: * Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<long> a(n); long s=0; for(auto& e: a) { cin>>e; s+=e; } auto m=n*(n+1L)/2; if (s%m>0) return cout<<"NO"<<endl, 0; int k=s/m; int t=0; for(int i=0; i<n; ++i) { auto e=a[(i+1)%n]-a[i]-k; ...
> Kyoto University Programming Contest is a programming contest voluntarily held by some Kyoto University students. This contest is abbreviated as Kyoto University Programming Contest and called KUPC. > > source: Kyoto University Programming Contest Information The problem-preparing committee met to hold this year's K...
//先頭の文字以外は必要ない。先頭の文字の個数をcnt[i]などで持ち、残り数が多いほうから使っていく。(未証明) #include <iostream> #include <string> #include <algorithm> #include <functional> using namespace std; int n, k; string p[10000]; int cnt[26]; int main() { int i, j; cin >> n >> k; for (i = 0; i < n; i++) { cin >> p[i]; cnt[p[i][0] - 'A']++; } for...
There is data that records the customer number of the business partner and the trading date on a monthly basis. Please create a program that reads this month's data and last month's data and outputs the customer number of the company with which you have transactions and the number of transactions for two consecutive mo...
#include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <cmath> #include <stack> #include <vector> #include <map> #include <set> #include <list> #include <iostream> #include <climits> #include <cfloat> using namespace std; int main() { map<int, int> first; map<int, int> seq; char buf[...
The greatest common divisor is an indispensable element in mathematics handled on a computer. Using the greatest common divisor can make a big difference in the efficiency of the calculation. One of the algorithms to find the greatest common divisor is "Euclidean algorithm". The flow of the process is shown below. <im...
def solve(): from sys import stdin f_i = stdin ans = "" while True: a, b = map(int, f_i.readline().split()) if a == 0 and b == 0: break if a < b: a, b = b, a # Euclidean Algorithm cnt = 1 while a...
At dusk in AIZU, it is crowded with tourists who hold their smartphones in the west sky and stop. AIZU is a big city with countless buildings, and in the west sky where the valleys of the buildings are long, the silhouette of the buildings and the spectacular view of the sunlight leaking from them spreads out. Accordi...
#include<bits/stdc++.h> #define rep(i,n) for(int i=0;i<(int)n;i++) #define all(c) (c).begin(),(c).end() #define pb push_back #define dbg(...) do{cerr<<__LINE__<<": ";dbgprint(#__VA_ARGS__, __VA_ARGS__);}while(0); using namespace std; namespace std{template<class S,class T>struct hash<pair<S,T>>{size_t operator()(cons...
problem The city of IOI, where JOI lives, has a rectangular shape with H sections in the north-south direction and W sections in the east-west direction, and is divided into H x W sections. The i-th section from the north and the j-th section from the west are represented as (i, j). A large-scale festival is currently...
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; const int inf = 1012345678; int A[1006][1006], dp[1006][1006][9]; int main() { cin.tie(0); ios_base::sync_with_stdio(false); int H, W; cin >> H >> W; for (int i = 0; i < H; ++i) { string S; cin >> S; for (int j ...
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles. Write a program to count the number of black tiles which he can r...
from collections import deque y = [-1,0,1,0] x = [0,-1,0,1] def main(): h,w = 0,0 c = [] def check(i,j): return 0<=i and i<h and 0<=j and j<w def bfs(a,b): res = 0 d = deque() d.append([a,b]) f = [[False]*w for _ in range(h)] while len(d): ...
Starting with x and repeatedly multiplying by x, we can compute x31 with thirty multiplications: x2 = x × x, x3 = x2 × x, x4 = x3 × x, ... , x31 = x30 × x. The operation of squaring can appreciably shorten the sequence of multiplications. The following is a way to compute x31 with eight multiplications: x2 = x × x, ...
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 100000...
Twin Trees Bros. To meet the demand of ICPC (International Cacao Plantation Consortium), you have to check whether two given trees are twins or not. <image> Example of two trees in the three-dimensional space. The term tree in the graph theory means a connected graph where the number of edges is one less than the nu...
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <cmath> #include <map> using namespace std; const double EPS = 1e-8; const double INF = 1e12; const double PI = acos(-1); #define EQ(n,m) (abs((n)-(m)) < EPS) struct Point{ double x,y,z; Point(double x, double y, double z):x...
Equilateral Triangular Fence Ms. Misumi owns an orchard along a straight road. Recently, wild boars have been witnessed strolling around the orchard aiming at pears, and she plans to construct a fence around many of the pear trees. The orchard contains n pear trees, whose locations are given by the two-dimensional Eu...
#include<bits/stdc++.h> using namespace std; int N, K; int X[10000], Y[10000]; void beet() { cin >> K; vector< int > vs; for(int i = 0; i < N; i++) { cin >> X[i] >> Y[i]; vs.push_back(Y[i]); } double sq3 = sqrt(3); vector< int > latte(N), malta(N); iota(begin(latte), end(latte), 0); iota(begi...
Alice and Bob are in love with each other, but they have difficulty going out on a date - Alice is a very busy graduate student at the ACM university. For this reason, Bob came to the ACM university to meet her on a day. He tried to reach the meeting spot but got lost because the campus of the university was very larg...
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define EPS (1e-5) #define equals(a,b) (fabs((a)-(b))<EPS) using namespace std; static const int COUNTER_CLOCKWISE = 1; static const int CLOCKWISE = -1; static const int ONLINE_BACK = 2; static const int ONLINE_FRONT = -2; st...
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to gain the power of business by running around the city and conducting trade. I want to earn as much money as possible for future training. In this world, roads in ...
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) #define repr(i, n) for (int i = (n); i >= 0; --i) #define FOR(i, m, n) for (int i = (m); i < (n); ++i) #define FORR(i, m, n) for (int i = (m); i >= (n); --i) #define equals(a, b) (fabs((a) - (b)) < EPS) using namespace std; typedef long long ll; t...
You are a researcher investigating algorithms on binary trees. Binary tree is a data structure composed of branch nodes and leaf nodes. Every branch nodes have left child and right child, and each child is either a branch node or a leaf node. The root of a binary tree is the branch node which has no parent. You are pr...
#include <bits/stdc++.h> using namespace std; using ll=long long; #define FOR(i,a,b) for(int i=int(a);i<int(b);i++) #define REP(i,b) FOR(i,0,b) using vi=vector<int>; #define PB push_back #define ALL(x) x.begin(),x.end() const int Nmax=415514; const int inf=1145141919; char tree[Nmax],buf[Nmax]; int sub[Nmax],idx; int...
In 20XX, the owners of the ICPC (Ikuta's Computer Pollutes Community) shopping district were suffering from air pollution. In order to regain the vitality of the past, the cleanliness of the atmosphere must be kept above a certain level. The shops in the shopping district are lined up in a row and are numbered from 1 ...
#include <bits/stdc++.h> using namespace std; using ll = long long; template <typename T> class fenwick_tree { const int n; vector<T> data; public: fenwick_tree(int n_) : n(n_), data(n + 1) {} T find(int p) const { T res = 0; while (p > 0) { res += data[p]; p -= p & -p; } return res; } T find(int l...
Problem statement Jota knows only the characters from `a` to` z` and the addition symbol `+`. Jota has an older sister, Tachiko. In addition to that, Tatsuko knows multiplication `*`, parentheses `(`, `)`, and integers (numbers) between `1` and` 9`. However, I don't know how to use multiple parentheses and how to mult...
#include "bits/stdc++.h" using namespace std; //#define int long long #define DBG 0 #define dump(o) if(DBG){cerr<<#o<<" "<<o<<endl;} #define dumpc(o) if(DBG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;} #define rep(i,c,b) for(int i=(c);i<(b);i++) #define rrep(i,c,b) for(int i=(b)-1;i>=(c);i--) #define all(c) c....
You are playing a game called Guru Guru Gururin. In this game, you can move with the vehicle called Gururin. There are two commands you can give to Gururin: 'R' and 'L'. When 'R' is sent, Gururin rotates clockwise by 90 degrees. Otherwise, when 'L' is sent, Gururin rotates counterclockwise by 90 degrees. During the ga...
#include<iostream> #include<algorithm> #include<cstdio> #include<cmath> #include<cctype> #include<math.h> #include<string> #include<string.h> #include<stack> #include<queue> #include<vector> #include<utility> #include<set> #include<map> #include<stdlib.h> #include<iomanip> using namespace std; #define ll long long #d...
Problem You were asked by your friend Tousa the day before yesterday. He wants to decorate a tree with an arithmetic progression and use it for a birthday party, but the tree is too big to be used alone. Therefore, he wants you, an excellent programmer, to write a program that efficiently decorates a tree with arithme...
#include<bits/stdc++.h> using namespace std; using Int = long long; struct HLDecomposition { Int n,pos; vector<vector<Int> > G; vector<Int> vid, head, sub, hvy, par, dep, inv, type; HLDecomposition(){} HLDecomposition(Int sz): n(sz),pos(0),G(n), vid(n,-1),head(n),sub(n,1),hvy(n,-1), par(n),dep...
A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations: * $insert(S, k)$: insert an element $k$ into the set $S$ * $extractMax(S)$: remove and return the element of $S$ with the largest key Write a program which perfo...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.lang.reflect.Array; import java.util.Comparator; public class Main { public static class PriorityQueue<T> { ...
Queue is a container of elements that are inserted and deleted according to FIFO (First In First Out). For $n$ queues $Q_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations. * enqueue($t$, $x$): Insert an integer $x$ to $Q_t$. * front($t$): Report the value which should be deleted next from $Q_t...
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int n=Integer.parseInt(in.next()),q=Integer.parseInt(in.next()); myqueue A[]=new myqueue[n]; for(int i=0;i<n;i++)A[i]=new my...
Chef has recently learnt some new facts about the famous number π. For example, he was surprised that ordinary fractions are sometimes used to represent this number approximately. For example, 22/7, 355/113 or even 103993/33102. Soon, by calculating the value of 22/7 and 355/113 on paper Chef became quite disappointed ...
def main(): cases = int(raw_input()) repetition='415926530119026040722614947737296840070086399613316' for i in range(cases): k = int(raw_input()) if(k == 0): print "3" elif(k==1): print "3.1" ...
In Wolf town there are 2 big markets S and T. The distance between these markets is D. Chef Ciel would like to run 2 restaurants in Wolf town, where the first restaurant will be supplied by the market S and the second one will be supplied by the market T. The markets run delivery service without charge within some dist...
def solve(da, db, d): if(da + db <= d): return d - da - db elif(da + d <= db): return db - d - da elif(db + d <= da): return da - d - db else: return 0 # main test = int(raw_input()) for i in range(test): # apply the function(int) to all items in the raw_input().split() da, db, d = map(int...
Mirrored Strings Davy Jones needs to conquer a ship for his pirates. But the only rule he has to follow is to conquer only those ships whose names are partially mirrored at the end. For Example: If a ship's name is 'abxyzba' then he can conquer the ship because the string has mirrored string at the beginning and at th...
x=raw_input() l=len(x) s="" for i in range(0,l): if x[i]==x[l-i-1]: s=s+x[i] else: break print s
Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. If there are odd number of characters in the string, we ignore the middle character and check for lapindrome. For example gaga is a lapindrome, since the two halves ga and ...
q=int(raw_input()) while(q>0): a=raw_input() a1=a[0:len(a)//2] if(len(a)%2==0): a2=a[(len(a)//2):len(a)] else: a2=a[(len(a)//2)+1:len(a)] a1=list(a1) a1.sort() a2=list(a2) a2.sort() cnt=0 for x, y in zip(a1, a2): if(x==y): cnt+=1 if(cnt==len(a)//2): print 'YES' else: print 'NO' q-=1
Yesterday, the CS Club hosted a massive party that put all the frat parties to shame. Today, they have to clean up everything. They also have to restock the strategic supply of Mountain Dew. Phillip hates cleaning and wants to pick up the dew instead. He knows that they intend to distribute the chores by having eve...
import sys def josephus(n,k): if n==1: return 1 else: return (josephus(n-1,k)+k-1)%n+1 n,k=map(int,sys.stdin.readline().split()) sys.stdout.write("%d"%josephus(n,k))
Given n words w[1..n], which originate from the same stem (e.g. grace, graceful, disgraceful, gracefully), we are interested in the original stem. To simplify the problem, we define the stem as the longest consecutive substring that occurs in all the n words. If there are ties, we will choose the smallest one in the al...
''' Created on 24-Oct-2015 @author: Venkatesh ''' def read_str_list(): return [x for x in raw_input().split()] def read_int(): return int(raw_input()) def get_stem(s_lst, n): fst_str = s_lst[0] m = len(fst_str) ans = "" all_stems = set() for k in xrange(1, m+1): for j in xrang...
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangle...
import java.util.*; public class helloWorld { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String ans = "YES"; int h = 1000000000; for(int i = 0; i < n; i++) { int a = in.nextInt(); int b = in.nextInt(); if(a > b) { int temp = a; ...
You are given a tuple generator f^{(k)} = (f_1^{(k)}, f_2^{(k)}, ..., f_n^{(k)}), where f_i^{(k)} = (a_i ⋅ f_i^{(k - 1)} + b_i) mod p_i and f^{(0)} = (x_1, x_2, ..., x_n). Here x mod y denotes the remainder of x when divided by y. All p_i are primes. One can see that with fixed sequences x_i, y_i, a_i the tuples f^{(k...
#include <bits/stdc++.h> using namespace std; using i64 = long long; using pii = pair<int, int>; const int V = 2e6 + 5, MOD = 1e9 + 7; map<int, pii> mp; vector<int> p, phi, prm; int n; int lst[V]; static void get_lst() { for (int i = 2; i < V; ++i) if (lst[i] == 0) for (int j = i; j < V; j += i) lst[j] = i;...
Euler is a little, cute squirrel. When the autumn comes, he collects some reserves for winter. The interesting fact is that Euler likes to collect acorns in a specific way. A tree can be described as n acorns connected by n - 1 branches, such that there is exactly one way between each pair of acorns. Let's enumerate th...
#include <bits/stdc++.h> using namespace std; int gi() { int res = 0, w = 1; char ch = getchar(); while (ch != '-' && !isdigit(ch)) ch = getchar(); if (ch == '-') w = -1, ch = getchar(); while (isdigit(ch)) res = res * 10 + ch - '0', ch = getchar(); return res * w; } const int MAX_N = 1e6 + 5; void Fail() {...
There is an array a of 2^{30} integers, indexed from 0 to 2^{30}-1. Initially, you know that 0 ≤ a_i < 2^{30} (0 ≤ i < 2^{30}), but you do not know any of the values. Your task is to process queries of two types: * 1 l r x: You are informed that the bitwise xor of the subarray [l, r] (ends inclusive) is equal to x. ...
#include <bits/stdc++.h> using namespace std; int intcmp(const void *v1, const void *v2) { return *(int *)v1 - *(int *)v2; } int q; map<int, int> fa, faxor; int find_fa(int v) { if (v != fa[v]) { int newfa = find_fa(fa[v]); faxor[v] ^= faxor[fa[v]]; fa[v] = newfa; } return fa[v]; } int main() { scan...
All bus tickets in Berland have their numbers. A number consists of n digits (n is even). Only k decimal digits d_1, d_2, ..., d_k can be used to form ticket numbers. If 0 is among these digits, then numbers may have leading zeroes. For example, if n = 4 and only digits 0 and 4 can be used, then 0000, 4004, 4440 are va...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(...
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water. There are only two types of water bottles in the nearby shop — 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop. The bottle of the first type costs a burles and the bottle of the se...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); while (0) { }; int q; cin >> q; long long n; int a, b; long long out = 0; while (q--) { cin >> n >> a >> b; if (a * 2 <= b) { out = (long long)a * n; } else { out = ...
You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero): 1. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|; 2. Choose a pair of indices (i, j) such that |i-j|=1 (indice...
from sys import stdin,stdout from math import gcd,sqrt from collections import deque input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') P=lambda x:stdout.write(x) hg=lambda x,y:((y+x-1)//x)*x pw=lambda x:1 if x==1 else 1+pw(x//2) chk=lambda x:chk(x//2) if not x%2 ...
Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and ...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string str; cin >> str; vector<char> v; int i = 0, j = 1; while (i < n && j < n) { if (str[i] != str[j]) { if (i > j) v.push_back(str[j]), v.push_back(str[i]); else v.push_back(str[i]), v.push_back(...
The Cybermen solved that first test much quicker than the Daleks. Luckily for us, the Daleks were angry (shocking!) and they destroyed some of the Cybermen. After the fighting stopped, Heidi gave them another task to waste their time on. There are n points on a plane. Given a radius r, find the maximum number of poin...
#include <bits/stdc++.h> using namespace std; const int OFF = (1 << 23); const int DOD = (1 << 22); int tour[2 * OFF], prop[2 * OFF], n, r; vector<pair<pair<int, int>, pair<int, int> > > v; void refresh(int i) { if (!prop[i]) return; tour[i] += prop[i]; if (i < OFF) { prop[2 * i] += prop[i]; prop[2 * i + ...
You are given a string t and n strings s_1, s_2, ..., s_n. All strings consist of lowercase Latin letters. Let f(t, s) be the number of occurences of string s in string t. For example, f('aaabacaa', 'aa') = 3, and f('ababa', 'aba') = 2. Calculate the value of ∑_{i=1}^{n} ∑_{j=1}^{n} f(t, s_i + s_j), where s + t is th...
#include <bits/stdc++.h> #pragma GCC optimize(2) #pragma G++ optimize(2) using namespace std; const int MAX_N = 2e5 + 5; struct AC_Automation { int nxt[MAX_N][26], ed[MAX_N], fail[MAX_N]; int root, L; int num[MAX_N]; int new_node() { ed[++L] = 0; for (register int i = 0; i <= 25; ++i) nxt[L][i] = -1; ...
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import static java.lang.Math.log; import static java.lang.Math.mi...
You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perfor...
#include <bits/stdc++.h> using namespace std; template <class t> t mag(t a) { return a > 0 ? a : -a; } template <class T, class U> T cdiv(T num, U den) { return (num / den) + ((num % den) > 0); } std::ifstream term("/dev/tty"); std::string tempstring; using ll = int_fast64_t; using ii = pair<int, int>; using vi = v...
Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint ...
#include <bits/stdc++.h> using namespace std; long long mod = 998244353; long long qpow(long long a, long long b) { long long ans = 1; while (b) { if (b & 1) ans = ans * a % mod; b >>= 1; a = a * a % mod; } return ans; } long long mul[800005]; long long p[200005], ip[200005]; long long multi[800005]...
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the...
import io import os from collections import Counter, defaultdict, deque # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default =...
The only difference between easy and hard versions is the constraint on k. Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue. Gildong is going to take videos for n days, starting from day 1 to day n. ...
#include <bits/stdc++.h> using namespace std; struct node { int le, ri; int mx, tag; } sgt[20005 << 2]; int n, m, k; int a[55][20005], sum[55][20005], dp[55][20005]; void build(int cur, int l, int r, int x) { sgt[cur].le = l, sgt[cur].ri = r; sgt[cur].tag = 0; if (l == r - 1) { sgt[cur].mx = dp[x - 1][l] ...
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as foll...
#include <bits/stdc++.h> using namespace std; const long long infl = 1LL << 60; int mod = 1e9 + 7; int main() { ios::sync_with_stdio(false); int t; cin >> t; while (t--) { long long n, m; cin >> n >> m; vector<long long> v; long long ans = 1, x = 1; while (ans <= n) { v.push_back(x); ...
Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to th...
import java.io.*; import java.util.*; import java.lang.*; public class Temp{ static PrintWriter w=new PrintWriter(System.out); public static void main (String[] args)throws IOException{ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=...
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determine...
#include <bits/stdc++.h> long long dx[8] = {0, 1, 0, -1, 1, 1, -1, -1}; long long dy[8] = {1, 0, -1, 0, -1, 1, 1, -1}; using namespace std; class pa3 { public: long long x; long long y, z; pa3(long long x = 0, long long y = 0, long long z = 0) : x(x), y(y), z(z) {} bool operator<(const pa3 &p) const { if (...
You have a simple and connected undirected graph consisting of n nodes and m edges. Consider any way to pair some subset of these n nodes such that no node is present in more than one pair. This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most ...
#include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); long long T; cin >> T; while (T--) { long long N, M; cin >> N >> M; vector<vector<long long>> L(N + 1); for (long long i = 0; i < M; i++) { long long a, b; cin >> a >> b; ...
You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array s...
#include <bits/stdc++.h> signed main() { int t; std::cin >> t; while (t--) { int n; std::cin >> n; int a[n]; int sum = 0; for (int i = 0; i < n; i++) { std::cin >> a[i]; sum += a[i]; } if (sum % n != 0) { std::cout << -1 << std::endl; continue; } std::ve...
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive. Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on. Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone...
for x in range(int(input())): a=input() s=(int(a[0])-1)*10 t= len(a) s+=t*(t+1)//2 print(s)
Given integers c_{0}, c_{1}, …, c_{k-1} we can define the cost of a number 0 ≤ x < 2^{k} as p(x) = ∑_{i=0}^{k-1} \left( \left⌊ \frac{x}{2^{i}} \right⌋ mod 2 \right) ⋅ c_{i}. In other words, the cost of number x is the sum of c_{i} over the bits of x which are equal to one. Let's define the cost of array a of length n ...
// iostream is too mainstream #include <cstdio> // bitch please #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <queue> #include <stack> #include <list> #include <chrono> #include <random> #include <cstdlib> #include <cmath> #include <ctime> #include <cstring> #include ...
The great hero guards the country where Homer lives. The hero has attack power A and initial health value B. There are n monsters in front of the hero. The i-th monster has attack power a_i and initial health value b_i. The hero or a monster is said to be living, if his or its health value is positive (greater than o...
import math for t in range(int(input())): a,b,n=map(int,input().split()) attack=list(map(int,input().split())) health=list(map(int,input().split())) val=[] for i in range(n): val+=[[attack[i],health[i]]] val.sort() poss=True for i in range(n): times=math.ceil(val[i][1]/a)...
A bitstring is a string that contains only the characters 0 and 1. Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length 2n. A valid novel for the contes...
#include<bits/stdc++.h> #define int long long #define N 200000 #define P 1000000007 using namespace std; int T,n,f[N+1],pf,g[N+1],pg; string s[3]; bool pd(string s1,string s2){ int n0=0,n1=0,n2=0,n3=0; for(int i=0;i<2*n;i++)if(s1[i]=='0')n0++;else n1++; for(int i=0;i<2*n;i++)if(s2[i]=='0')n2++;else n3++; int nfl=0;...
Little Dormi received a histogram with n bars of height a_1, a_2, …, a_n for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking. To modify the histogram, Little Dormi is able to perform the following operation an arbitrar...
t = int(input()) for _ in range(t): n = int(input()) res = 0 a = map(int, input().split()) p = 0 pp = 0 ugly = 0 for k in a: if k > p: ugly += k - p pp = p else: down = max(0, min(p - k, p - pp)) ugly += p - k - down ...
A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactl...
import javax.xml.bind.SchemaOutputResolver; import java.io.*; import java.util.Vector; public class SOLVE { static public final int maxn = (int)5e4 + 5; static public int n, k, cent; static public int[] size = new int[maxn]; static public int[] used = new int[maxn]; static public Vector<Intege...
Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≤ i ≤ n) has a best friend p[i] (1 ≤ p[i] ≤ n). In fact, each student is a best frie...
import java.util.Scanner; public class i { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n+1]; int[] p = new int[n+1]; for (int i=1;i<=n;i++) a[sc.nextInt()]=i; for (int i=1;i<=n;i++) p[...
The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks...
#include <bits/stdc++.h> using namespace std; template <typename T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; } inline void read(int &x) { x = 0; char c = getchar(); int f = 1; while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = 10 * x +...
You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the valu...
#include <bits/stdc++.h> using namespace std; int c[10000]; int a[10000]; int b[10000]; int inf = 99999; int main() { int n, i, j, k, t, m; int sign; int ans; char ch; while (scanf("%d%d", &n, &m) != EOF) { sign = 0; for (i = 0; i < m; i++) c[i] = 0; for (i = 0; i < n; i++) { scanf("%*c"); ...