input
stringlengths
29
13k
output
stringlengths
9
73.4k
Two players are playing the following game with a positive integer N. On his turn a player has to write down on paper some integer between 1 and N. But it's forbidden to write an integer which is a divisor of some number already written on paper. For example N = 8 and numbers already written are: 6, 4, 7. In this case ...
for i in range(input()): z=raw_input() print 1
After the Tatvik Hiring Challenge, Karan's NLP professor has given him another homework. Since Manhattan Associates Hiring Challenge is round the corner and Karan is busy preparing for it, he turns to you for help. Given a string, replace all the consecutively occurring characters by a single, same character. Input: ...
t=int(raw_input()) i=0 while(i<t): s=raw_input() s1='' s1+=s[0] for j in s[1:]: if(j!=s1[-1]): s1+=j print(s1) i+=1
Mittal lives in the Niti Colony. The colony has N houses numbered from 1 to N. There are M bidirectional roads in the colony for travelling between houses. There might be multiple roads between two houses. Mittal lives in the house with index 1. He has friends in all houses of the colony. He is always wanting to visi...
import heapq from bisect import bisect_left INF = 1 + 25 * 10**8 def dijkstra(G, n, s): dist = [INF] * (n+1) dist[s] = 0 heap = [] heapq.heappush(heap, (0,s)) while heap: d, u = heapq.heappop(heap) if dist[u] < d: continue for (v, w) in G[u]: if dis...
Panda loves solving problems which are deemed impossible by his fellow classmates. The current problem which he is working on is to express a number N as sum of powers of number X (Not necessarily distinct) such that the number of powers of number X used should be minimum. Note: The powers of a number can be 0, 1,...
for _ in xrange(input()): n,m=map(int,raw_input().split()) if(n<m or m==1): print n continue ans=0 while n>0: ans = ans + n%m n = n/m print ans
A young mischievous boy Harsh, got into a trouble when his mechanical workshop teacher told him to cut Iron rods. The rod cutting algorithm is as follows: Step 1. If the rod can be divided into two equal parts, cut it and choose any one of them. Step 2. Else cut the rod into two parts having non-zero integral ...
def count_special(N): count = 0 prev = 0 curr = 3 while(curr <= N): prev = curr curr = 2*prev + 1 count += 1 return count T = int(raw_input()) for t in xrange(T): N = int(raw_input()) count = count_special(N) print count
It’s the company's 3^rd anniversary, and everyone is super-excited about it. There is a tradition in the company, that the interns decide the seating arrangement of all the members. The requirements of this order are: The CEO of the company must sit in the middle. (In case of even number of team members, he can sit on ...
#mod = 10**9 + 7 #test = int(raw_input()) #for i in range(test): ceo , coo , cto = [int(x) for x in raw_input().split()] n = int( raw_input() ) arr = [int(x) for x in raw_input().split()] arr.sort(reverse = True) res = [0 for i in range(n+3)] l = len(res) res[0] = min( coo , cto ) res[l-1] = max( coo , cto ) res[l/2] =...
Ramu’s uncle has left him a stable in his Will. But the stable is not in a good condition. The roofs leak and need to be repaired. There are a number of stalls in the stable. A stall may or may not contain a horse. Ramu has to buy new cement sheets to cover these stalls. He has to cover atleast all those stalls that h...
# /he/uncle's-will no_of_tc = input() for tc in range(no_of_tc) : line = raw_input() max_sheets = int(line.split(' ')[0]) total_stalls = int(line.split(' ')[1]) filled_stalls = int(line.split(' ')[2]) stall_map = [False] * total_stalls for i in range(filled_stalls) : stall_map[input() - 1] = True while stall_ma...
There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i. Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, ...
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.LongStream; public cla...
We have three boxes A, B, and C, each of which contains an integer. Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively. We will now do the operations below in order. Find the content of each box afterward. * Swap the contents of the boxes A and B * Swap the contents of the boxes A and C C...
X, Y, Z = map(int,input().split()) print(Z, X, Y)
Takahashi and Aoki are training for long-distance races in an infinitely long straight course running from west to east. They start simultaneously at the same point and moves as follows towards the east: * Takahashi runs A_1 meters per minute for the first T_1 minutes, then runs at A_2 meters per minute for the subse...
t = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) x = t[0] * (a[0] - b[0]) y = x + t[1] * (a[1] - b[1]) if x*y > 0: print(0) elif x*y == 0: print('infinity') elif abs(x) % abs(y) == 0: print(2 * (abs(x) // abs(y))) else: print(2 * (abs(x) // abs(y)) + 1)
You are given two non-negative integers L and R. We will choose two integers i and j such that L \leq i < j \leq R. Find the minimum possible value of (i \times j) \mbox{ mod } 2019. Constraints * All values in input are integers. * 0 \leq L < R \leq 2 \times 10^9 Input Input is given from Standard Input in the fol...
l,r = map(int,input().split()) r = min(r, l+4038) ans = 2018 for i in range(l,r): for j in range(l+1,r+1): if ans > i*j%2019: ans = i*j%2019 print(ans)
You are given positive integers A and B. If A is a divisor of B, print A + B; otherwise, print B - A. Constraints * All values in input are integers. * 1 \leq A \leq B \leq 20 Input Input is given from Standard Input in the following format: A B Output If A is a divisor of B, print A + B; otherwise, print B -...
#include <bits/stdc++.h> int main() { int a, b; scanf("%d%d", &a, &b); if (b % a == 0) printf("%d\n", a+b); else printf("%d\n", b-a); }
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists. * The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N. * The number o...
#解説参照 l=int(input()) r=0 while 2**(r+1)<=l: r+=1 n=r+1 ans=[] for i in range(r): ans.append((i+1,i+2,0)) ans.append((i+1,i+2,2**i)) for t in range(n-1,0,-1): if l-2**(t-1)>=2**r: ans.append((t,n,l-2**(t-1))) l-=2**(t-1) print(n,len(ans)) for a in ans: print(*a)
There are N people. The name of the i-th person is S_i. We would like to choose three people so that the following conditions are met: * The name of every chosen person begins with `M`, `A`, `R`, `C` or `H`. * There are no multiple people whose names begin with the same letter. How many such ways are there to choo...
import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashMap<String,Long> namelist = new HashMap<>(); String s = "MARCH"; for(int i = 0;i<s.length();i++){ ...
For a string S, let f(S) be the lexicographically smallest cyclic shift of S. For example, if S = `babca`, f(S) = `ababc` because this is the smallest among all cyclic shifts (`babca`, `abcab`, `bcaba`, `cabab`, `ababc`). You are given three integers X, Y, and Z. You want to construct a string T that consists of exact...
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<algorithm> #include<set> using namespace std; #define REP(i,st,ed) for(int i=st,i##end=ed;i<=i##end;++i) #define DREP(i,st,ed) for(int i=st,i##end=ed;i>=i##end;--i) multiset<string>s; multiset<string>::iterator it1,it2; int...
You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one. At least how many operations are necessary to satisfy the following conditions? * For every i (1≤i≤n), the sum of the terms from the 1-st through i-...
n=int(input()) a=list(map(int,input().split())) u=0 s=1 x=0 y=0 for i in a: u+=i if s*u<=0: x+=1-s*u u=s s=s*(-1) s=-1 u=0 for i in a: u+=i if s*u<=0: y+=1-s*u u=s s=-1*s print(min(x,y))
Aoki is in search of Takahashi, who is missing in a one-dimentional world. Initially, the coordinate of Aoki is 0, and the coordinate of Takahashi is known to be x, but his coordinate afterwards cannot be known to Aoki. Time is divided into turns. In each turn, Aoki and Takahashi take the following actions simultaneou...
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; class Main{ static void solve(){ int x = ni(); double p = ni()/100.0; double ans = 0; if(x%2==0)ans=(double)x/(2*p); else{ ans=1; ans += (x-1)/2; ans += ((1-p)*((double)x+1))/(p*2); } ...
Your friend who lives in undisclosed country is involved in debt. He is borrowing 100,000-yen from a loan shark. The loan shark adds 5% interest of the debt and rounds it to the nearest 1,000 above week by week. Write a program which computes the amount of the debt in n weeks. Input An integer n (0 ≤ n ≤ 100) is g...
#encoding=utf-8 inp = input() x = 100000 for i in xrange(inp): x = x * 1.05 if int(x % 1000) != 0: x += 1000 - int(x % 1000) print int(x)
In a world, a mysterious snake made of only letters lives. Two types of snakes are currently identified, type A and type B, but there may be other types as well. For class A, after ">'" is followed by one or more "=", "#" comes, and after the same number of "=" as before, "~" (half-width tilde) finish. Class B ends w...
#include<iostream> #include<regex> #include<string> int main() { int n; std::cin >> n; std::cin.ignore(); while( n-- ) { std::string s; std::getline( std::cin, s ); std::smatch m; if( std::regex_match( s, m, std::regex( ">\'(=+)#(=+)~" ) ) && m[1].length() == m[2].length() ) std::cout << 'A' << std::...
Today is the ticket release date for Aizu Entertainment's recommended idol group "Akabeko & Koboushi". There are four types of tickets: S seat 6000 yen A seat 4000 yen B seat 3000 yen C seat 2000 yen You, the sales manager, are excitedly waiting for the launch. Finally on sale. It's selling very well! Shortly after ...
for i in range(4): t,n=map(int,input().split()) if t==1: print(f'{6000*n}') elif t==2: print(f'{4000*n}') elif t==3: print(f'{3000*n}') elif t==4: print(f'{2000*n}')
problem In one programming contest, it is customary to play a bingo game at a social gathering after the competition. However, the bingo card used in this bingo game is a little special and is created according to the following conditions. * The Bingo card is divided into squares of N rows and N columns, and one posi...
#include<cstdio> #include<cstring> #include<iostream> #include<vector> #include<algorithm> #include<string> using namespace std; int N,M,S; int dp[2][50][3001]; #define AMA (100000) int solve(){ memset(dp,0,sizeof(dp)); int now; int next; int ret = 0; dp[1][0][0]=1; for(int m=1;m<=M;m++){ now = m&1; ...
Mr. Dango's family has an extremely huge number of members. Once it had about 100 members, and now it has as many as population of a city. It is jokingly guessed that the member might fill this planet in the near future. Mr. Dango's family, the huge family, is getting their new house. Scale of the house is as large as...
#include <bits/stdc++.h> using namespace std; #define dump(...) cout<<"# "<<#__VA_ARGS__<<'='<<(__VA_ARGS__)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define all(c) begin(c),end(c) #define mp mak...
A huge amount of information is being heaped on WWW. Albeit it is not well-organized, users can browse WWW as an unbounded source of up-to-date information, instead of consulting established but a little out-of-date encyclopedia. However, you can further exploit WWW by learning more about keyword search algorithms. Fo...
import java.util.Arrays; import java.util.Scanner; public class Main { static Scanner sc = new Scanner(System.in); static int[] key = new int[256]; public static void main(String[] args) { while (true) { StringBuilder sb = new StringBuilder(); while (true) { String line = sc.nextLine(); if (line.i...
Example Input 10 3 3 7 8 9 2 5 Output 23
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int n,m; cin >> n >> m; vector<int> after(n+2, 0); for(int i=0; i<m; i++){ int c,d; cin >> c >> d; after[c] = max(after[c], d); } int ans = 0; int farthest = 0; for(int i=0; i<=n; i++){ farthest = max(farthest, ...
Problem N idols, numbered from 1 to n in order, are lined up in a row. Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1. At time 0, m idols with numbers a1, a2, ..., am have secret i...
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<map> #include<set> #include<utility> #include<cmath> #include<cstring> #include<queue> #include<cstdio> #define loop(i,a,b) for(int i=a;i<b;i++) #define rep(i,a) loop(i,0,a) #define pb push_back #define mp make_pair #define all(in) in.be...
Grated radish (daikon-oroshi) is one of the essential spices in Japanese cuisine. As the name shows, it’s made by grating white radish. You are developing an automated robot for grating radish. You have finally finished developing mechan- ical modules that grates radish according to given instructions from the microco...
#include <stdio.h> #include <math.h> #include <iostream> #include <complex> #include <vector> #include <utility> #include <algorithm> using namespace std; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define mp make_pair const double EPS = 1e-12; const double pi = atan2(0.0, -1.0); typedef complex<double> P; d...
The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back. However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not complete...
#include<iostream> #include<string> #include<queue> #include<algorithm> #include<set> using namespace std; #define rep(i,n) for ( int i = 0; i < n; i++) static const int MAX = 50; static const int PMAX = 11; static const string DT = "URDL"; static const int di[4] = {-1, 0, 1, 0}; static const int dj[4] = {0, 1, 0, -1};...
Mary Thomas has a number of sheets of squared paper. Some of squares are painted either in black or some colorful color (such as red and blue) on the front side. Cutting off the unpainted part, she will have eight opened-up unit cubes. A unit cube here refers to a cube of which each face consists of one square. She is...
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include...
I-σ A permutation of magnitude N is a sequence of elements in a sequence (1, 2, 3,…, N). For example, (5, 2, 1, 4, 3) is a permutation of size 5, while (1, 5, 1, 2, 3) is not. This problem is a reactive task. You play a response program and a "permutation guessing game". First of all, the response program internally ...
#include<stdio.h> #include<algorithm> using namespace std; int p[500]; int q[250][500]; int r[250][500]; int ret[500]; int s[500]; int t[250][500]; int u[500]; int v[250][500]; int w[250][500]; int ABS(int a){return max(a,-a);} int LIM=240; int main(){ int a; scanf("%d",&a); for(int i=0;i<a;i++)p[i]=i; for(int i=0;...
Let's solve the geometric problem Mr. A is still solving geometric problems today. It is important to be aware of floating point errors when solving geometric problems. Floating-point error is the error caused by the rounding that occurs when representing a number in binary finite decimal numbers. For example, 0.1 in...
#include <bits/stdc++.h> using namespace std; using VI = vector<int>; using VVI = vector<VI>; using PII = pair<int, int>; using LL = long long; using VL = vector<LL>; using VVL = vector<VL>; using PLL = pair<LL, LL>; using VS = vector<string>; #define ALL(a) begin((a)),end((a)) #define RALL(a) (a).rbegin(), (a).rend...
G: Almost Infinite Glico problem There is a field where N squares are arranged in a ring. The i-th (1 \ leq i \ leq N-1) cell is ahead of the i + 1th cell. However, if i = N, the next cell is the first cell. The first cell you are in is the first cell. From there, play rock-paper-scissors K times in a row according ...
#include<bits/stdc++.h> using namespace std; // macro #define rep(i,n) for(i=0;i<n;i++) #define ll long long #define all(v) v.begin(), v.end() // code starts #define MOD 1000000007 int main() { ll n,m,k;cin>>n>>m>>k; vector<int> p(m); ll i,j,l; rep(i,m)cin>>p[i]; ll num=1; ll needs=0; while(num<=k) {...
F: Invariant Tree Problem Statement You have a permutation p_1, p_2, ... , p_N of integers from 1 to N. You also have vertices numbered 1 through N. Find the number of trees while satisfying the following condition. Here, two trees T and T' are different if and only if there is a pair of vertices where T has an edge ...
#include<bits/stdc++.h> #define pb push_back #define mp make_pair #define fi first #define se second using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; typedef pair<ll,ll> pll; template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;} template <typena...
test UnionFind(バイナリ入力) Example Input Output
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <limits> #include <random> #include <utility> #include <vector> namespace procon { class UnionFind { private: struct nodeinfo { int par; int rank; nodeinfo(int par) : par(par), rank(0) {} }; std::vector<nodeinfo> n...
Examples Input 4 5 2 0 1 2 1 0 2 1 2 1 2 1 1 1 3 1 3 2 3 2 1 Output 6 Input Output
#include <bits/stdc++.h> using namespace std; struct SuccessiveShortestPath { struct Edge{ int to, cap, cost, rev; }; int n, init; vector<vector<Edge>> g; vector<int> dist, pv, pe, h; SuccessiveShortestPath() {} SuccessiveShortestPath(int n, int INF = 1e9) : n(n), g(n), init(INF), dist(n), pv(n), pe(n...
Andi and Budi were given an assignment to tidy up their bookshelf of n books. Each book is represented by the book title — a string s_i numbered from 1 to n, each with length m. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending. Settling their figh...
#include <bits/stdc++.h> using namespace std; bool isrange(int second, int first, int n, int m) { if (0 <= second && second < n && 0 <= first && first < m) return true; return false; } int dy[4] = {1, 0, -1, 0}, dx[4] = {0, 1, 0, -1}, ddy[8] = {1, 0, -1, 0, 1, 1, -1, -1}, ddx[8] = {0, 1, 0, -1, 1, -1, 1, -1}; c...
Mr. Chanek lives in a city represented as a plane. He wants to build an amusement park in the shape of a circle of radius r. The circle must touch the origin (point (0, 0)). There are n bird habitats that can be a photo spot for the tourists in the park. The i-th bird habitat is at point p_i = (x_i, y_i). Find the m...
#include <bits/stdc++.h> const double PI = 3.1415926535897932384626433; const int KL = 3e5 + 10; const long long MOD = 1e9 + 7; using namespace std; struct point { long double x, y; void go(long long x1, long long y1) { x = x1; y = y1; } void read() { cin >> x >> y; } point operator-(point b) { return...
Denote a cyclic sequence of size n as an array s such that s_n is adjacent to s_1. The segment s[r, l] where l < r is the concatenation of s[r, n] and s[1, l]. You are given an array a consisting of n integers. Define b as the cyclic sequence obtained from concatenating m copies of a. Note that b has size n ⋅ m. You ...
#include <bits/stdc++.h> using namespace std; struct comp { double a, b; comp() {} comp(double x) : a(x), b(0) {} comp(double x, double y) : a(x), b(y) {} }; inline comp operator+(comp a, comp b) { return comp(a.a + b.a, a.b + b.b); } inline comp operator-(comp a, comp b) { return comp(a.a - b.a, a.b - b.b); } ...
Mr. Chanek has an integer represented by a string s. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit. Mr. Chanek wants to count the number of possible integer s, where s is divisible by 25. Of course, ...
s = input() ways = 0 if len(s) == 1: if s in ['_', 'X', '0']: ways = 1 elif len(s) == 2: if s in ['25', '50', '75']: ways = 1 elif s in ['__', '_X', 'X_']: ways = 3 elif s == '_0': ways = 1 elif s in ['_5', 'X5']: ways = 2 elif s in ['2_', '5_', '7_', '2X'...
There is a city park represented as a tree with n attractions as its vertices and n - 1 rails as its edges. The i-th attraction has happiness value a_i. Each rail has a color. It is either black if t_i = 0, or white if t_i = 1. Black trains only operate on a black rail track, and white trains only operate on a white r...
#include <bits/stdc++.h> #pragma GCC optimize(2, 3, "Ofast") using namespace std; template <typename T1, typename T2> void ckmin(T1 &a, T2 b) { if (a > b) a = b; } template <typename T1, typename T2> void ckmax(T1 &a, T2 b) { if (a < b) a = b; } int read() { int x = 0, f = 0; char ch = getchar(); while (!isdi...
Mr. Chanek opened a letter from his fellow, who is currently studying at Singanesia. Here is what it says. Define an array b (0 ≤ b_i < k) with n integers. While there exists a pair (i, j) such that b_i ≠ b_j, do the following operation: * Randomly pick a number i satisfying 0 ≤ i < n. Note that each number i has a...
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 11, mod = 1e9 + 7; int f[N], g[N], a[N], b[N], c[N], d[N], fac[N], ifac[N], ik[N], ik0[N]; int n, s, ans, cnt, k, m; int fp(int a, int b) { int res = 1; for (; b; b >>= 1, a = 1ll * a * a % mod) if (b & 1) res = 1ll * res * a % mod; return res;...
Mr. Chanek has an array a of n integers. The prettiness value of a is denoted as: $$$∑_{i=1}^{n} {∑_{j=1}^{n} {\gcd(a_i, a_j) ⋅ \gcd(i, j)}}$$$ where \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y. In other words, the prettiness value of an array a is the total sum of \gcd(a_i, a_j) ⋅ \gcd(...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using str = string; using pi = pair<int, int>; using pl = pair<ll, ll>; using vi = vector<int>; using vl = vector<ll>; using vpi = vector<pair<int, int>>; using vvi = vector<vi>; const int md = 1e9 + 7; int add(const int &a, con...
The Winter holiday will be here soon. Mr. Chanek wants to decorate his house's wall with ornaments. The wall can be represented as a binary string a of length n. His favorite nephew has another binary string b of length m (m ≤ n). Mr. Chanek's nephew loves the non-negative integer k. His nephew wants exactly k occurre...
#include <bits/stdc++.h> using namespace std; const int N = 510; int dp[2][N][N]; char s[N], str[N], ss[N]; int nxt[N][2]; int fail_all; int get_lcp(int cnt) { for (int l = cnt - 1; l >= 1; l--) { bool flag = true; for (int j = 0; j < l; j++) { if (str[l - j] != ss[cnt - j]) { flag = false; ...
Chanek Jones is back, helping his long-lost relative Indiana Jones, to find a secret treasure in a maze buried below a desert full of illusions. The map of the labyrinth forms a tree with n rooms numbered from 1 to n and n - 1 tunnels connecting them such that it is possible to travel between each pair of rooms throug...
#include <bits/stdc++.h> using namespace std; mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()); const long long N = 1e5 + 10; vector<long long> g[N]; vector<long long> d(N); vector<long long> arr; vector<long long> in(N), out(N); long long po[20][N], t[4 * N], add[4 * N]; void dfs(long long ...
Mr. Chanek has a new game called Dropping Balls. Initially, Mr. Chanek has a grid a of size n × m Each cell (x,y) contains an integer a_{x,y} denoting the direction of how the ball will move. * a_{x,y}=1 — the ball will move to the right (the next cell is (x, y + 1)); * a_{x,y}=2 — the ball will move to the bott...
#include <bits/stdc++.h> using namespace std; const int NMAX = 1000; int N, M, K; int a[NMAX + 2][NMAX + 2]; struct state { int dad, sz; int down; }; state ds[NMAX + 2][NMAX + 2]; bool active[NMAX + 2][NMAX + 2]; int root(int col, int p) { if (ds[p][col].dad != p) { return ds[p][col].dad = root(col, ds[p][col...
Mr. Chanek wants to knit a batik, a traditional cloth from Indonesia. The cloth forms a grid a with size n × m. There are k colors, and each cell in the grid can be one of the k colors. Define a sub-rectangle as an ordered pair of two cells ((x_1, y_1), (x_2, y_2)), denoting the top-left cell and bottom-right cell (in...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; template <int MOD> struct ModInt { int val; ModInt(ll v = 0) : val(int(v % MOD)) { if (val < 0) val += MOD; }; ModInt operator+() const { return ModInt(val); } ModInt operator-() const { return ModInt(MOD - val...
Mr. Chanek gives you a sequence a indexed from 1 to n. Define f(a) as the number of indices where a_i = i. You can pick an element from the current sequence and remove it, then concatenate the remaining elements together. For example, if you remove the 3-rd element from the sequence [4, 2, 3, 1], the resulting sequen...
#include <bits/stdc++.h> using namespace std; int const N = 2e5 + 123; vector<int> ST(4 * N, 0); void update(int k, int l, int r, int idx, int val) { if (l > idx || r < idx) return; if (l == r && l == idx) { ST[k] = val; return; } int m = (l + r) >> 1; update(k << 1, l, m, idx, val); update(k << 1 |...
Mr. Chanek's city can be represented as a plane. He wants to build a housing complex in the city. There are some telephone poles on the plane, which is represented by a grid a of size (n + 1) × (m + 1). There is a telephone pole at (x, y) if a_{x, y} = 1. For each point (x, y), define S(x, y) as the square of the Euc...
#include <bits/stdc++.h> using namespace std; const int N = 2e3 + 5; int n, m, mp[N][N], pre[N], qu[N], head, tail; long long dp[N][N]; char ch[N]; long double slope(int fi, int se, int id) { long double X1 = 2 * fi, Y1 = fi * fi + (id - pre[fi]) * (id - pre[fi]); long double X2 = 2 * se, Y2 = se * se + (id - pre[s...
Casimir has a string s which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions: * he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent); * or he can ...
#include <bits/stdc++.h> using namespace std; const long long int mod = 998244353; const int limit = 3e5 + 10; void solve() { string s; cin >> s; int finally = 0; for (char ch : s) { if (ch == 'A' || ch == 'C') { finally--; } else { finally++; } } if (finally == 0) { cout << "Yes...
The new generation external memory contains an array of integers a[1 … n] = [a_1, a_2, …, a_n]. This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same ...
#include <bits/stdc++.h> using namespace std; void Pagla() { int i, j; int n; cin >> n; vector<long long int> a, b; for (i = 0; i < n; i++) { int num; cin >> num; a.push_back(num); } b = a; vector<pair<int, int>> pos; sort(b.begin(), b.end()); int k = 0; int kk = 0; int left = 0; i...
Casimir has a rectangular piece of paper with a checkered field of size n × m. Initially, all cells of the field are white. Let us denote the cell with coordinates i vertically and j horizontally by (i, j). The upper left cell will be referred to as (1, 1) and the lower right cell as (n, m). Casimir draws ticks of di...
import java.io.*; import java.util.*; public class Main { //----------- StringBuilder for faster output------------------------------ static StringBuilder out = new StringBuilder(); static int cnt = 0; public static void main(String[] args) { FastScanner fs=new FastScanner(); /****** CODE STARTS HERE ***...
An important meeting is to be held and there are exactly n people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting. Each person has limited sociability. The sociability of the i-th person is a non-negative integer a_...
###pyrival template for fast IO import os import sys from io import BytesIO, IOBase ##########region fastio BUFSIZE = 8192 ###pyrival template for fast IO class FastIO(IOBase): newlines = 0 ###pyrival template for fast IO def __init__(self, file): self._fd = file.fileno() self.buffer = Bytes...
In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems. You are given an integer array a[1 … n] = [a_1, a_2, …, a_n]. Let us consider an empty [deque](https://tinyurl.com/pfeucbux) (double-ended queue). A deque is a data structure that supports adding el...
import sys from math import factorial, gcd #from math import comb, perm from collections import Counter, deque, defaultdict from bisect import bisect_left, bisect_right from heapq import heappop, heappush, heapify, nlargest, nsmallest from itertools import groupby from copy import deepcopy MOD = 10**9+7 INF = floa...
You are given an array a[0 … n - 1] = [a_0, a_1, …, a_{n - 1}] of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one. In one step, the array a is replaced by another array of length n according to the following rules: 1. First, a new array a^{...
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e6 + 7; const int ALPHA = 40; const long long INF = 1e16 + 7; const int MOD = 1e9 + 7; const int LOG = 22; const int BASE[2] = {313, 239}; long long n, d; bool ns[MAXN], seen[MAXN]; vector<long long> group[MAXN], plast[MAXN]; void solve() { cin >> n >> d...
You are given n lengths of segments that need to be placed on an infinite axis with coordinates. The first segment is placed on the axis so that one of its endpoints lies at the point with coordinate 0. Let's call this endpoint the "start" of the first segment and let's call its "end" as that endpoint that is not the ...
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int M = 10005; int dp[M][2005]; int a[M], len, n; int dpcall(int id, int pos) { if (pos > len || pos < 0) return 0; if (id == n) return 1; int &ret = dp[id][pos]; if (~ret) return ret; ret ...
CQXYM found a rectangle A of size n × m. There are n rows and m columns of blocks. Each block of the rectangle is an obsidian block or empty. CQXYM can change an obsidian block to an empty block or an empty block to an obsidian block in one operation. A rectangle M size of a × b is called a portal if and only if it sa...
#include <bits/stdc++.h> using namespace std; int T; int n, m; int mp[410][410], s[410][410], mx[410], p[410]; int sum(int i, int j, int k) { return s[j - 1][k] - s[i][k]; } int main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); cin >> T; while (T--) { cin >> n >> m; for (int i = 1; i <= n; i++)...
Let c_1, c_2, …, c_n be a permutation of integers 1, 2, …, n. Consider all subsegments of this permutation containing an integer x. Given an integer m, we call the integer x good if there are exactly m different values of maximum on these subsegments. Cirno is studying mathematics, and the teacher asks her to count th...
#include <bits/stdc++.h> using namespace std; const int NMAX = 100; int N, M, K, P; int memo[NMAX + 2][NMAX + 2][NMAX + 2]; int fact[NMAX + 2], c[NMAX + 2][NMAX + 2]; int comb(int k, int n) { return c[n][k]; } int ways(int len, int levels_deep, int count) { if (memo[len][levels_deep][count] != -1) { return memo[l...
Kawasiro Nitori is excellent in engineering. Thus she has been appointed to help maintain trains. There are n models of trains, and Nitori's department will only have at most one train of each model at any moment. In the beginning, there are no trains, at each of the following m days, one train will be added, or one t...
#include <bits/stdc++.h> using namespace std; template <typename A, typename B> ostream &operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template <typename T_container, typename T = typename enable_if< !is_same<T_container, s...
Alice has an integer sequence a of length n and all elements are different. She will choose a subsequence of a of length m, and defines the value of a subsequence a_{b_1},a_{b_2},…,a_{b_m} as $$$∑_{i = 1}^m (m ⋅ a_{b_i}) - ∑_{i = 1}^m ∑_{j = 1}^m f(min(b_i, b_j), max(b_i, b_j)), where f(i, j) denotes \min(a_i, a_{i + 1...
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; template <class T> using vi2 = vector<vector<T>>; using ll = long long; using pii = pair<int, int>; int main() { auto solve = [&]() { int n, m; cin >> n >> m; vector<int> a(n + 1), per(n + 1), fa(n + 1), sz(n + 1); for (int i = 1...
Because the railway system in Gensokyo is often congested, as an enthusiastic engineer, Kawasiro Nitori plans to construct more railway to ease the congestion. There are n stations numbered from 1 to n and m two-way railways in Gensokyo. Every two-way railway connects two different stations and has a positive integer ...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") using namespace std; const int N = 6e5 + 7; int n, m, q; long long cw[N]; int ehd[N], ev[N], enx[N], ew[N], eid; int ord[N], mp[N], tp, Fa[N]; void eadd(int u, int v, int w) { ++eid, enx[eid] = ehd[u], ev[eid] = v, ew[eid] = w...
XYMXYM and CQXYM will prepare n problems for Codeforces. The difficulty of the problem i will be an integer a_i, where a_i ≥ 0. The difficulty of the problems must satisfy a_i+a_{i+1}<m (1 ≤ i < n), and a_1+a_n<m, where m is a fixed integer. XYMXYM wants to know how many plans of the difficulty of the problems there ar...
#include <bits/stdc++.h> using namespace std; const int N = 280010; const int mod = 998244353, gn = 3; const int inf = 2147483647; long long read() { long long x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') x = ...
CQXYM is counting permutations length of 2n. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). A...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { private static final FastReader fs = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); private stat...
CQXYM wants to create a connected undirected graph with n nodes and m edges, and the diameter of the graph must be strictly less than k-1. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most one ed...
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 7; const double eps = 1e-6; const int mod = 1e9 + 7; int a[N]; long long get(long long n) { return n * (n + 1) / 2; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { long long n, m, k; cin...
Luntik has decided to try singing. He has a one-minute songs, b two-minute songs and c three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert. He wants to make the absolute difference of durations of the concerts as small as possible. The d...
#include <bits/stdc++.h> using namespace std; void solve() { long long a, b, c; cin >> a >> b >> c; long long s = (a + 2 * b + 3 * c); if (s % 2 != 0) cout << 1; else cout << 0; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long t = 1; cin >> t; while (t...
Luntik came out for a morning stroll and found an array a of length n. He calculated the sum s of the elements of the array (s= ∑_{i=1}^{n} a_i). Luntik calls a subsequence of the array a nearly full if the sum of the numbers in that subsequence is equal to s-1. Luntik really wants to know the number of nearly full su...
a=input() while True: try: t=int(input()) a=[int(i) for i in input().split()] n_0=a.count(0) n_1=a.count(1) #print(n_0,n_1) ans=0 #if n_1>1: #n_1-=1 ans+=n_1*2**n_0 if sum(a)==1: ans=2**(n_0) print(ans) exce...
Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string s of length n. Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is ...
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; public final class B { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<Integer> g[]; static long mod=(long) 99...
Vupsen and Pupsen were gifted an integer array. Since Vupsen doesn't like the number 0, he threw away all numbers equal to 0 from the array. As a result, he got an array a of length n. Pupsen, on the contrary, likes the number 0 and he got upset when he saw the array without zeroes. To cheer Pupsen up, Vupsen decided ...
import java.io.*; import java.util.*; public class yo { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); for (int xx = 0; xx < t; xx++) { int n = sc.nextInt(); int[] arr = new int[n]; for...
Pchelyonok decided to give Mila a gift. Pchelenok has already bought an array a of length n, but gifting an array is too common. Instead of that, he decided to gift Mila the segments of that array! Pchelyonok wants his gift to be beautiful, so he decided to choose k non-overlapping segments of the array [l_1,r_1], [l_...
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int M = 200005; long long a[M]; long long dp[M], dpp[M]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t, tt = 1; cin >> t; while (t--) { memset((dp), 0, siz...
This is an easier version of the problem with smaller constraints. Korney Korneevich dag up an array a of length n. Korney Korneevich has recently read about the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), so he wished to experiment with it. For this purpose, he decided to find all in...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; const int MOD = 1e9 + 7; int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); ret...
This is a harder version of the problem with bigger constraints. Korney Korneevich dag up an array a of length n. Korney Korneevich has recently read about the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), so he wished to experiment with it. For this purpose, he decided to find all inte...
#include <bits/stdc++.h> using namespace std; const int N = 5e3 + 10, mod = 998244353; vector<int> v[N]; int dp[N][8192]; int main() { int n; scanf("%d", &n); memset(dp, 0x3f, sizeof dp); dp[0][0] = 0; for (int i = 1, x; i <= n; i++) scanf("%d", &x), v[x].push_back(i); for (int i = 1; i <= 5e3; i++) for...
Kuzya started going to school. He was given math homework in which he was given an array a of length n and an array of symbols b of length n, consisting of symbols '*' and '/'. Let's denote a path of calculations for a segment [l; r] (1 ≤ l ≤ r ≤ n) in the following way: * Let x=1 initially. For every i from l to ...
#include <bits/stdc++.h> using namespace std; template <typename T> void chkMax(T &x, T y) { if (y > x) x = y; } template <typename T> void chkMin(T &x, T y) { if (y < x) x = y; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '...
A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person. You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of n (n ≥ 3) positive distinct integers (i.e. different, no duplicates are allowed). Find the largest subset (i.e. having th...
#include <bits/stdc++.h> using namespace std; const int maxn = 8e5 + 100; const int inf = 1e9 + 10; const int mod = 1e9 + 7; int zs(int x) { int m = (int)sqrt(x + 0.5); for (int i = 2; i <= m; i++) { if (x % i == 0) return 0; } return 1; } int a[200]; int main() { int T, n; scanf("%d", &T); while (T--...
Lord Omkar would like to have a tree with n nodes (3 ≤ n ≤ 10^5) and has asked his disciples to construct the tree. However, Lord Omkar has created m (1 ≤ m < n) restrictions to ensure that the tree will be as heavenly as possible. A tree with n nodes is an connected undirected graph with n nodes and n-1 edges. Note ...
import sys,os,io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline for _ in range (int(input())): n,m = [int(i) for i in input().split()] a = [] vis = [0]*n for i in range (m): r = [int(i)-1 for i in input().split()] vis[r[1]]=1 ind = vis.index(0) edges = [] for i...
The problem statement looms below, filling you with determination. Consider a grid in which some cells are empty and some cells are filled. Call a cell in this grid exitable if, starting at that cell, you can exit the grid by moving up and left through only empty cells. This includes the cell itself, so all filled in ...
import java.io.*; import java.util.*; import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.Arrays.fill; public class Current { FastScanner in; PrintWriter out; private void solve() throws IOException { int n = in.nextInt(), m = in.nextInt(); boolean[...
It turns out that the meaning of life is a permutation p_1, p_2, …, p_n of the integers 1, 2, …, n (2 ≤ n ≤ 100). Omkar, having created all life, knows this permutation, and will allow you to figure it out using some queries. A query consists of an array a_1, a_2, …, a_n of integers between 1 and n. a is not required ...
#include <bits/stdc++.h> using namespace std; long long int query(vector<long long int> a) { long long int response; cout << "? "; for (auto i : a) cout << i << " "; cout << endl; cin >> response; return response; } int32_t main() { long long int n; cin >> n; long long int t = 0; vector<long long in...
She does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang. Hu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of n nodes with m edges. You also have q queries. Each query consists...
#include <bits/stdc++.h> using namespace std; struct no { int fa; vector<int> ch; int dep = -1; }; vector<no> te; void dfs(int r, int f) { te[r].fa = f; te[r].dep = te[te[r].fa].dep + 1; for (int i = 0; i < te[r].ch.size(); i++) { if (te[r].ch[i] == f) { continue; } dfs(te[r].ch[i], r); ...
Even if you just leave them be, they will fall to pieces all by themselves. So, someone has to protect them, right? You find yourself playing with Teucer again in the city of Liyue. As you take the eccentric little kid around, you notice something interesting about the structure of the city. Liyue can be represented ...
#include <bits/stdc++.h> using namespace std; int n, k, ans, x, y, t; int main() { cin >> n >> k, x = n - 1; while (x) x /= k, ++ans; cout << ans << endl; for (int i = 1; i < n; ++i) { for (int j = i + 1; j <= n; ++j) { x = i - 1, y = j - 1, t = 0; while (x != y) x /= k, y /= k, ++t; cout ...
El Psy Kongroo. Omkar is watching Steins;Gate. In Steins;Gate, Okabe Rintarou needs to complete n tasks (1 ≤ n ≤ 2 ⋅ 10^5). Unfortunately, he doesn't know when he needs to complete the tasks. Initially, the time is 0. Time travel will now happen according to the following rules: * For each k = 1, 2, …, n, Okabe w...
#include <bits/stdc++.h> using namespace std; long long mod = 1e9 + 7; vector<long long> dp; long long sum(int r) { long long res = 0; for (; r > 0; r -= r & -r) { res += dp[r]; res %= mod; } return res; } long long sum(int l, int r) { return ((sum(r) - sum(l - 1)) + mod) % mod; } void add(int k, int x)...
Omkar is hosting tours of his country, Omkarland! There are n cities in Omkarland, and, rather curiously, there are exactly n-1 bidirectional roads connecting the cities to each other. It is guaranteed that you can reach any city from any other city through the road network. Every city has an enjoyment value e. Each r...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5, M = 4e5 + 5; int n, m, a[N], fa[N], siz[N], f[N][22], w[N][22], dep[N], lca[N], mx[N], val[N]; struct edge { int x, y, c, z; } e[N]; struct query { int x, z, id; } q[N]; vector<pair<int, int> > G[N]; pair<int, int> ans[N]; int getf(int x) { re...
Omkar is creating a mosaic using colored square tiles, which he places in an n × n grid. When the mosaic is complete, each cell in the grid will have either a glaucous or sinoper tile. However, currently he has only placed tiles in some cells. A completed mosaic will be a mastapeece if and only if each tile is adjace...
import sys o = {'G':'S', 'S':'G'};n = int(input());d = [list(input()[:n]) for _ in range(n)];f = [1] * (n * n);finished = 1 if n % 2: print('NONE'); sys.exit() x = [''] * (n // 2) def findt(i, j): return abs(j - i) // 2 if (j - i) % 2 else min(i + j, 2 * (n - 1) - j - i) // 2 def findr(i, j, t): if (j - i) % 2: ret...
Petya has got an interesting flower. Petya is a busy person, so he sometimes forgets to water it. You are given n days from Petya's live and you have to determine what happened with his flower in the end. The flower grows as follows: * If the flower isn't watered for two days in a row, it dies. * If the flower ...
for _ in range(int(input())): n = int(input()) lst = [*map(int, input().split())] tall = 1 age = 0 for i in range(n): if i != 0 and lst[i - 1] == 1 and lst[i] == 1: tall += 5 age = 0 elif lst[i] == 1: tall += 1 age = 0 elif lst[...
You are given an array a of length n. Let's define the eversion operation. Let x = a_n. Then array a is partitioned into two parts: left and right. The left part contains the elements of a that are not greater than x (≤ x). The right part contains the elements of a that are strictly greater than x (> x). The order of ...
#include <bits/stdc++.h> #pragma GCC target("avx2") #pragma GCC optimization("O3") #pragma GCC optimization("unroll-loops") using namespace std; long long int expo(long long int a, long long int b, long long int mod) { long long int res = 1; while (b > 0) { if (b & 1) res = (res * a) % mod; a = (a * a) % mo...
A total of n depots are located on a number line. Depot i lies at the point x_i for 1 ≤ i ≤ n. You are a salesman with n bags of goods, attempting to deliver one bag to each of the n depots. You and the n bags are initially at the origin 0. You can carry up to k bags at a time. You must collect the required number of ...
import java.util.*; import java.io.*; import java.math.*; public class Main { // -- static variables --- // static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static int mod = (int) 1000000007; public static void main(S...
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it. Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and ...
#include <bits/stdc++.h> using namespace std; template <class c> struct rge { c b, e; }; template <class c> rge<c> range(c i, c j) { return rge<c>{i, j}; } template <class c> auto dud(c *x) -> decltype(cerr << *x, 0); template <class c> char dud(...); struct debug { template <class c> debug &operator<<(const c ...
Petya has a rooted tree with an integer written on each vertex. The vertex 1 is the root. You are to answer some questions about the tree. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node v is the next vertex on the shortest path from v to the root. ...
#include <bits/stdc++.h> using namespace std; const int maxn = 1000005; int T, n, q; int a[maxn], p[maxn], ans[maxn], ll[maxn], kk[maxn], cnt[maxn], cntcnt[maxn]; vector<int> v[maxn], g[maxn]; set<int> s[maxn]; void dfs(int x, int last) { if (cnt[a[x]] > 0) s[cnt[a[x]]].erase(a[x]); cnt[a[x]]++, cntcnt[cnt[a[x]]]++...
You are given an array of n positive integers a_1, a_2, …, a_n. Your task is to calculate the number of arrays of n positive integers b_1, b_2, …, b_n such that: * 1 ≤ b_i ≤ a_i for every i (1 ≤ i ≤ n), and * b_i ≠ b_{i+1} for every i (1 ≤ i ≤ n - 1). The number of such arrays can be very large, so print it ...
#include <bits/stdc++.h> using namespace std; const int p = 998244353; long long powmod(long long a, long long b) { b %= p - 1; long long r = 1; while (b) { if (b & 1) r = r * a % p; a = a * a % p; b >>= 1; } return r; } long long C(long long n, long long m) { if (n < m) return m; static vecto...
Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese). You are given an integer n. You need to find two integers l and r such that -10^{18} ≤ l < r ≤ 10^{18} and l + (l + 1) + … + (r - 1) + r = n. Input The first line contains a single integ...
import java.util.*; import java.lang.*; import java.math.*; public class Main { public static void main(String args[]) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t > 0) { long n = scn.nextLong(); if(n == 1) { ...
Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers. Let's call a positive number special if it can be written as a sum of different non-negative powers of n. For example, for n = 4 number 17 is special, because...
import bisect import math from collections import deque import heapq mod = 1000000007 N = 200005 def mul(a, b): return (a*b)%mod def add(a, b): return (a+b) if (a+b<mod) else (a+b)-mod def sub(a, b): return (a-b) if (a-b>0) else (a-b)+mod def powr(a, b): ans = 1 while b>0: if b & 1: ans=mul(ans,a) a ...
Theofanis has a string s_1 s_2 ... s_n and a character c. He wants to make all characters of the string equal to c using the minimum number of operations. In one operation he can choose a number x (1 ≤ x ≤ n) and for every position i, where i is not divisible by x, replace s_i with c. Find the minimum number of oper...
#include <bits/stdc++.h> using namespace std; const long long MAX = 900000; const long long MOD = 1000000007; const long long OO = 0x3f3f3f3f; const double EPS = 1e-9; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); long long sum(long long l, long long r) { return (l + r) * (r - l + 1) / 2; } long ...
Theofanis started playing the new online game called "Among them". However, he always plays with Cypriot players, and they all have the same name: "Andreas" (the most common name in Cyprus). In each game, Theofanis plays with n other players. Since they all have the same name, they are numbered from 1 to n. The playe...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class problem1594d { static class Solution { List<Map<Integer, Boolean>> nbr; boolean[] visited; boolean[] assignedHonest; int n; Solution(int n) { ...
It is the easy version of the problem. The difference is that in this version, there are no nodes with already chosen colors. Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem? You have a perfect binary tree of 2^k...
import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; public class cf2 { static PrintWriter out; static int MOD = 1000000007; static FastReader scan; /*-------- I/O using short named function ---------*/ public static String ns()...
It is the hard version of the problem. The difference is that in this version, there are nodes with already chosen colors. Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem? You have a perfect binary tree of 2^k - ...
#include <bits/stdc++.h> using namespace std; const long long N = 100005, Mod = 1000000007; long long Mxdp, n, dp[N]; map<long long, bool> tagged; map<long long, long long> col; char buf[15]; inline long long read() { long long x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ...
Theofanis decided to visit his uncle's farm. There are s animals and n animal pens on the farm. For utility purpose, animal pens are constructed in one row. Uncle told Theofanis that a farm is lucky if you can distribute all animals in all pens in such a way that there are no empty pens and there is at least one conti...
#include <bits/stdc++.h> using namespace std; void mian() { long long s, n, k; cin >> s >> n >> k; cout << (k > s || n / k * 2 * k + n % k <= s && k != s ? "NO\n" : "YES\n"); } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T; cin >> T; while (T--) mian(); return 0; }
Monocarp is playing a computer game. Now he wants to complete the first level of this game. A level is a rectangular grid of 2 rows and n columns. Monocarp controls a character, which starts in cell (1, 1) — at the intersection of the 1-st row and the 1-st column. Monocarp's character can move from one cell to anothe...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long int t, sum, n; cin >> t; while (t--) { sum = 0; cin >> n; string s, s1; cin >> s >> s1; for (int i = 0; i < s.length(); i++) { if (s[i + 1] == '1' &...
n students attended the first meeting of the Berland SU programming course (n is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must b...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e3 + 5; const int mod = 1e9 + 7; int a[1005][5]; void solve() { int n; cin >> n; set<int> st, b[5]; for (int i = 0; i < n; i++) for (int j = 0; j < 5; j++) { cin >> a[i][j]; if (a[i][j] == 1) { st.insert(j); b[j].ins...
Monocarp has got an array a consisting of n integers. Let's denote k as the mathematic mean of these elements (note that it's possible that k is not an integer). The mathematic mean of an array of n elements is the sum of elements divided by the number of these elements (i. e. sum divided by n). Monocarp wants to de...
from __future__ import division, print_function import math import sys import os from io import BytesIO, IOBase #from collections import deque, Counter, OrderedDict, defaultdict #import heapq #ceil,floor,log,sqrt,factorial,pow,pi,gcd #import bisect #from bisect import bisect_left,bisect_right BUFSIZE = 8192 class Fa...
Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams. Monocarp has n problems that none of his students have seen yet. The i-th problem has a topic a_i (an integer from 1 to n) and a difficulty b_i (an integer from 1 to n). All...
import sys input=sys.stdin.readline for t in range(int(input())): n=int(input()) val=(n*(n-1)*(n-2))//6 arr=[[] for i in range(n)] t=[[] for i in range(n)] for i in range(n): a,b=map(int,input().split()) a-=1;b-=1 arr[a].append(b);t[b].append(a) for i in range(n): ...
You are given a matrix, consisting of n rows and m columns. The rows are numbered top to bottom, the columns are numbered left to right. Each cell of the matrix can be either free or locked. Let's call a path in the matrix a staircase if it: * starts and ends in the free cell; * visits only free cells; * ha...
#include <bits/stdc++.h> using namespace std; clock_t time_p = clock(); void time_taken() { time_p = clock() - time_p; cerr << "Time Taken : " << (float)(time_p) / CLOCKS_PER_SEC << "\n"; } const long long mod = 1e9 + 7; const long long INF = 1e18; const int N = 1004; int dp[N][N][2]; int main() { ios_base::sync_...
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: * bracket sequen...
import sys from sys import stdin n = int(stdin.readline()) s = [list(stdin.readline()[:-1]) for i in range(n)] smin = [0] * n smnum = [0] * n h = [0] * n cnts = [{} for i in range(n)] for i in range(n): ts = s[i] nmin = 0 nh = 0 for c in ts: if c == "(": nh += 1 else:...
Let's call a positive integer good if there is no digit 0 in its decimal representation. For an array of a good numbers a, one found out that the sum of some two neighboring elements is equal to x (i.e. x = a_i + a_{i + 1} for some i). x had turned out to be a good number as well. Then the elements of the array a wer...
#include <bits/stdc++.h> using namespace std; const int N = 500000; mt19937 Rand(time(0)); int mod[3]; struct hasher { int a[3]; hasher(int x = 0) { a[0] = a[1] = a[2] = x; } friend hasher operator+(const hasher &a, const hasher &b) { hasher res; for (int i = 0; i < 3; ++i) { res.a[i] = a.a[i] + b.a...
You are given an array A of length N weights of masses A_1, A_2...A_N. No two weights have the same mass. You can put every weight on one side of the balance (left or right). You don't have to put weights in order A_1,...,A_N. There is also a string S consisting of characters "L" and "R", meaning that after putting the...
#include <bits/stdc++.h> using namespace std; const long long N = (long long)2e5 + 7; long long n, a[N]; string s; signed main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n; for (long long i = 1; i <= n; i++) { cin >> a[i]; } sort(a + 1, a + n + 1); vector<long long> speciale, normale; cin >> s;...