input
stringlengths
29
13k
output
stringlengths
9
73.4k
The only difference between easy and hard versions is the constraints. Polycarp has to write a coursework. The coursework consists of m pages. Polycarp also has n cups of coffee. The coffee in the i-th cup has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups i...
import java.io.*; import java.util.*; public class MainClass{ public static void task(InputReader in,PrintWriter out){ //---------------------------------Solve here------------------------------- int n=in.nextInt(); int m=in.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++)...
Two integer sequences existed initially, one of them was strictly increasing, and another one — strictly decreasing. Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and the s...
#include <bits/stdc++.h> #pragma GCC optimize(3, "Ofast", "inline") using namespace std; mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()); const long long maxn = (long long)1e6 + 5; const long long mod = 998244353; const long long inf = 0x3f3f3f3f; long long T = 1; long long n, a[maxn], in[m...
The only difference between easy and hard versions is constraints. Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them. E...
#include <bits/stdc++.h> using namespace std; int n, m; vector<long long> a; vector<vector<long long> > d; bool ok(long long k) { long long sum = accumulate(a.begin(), a.end(), 0ll); if (k >= 2 * sum) return true; if (k < sum) return false; long long num = 2 * sum - k; vector<long long> z(n, 0); for (int i ...
Heidi enjoyed performing the simulation because she knew exactly when a new universe would be formed and where, and when a non-existent link would be broken and where. However, the multiverse itself works in mysterious ways. Well, it works using probabilities, which to some people is mysterious. At each unit time, wh...
#include <bits/stdc++.h> using namespace std; const int M = 260; const int mod = 1e9 + 7; array<int, M - 1> f[M][M + 1]; array<int, M - 1> eq[M - 1]; int v[M - 1]; array<int, M - 1> sl[M][M + 1], sr[M][M + 1]; int n, k, m; int inv[M + 1]; array<int, M - 1> mul(array<int, M - 1> x, int y) { for (int i = 0; i < m - 1; ...
You are given 4n sticks, the length of the i-th stick is a_i. You have to create n rectangles, each rectangle will consist of exactly 4 sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only...
q = int(input()) for w in range(q): n = int(input()) a = list(map(int, input().split())) a.sort() n *= 4 x = a[0] * a[n - 1] ok = 1 for i in range(0, n // 2, 2): if a[i] * a[n - i - 1] != x or a[i] != a[i + 1] or a[n - i - 1] != a[n - i - 2]: ok = 0 break ...
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. Petya has n number segments [l1; r1], [l2; r2], ..., [ln; rn]. During one move Petya can take any se...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; const int M = 1 << 19; int n, m; long long k, mn = 1e18, l[N], r[N]; long long lucky[M], dp1[M], dp2[M]; vector<int> vec[M]; inline long long Mul(long long a, long long b) { return a && k / a < b ? k + 10 : a * b; } inline void Sum(long long &a, lon...
Consider the set of all nonnegative integers: {0, 1, 2, ...}. Given two integers a and b (1 ≤ a, b ≤ 10^4). We paint all the numbers in increasing number first we paint 0, then we paint 1, then 2 and so on. Each number is painted white or black. We paint a number i according to the following rules: * if i = 0, it ...
def gcd(a,b): if a==0: return b elif b==0: return a elif a>=b: return gcd(a%b,b) else: return gcd(a,b%a) t=int(input()) for i in range(t): a,b=input().strip().split(" ") a,b=[int(a),int(b)] if gcd(a,b)==1: print("Finite") else: print("Infin...
A football league has recently begun in Beautiful land. There are n teams participating in the league. Let's enumerate them with integers from 1 to n. There will be played exactly (n(n-1))/(2) matches: each team will play against all other teams exactly once. In each match, there is always a winner and loser and there...
#include <bits/stdc++.h> const int N = 1000005, inf = 1e9; int n, m, S, T, a[1005][1005], id[1005][1005], cid, h[N], nxt[N], adj[N], w[N], c[N], t = 1, vs[1005][1005]; long long ans; namespace MXF { int a[N], d[N], pre[N], q[N], top1, top2, S, T; bool inq[N]; inline int Min(const int p, const int q) { return p < q ...
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first...
from sys import stdin from collections import * from copy import copy from bisect import * class graph: # initialize graph def __init__(self, gdict=None): self.gdict = defaultdict(list) # add edge def addEdge(self, node1, node2, w=None): self.gdict[node1].append(node2) self.gd...
To become the king of Codeforces, Kuroni has to solve the following problem. He is given n numbers a_1, a_2, ..., a_n. Help Kuroni to calculate ∏_{1≤ i<j≤ n} |a_i - a_j|. As result can be very big, output it modulo m. If you are not familiar with short notation, ∏_{1≤ i<j≤ n} |a_i - a_j| is equal to |a_1 - a_2|⋅|a_1 ...
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) a = list(map(int,input().split())) lst = [0]*m for i in a: lst[i%m] += 1 if max(lst) >= 2: print(0) else: ans = 1 ...
There is a string of length n+1 of characters 'A' and 'B'. The first character and last character of the string are equal to 'A'. You are given m indices p_1, p_2, …, p_m (0-indexation) denoting the other indices of characters 'A' in the string. Let's denote the minimum distance between two neighboring 'A' as l, and ...
#include <bits/stdc++.h> using namespace std; long long up(long long a, long long b) { return (a + b - 1) / b; } long long down(long long a, long long b) { return a / b; } long long a[400010]; pair<long long, long long> b[400010]; long long mx[400010]; void solve() { long long n, k; int m; scanf("%I64d %d %I64d",...
Slime and Orac are holding a turn-based game. In a big room, there are n players sitting on the chairs, looking forward to a column and each of them is given a number: player 1 sits in the front of the column, player 2 sits directly behind him; player 3 sits directly behind player 2, and so on; player n sits directly b...
#include <bits/stdc++.h> using namespace std; template <class T> int chkmax(T& a, T b) { if (b > a) { a = b; return 1; } return 0; } template <class T> int chkmin(T& a, T b) { if (b < a) { a = b; return 1; } return 0; } template <class iterator> void output(iterator begin, iterator end, ostr...
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that als...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; public class Replacement { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatE...
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible. Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he...
import sys T = int(sys.stdin.readline().strip()) for t in range (0, T): n = int(sys.stdin.readline().strip()) a = list(map(int, sys.stdin.readline().strip().split())) ans = 0 for i in range (1, n): if a[i] < a[i-1]: ans = ans + a[i-1] - a[i] print(ans)
One day, BThero decided to play around with arrays and came up with the following problem: You are given an array a, which consists of n positive integers. The array is numerated 1 through n. You execute the following procedure exactly once: * You create a new array b which consists of 2n positive integers, where f...
#include <bits/stdc++.h> using namespace std; void read(long long &a) { a = 0; char c = getchar(); while (c < '0' || c > '9') { c = getchar(); } while (c >= '0' && c <= '9') { a = (a << 1) + (a << 3) + (c ^ 48); c = getchar(); } } const long long Maxn = 500000; long long T; struct Reverse_Set { ...
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other. You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts). If two...
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int[] a = new int[n]; int x= -1,f=0; for(int i=0;i<n;i++){ ...
You are given a square matrix of size n. Every row and every column of this matrix is a permutation of 1, 2, …, n. Let a_{i, j} be the element at the intersection of i-th row and j-th column for every 1 ≤ i, j ≤ n. Rows are numbered 1, …, n top to bottom, and columns are numbered 1, …, n left to right. There are six t...
#include <bits/stdc++.h> using namespace std; #define pb push_back #define ll long long #define vi vector<ll > #define vvi vector<vi > #define all(x) x.begin(), x.end() int n, q; vvi v, w; vi e, p; string s; void add(ll& x, ll y) { x = (x + y + n) % n; } void f() { cin >> n >> q; v.assign(n, vi(n)); ...
You finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence — so plain and boring, that you'd like to repaint it. <image> You have a fence consisting of n planks, where the i-th plank has the color a_i. You want to repaint the fence in such a way that t...
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; import static java.lang.Math.*; /* Name of the class has to be "Main" only if the class is public. */ // class Codechef public class CFencePainting { static InputReader in = new InputReader(System.in); ...
Based on a peculiar incident at basketball practice, Akari came up with the following competitive programming problem! You are given n points on the plane, no three of which are collinear. The i-th point initially has a label a_i, in such a way that the labels a_1, a_2, ..., a_n form a permutation of 1, 2, ..., n. Yo...
#include<bits/stdc++.h> using namespace std; typedef long long LL; const int N = 2222; int n,a[N],x[N],y[N],p[N],f[N]; bool cmp(int i,int j){ return (LL)x[i]*y[j]-(LL)x[j]*y[i]>0; } void ff(){ int i,x; for(i=1;i<=n;i++) f[i]=0; for(i=1;i<=n;i++){ if(!f[i]){ f[i]=i; for(x=a[i];x!=i;x=a[x]) f[x]=i; } ...
This is an interactive problem. Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, whi...
import static java.util.Arrays.*; import java.util.*; public class E { public Object solve () { int N = sc.nextInt(), K = sc.nextInt(); if (N % 2 == 1 && K % 2 == 0) return -1; int [][] Z = new int [N][]; for (int i : rep(N)) Z[i] = new int [] { i, 1 }; int S = N, M = 1; for (int i = 0; S % K !...
To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the sellin...
#include <bits/stdc++.h> using namespace std; int n, m, k; string str; int main() { while (cin >> n >> m >> k) { vector<vector<int> > a(n, vector<int>(m)), b(n, vector<int>(m)), c(n, vector<int>(m)); for (int i = 0; i < (n); ++i) { cin >> str; for (int j = 0; j < (m); ++j) { scanf(...
The Little Elephant loves strings very much. He has an array a from n strings, consisting of lowercase English letters. Let's number the elements of the array from 1 to n, then let's denote the element number i as ai. For each string ai (1 ≤ i ≤ n) the Little Elephant wants to find the number of pairs of integers l a...
#include <bits/stdc++.h> using namespace std; struct SAComp { const int h, *g; SAComp(int h, int* g) : h(h), g(g) {} bool operator()(int a, int b) { return a == b ? false : g[a] != g[b] ? g[a] < g[b] : g[a + h] < g[b + h]; } }; int* buildSA(const char* t, int n) { int g[n + 1], b[n + 1], *v = new int[n + ...
The city of D consists of n towers, built consecutively on a straight line. The height of the tower that goes i-th (from left to right) in the sequence equals hi. The city mayor decided to rebuild the city to make it beautiful. In a beautiful city all towers are are arranged in non-descending order of their height from...
#include <bits/stdc++.h> using namespace std; long long rez, s, dp[5010][5010], n, a[5010], k, k1, k2, i, j; int main() { cin >> n; for (i = 1; i <= n; i++) cin >> a[i]; for (i = 0; i <= n; i++) for (j = 0; j <= n; j++) dp[i][j] = 1000000000; dp[0][0] = 0; for (i = 1; i <= n; i++) { k = -1; s = 0;...
One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class PhysicsPractical { public static void main(String[] args) { int...
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official language...
import java.io.*; import java.util.*; public class learninglanguages{ public static void main(String[] args) throws Exception { InputReader in=new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); int m=in.nextInt(); disjointset ds=ne...
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive. Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the sa...
import static java.lang.System.*; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class B181 { public static Scanner sc=new Scanner(in); //public static Random sc=new Random(); public static final String br=System....
Piegirl found the red button. You have one last chance to change the inevitable end. The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-8; const double pi = acos(-1.0); const int N = 1e5 + 10; vector<int> vec[N]; bool vis[N]; int dis[N], tt[N]; int n; int spfa(int u) { if (vis[u]) return -1; vis[u] = 1; if (dis[u] != -1) return dis[u]; if ((u * 2 + 1) % n == u) return dis[u] = ...
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the...
#include <bits/stdc++.h> using namespace std; long long int x[1000007], y[1000007], z[1000007]; string s; int main() { { long long int a = 0, b = 0, d, e, i, j, k, l, m, n, p = 1, q, r, t, u, val, w, tc, mn = 2134567891, mx = 0, sum = 0, ans = 0; cin >> n; for (i = 0; i < n; i++) cin >> ...
There is an n × m rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the i-th row and the j-th column as (i, j). Let's define a "rectangle" as four integers a, b, c, d (1 ≤ a ≤ c ≤ n; 1 ≤ b ≤ d ≤ m). Rectangle denotes a set of cells of the grid {(x, y) : a ≤ x ≤ c, b...
#include <bits/stdc++.h> using namespace std; struct prefSum { short int cnt[41][41]; bool val[41][41]; prefSum() { for (int i = 0; i < 41; i++) for (int j = 0; j < 41; j++) cnt[i][j] = val[i][j] = 0; } inline void build(int n, int m) { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; ...
The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the pu...
#include <bits/stdc++.h> using namespace std; long long cost[200][200], dp[100][10][10], n, rem; int main() { ios_base::sync_with_stdio(0); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) cin >> cost[i][j]; cin >> n; for (int k = 1; k <= n; k++) for (int i = 0; i < 3; i++) for (int j = 0; ...
Good old Berland has n cities and m roads. Each road connects a pair of distinct cities and is bidirectional. Between any pair of cities, there is at most one road. For each road, we know its length. We also know that the President will soon ride along the Berland roads from city s to city t. Naturally, he will choose...
#include <bits/stdc++.h> using namespace std; int n, m, j, k, i, l; int Sp[505][505]; int x, y, z; vector<pair<pair<int, int>, int> > V; int W[505][505]; int main() { scanf("%d %d", &n, &m); for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) Sp[i][j] = INT_MAX / 2; for (i = 1; i <= m; i++) { scanf("%d %d %...
Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game. Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards excep...
#include <bits/stdc++.h> using namespace std; int n, c[200], v[200], ans = 123456; bool visc[200], visv[200]; char setc[] = {'R', 'G', 'B', 'Y', 'W'}; map<char, int> mp; set<pair<int, int> > ss; int main() { scanf("%d", &n); for (int i = 0; i < 5; i++) mp[setc[i]] = i; for (int i = 0; i < n; i++) { char a, b;...
Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — c...
/// Restore Cube //import java./awt.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class RestoreCube { final int[][] perms = { { 0, 1, 2 }, { 0, 2, 1 }, { 1, 0, 2 }, { 1, 2, 0 }, { 2, 0, 1 }, { 2, 1, 0 } }; boolean yes; int[][] coords; Set<Long> set; void solve...
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes. Input The single line of the input contains a pa...
m,s = list(map(int,input().split())) flag = True large = 0 small = 0 m1 = m-1 m2 = 0 s1 = s if s==0 and m==1: small,large = 0,0 flag = False elif s>9*m or s<1: flag = False large = -1 small = -1 if flag: while (s1 != 0): if s1 >9: large += 9*10**(m1) small += 9*10**(m2) s1 -= 9 m1 -= 1 m2 += 1 ...
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn...
def main(): n, m = [int(i) for i in raw_input().split()] m -= 1 num = int(pow(2,n-1)) poss = 1 L = [0 for i in range(n)] for i in range(n): if (m < num/2): L[L.index(0)] = poss else: L.reverse() L[L.index(0)] = poss L.revers...
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. ...
""" Satwik_Tiwari ;) . 20 june , 2020 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IO...
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company. There are n people working for the Large Software Company. Each person be...
#include <bits/stdc++.h> using namespace std; const int maxn = 200000 + 10; int nex[maxn], par[maxn], siz[maxn]; int find_par(int x) { if (par[x] != x) par[x] = find_par(par[x]); return par[x]; } void merge(int x, int y) { x = find_par(x); y = find_par(y); if (siz[y] < siz[x]) swap(x, y); par[x] = y; siz[...
Duff is the queen of her country, Andarz Gu. She's a competitive programming fan. That's why, when he saw her minister, Malek, free, she gave her a sequence consisting of n non-negative integers, a1, a2, ..., an and asked him to perform q queries for her on this sequence. <image> There are two types of queries: 1....
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 1; int t1[N << 1]; vector<int> t2[N << 1]; void add(vector<int> &v, int x) { for (int &a : v) if (a & -a & x) x ^= a; if (x == 0) return; for (int &a : v) if (x & -x & a) a ^= x; v.push_back(x); } vector<int> operator+(vector<int> a, vect...
<image> One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the l...
n, m = input().split(' ') n = int(n) m = int(m) hints = {} max_right = None min_left = None if m > 0: for i in range(m): do_nothing = False line = input().split(' ') hint_position = int(line[4])-1 if line[2] == 'left': hint_box = hint_position - 1 if m...
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the n...
from math import factorial def c(n, k): cur = factorial(n) // factorial(k) return cur // factorial(n - k) n = int(input()) ans = c(n, 5) + c(n, 6) + c(n, 7) print(ans)
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n. Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only th...
import java.io.*; import java.util.*; public class B { public void solve() { int n = in.nextInt(); int d = in.nextInt(), h = in.nextInt(); if (2 * h < d) { out.println(-1); return; } if (d == 1) { if (n == 2) { out.println...
You have a grid with n rows and n columns. Each cell is either empty (denoted by '.') or blocked (denoted by 'X'). Two empty cells are directly connected if they share a side. Two cells (r1, c1) (located in the row r1 and column c1) and (r2, c2) are connected if there exists a sequence of empty cells that starts with ...
#include <bits/stdc++.h> using namespace std; int n, k, z[510][510], used[510][510], second[250000], u[250000], ans = -1; char a[510][510]; vector<int> v; void dfs(int i, int j, int t) { used[i][j] = t; if (i + 1 < n && !used[i + 1][j] && a[i + 1][j] == '.') dfs(i + 1, j, t); if (j + 1 < n && !used[i][j + 1] && a...
Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements! Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because...
#include <bits/stdc++.h> using namespace std; const long long inf = 1e15, mod = 1e9 + 7; long long arr[1000001], st[4 * 1000001], pre[1000001], ans[1000001]; std::vector<pair<long long, int> > g[1000001]; map<long long, int> last; void update(int node, int l, int r, int ind, long long val) { if (l > r or l > ind or i...
One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there ...
import java.io.*; import java.util.Comparator; import java.util.PriorityQueue; /** * @author pvasilyev * @since 23 Oct 2016 */ public class DAlt implements Runnable { private static final boolean DEBUG = true; private static final String FILE_NAME = "connect2"; public static void main(String[] args) ...
The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day. Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of win...
n,k=map(int,input().split()) d=list(map(int,input().split())) p=[] count=0 count1=0 for i in range(len(d)): if d[i]>=0: count+=1 if d[i]<0 or i==len(d)-1: p.append(count) count=0 count1+=1 if d[len(d)-1]>=0: count1-=1 if count1==0: print(0) exit() a=p.pop() if d[len(d...
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: * the length of the password must be equal to n, * the password should con...
n, k = eval(input().rstrip().replace(" ", ",")) k = min(k, 26) letters = [chr(i) for i in range(97, 123)] for i in range(n): print(letters[i%k], end="")
Oleg the bank client lives in Bankopolia. There are n cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from 1 to n. There are a total of m roads in Bankopolia, the i-th road connects cities ui and vi. It is guaranteed that from each city it is possible...
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 1; const int M = 1e9 + 7; const double eps = 1e-6; const int inf = 1e9; const long long INF = 1e18; const double PI(acos(-1.0)); vector<int> g[N]; set<int> G[N]; map<vector<int>, int> mp; int ans[N]; int n, m; int t = 1, id[N]; int main() { cin >> n >>...
On the way home, Karen decided to stop by the supermarket to buy some groceries. <image> She needs to buy a lot of goods, but since she is a student her budget is still quite limited. In fact, she can only spend up to b dollars. The supermarket sells n goods. The i-th good can be bought for ci dollars. Of course, ea...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using ii = pair<int, int>; using vi = vector<int>; constexpr int N = 5010, INF = 1000000010; int n, c[N], d[N], s[N]; int b, dp[N][2][N]; vi g[N]; void dfs(int u) { s[u] = 1; for (int i = 0; i <= n; ++i) dp[u][0][i] = dp[u][...
A year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 ≤ i < n condition, that api·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7. Input First line of input data contains single integer n (1 ...
#include <bits/stdc++.h> using namespace std; const int maxn = 300 + 15; const int mod = 1e9 + 7; unordered_map<int, int> ff; int n, dp[2][maxn], cur, C[maxn][maxn], fac[maxn], inv[maxn]; int power(int x, int y) { int ret = 1; while (y) { if (y & 1) ret = 1LL * ret * x % mod; y >>= 1; x = 1LL * x * x % ...
All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland! It is well-known that there are n cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that th...
#include <bits/stdc++.h> using namespace std; template <class T> inline void rread(T& num) { num = 0; T f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') num = num * 10 + ch - '0', ch = getchar(); num *= f; } const lo...
During the breaks between competitions, top-model Izabella tries to develop herself and not to be bored. For example, now she tries to solve Rubik's cube 2x2x2. It's too hard to learn to solve Rubik's cube instantly, so she learns to understand if it's possible to solve the cube in some state using 90-degrees rotation...
#include <bits/stdc++.h> using namespace std; int const N = 1 << 18; int const M = 1 << 18; int main(int argc, char* argv[]) { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int color[30]; for (int i = 0; i < 24; ++i) cin >> color[i]; const char* ans[12] = { "111155223333224466554466", "1111442...
It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right. Unfortunately, Joe ...
#include <bits/stdc++.h> using namespace std; long long n, m, k, mn = 1e6, tmp; int main() { cin >> n >> m >> k; for (int i = 0; i < n; i++) { scanf("%d", &tmp); if (i % 2 == 0) mn = min(mn, tmp); } if (n % 2 == 0) { cout << 0 << endl; } else { long long res = 0; for (int i = 0; i < min(k,...
Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;m] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor ...
#include <bits/stdc++.h> #pragma warning(disable : 4996) using namespace std; using ld = long double; template <class T> using Table = vector<vector<T>>; const ld eps = 1e-9; template <class S, class T> ostream &operator<<(ostream &os, const pair<S, T> v) { os << "( " << v.first << ", " << v.second << ")"; return o...
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: * 1 ≤ a ≤ n. * If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has...
import sys def solve(): n = int(input()) if n%2 == 0: ans = "Mahmoud" else: ans = "Ehab" return ans ans = solve() print(ans)
You are given a string s of length n consisting of lowercase English letters. For two given strings s and t, say S is the set of distinct characters of s and T is the set of distinct characters of t. The strings s and t are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) f between S...
#include <bits/stdc++.h> using namespace std; const long long B = 131; const long long P = 1e9 + 9; int n, m; char s[200000 + 10]; long long h[26][200000 + 10]; long long t[200000 + 10]; long long add(long long a, long long b) { return (a + b) % P; } long long sub(long long a, long long b) { long long c = (a - b) % P...
See Russian Translation W.T.H.S.E.C Confused? Well it stands for Welcome To HackerEarth September Easy Challenge :). It's quite amazing when long words like this get reduced to such a short string. They sound pretty cool and often make the chat interesting. They are almost used everywhere these days. Our friend Hars...
n = int(raw_input()) out = [None] * n for _ in range(n): out[_] = raw_input() t = int(raw_input()) s = raw_input().split() string = '' for i in s: if i not in out: string += i[0].upper() + '.' string = string[:-1] print string
You're about to play a simplified "battleship" game with your little brother. The board for this game is a rectangular grid with R rows and C columns. At the start of the game, you will close your eyes, and you will keep them closed until the end of the game. Your little brother will take a single rectangular 1 x W shi...
for _ in range(input()): r, c, w = map(int, raw_input().split()) ret = r * (c/w) if(c%w==0): ret+=w-1 else: ret+=w print "Case #%d: %d" % (_+1, ret)
Raju is very fond of strings.Once he was playing a game with his friend.His friend gave him a string to decipher.As Raju is not very good at programming, he ask for your help. So he provide you a string and your task is to decipher it. Note : The pattern is hidden in the Sample Test Cases. INPUT A single integer T...
for i in range(input()): p = raw_input() shift = len(p) str1 = "" for i in range(0,shift): if p[i].isalpha(): k = ord(p[i]) + i if k > ord('z'): k -= 26 finalLetter = chr(k) str1 +=finalLetter print str1
Xavier challenges one of his friend to perform some crazy string functions by giving him some words and each word basically denotes a type of string function which his friend has to perform. WORDS WITH THEIR MEANING:- Wordrev n->To arrange each words of the string in reverse order.The last letter n denotes upto whi...
st = raw_input() task = int(raw_input()) for op in range(task): tas, n = raw_input().split() n = int(n) if tas == "Wordrev": k = [''.join(p[::-1]) for p in st.split()] l = st.split() new = k[:n] + l[n:] print ' '.join(new) elif tas == "sortword": z = st.split() z.sort() res = z[:n] for w in st.split...
You are given an empty graph of N vertices and M queries of two types: Given a number X answer what is the shortest distance from the vertex 1 to the vertex X. Given two integers X, Y add the new oriented edge from X to Y. Input The first line contains two integers N and M. The following M lines describe queries in th...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' import Queue def updateDis(f, g, d): q = Queue.Queue() q.put(f) while not q.empty(): cur = q.get() for i in g[cur]: if d[i]>d[cur]+1: d[i]=d[cur]+1 q.put(i) de...
Magic is great, isn't it?. We all love it. However if you do the same magic trick again and again, it will become boring. Also there are chances people might see through your trick. So you always want to minimize the number of times you perform the same magic trick again and again. In this question, you are given a pe...
for i in range(input()): h = input() n = 2**(h-2) ans=0 while n>1: ans+=n n = n/4 print (ans+1)%1000000007
Arnab is given a string, but being the evil Lord he is, he has his own whims and fantasies about the string he wants to keep with himself. If he can convert a string into a palindrome by rearranging the characters, he will keep that string, otherwise he will discard that string. You’ve to tell if Arnab will keep that s...
from sys import stdin t = int(stdin.readline()) for _ in xrange(t): a = stdin.readline().strip() di = {} for i in a: di[i] = di.get(i,0)+1 od = 0 for i in di: if di[i]%2: od+=1 ans = 'Yes' if od > 1: ans = 'No' print ans
The CS & IT Department students have been facing tough competitions from each other since ages, in being the best in research & innovation. This time CS Department is taken the edge over IT Department by designing a special weather predictor device which inputs previous years data and perform analysis over it to give a...
T=input() while(T!=0): D=raw_input() A=raw_input() opp=0 l=[] if len(D)==len(A): for i in range(0,len(D)): if A[i]!=D[i]: opp+=1 print opp else: if len(D)>len(A): temp=D D=A A=temp for i in range(0,len(A)-len(D)+1): for j in range(0,len(D)): #if i+j < len(A): if D[j]!=A[i+j]: ...
Rani has challenged Nandu to generate Splendid Matrices. Splendid matrices are square matrices with dimensions 2^n X 2^n filled in a particular manner. To explain this manner, Rani gives Nandu the matrices for n=1, n=2 and n=3 : n=1 1 2 3 4 n=2 (spacing for clarity) 1 2 5 6 3 4 7 8 9 10 13 14 11 12 15 16 n=3...
# Splendid Matrices matrix=[[0 for x in range(1024)] for x in range(1024)] def splendid(n,s,a,b): if n>1: p=(2**(n-1))*(2**(n-1)) k=(2**n)/2; splendid(n-1,s,a,b) splendid(n-1,s+p,a,b+k) splendid(n-1,s+p*2,a+k,b) splendid(n-1,s+p*3,a+k,b+k) elif n==1: m...
Raghav is good in mathematics. He loves to ask puzzles with his friends. One day, he decides to challenge his friend Aditya who is not good with puzzles. So, Aditya needs your help in determining the solution to the puzzle asked by his friend which is stated as:- Tell the total number of ways he can choose three numbe...
t = int(raw_input()) numbers = map(int, raw_input().strip().split()) c=0 for i in range(0,t): for j in range(i+1,t): for k in range(j+1,t): if (numbers[j] - numbers[i] == numbers[k] - numbers[j]): c+=1 print c
A maze is composed of a grid of H \times W squares - H vertical, W horizontal. The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is `#` and a road if S_{ij} is `.`. There is a magician in (C_h,C_w). He can do the following two kinds of moves: * Move A: Walk to a ...
#include<bits/stdc++.h> using namespace std; typedef pair<int,int> pi; int h,w; int arr[1005][1005]; int dy[4]={0,0,1,-1}; int dx[4]={1,-1,0,0}; bool visited[1005][1005]; int main(){ int sx,sy; int des_x,des_y; cin>>h>>w>>sy>>sx>>des_y>>des_x; for(int i=1; i<=h; i++){ string s; cin>>s; for(int j=0; s[j]; j++)...
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. Additionally, each vertex is painted in a color, and the color of Vertex i is c_i. Here, the color of each vertex is represented by an integer between 1 and N (inclusive). The same integer corresponds to the same col...
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.InputMismatchException; import java.io.IOException; import java.util.Stack; import java.util.ArrayList; i...
We have 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. The square (i, j) has two numbers A_{ij} and B_{ij} written on it. First, for each square, Takahashi paints one of the written numbers red and the other blue. Then...
from sys import stdin input = stdin.buffer.readline h, w = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(h)] b = [list(map(int, input().split())) for _ in range(h)] dp = [0] * -~w dp[0] = 1 << 6400 for i in range(h): for j in range(w): t = dp[j] if j: t...
You are given a simple connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex A_i and Vertex B_i. Takahashi will assign one of the two possible directions to each of the edges in the graph to make a directed graph. Determine if it is possible to make ...
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; int read(){ int a=0,b=getchar(),c=1; while(!isdigit(b))c=b=='-'?-1:1,b=getchar(); while(isdigit(b))a=a*10+b-'0',b=getchar(); return a*c; } void print(int x){ char y=x%10+'0'; if(x>=10)print(x/10); p...
Along a road running in an east-west direction, there are A shrines and B temples. The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road. Answer the following Q queries: ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStre...
Snuke has found two trees A and B, each with N vertices numbered 1 to N. The i-th edge of A connects Vertex a_i and b_i, and the j-th edge of B connects Vertex c_j and d_j. Also, all vertices of A are initially painted white. Snuke would like to perform the following operation on A zero or more times so that A coincid...
#include<bits/stdc++.h> using namespace std; typedef long long lint; typedef long double louble; #define lf ('\n') template<typename T1,typename T2> inline T1 max(T1 a,T2 b){return a<b?b:a;} template<typename T1,typename T2> inline T1 min(T1 a,T2 b){return a<b?a:b;} namespace ae86 { const int bufl = 1<<15; char...
We have a 3×3 square grid, where each square contains a lowercase English letters. The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}. Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bot...
#include<iostream> using namespace std; int main(){ char a,b,c,d,e,f,g,h,i; cin>>a>>b>>c>>d>>e>>f>>g>>h>>i; cout<<a<<e<<i; }
You are given an undirected connected graph with N vertices and M edges that does not contain self-loops and double edges. The i-th edge (1 \leq i \leq M) connects Vertex a_i and Vertex b_i. An edge whose removal disconnects the graph is called a bridge. Find the number of the edges that are bridges among the M edges....
#include <iostream> #include <cstdio> using namespace std; int n, m, ans, s[55]; bool a[55][55]; void f(int p) { int i; if (s[p] == 1) { ans++; for (i =1; i <= n; i++) { if (a[p][i] == 1) break; } a[p][i] = a[i][p] = 0; s[p]--; s[i]--; f(i); } } int main() { int i ,j, t1, t2; cin >> n >> m; whil...
We ask you to select some number of positive integers, and calculate the sum of them. It is allowed to select as many integers as you like, and as large integers as you wish. You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer. Your objecti...
#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; cin>>a>>b>>c; for(int i = 0 ; i < 100 ; i++) { if ((b*i + c)%a == 0) { cout<<"YES"; return 0; } } cout<<"NO"; return 0; }
You have N cups and 1 ball. The cups are arranged in a row, from left to right. You turned down all the cups, then inserted the ball into the leftmost cup. Then, you will perform the following Q operations: * The i-th operation: swap the positions of the A_i-th and B_i-th cups from the left. If one of these cups co...
#include <bits/stdc++.h> using namespace std; #define int long long #define ld long double #define ll long long #define P pair<int,int> #define fi first #define se second #define rep(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(),v.end() #define pb push_back #define eb emplace_back template<class T>void chmax(T &a,...
Write a program which prints multiplication tables in the following format: 1x1=1 1x2=2 . . 9x8=72 9x9=81 Input No input. Output 1x1=1 1x2=2 . . 9x8=72 9x9=81 Example Input Output
a='range(1,10)';exec("for i in "+a+":\n"+" "*4+"for d in "+a+":\n"+" "*8+"print str(i)+'x'+str(d)+'='+str(i*d)")
Brain training puzzle games are popular from children to adults. We decided to make a puzzle game and play with everyone so that we could keep up. We thought of a jigsaw puzzle game where you pick the pieces you need to fill in the unfinished parts. Figure 1 (a) is an example of a puzzle frame. The part where black is...
/* sample input real 0m1.756s user 0m1.652s sys 0m0.012s */ #include<iostream> #include<set> #include<algorithm> #include<vector> #include<map> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) const int R =20,C=20; class st{ public: int r,c; bool m[R][C]; boo...
Give you N cards. Only one natural number is written on each card. However, the same number is never written. From now on, as a question, I will say an appropriate natural number. Please answer the largest remainder you get when you divide the number on the card you have by the number I said. For example, suppose you...
#include<iostream> #include<set> using namespace std; #define rep(i, n) for(int i=0; i<n; ++i) #define max(a, b) (a>b?a:b) int main() { int n, Q, c, q; set<int> card; cin >> n >> Q; rep(i, n) { cin >> c; card.insert(c); } int ma = *(--card.end()); rep(i, Q) { cin >> q; if(q==1) { cout << "0" << e...
problem You have to play a darts game with the following rules. You can throw up to four arrows towards the target. You don't have to throw all four, you don't have to throw one. The target is divided into N parts. The score P1, ..., PN is written in each part. The total score S of the place where the arrow is stuck ...
#include <iostream> #include <algorithm> int n; long m, p[1001], q[1100000]; int main(){ while(std::cin >> n >> m){ if(n == 0 && m == 0){ break; } p[0]=0; for(int i=1; i<=n; ++i){ std::cin >> p[i]; } std::sort(p, p+n); long k=0; for(int i=0; i<=...
The north country is conquered by the great shogun-sama (which means king). Recently many beautiful dice which were made by order of the great shogun-sama were given to all citizens of the country. All citizens received the beautiful dice with a tear of delight. Now they are enthusiastically playing a game with the dic...
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; //Rolling Dice public class Main{ static class Dice <T>{ public T[] id; enum Face{TOP, BOTTOM, FRONT, BACK, RIGHT, LEFT}; public T get(Face f){ ...
You have an ideally small racing car on an x-y plane (0 ≤ x, y ≤ 255, where bigger y denotes upper coordinate). The racing circuit course is figured by two solid walls. Each wall is a closed loop of connected line segments. End point coordinates of every line segment are both integers (See Figure 1). Thus, a wall is re...
#include<iostream> #include<cmath> #include<vector> #include<complex> #include<cassert> using namespace std; #define OVER 0x01 #define RIGHT 0x02 #define LEFT 0x04 #define FRONT 0x08 #define BACK 0x10 typedef long long elem; typedef complex<elem> point, vec; typedef pair<point,point> line, seg; elem dot(point a, po...
Vectors have their directions and two vectors make an angle between them. Given a set of three-dimensional vectors, your task is to find the pair among them that makes the smallest angle. Input The input is a sequence of datasets. A dataset specifies a set of three-dimensional vectors, some of which are directly gi...
#include <bits/stdc++.h> using namespace std; using ld = long double; #define rep(i, j) for(int i=0; i < (int)(j); i++) #define all(v) v.begin(),v.end() const ld EPS = 1e-8; bool eq(ld a, ld b) { return abs(a - b) < EPS; } template<class T> struct Point { T x, y, z; bool operator < (const Point<T> &r) const { ...
Problem Taro decided to watch one movie every day at a nearby movie theater during the summer vacation. (Taro has 31 days of summer vacation from August 1st to August 31st.) The theater is set to show n movies during the summer vacation. Each movie is assigned a number from 1 to n, and the i-th movie will only be sho...
#include <iostream> #include <algorithm> #include <vector> #include <queue> #include <map> #include <set> #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <time.h> #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define FFOR(i,a,b) for(int i=(a);i<=(b);i++) #define REP(i,b) FOR(i,0,b) #def...
Isaac H. Ives is attending an international student party (maybe for girl-hunting). Students there enjoy talking in groups with excellent foods and drinks. However, since students come to the party from all over the world, groups may not have a language spoken by all students of the group. In such groups, some student(...
#include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace ...
Yui Hirasawa, who attends private Sakuragaoka Girls' High School, has to make a career hope by the day after tomorrow, but the trouble is that she hasn't decided anything yet. When I consulted with my friend Wa, I knew that my first choice was K University, so I consulted with my career guidance teacher to see if I cou...
#include <iostream> #include <algorithm> using namespace std; int main(){ int n; while(cin >> n ,n){ int MAX_POINT = 0,MIN_POINT = 1<<28,sum,a[5]; for(int i = 0 ; i < n ; i++){ sum = 0; for(int j = 0 ; j < 5 ; j++){ cin >> a[j]; sum += a[j]; } MAX_POINT = max(MAX_POINT,sum); ...
Example Input 5 Output 5
#include <iostream> #include <vector> using namespace std; constexpr long long int Mod = 1e9 + 7; vector< vector<long long int> > matrix_product(vector< vector<long long int> > &A, vector< vector<long long int> > &B){ int n = A.size(), m = B[0].size(), l = A[0].size(); vector< vector<long long int> > ret(n,vector<...
Problem Statement Let b_i(x) be the i-th least significant bit of x, i.e. the i-th least significant digit of x in base 2 (i \geq 1). For example, since 6 = (110)_2, b_1(6) = 0, b_2(6) = 1, b_3(6) = 1, b_4(6) = 0, b_5(6) = 0, and so on. Let A and B be integers that satisfy 1 \leq A \leq B \leq 10^{18}, and k_i be the...
import java.util.Arrays; import java.util.Scanner; public class Main { static Scanner sc = new Scanner(System.in); static int N; static long[] K; static final long INF = 1000L * 1000 * 1000 * 1000 * 1000 * 1000; public static void main(String[] args) { while (true) ...
Koto Municipal Subway Koto Municipal Subway Koto City is a famous city whose roads are in a grid pattern, as shown in the figure below. The roads extending from north to south and the roads extending from east to west are lined up at intervals of 1 km each. Let Koto station at the southwestern intersection of Koto ci...
#define _USE_MATH_DEFINES #include<stdio.h> #include<string> #include<iostream> #include<cctype> #include<cstdio> #include<vector> #include<stack> #include <algorithm> #include<math.h> #include<set> #include<map> #include<iomanip> using namespace std; int main(){ int n,m; while(1){ cout<<setprecision(20); cin>>n...
problem AOR Ika-chan visited AOR Co., Ltd. AOR Co., Ltd. is a $ N $ building with no basement floor. AOR Ika started the tour from the $ 1 $ floor and decided to move just $ M $. You can move from the $ i $ floor to the $ i + 1 $ floor, or the $ i --1 $ floor with $ 1 $ movements. However, it cannot be moved to the $ ...
// https://arxiv.org/ftp/arxiv/papers/1501/1501.04750.pdf #include <cstdio> #include <cstring> using int64 = long long; const int N = 1e5 + 10, mod = 1e9 + 7; int fac[N], ifac[N], inv[N]; int calc(int n, int m) { int ret = 0; for (int64 j = -m; j <= m; ++j) { if (m + j * (n + 2) < 0) continue; int64 s =...
Problem Statement "Rooks Game" is a single-player game and uses a chessboard which has $N \times N$ grid and $M$ rook pieces. A rook moves through any number of unoccupied squares horizontally or vertically. When a rook can attack another rook, it can capture the rook and move to the square which was occupied. Note t...
#include <bits/stdc++.h> #define fi first #define se second #define inf (long long)1e8 using namespace std; using p = pair<long long,long long>; struct Unionfind{ vector<int> par; vector<int> treerank; Unionfind(int n = 1){stree(n+1);} void stree(int n = 1){ par.assign(n,-1); treerank.a...
Problem statement There is a tree consisting of $ N $ vertices $ N-1 $ edges, and the $ i $ th edge connects the $ u_i $ and $ v_i $ vertices. Each vertex has a button, and the button at the $ i $ th vertex is called the button $ i $. First, the beauty of the button $ i $ is $ a_i $. Each time you press the button ...
#include<iostream> #include<string> #include<algorithm> #include<vector> #include<iomanip> #include<math.h> #include<complex> #include<queue> #include<deque> #include<stack> #include<map> #include<set> #include<bitset> #include<functional> #include<assert.h> #include<numeric> using namespace std; #define REP(i,m,n) for...
<image> A directed acyclic graph (DAG) can be used to represent the ordering of tasks. Tasks are represented by vertices and constraints where one task can begin before another, are represented by edges. For example, in the above example, you can undertake task B after both task A and task B are finished. You can obt...
#include<bits/stdc++.h> using namespace std; int main(){ int v,e,s,t,a[10001]={}; vector<int> vec[10001]; cin >> v >> e; for(int i=0;i<e;i++){ cin >> s >> t; vec[s].push_back(t); a[t]++; } stack<int> st; for(int i=0;i<v;i++){ if(a[i] == 0) st.push(i); } while(!st.empty()){ cout << ...
There is a country which recently got invaded by a fleet of aliens. They started living with the people there. Relations between the aliens and humans were generally bitter. The government at the center decided that they will divide the country into 2 states (initially there were none). There are N citizens in the coun...
n=input() for I in range(n): a=input() c=map(int,raw_input().split()) l1=[] l2=[] for i in range(len(c)): if c[i]==-1: l1.append(-1) if c[i]==1: l2.append(1) for j in l2: l1.append(j) for i in l1: print i,
Tic-Tac-Toe used to be Chef's favourite game during his childhood. Reminiscing in his childhood memories, he decided to create his own "Tic-Tac-Toe", with rules being similar to the original Tic-Tac-Toe, other than the fact that it is played on an NxN board. The game is played between two players taking turns. First ...
def read(): return map(int, raw_input().split()) def is_X(c): if c == 'X': return 1 else: return 0 T = read()[0] for n in range(T): N, K = read() Box =[None for i in range(N)] for i in range(N): s = raw_input() Box[i] = list(s) H1 = [ [0 for i in ...
Problem You are living in 2050, People do not work any more. Only surrogates (clone having same features & DNA characteristics) work for every individual. Government is substituting man labor by surrogates. Every person can control his own surrogate from his home and paid for his services one of the criminal master mi...
while True: [n, m] = [int(i) for i in raw_input().split()] if n == 0 and m == 0: break count = {} for nn in xrange(n): dna = raw_input() if dna not in count: count[dna] = 1 else: count[dna] += 1 x = [0] * n for c in count: x[count[c] - 1] += 1 for i in x: print i
Points:15 The Environmental Protection Agency is a billion dollar organisation that works to protect the environment from hazardous changes worldwide. It is funded by the national governments, charitable organisations, business donations as well as its own earnings. To evaluate the ground realities of the theory of glo...
def process(N, M): Nrow, Ncol, Crow, Ccol = 0, 0, 0, 0 for i in xrange(N): row = M[i] col = map(lambda x: x[i], M) if sum(row) % 2: Nrow, Crow = Nrow + 1, i + 1 if sum(col) % 2: Ncol, Ccol = Ncol + 1, i + 1 if Nrow==1 and Ncol==1: return '(%s,%s)' % (Crow, ...
According to folklore, the great mathematician Gauss was able to calculate the sum of the first 50 natural numbers in mere seconds. You are given a similar problem, where you have to calculate the sum of the first 'n' natural numbers. The only catch being that the the number 'n' can be really very large. You have to ca...
import sys import math # def ndigits(n): # return int(math.floor(math.log10(n)) + 1.1) # # m = 10**100 # # def tostr(n): # if n < m: # return str(n) # ndig = ndigits(n) # botdig = ndig//2 # mid = 10 ** botdig # top = tostr(n // mid) # bot = tostr(n % mid) # if len(bot) != bot...
You are given a sequence a1, a2, ..., aN. Find the smallest possible value of ai + aj, where 1 ≤ i < j ≤ N. Input The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.  The first line of each description consists of a single integer N. The second ...
T = input() for test in range(T): N = input() numbers = map(int, raw_input().split()) a = min(numbers) numbers.remove(a) b = min(numbers) print a+b
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,...
import java.util.*; public class TanyaAndStairways { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] A = new int[n]; scan.nextLine(); for(int i = 0; i < n; i++) { A[i] = scan.nextInt(); } int res = 0; ArrayList<Integer> list = new Array...
This problem is interactive. You should guess hidden number x which is between 1 and M = 10004205361450474, inclusive. You could use up to 5 queries. In each query, you can output an increasing sequence of k ≤ x integers, each between 1 and M, inclusive, and you will obtain one of the following as an answer: * ei...
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; public class G { static final int K = 10000; static final int Q = 5; static final long M = 10004205361450475L; long[][] dp = new long[Q + 1][K + 1]; { for (long[] row : dp) { Arrays.fill(row, -1); } } long go(long ...