input
stringlengths
29
13k
output
stringlengths
9
73.4k
You are given an integer n and an integer k. In one step you can do one of the following moves: * decrease n by 1; * divide n by k if n is divisible by k. For example, if n = 27 and k = 3 you can do the following steps: 27 → 26 → 25 → 24 → 8 → 7 → 6 → 2 → 1 → 0. You are asked to calculate the minimum numbe...
#include <bits/stdc++.h> using namespace std; int64_t R = 1; void solution() { int64_t n, k, s = 0, ans = 0; cin >> n >> k; while (n > 0) { if (n % k == 0) { n = n / k; ans++; } else { s = n % k; ans += s; n = n - s; } } cout << ans << "\n"; } int main() { cin >> R;...
You are given a piece of paper in the shape of a simple polygon S. Your task is to turn it into a simple polygon T that has the same area as S. You can use two tools: scissors and tape. Scissors can be used to cut any polygon into smaller polygonal pieces. Tape can be used to combine smaller pieces into larger polygon...
#include <bits/stdc++.h> using namespace std; double eps = 1e-6, pi = 3.14159265358979323846; struct pct { double x, y; pct() {} pct(double x2, double y2) : x{x2}, y{y2} {} pct operator+(const pct p) const { return {this->x + p.x, this->y + p.y}; } pct *operator+=(const pct p) { this->x += p.x; this->...
Wojtek has just won a maths competition in Byteland! The prize is admirable — a great book called 'Card Tricks for Everyone.' 'Great!' he thought, 'I can finally use this old, dusted deck of cards that's always been lying unused on my desk!' The first chapter of the book is 'How to Shuffle k Cards in Any Order You Wan...
#include <bits/stdc++.h> using namespace std; string to_string(string s) { return '"' + s + '"'; } string to_string(const char *s) { return to_string((string)s); } string to_string(bool b) { return (b ? "true" : "false"); } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.fi...
In this problem, a n × m rectangular matrix a is called increasing if, for each row of i, when go from left to right, the values strictly increase (that is, a_{i,1}<a_{i,2}<...<a_{i,m}) and for each column j, when go from top to bottom, the values strictly increase (that is, a_{1,j}<a_{2,j}<...<a_{n,j}). In a given ma...
#include <bits/stdc++.h> using namespace std; int main() { int64_t n, m, i, j, r, s, a[600][600]; cin >> n >> m; s = 0; r = 0; for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { cin >> a[n - i][m - j]; } for (i = 0; i < n; i++) for (j = 0; j < m; j++) { if (a[i][j] == 0) { i...
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 ≤ i - a_i) or to the position i + a_i (if i + a_i ≤ n). For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the ...
#include <bits/stdc++.h> using namespace std; int n, a[200005], dp[200005], vis[200005]; std::vector<int> v[200005]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; dp[i] = n; vis[i] = 0; if (i - a[i] >= 0) v[i - a[i]...
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared n problems; and since the platform is very popular, 998244351 coder from all over the world is going to solve them. For each problem, the authors estimated the number of people who would solve it: fo...
#include <bits/stdc++.h> int read() { register int x = 0; register char f = 1, ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') f ^= 1; for (; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ '0'); return f ? x : -x; } const int N = 55, P = 998244353; int n, l[N], r[N], m, a...
There are n officers in the Army of Byteland. Each officer has some power associated with him. The power of the i-th officer is denoted by p_{i}. As the war is fast approaching, the General would like to know the strength of the army. The strength of an army is calculated in a strange way in Byteland. The General sele...
#include <bits/stdc++.h> using namespace std; int mod = 1e9 + 7; long long p2[300005]; long long f_pow(long long a, long long b) { long long res = 1, temp = a; while (b) { if (b & 1) res = res * temp % mod; temp = temp * temp % mod; b >>= 1; } return res; } struct treap { treap *l, *r; int Size;...
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_...
#include <bits/stdc++.h> using namespace std; using ull = unsigned long long; int n, flg = 1, tot; basic_string<int> v[1 << 17]; void dfs(int p, int f = 0, int dep = 1) { int fs = 1; for (int i : v[p]) if (i != f) { if (v[i].size() == 1) { if (fs) fs = 0, tot += dep != 2; } else tot+...
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ...
num=int(input("")) i=0 while i<num: a,b=(input("")).split() minimum=min(int(a),int(b)) maximum=max(int(a),int(b)) if minimum*2<maximum: print(maximum**2) else: print((minimum*2)**2) i+=1
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P. While initializing, the bot is choosing a starting index pos (1 ≤ pos ≤ n), and then it can play any numbe...
import sys range = xrange input = raw_input mapper = {'R':0, 'P':1, 'S':2} t = int(input()) for _ in range(t): S = [mapper[c] for c in input()] count = [0]*3 for s in S: count[s] += 1 maxi = max(range(3), key = count.__getitem__) maxi -= 2 print ('RPS'[maxi]) * len(S)
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course. You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units. ...
# cook your dish here # cook your dish here from sys import stdin,stdout from collections import Counter from itertools import permutations import bisect import math I=lambda: map(int,stdin.readline().split()) I1=lambda: stdin.readline() for _ in range(int(I1())): p,f=I() cs,cw=I() s,w=I() if s>w: ...
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper. ...
#include <bits/stdc++.h> using namespace std; inline long long read() { long long num = 0, neg = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') neg = -1; c = getchar(); } while (isdigit(c)) { num = (num << 3) + (num << 1) + c - '0'; c = getchar(); } return num * neg; } const in...
The new academic year has started, and Berland's university has n first-year students. They are divided into k academic groups, however, some of the groups might be empty. Among the students, there are m pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups. A...
#include <bits/stdc++.h> using namespace std; typedef struct { int u, v, cu, cv; } Edge; const int N = 500010, M = 1000010; int fa[M]; Edge e[M]; int cnt; int sz[M]; int co[N]; int st[N]; pair<int, int> stk[M]; int top; int n, m, k; void init() { for (int i = 1; i <= n + n; i++) { fa[i] = i; sz[i] = 1; } ...
You have an array a_1, a_2, ..., a_n where a_i = i. In one step, you can choose two indices x and y (x ≠ y) and set a_x = \left⌈ (a_x)/(a_y) \right⌉ (ceiling function). Your goal is to make array a consist of n - 1 ones and 1 two in no more than n + 5 steps. Note that you don't have to minimize the number of steps. ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class TaskD { public static void main(String[] arg) { final Fas...
You are given an undirected connected graph consisting of n vertices and m edges. Your goal is to destroy all edges of the given graph. You may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if it is...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair <int, int> pii; const int N = 3005, M = N << 1; int n, m, edgenum, Head[N], Next[M], vet[M], u, v, deg[N], tot, B, vis[N], ans[M], len; bool Cut[M], _Cut[M]; inline void add(int u, int v) { Next[++edgenum] = Head[u]; Head[u] = edgenum; ...
In the 2050 Conference, some people from the competitive programming community meet together and are going to take a photo. The n people form a line. They are numbered from 1 to n from left to right. Each of them either holds a cardboard with the letter 'C' or a cardboard with the letter 'P'. Let C=\\{c_1,c_2,...,c_m\...
// Skyqwq #include <iostream> #include <cstdio> #include <vector> #include <algorithm> #define pb push_back using namespace std; typedef long long LL; // char buf[1<<23], *p1=buf, *p2=buf, obuf[1<<23], *O=obuf; // #define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<21, stdin), p1 == p2) ? EOF : *p1++) ...
Cirno gives AquaMoon a problem. There are m people numbered from 0 to m - 1. They are standing on a coordinate axis in points with positive integer coordinates. They are facing right (i.e. in the direction of the coordinate increase). At this moment everyone will start running with the constant speed in the direction o...
#include<bits/stdc++.h> using namespace std; const int maxn = 1e6+1; long long a[1001][1001], sum[1001], sum2[1001]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T = 1; while(T --) { int m, k; cin >> m >> k; for(int i = 0; i < k; ++ i) { for(int...
There is a bus stop near the university. The lessons are over, and n students come to the stop. The i-th student will appear at the bus stop at time ti (all ti's are distinct). We shall assume that the stop is located on the coordinate axis Ox, at point x = 0, and the bus goes along the ray Ox, that is, towards the po...
import java.util.*; import java.io.*; public class Main { FastScanner in; PrintWriter out; class Student implements Comparable<Student> { public int t, x, num; Student(int t, int x, int num) { this.t = t; this.x = x; this.num = num; } ...
In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares. Bertown has n squares, numbered from 1 to n, they are numb...
#include <bits/stdc++.h> using namespace std; const int N = 100010; int n, m; long long money; int a[N]; int aux[N], size[N], key[N], lc[N], rc[N], top, root; long long sum[N]; void l_rotate(int &x) { int y = rc[x]; rc[x] = lc[y]; lc[y] = x; size[y] = size[x]; size[x] = size[lc[x]] + size[rc[x]] + 1; sum[y]...
Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web. <image> There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are in...
#include <bits/stdc++.h> using namespace std; const int maxint = -1u >> 1; const double pi = 3.14159265358979323; const double eps = 1e-8; int n; int lim; struct BIT { int t[100110]; void clr() { memset(t, 0, sizeof(t)); } void add(int idx) { for (; idx <= lim; idx += idx & -idx) t[idx]++; } int query(int...
You're given the centers of three equal sides of a strictly convex tetragon. Your task is to restore the initial tetragon. Input The first input line contains one number T — amount of tests (1 ≤ T ≤ 5·104). Each of the following T lines contains numbers x1, y1, x2, y2, x3, y3 — coordinates of different points that ar...
#include <bits/stdc++.h> const double zero = 1e-12; struct points { double x, y; points() {} points(double xx, double yy) { x = xx, y = yy; } void scan1() { scanf("%lf%lf", &x, &y); } void print1() { printf("%.12lf %.12lf", x, y); } } p1, p2, p3; inline double cfabs(double x) { if (x > zero) return x; if ...
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts. Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following act...
from Queue import * # Queue, LifoQueue, PriorityQueue from bisect import * #bisect, insort from datetime import * from collections import * #deque, Counter,OrderedDict,defaultdict import calendar import heapq import math import copy import itertools myread = lambda : map(int,raw_input().split()) def solver(): n = ...
Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij. In one move the penguin can add or subtract number...
import java.util.*; import java.io.*; public class PoloPenguinAndMatrix { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.n...
Let's introduce the designation <image>, where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc. We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, string...
import java.util.*; public class Main{ static int MCntNb(String x,int p,String y){ int s=0,a=x.length(),b=y.length(),c,n=p*a,z,i=-1; for(int[]E=new int[a],S=new int[a];;E[c]=i,S[c]=s){ for(z=0;b>z;++z){ for(c=y.codePointAt(z);n>++i&&x.codePointAt(i%a)!=c;); if(n==i) return s; } ++s; if(0<S[c=i%...
Vasily the Bear loves beautiful strings. String s is beautiful if it meets the following criteria: 1. String s only consists of characters 0 and 1, at that character 0 must occur in string s exactly n times, and character 1 must occur exactly m times. 2. We can obtain character g from string s with some (possibl...
#include <bits/stdc++.h> using namespace std; const int N = 2e6; const int INF = 1e9 + 9; const int B = 1e9 + 7; void relax(long long &a, const long long &b) { a = (a + b % B) % B; } long long pwr(long long a, long long b) { long long res = 1; while (b) { if (b & 1) res = (res * a) % B; a = (a * a) % B, b >...
Simon loves neatness. So before he goes to bed, Simon wants to complete all chores in the house. Simon's house looks like a rectangular table consisting of n rows and n columns from above. All rows of the table are numbered from 1 to n from top to bottom. All columns of the table are numbered from 1 to n from left to ...
#include <bits/stdc++.h> using namespace std; const int N = 500 + 7; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template <class T, class S> inline void add(T& a, S b) { a += b; if (a >= mod) a -= mod; } template...
Ksenia has a chessboard of size n × m. Each cell of the chessboard contains one of the characters: "<", ">", "^", "v", "#". The cells that contain character "#" are blocked. We know that all chessboard cells that touch the border are blocked. Ksenia is playing with two pawns on this chessboard. Initially, she puts the...
#include <bits/stdc++.h> using namespace std; using ll = long long; using PII = pair<int, int>; using VI = vector<int>; const int N = 2005; char grid[N][N]; int dp[N][N][2], best[N][N]; int vis[N][N]; vector<PII> sub; int compute(int i, int j, bool root) { sub.clear(); if (i > 0 && grid[i - 1][j] == 'v') { int ...
You have matrix a of size n × n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column. Matrix a meets the following two conditions: * for any numbe...
#include <bits/stdc++.h> using namespace std; int N; vector<int> adj[2005]; int num[2005], low[2005], cnt; void dfs(int u) { low[u] = num[u] = ++cnt; for (int i = (0), _b = ((int)adj[u].size() - 1); i <= _b; i++) { int v = adj[u][i]; if (num[v]) low[u] = min(low[u], num[v]); else { dfs(v); ...
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column. Iahub starts with ...
#include <bits/stdc++.h> using namespace std; const int nMax = 1003; int dp1[nMax][nMax]; int dp2[nMax][nMax]; int dp3[nMax][nMax]; int dp4[nMax][nMax]; int a[nMax][nMax]; int main() { cin.sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m...
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ...
import java.util.*; import java.io.*; public class Main{ static int mod=(int)1e9+7; public static void main(String[] args) throws IOException { PrintWriter out=new PrintWriter(System.out); Reader in=new Reader(System.in); int ts=1; // ts=in.nextInt(); outer: while(ts-->0) { //let us say she gets ...
Imagine a city with n junctions and m streets. Junctions are numbered from 1 to n. In order to increase the traffic flow, mayor of the city has decided to make each street one-way. This means in the street between junctions u and v, the traffic moves only from u to v or only from v to u. The problem is to direct the...
#include <bits/stdc++.h> using namespace std; const int N = 2000 + 10; int n, col, h[N], mn[N], cnt[N], dp[N]; vector<int> adj[N], adj_c[N]; bool e[N][N], mark[N]; bitset<N> B; void dfs(int u = 0, int l = 0) { mn[u] = h[u] = l, mark[u] = true; for (auto v : adj[u]) if (!mark[v]) dfs(v, l + 1), mn[u] = min...
You have written on a piece of paper an array of n positive integers a[1], a[2], ..., a[n] and m good pairs of integers (i1, j1), (i2, j2), ..., (im, jm). Each good pair (ik, jk) meets the following conditions: ik + jk is an odd number and 1 ≤ ik < jk ≤ n. In one operation you can perform a sequence of actions: * ...
#include <bits/stdc++.h> using namespace std; const int MAXI = numeric_limits<int>::max() / 2; const int MINI = numeric_limits<int>::min() / 2; const long long MAXL = numeric_limits<long long>::max() / 2; const long long MINL = numeric_limits<long long>::min() / 2; static const int N = 110; struct edge { edge(int a, ...
In this problem you will have to deal with a real algorithm that is used in the VK social network. As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a cer...
from sys import stdin, stdout def precalc_partial_sums(array): partials = [0] s = 0 for elem in array: s += elem partials.append(s) return partials def precalc_means(T, fT, c, reqs): means = [] mean = 0.0 for req_count in reqs: mean = (mean + req_count / fT) / c...
The determinant of a matrix 2 × 2 is defined as follows: <image> A matrix is called degenerate if its determinant is equal to zero. The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements. You are given a matrix <image>. Consider any degenerate matrix B such that norm ||A - B|| is m...
a,b = map(int, raw_input().split()) c,d = map(int, raw_input().split()) def solve(c,b,a): if a == 0: return [] if b == 0 else [-1.0 * c / b] delta = b * b - 4.0 * a * c if delta < 0: return []; if delta == 0: return [-b / a / 2]; return [(-b + delta ** .5 ) / a / 2, (-b - delta ** .5) / a / 2] B...
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number y?". The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no ...
import java.util.*; import java.io.*; public class Solution{ long rem = 1000000007L; public Solution(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(n == 1){ System.out.println(0); return; } int arrLen = 1; int[] arr = new int[n]; arr[0] = 2; int num = arr[0]*arr[0];...
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar. In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically...
//package educational.round0x; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class E { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int I = ...
It's now 260 AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran. Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captu...
#include <bits/stdc++.h> using namespace std; struct Digit { vector<int> d; Digit() {} Digit(long long n, int b) { if (!n) { d.push_back(0); return; } for (; n; n /= b) d.push_back(n % b); } void out() { for (int i = (((int)(d).size())) - 1; i >= (0); --i) printf("%c", d[i] <...
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either inc...
import java.util.*; import java.lang.*; import java.io.*; public class Settlers_Training { public static void main(String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); StringTokenizer s=...
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions. To be precise, researchers introd...
#include <bits/stdc++.h> using namespace std; struct ls { int xs, xe, ys, ye; int i; bool operator<(const ls &o) const { return i < o.i; } bool operator==(const ls &o) const { return vector<int>({xs, xe, ys, ye}) == vector<int>({o.xs, o.xe, o.ys, o.ye}); } }; bool bad; ls l[4]; void solve() { ...
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of ...
#include <bits/stdc++.h> using namespace std; vector<pair<long long, long long> > h; vector<vector<long long> > g; long long p[500001][21]; long long volume[500001]; long long n, ans, s, f; void dfs(long long v, long long m) { p[v][0] = m; for (long long i = 0; i < g[v].size(); i++) { long long k = g[v][i]; ...
Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help. Filya is given an array of non-negative integers a1, a2, ..., an. First, he pick an integer x and then he adds x to some elements of the array (no more than once), subtract x ...
import java.util.Arrays; import java.util.Scanner; public class Main { static int counter; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long [] array = new long[n]; long type1 = -1,type2 = -1,type3=-1; boolean...
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph. There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white). To c...
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main extends Reader { static int s[], ss[], c[], f[]; static int fa(int x) { if (x == f[x]) return x; return f[x]=fa(f[x]); } static class Link { Link(int to, Link next) { this.to = ...
You are given a tree that has n vertices, which are numbered from 1 to n, where the vertex number one is the root. Each edge has weight wi and strength pi. Botanist Innokentiy, who is the only member of the jury of the Olympiad in Informatics, doesn't like broken trees. The tree is broken if there is such an edge th...
#include <bits/stdc++.h> static const int N = 200000 + 8; long long ans; int n, ne; int head[N]; int nxt[N]; int dst[N]; int we[N], st[N], rec[N], rwe[N], rst[N]; long long sum_we[N]; void addEdge(int u, int v, int w, int s) { ++ne; nxt[ne] = head[u]; head[u] = ne; dst[ne] = v; we[ne] = w; st[ne] = s; rec...
"Eat a beaver, save a tree!" — That will be the motto of ecologists' urgent meeting in Beaverley Hills. And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with t...
#include <bits/stdc++.h> using namespace std; bool kjg[100002]; int isi[100002]; long long dp[100002]; vector<int> adlis[100002], radlis[100002]; int rut, nvert, u, v; void ruted(int x) { kjg[x] = 1; for (int i = 0; i < adlis[x].size(); i++) { if (!kjg[adlis[x][i]]) { radlis[x].push_back(adlis[x][i]); ...
You are given the array of integer numbers a0, a1, ..., an - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array. Input The first line contains integer n (1 ≤ n ≤ 2·105) — length of the array a. The second line contains...
/** * Created by Martin on 4/28/2017. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import java.io.PrintWriter; public class Main { public static void main(String[]args) throws IOException { Buff...
Arkady likes to walk around his kitchen. His labyrinthine kitchen consists of several important places connected with passages. Unfortunately it happens that these passages are flooded with milk so that it's impossible to pass through them. Namely, it's possible to pass through each passage in any direction only during...
#include <bits/stdc++.h> using namespace std; template <typename T, typename U> inline void smin(T &a, const U &b) { if (a > b) a = b; } template <typename T, typename U> inline void smax(T &a, const U &b) { if (a < b) a = b; } template <class T> inline void gn(T &first) { char c, sg = 0; while (c = getchar(), ...
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of n men (n is always even). The current player sp...
#include <bits/stdc++.h> using namespace std; int main() { long long int n; cin >> n; cout << n * 2 - n / 2 << endl; }
You are given n distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing. You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo 109 + 7....
#include <bits/stdc++.h> using namespace std; const int mo = 1000000007; int n, ans, v[200005], X, Y, t, H[200005], fl, e[200005]; vector<int> d, b[100005]; struct O { int x, y, i; } a[100005]; bool cmx(O a, O b) { return a.x < b.x; } bool cmy(O a, O b) { return a.y < b.y; } bool cmi(O a, O b) { return a.i < b.i; } v...
Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers. Vasya decided to organize information about the phone numbers of friends. You will be given n strings — all entries from Vasya's phone books. Each entry starts with a fri...
n=input() di={} for i in range(0,n): s=raw_input().split() s1=str(s[0]) k=int(s[1]) t=[] for i in range(2,len(s)): t.append(s[i]) if s1 in di: di[s1]=di[s1]+t else: di[s1]=t print len(di) for k in di: val=di[k] ans=[] for i in range(0,len(val)): val[i]=(len(val[i]),val[i]) ...
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest. I...
from collections import defaultdict import sys from sys import stdin def check(a): for i in a: if i: return True return False def change(x): return ord(x)-ord('a') def solve(): n, m = map(int, stdin.readline().split()) s = input() d = {} for i in range(n): d[i+1...
You are given a string s consisting of |s| small english letters. In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter. Your target is to make some number of ...
i = 97 j = 0 s = [x for x in input()] for item in s: if item <= chr(i): s[j] = chr(i) i += 1 if i>122: print("".join(s)) break j += 1 else: print(-1)
In Aramic language words can only represent objects. Words in Aramic have special properties: * A word is a root if it does not contain the same letter more than once. * A root and all its permutations represent the same object. * The root x of a word y is the word that contains all letters that appear in y ...
#include <bits/stdc++.h> const long double eps = 0.00000001; const long long MOD = 1e9 + 7; using namespace std; int main() { fflush(stdin); cout << fixed, cout.precision(18); ios_base::sync_with_stdio(false); int i, j, n, m; cin >> n; set<string> se; for (i = 0; i < n; ++i) { string second, cur = "";...
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume. You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task ca...
#include <bits/stdc++.h> using namespace std; const int ms = 100 + 10; long long dp[ms][ms], sum[ms]; pair<long long, long long> a[ms], b[ms]; int n, re[ms]; bool cmp(const pair<long long, long long>& l, const pair<long long, long long>& r) { return l.first < r.first || (l.first == r.first && l.second > r.se...
After a long vacation due to Swine Flu, 1st Year SVNIT students have returned back to Gajjar Bhavan. Students in Gajjar Bhavan generally handshake to greet each other but due to Swine Flu it's still risky to handshake so students greet each other by just words instead of handshakes. Bagha is an interesting(really?) Ma...
pr=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, ...
"It all started with a kiss." Chotu was up all night, planning for his first kiss. He has collected the data about all the kissing spots in Allahabad. According to his survey there are N kissing spots in the city, each spot i is associated with a security value Si. Chotu wants to visit as many spot as they can, but un...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' import sys n=input() s=[int(i) for i in raw_input().split()] t=input() s.sort() for i in range(n): x=t-s[i] l=0 r=n-1 while(l<r): if s[l]+s[r]==x: prin...
Kevin has a sequence of integers a1, a2, ..., an. Define the strength of the sequence to be |a1 - a2| + |a2 - a3| + ... + |an-1 - an| + |an - a1|. Kevin wants to make his sequence stronger, so he reorders his sequence into a new sequence b1, b2, ..., bn. He wants this new sequence to be as strong as possible. What is...
t=int(raw_input()) l=list(map(int,raw_input().split(" "))) l.sort() m=[] for j in range(len(l)//2): m.append(l[j]) m.append(l[len(l)-j-1]) if(len(l)%2!=0): m.append(l[len(l)//2]) s=0 for h in range(len(m)-1): s=s+abs(m[h]-m[h+1]) s=s+abs(m[len(m)-1]-m[0]) print s
Hermione is very good in Magic but she is not good enough in Mathematics. She got stuck in a problem of mathematics in which she has to find out whether a combination M objects out of N is even or odd. Harry is quite good in mathematics so Hermione goes to get the help from Harry. Input: You have T number of test ca...
for t in range(input()): n,r=map(long,raw_input().split()) if n>=r: if (r & n-r): print "even" else: print "odd" else: print "odd"
Bubli and shivani are in lab. Bubli wants to send a message to shivani. But he can't send it directly. Bubli is on 1st computer and shivani is on the nth computer. Now the computer's are connected in a chain. 1st is connected to 2nd, 2nd is connected to 3rd and so on. Now for shivani to read the message all computers b...
t=int(input()) while (t>0): s = raw_input() tokens = s.split() n= int(tokens[0]) k = int(tokens[1]) temp=k%(2**n) if(temp==0): print("NO") elif(temp==(2**n)-1): print("YES") else: print("NO") t=t-1
Solve the mystery. Input The first line contains T, the number of test cases. T lines follow each containing a single integer N. Output Output the answer for each test case in a new line. Constraints 1 ≤ T ≤ 10^5 1 ≤ N ≤ 365 NOTE There is partial marking for this question SAMPLE INPUT 5 10 60 100 200 360 SA...
t = input() for i in xrange(t): n = input() if n > 0 and n < 32: print 1 elif n < 60: print 2 elif n <91: print 3 elif n < 121: print 4 elif n < 152: print 5 elif n < 182: print 6 elif n < 213: print 7 elif n < 244: print 8 elif n < 274: print 9 elif n < 305: print 10 elif n < 335: pri...
Rama is in love with geometry. So once he was playing with circles and rectangles. Given the center of circle and radius and also the co-ordinates of vertices of rectangle, he wants to check whether the rectangle lies inside the circle or not. Note: If all the vertices are lie the circumference of circle then it shoul...
for t in xrange(int(raw_input())): r,xc,yc=map(int,raw_input().split()) ans=0 for i in xrange(4): x,y=map(int,raw_input().split()) if (xc-x)**2 + (yc-y)**2>r**2: ans=1 if ans: print "No" else: print "Yes"
James has decided to take a break from his work. He makes a plan to visit India for a few days with his family. He knows a lot about India, and also about the various cities he could visit. He decides to write down all the cities on a paper. Let the number of cities be n. Now, he shows the list to his wife and asks her...
t = int(raw_input()) if(t>=1 and t<=100000): i=0 while(i<t): n = int(raw_input()) if(n>=1 and i<=1000000000000): print(pow(2,n,1000000007)-1) i = i+1
Rohit was doing the work of his math class about three days but he is tired of make operations a lot and he should deliver his task tomorrow. His math’s teacher gives two numbers a and b. The problem consist in find the last digit of the potency of base a and index b. Help Rohit with his problem. You are given two inte...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t=input() i=0 while i<t: aa=raw_input() a=aa.split(' ') a1=long(a[0]) b1=long(a[1]) a1=a1%10 a1=a1**b1 c=a1%10 print "%s" %(str(c)) i=i+1
Xavier is a computer science student.He is given a task by his teacher the task is to generate a code which accepts an array of n integers.He now has to select an integer from this array but there is a trick in selection of integer from the array. For the selection process he first has to accept an ...
n=input() arr=map(int,raw_input().split()) even=[] odd=[] for i in xrange(n): if arr[i]%2:odd.append(arr[i]) else:even.append(arr[i]) even.sort() odd.sort() m=input()-1 j=0 c=0 for i in xrange(n-1): pos=(m+j)%(n-c) del arr[pos] j=pos c+=1 if arr[0]%2: for i in xrange(len(odd)): print odd[i], else: for i in xran...
Given are integers N and K, and a prime number P. Find the number, modulo P, of directed graphs G with N vertices that satisfy below. Here, the vertices are distinguishable from each other. * G is a tournament, that is, G contains no duplicated edges or self-loops, and exactly one of the edges u\to v and v\to u exists...
#include <cstdio> #include <algorithm> int n,m,k,P; int f[201][201],C[201][201],_mul[201],invmul[201]; inline int mul(const int &a,const int &b){return 1ll*a*b%P;} inline int add(int a,const int &b){a+=b;return(a>=P)?a-P:a;} int calc(int n,int m,int k){ if(n>k+1||m>k)return 0; --n; for(int i=1;i<=n;i++) for(int j...
There is a building with n rooms, numbered 1 to n. We can move from any room to any other room in the building. Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j). Initially, there was one person in each room in the building. After that, we know that there were exactl...
n,k=map(int,input().split()) mod=10**9+7 lim=n fcl=[1]*(lim+1) for i in range(1,lim+1): fcl[i]=(fcl[i-1]*i)%mod def comb(x,y,p): return ((fcl[x]*pow(fcl[y],p-2,p))%p*pow(fcl[x-y],p-2,p))%p ans=0 for i in range(min(n,k+1)): ans+=comb(n-1,n-i-1,mod)*comb(n,i,mod) ans%=mod print(ans)
Snuke has a permutation (P_0,P_1,\cdots,P_{N-1}) of (0,1,\cdots,N-1). Now, he will perform the following operation exactly once: * Choose K consecutive elements in P and sort them in ascending order. Find the number of permutations that can be produced as P after the operation. Constraints * 2 \leq N \leq 200000...
n, k = map(int,input().split()) P = list(map(int,input().split())) # for i in range(n-k+1): # pp = P[i:i+k] # pp.sort() # print(P[:i] + pp + P[i+k:]) A = [] B = [] VA = [0] * n VB = [0] * n import heapq for i in range(k): heapq.heappush(A, P[i]) # 最小値用 heapq.heappush(B, -P[i]) # 最大値用 ans = 1 fo...
We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them. If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is...
/** * Created at 00:27 on 2019-07-01 */ import java.io.*; import java.util.*; public class Main { static FastScanner sc = new FastScanner(); static PrintStream out = System.out; static PrintWriter pw = new PrintWriter(out); static final int[] dx = {0, 1, 0, -1}; static final int[] dy = {-1, 0, 1, 0}; ...
There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of...
#include <bits/stdc++.h> using namespace std; long long dp[100005], n, a[20][20]; long long solve(int bitmask){ if (dp[bitmask]!=-1) return dp[bitmask]; dp[bitmask]=0; for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ if (bitmask&(1<<i) and bitmask&(1<<j)) dp[bitmask]+=a[i][j]; } } int ekstramask=bitm...
In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter. It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not cov...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int diff = b - a; int alen = 0; for (int i = 1; i < diff; i++) { alen += i; } int ans = alen - a; System.out.println(ans); ...
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc. A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i. He would like to make one as follows: * Specify two non-negative integers A and B. * Pr...
#include <bits/stdc++.h> using namespace std; const int N = 100005; int n, A; vector<int> e[N]; int g(vector<int> &v, int z){ for(int i = -(v.size() & 1), j = int(v.size()) - 1; i < j; i++, j--){ int t = v[j]; if(i >= 0) t += v[i]; if(t > z) return -1; } return 0; } int h(vector<...
We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller. (The operation is the same as the one in Problem D.) * Determine the largest element in the sequence (if there is more than...
import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) A.sort(reverse=True) count = 0 B = [A[0]] for i in range(N-1): a = A[i+1]+count C = [] for b in B: x = (b-a)//(N+1) C.append(x) s = sum(C) count += s new_B = [] for i, b in enumerate(...
You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and vi...
import itertools n,m = map(int,input().split()) ab = [] count = 0 for i in range(m): ab.append(set(map(int,input().split()))) ns = [i for i in range(1,n+1)] ptn = [i for i in list(itertools.permutations(ns)) if i[0]==1] for i in ptn: first = i[0] for s in range(1,n): if {first,i[s]} not in ab: break ...
N people are waiting in a single line in front of the Takahashi Store. The cash on hand of the i-th person from the front of the line is a positive integer A_i. Mr. Takahashi, the shop owner, has decided on the following scheme: He picks a product, sets a positive integer P indicating its price, and shows this product...
#include <cstdio> int N; int A[100010]; int main(int argc, const char * argv[]) { scanf("%d", &N); for(int i=0;i<N;++i) { scanf("%d", &A[i]); } long long answer = 0; int last = 2; for(int i=0;i<N;++i) { if (i==0) { answer += A[0]-1; continue; } if (A[i]==last) { last++;...
Consider creating the following number pattern. 4 8 2 3 1 0 8 3 7 6 2 0 5 4 1 8 1 0 3 2 5 9 5 9 9 1 3 7 4 4 4 8 0 4 1 8 8 2 8 4 9 6 0 0 2 5 6 0 2 1 6 2 7 8 Five This pattern follows the rules below. A B C In the sequence of numbers, C is the ones digit of A + B. For example 9 5 Four Now, the ones digit of 9...
import java.util.*; import java.io.*; public class Main{ public static int solve(int[] n){ if( n.length == 1 ){ return n[0]%10; } int[] temp = new int[n.length-1]; for(int i = 0; i < temp.length; i++){ temp[i] = n[i]+n[i+1]; } return solve(temp); } public static void main(String[] args) throws I...
Convenience store Deven Eleven is planning to open its first store in Aizuwakamatsu City to expand its business. There are already many other convenience stores in Aizuwakamatsu, so the place to open a new store is likely to be the key to success. Under the premise that "customers use the convenience store closest to t...
import sys def generate_next_hexes(x, y): hexes = [(x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y)] if y % 2: hexes += [(x - 1, y - 1), (x - 1, y + 1)] else: hexes += [(x + 1, y - 1), (x + 1, y + 1)] return hexes def update_map(hex_map, hexes): num_updated_hexes = 0 distance = 0...
After entering high school, Takeko, who joined the programming club, gradually became absorbed in the fun of algorithms. Now, when I'm in the second grade, I'd like to participate in Programming Koshien. At one point, Takeko, who learned about sorting algorithms, tried to design a sorting algorithm herself. The sort a...
#include <bits/stdc++.h> #define FOR(i, a, b) for (int i = a; i <= b; ++i) #define ii pair <int, int> using namespace std; const int N = 2e5 + 3; int n, dsu[N]; long long res; vector <ii> V; deque <int> dq; void init() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); //freopen("main.inp","r"...
problem President K decided to make a flag for IOI 2016 in Russia. Chairman K first took out the old flag from the warehouse. This flag is divided into squares of N rows and M columns, and each square is painted in one of white, blue, and red. Chairman K is trying to repaint some of the squares on this flag to make i...
#include <bits/stdc++.h> using namespace std; int n, m; vector<string> s; int f(int w, int b, int r) { int res = 0; for (int i = 0; i < w; i++) { for (int j = 0; j < m; j++) { res += s[i][j] != 'W'; } } for (int i = w; i < w + b; i++) { for (int j = 0; j < m; j++) { res += s[i][j] != ...
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task. The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessar...
#include <cstdio> #include <iostream> #include <queue> #include <vector> #include <cmath> using namespace std; double prim(int n, vector< vector<double> > &G){ double ans = 0.0; priority_queue< pair<double,int> > wait; bool connected[n]; fill(connected,connected+n,false); wait.push(make_pair(0.0,0)); while...
Let's play a puzzle using eight cubes placed on a 3 × 3 board leaving one empty square. Faces of cubes are painted with three colors. As a puzzle step, you can roll one of the cubes to the adjacent empty square. Your goal is to make the specified color pattern visible from above by a number of such steps. The rules o...
#include <iostream> #include <cstring> using namespace std; char dx[] = {-1,1,0,0}; char dy[] = {0,0,-1,1}; char dice[6][2] = { {4,2}, {3,5}, {5,0}, {1,4}, {0,3}, {2,1} }; int board[9], goal[9]; void dfs(int x, int y, int px, int py, int step, int &res){ if(step >= res) return; int dif = 0; for(int j=0;j<9;j++...
Fast Forwarding Mr. Anderson frequently rents video tapes of his favorite classic films. Watching the films so many times, he has learned the precise start times of his favorite scenes in all such films. He now wants to find how to wind the tape to watch his favorite scene as quickly as possible on his video player. ...
#include <iostream> #include <algorithm> #define long long long using namespace std; long f(long x) { if (x <= 0) return 0; return min(x, 2 + f((x - 2) / 3) + (x - 2) % 3); } int main() { long x; cin >> x; cout << f(x + 1) - 1 << '\n'; return 0; }
Skyscraper "MinatoHarukas" Mr. Port plans to start a new business renting one or more floors of the new skyscraper with one giga floors, MinatoHarukas. He wants to rent as many vertically adjacent floors as possible, because he wants to show advertisement on as many vertically adjacent windows as possible. The rent fo...
#include <bits/stdc++.h> using namespace std; int b; int main(){ cin.tie(0); ios::sync_with_stdio(false); while(1){ cin >> b; if(b == 0) return 0; int m = 1e9, n = 0; for(int i=1; i*i<=2*b; ++i){ if(2 * b % i != 0) continue; int c = 2 * b / i; if(i % 2 != c % 2){ int s = (i + c - 1) / 2; i...
A linguist, Nodvic Natharus Damenhof (commonly called Dr. Usoperant), invented an artificial language Usoperant in 2007. The word usoperant means ‘one which tires’. Damenhof’s goal was to create a complex and pedantic language that would remind many difficulties in universal communications. Talking in Usoperant, you sh...
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> void chmin(T1 &a,T2 b){if(a>b) a=b;}; template<typename T1,typename T2> void chmax(T1 &a,T2 b){if(a<b) a=b;}; signed main(){ Int n; Int cnt=0; while(cin>>n,n){ vector<string> ss(n); vector<Int> ls(n),vs...
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 dexterity that never mistypes by carefully stacking blocks. Since there are many building blocks, let's build a tall tower. There are N blocks, and the i-th (...
#include <bits/stdc++.h> using namespace std; #define FOR(i,k,n) for(int i = (k); i < (n); i++) #define REP(i,n) FOR(i,0,n) #define ALL(a) a.begin(), a.end() #define MS(m,v) memset(m,v,sizeof(m)) #define D10 fixed<<setprecision(10) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<str...
Given a tree with n (1 ≤ n ≤ 200,000) nodes and a list of q (1 ≤ q ≤ 100,000) queries, process the queries in order and output a value for each output query. The given tree is connected and each node on the tree has a weight wi (-10,000 ≤ wi ≤ 10,000). Each query consists of a number ti (ti = 1, 2), which indicates th...
#include <bits/stdc++.h> #define N 200010 using namespace std; int n, q, data[N]; vector<int> edge[N]; int dfn[N], top[N], f[N], size[N], son[N], d[N]; int _index; void dfs(int u, int fa) { f[u] = fa; d[u] = d[fa] + 1; size[u] = 1; for (int i = 0; i < edge[u].size(); ++i) { int v = edge[u][i]; if (v == fa) co...
The unlucky Ikta-kun has rewritten the important character string T that he had to a different character string T'by the virus. It is known that the virus has rewritten one letter of T to a different letter. That is, T and T'are different by exactly one character. In order to restore T, Ikta prepared a document S in wh...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #defi...
G: Travel Support-Travel Support- story I, Honoka Kosaka, 16 years old! I'm a student idol! !! In order to give a live performance to convey the goodness of student idols to everyone, we invite many student idols to perform live at Akiba Stadium. However, some live participants come from afar and it costs a lot of ...
#include "iostream" #include "random" #include "string" #include "bitset" #include "algorithm" #include "map" #include "queue" #include "list" #include "set" #include "climits" #include "iomanip" #include "stack" #include "functional" using namespace std; using ll = long long int; using PII = pair<ll, ll>; struct Edg...
problem Given the sequence $ A $ of length $ N $. The $ i $ item in $ A $ is $ A_i $. You can do the following for this sequence: * $ 1 \ leq i \ leq N --Choose the integer i that is 1 $. Swap the value of $ A_i $ with the value of $ A_ {i + 1} $. Find the minimum number of operations required to make $ A $ a sequ...
#include<bits/stdc++.h> #define X first #define Y second #define pb push_back #define eb pb #define rep(X,Y) for(int X=0;X<(Y);++X) #define reps(X,O,Y) for(int X=O;X<(Y);++X) #define all(X) (X).begin(),(X).end() using namespace std; using ll=long long; const ll MOD=1e9+7; map<int,int> dp[112345]; int main(){ int n; ...
Problem Here is a list of strings. Let's take a break and play with shiritori. Shiritori is performed according to the following rules. 1. First of all, select one of your favorite strings from the list and exclude that string from the list. 2. Next, select one character string from the list in which the last charact...
#include<bits/stdc++.h> using namespace std; #define pb push_back #define INF 1000000000 struct max_flow { int V; struct edge{int to,cap,rev;}; using Graph=vector<vector<edge>>; Graph graph; vector<bool> visit; public: max_flow(int n) //与えられた頂点は別にスタートとシンクを設定する場合 { V=n; graph...
A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain t...
#include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(), (x).end() using namespace std; template <typename T> T &chmin(T &a, const T &b) {return a = min(a, b);} template <typename T> T &chmax(T &a, const T &b) {return a = max(a, b);} using ll = long long; using ld = long dou...
For a dynamic list $L$ of integers, perform a sequence of the following operations. $L$ has a special element called END at the end of the list and an element of $L$ is indicated by a cursor. * insert($x$): Insert $x$ before the element indicated by the cursor. After this operation, the cursor points the inserted elem...
#include <iostream> #include <stdio.h> #include <list> using namespace std; int main(){ list<int> A; int q; scanf("%d", &q); int query,x,d; list<int>::iterator itr=A.end(); for (int i = 0; i < q; i++) { scanf("%d",&query); switch (query) { case 0: ...
Note: For Turbo C++, select "Text" as your language Resubmit your incorrect solutions to the Debugging problems, if you were getting template errors for Java and Python. Problem Description: IIITD is hosting a guessing game. The game starts with a player coming up with a word (not necessarily a valid English word). Th...
def sort_array ( array , length): for c in range(0,length-1): for d in range(0,(length-c)-1): if array[d] > array[d+1] : temp=array[d] array[d]=array[d+1] array[d+1] = temp a1 = raw_input() a = list(a1) b1 = raw_input() b = list(b1) l1=len(a) l2=...
Petr is organizing Petr Mitrichev Contest #11. The top N coders according to codechef ratings (excluding Petr himself) agreed to participate in the contest. The participants have been ranked from 0 to N-1 according to their ratings. Petr had asked each participant to choose a coder with rating higher than himself/ hers...
for _ in range(input()): n = input() arr = map(int, raw_input().split()) count = 0 # Stores the count of the number of lazy people for i in arr: if i == -1 : count += 1 count -= 1 # to exclude Gennady print (1+float(count)/2)
This is the algorithmic version of a game that kids play in our part of the country. You will be provided with a few sticks. The length of the sticks will be in the order of powers of 2. (1,2,4,8,16,32....). You will also be given another test stick of any length. The task is to write a program that finds the minimum n...
#!/usr/bin/python num = int(raw_input()) div = 8192 count = 0 while div > 0: if num >= div: count = count + 1 num = num - div div = div / 2 print count
Chef loves palindromes. Chef initially has odd number of charachters. Chef wants to create a palindrome of maximum even length using these characters. For this Chef needs to discard one character. Help Chef find the character which needs to be discarded so that he can use the rest characters in any order to form a pali...
# cook your code here def findOccurences(s, ch): return [i for i, letter in enumerate(s) if letter == ch] t=int(raw_input()) while(t>0): n=int(raw_input()) s=raw_input() i=0 while(i<n): r=findOccurences(s,s[i]) r=len(r) if(r%2==1): print(s[i]) break ...
Phantasialand boasts of its famous theme park. The park is frequently visited. It is quite large park that some tourists visit it more than once to fully appreciate its offerings. One day, our Chefs decided to visit the park. There are total n Chefs, i-th of them wants to visit the park ti times. Usually, the entry t...
n = input() t = map(int, raw_input().split()) arr = [2]*n count = n t.sort() for i in xrange(0, n): if arr[i] - t[i] > 0: if i != n-1: arr[i+1]+= arr[i] - t[i] #print arr arr[i] = t[i] #print arr elif arr[i] - t[i] < 0: count+= ((t[i]-arr[i])/...
Dennis is programming a robot that is supposed to paint a horizontal line. Not being one to care much about efficiency, Dennis programs the robot to move in an anti-clockwise spiral as shown below. 0 1 10 6 7 8 9 The robot starts at position zero, then moves to position 1, then position 2 and so on. Dennis wants a...
import math t=input() while(t): t=t-1 n=input() if n==0: print 0 elif n==1: print 1 else: p=2*n-1 m=math.pow(p,2) m=m+n-1 print int(m)
You are given an array d_1, d_2, ..., d_n consisting of n integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, em...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.PrintWriter; public class Main { static long binary_search(long A[], int n, long x) { int l = 0, r = n - 1; while (l <= r) { int m = (l + r) / ...
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di...
/** * */ //package codeforces; import java.util.*; /** * @author Shivansh Singh * */ public class Cf102B { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int i,j,c=0,l,n; String str=sc.next(); while(str.length()!...
You are given a set of all integers from l to r inclusive, l < r, (r - l + 1) ≤ 3 ⋅ 10^5 and (r - l) is always odd. You want to split these numbers into exactly (r - l + 1)/(2) pairs in such a way that for each pair (i, j) the greatest common divisor of i and j is equal to 1. Each number should appear in exactly one o...
l,r=map(int,input().split()) print('YES') for i in range((r-l+1)//2): print(l+i*2,l+i*2+1)
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell (0, 0). Robot can perform the following four kinds of operations: * U — move from (x, y) to (x, y + 1); * D — move from (x, y) to (x, y - 1); * L — move from (x, y) to (x - 1, y); * R — move from (x, y) to (x + 1,...
#include <bits/stdc++.h> using namespace std; long long x, y; int n; string s; void update(pair<int, int>& p, char c, int d) { if (c == 'U') p.second += d; else if (c == 'D') p.second -= d; else if (c == 'R') p.first += d; else p.first -= d; } bool check_len(pair<int, int> p, long long len) { ...