input
stringlengths
29
13k
output
stringlengths
9
73.4k
ButCoder Inc. is a startup company whose main business is the development and operation of the programming competition site "ButCoder". There are N members of the company including the president, and each member except the president has exactly one direct boss. Each member has a unique ID number from 1 to N, and the m...
#include <bits/stdc++.h> #define ll long long #define INF 1000000005 #define MOD 1000000007 #define EPS 1e-10 #define rep(i,n) for(int i=0;i<(int)(n);++i) #define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i) #define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i) #define each(a,b) for(auto& (a): (b)) #define all(v) (v).begi...
There are M chairs arranged in a line. The coordinate of the i-th chair (1 ≤ i ≤ M) is i. N people of the Takahashi clan played too much games, and they are all suffering from backaches. They need to sit in chairs and rest, but they are particular about which chairs they sit in. Specifically, the i-th person wishes to...
#include <cstdio> #include <algorithm> #include <iostream> #include <vector> #include <cstring> #include <set> #include <utility> #include <cstdlib> #include <cmath> #include <queue> #include <stack> #include <string> #include <map> #include <cmath> #include <deque> #include <bitset> #include <unordered_map> #define ll...
There are N squares aligned in a row. The i-th square from the left contains an integer a_i. Initially, all the squares are white. Snuke will perform the following operation some number of times: * Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares...
#include <bits/stdc++.h> using namespace std; int main(){ int N, K; cin >> N >> K; vector<int> a(N); for (int i = 0; i < N; i++){ cin >> a[i]; } vector<long long> S1(N + 1, 0); for (int i = 0; i < N; i++){ S1[i + 1] = S1[i] + max(a[i], 0); } vector<long long> S2(N + 1, 0); for (int i = 0; i ...
Snuke lives in another world, where slimes are real creatures and kept by some people. Slimes come in N colors. Those colors are conveniently numbered 1 through N. Snuke currently has no slime. His objective is to have slimes of all the colors together. Snuke can perform the following two actions: * Select a color i ...
#include <iostream> #include <cstdio> using namespace std; typedef long long ll; ll n, m, s, ans, mn[2005], a[2005]; int main() { ll i, j; cin >> n >> m; for (i = 0; i < n; i++) { scanf ("%lld", &a[i]); } for (i = 0; i < n; i++) { mn[i] = 2e9; } for (i = 0; i < n; i++) { s = i * m; for (j = 0; j < n; j+...
There are a total of n x n squares, n rows vertically and n columns horizontally. Some squares are marked. Create a program that reads the marked state of each square and displays the length of the side of the largest square consisting of only the unmarked squares as an output. For example, each dataset is given the f...
import java.util.*; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); while(true) { int n=in.nextInt(); if(n==0)break; int dp[][]=new int[n][n]; for(int i=0;i<n;i++) { String str=in.next(); for(int j=0;j<n;j++) { dp[i][j]=str.charAt(j)=='...
Mr. A loves sweets, but recently his wife has told him to go on a diet. One day, when Mr. A went out from his home to the city hall, his wife recommended that he go by bicycle. There, Mr. A reluctantly went out on a bicycle, but Mr. A, who likes sweets, came up with the idea of ​​stopping by a cake shop on the way to e...
#include <iostream> #include <vector> #include <string> #include <sstream> #include <algorithm> using namespace std; int M,N,K,D; int cal[6]; #define HE (M) #define CH (M+1) #define pb push_back #define INF (1<<24) class Edge { public: int u,v,c; Edge(int u, int v, int c) :u(u),v(v),c(c) {} }; int toNum(strin...
You are a teacher at Iazu High School is the Zuia Kingdom. There are $N$ cities and $N-1$ roads connecting them that allow you to move from one city to another by way of more than one road. Each of the roads allows bidirectional traffic and has a known length. As a part of class activities, you are planning the follow...
#include<bits/stdc++.h> using namespace std; using UL = unsigned int; using ULL = unsigned long long; using LL = long long; #define rep(i, n) for(UL i = 0; i < (n); i++) UL N, Q; UL P[100000][18]; UL D[100000]; UL C[100000]; vector<pair<UL, UL>> E[100000]; UL LCA(UL a, UL b) { if (C[a] < C[b]) swap(a, b); UL d = C[...
Fibonacci number f(i) appear in a variety of puzzles in nature and math, including packing problems, family trees or Pythagorean triangles. They obey the rule f(i) = f(i - 1) + f(i - 2), where we set f(0) = 1 = f(-1). Let V and d be two certain positive integers and be N ≡ 1001 a constant. Consider a set of V nodes, e...
#include<bits/stdc++.h> #define N 1005 #define M 1001 #define P 30 using namespace std; typedef long long ll; int main(){ int v,d; ll f[N]; vector<ll> F; while(cin>>v>>d){ f[0]=f[1]=1; for(int i=2;i<2+v;i++){ f[i]=(f[i-1]+f[i-2])%M; F.push_back(f[i]); } sort(F.begin(),F.end()); ...
ACM University holds its sports day in every July. The "Roll-A-Big-Ball" is the highlight of the day. In the game, players roll a ball on a straight course drawn on the ground. There are rectangular parallelepiped blocks on the ground as obstacles, which are fixed on the ground. During the game, the ball may not collid...
#include<bits/stdc++.h> using namespace std; ///////////////// // 2D geometry // ///////////////// // 2D geometry basic // const double EPS = 1e-8; const double INF = 1e12; typedef complex<double> P; #define X real #define Y imag namespace std { bool operator < (const P& a, const P& b) { return real(a) != real...
Origami is the traditional Japanese art of paper folding. One day, Professor Egami found the message board decorated with some pieces of origami works pinned on it, and became interested in the pinholes on the origami paper. Your mission is to simulate paper folding and pin punching on the folded sheet, and calculate t...
#include <stdio.h> #include <assert.h> #include <iostream> #include <complex> #include <vector> #include <queue> #include <map> #include <algorithm> using namespace std; #define rep(i, n) for(int i=0; i<(int)(n); i++) #define mp make_pair typedef complex<double> P; typedef vector<P> convex; typedef vector<pair<P, int> ...
Problem In 20XX, a scientist developed a powerful android with biotechnology. This android is extremely powerful because it is made by a computer by combining the cells of combat masters. At this rate, the earth would be dominated by androids, so the N warriors decided to fight the androids. However, today's warriors...
#include<iostream> #include <list> #include<stack> #include<queue> #include <vector> #include <set> #include<algorithm> #include<math.h> #include<stdlib.h> #include<string> #include <functional> #include<fstream> #define FOR(k,m,n) for(int (k)=(m);(k)<(n);(k)++) #define LL long long #define CLR(a) memset((a),0,sizeof(...
Lifeguard in the Pool Pool guard English text is not available in this practice contest. Horton Moore works as a pool watchman. As he walked around the edge of the pool to look around, he noticed a girl drowning in the pool. Of course, he must go to rescue immediately. Moreover, it is difficult for the girl to have ...
#include <iostream> #include <cmath> #include <vector> #include <algorithm> #include <queue> using namespace std; inline long double add(long double a, long double b){ return abs(a+b)<(1e-11)*(abs(a)+abs(b)) ? 0.0 : a+b; } struct vec{ long double x,y; vec operator-(vec b){ return (vec){add(x,-b.x...
The volume of access to a web service varies from time to time in a day. Also, the hours with the highest volume of access varies from service to service. For example, a service popular in the United States may receive more access in the daytime in the United States, while another service popular in Japan may receive m...
#include<iostream> #include<vector> #include<algorithm> #include<queue> #include<map> #include<stack> #include<cmath> #include<iomanip> #include<set> #include<numeric> #include<sstream> #include<random> #include<cassert> #include<complex> #include<list> using namespace std; typedef long long ll; #define rep(i, n) for (...
I have a lot of friends. Every friend is very small. I often go out with my friends. Put some friends in your backpack and go out together. Every morning I decide which friends to go out with that day. Put friends one by one in an empty backpack. I'm not very strong. Therefore, there is a limit to the weight of friends...
#include<iostream> #include<algorithm> using namespace std; #define MOD 1000000007 #define MAX_N 210 #define MAX_W 10100 int dp[2][MAX_N][MAX_W]; int N, W, x[MAX_N]; int main() { cin >> N >> W; for (int i = 1; i <= N; i++) { cin >> x[i]; } x[N + 1] = W + 1; sort(x + 1, x + N + 1); dp[1][1][0] = 1; for (int i ...
Problem J: Tree Construction Consider a two-dimensional space with a set of points (xi, yi) that satisfy xi < xj and yi > yj for all i < j. We want to have them all connected by a directed tree whose edges go toward either right (x positive) or upward (y positive). The figure below shows an example tree. <image> Figu...
#include<vector> #include<iostream> #include<algorithm> #include<map> #include<set> #include<queue> #include<string> #include<cctype> #include<cassert> #include<cmath> #include<climits> #define INF (1<<29) #define all(c) (c).begin(),(c).end() #define D(x) cout << #x " is " << (x) << endl #define rep(i,n) for(int i = 0...
Given the string S and m queries. The i-th query is given by the two strings xi and yi. For each query, answer the longest substring of the string S, starting with xi and ending with yi. For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character stri...
#include<stdio.h> #include<algorithm> #include<string> #include<iostream> using namespace std; #define MAX 200005 #define INF (1<<26) int segN=1000000; struct data{ int value; data* ch[2]; void init(){ value=INF; ch[0]=new data; ch[1]=new data; ch[0]->ch[0]=NULL; ...
Problem statement There is a rectangular piece of paper divided in a grid with a height of $ H $ squares and a width of $ W $ squares. The integer $ i \ times W + j $ is written in the cell of the $ i $ line from the top and the $ j $ column from the left counting from $ 0 $. An example of $ H = 2 and W = 3 $ is shown...
#include <iostream> #include <vector> #include <algorithm> using namespace std; using ll = long long; constexpr ll TEN(int n) { return (n == 0) ? 1 : 10LL * TEN(n-1); } using P = pair<int, int>; bool ok(vector<P> v) { for (auto &p: v) { if (p.first > p.second) { swap(p.first, p.second); ...
D: Arrow / Arrow problem rodea is in a one-dimensional coordinate system and stands at x = 0. From this position, throw an arrow of positive integer length that always moves at speed 1 towards the target at x = N. However, rodea is powerless, so we have decided to put a total of M blowers in the section 0 \ leq x \ l...
#include <bits/stdc++.h> using namespace std; #define ALL(x) (x).begin(), (x).end() #define AND(x,y,z) #define DUMP(xs) for (auto x:xs) cout<<x<<' ';cout<<endl #define DUMPP(xs) for (auto x:xs) cout<<'('<<x.first<<','<<x.second<<')';cout<<endl #define FOR(i,a,b) for (ll i=(ll)(a);i<(ll)(b);++i) #define OUT(x) cout<<...
problem Cryptography is all the rage at xryuseix's school. Xryuseix, who lives in a grid of cities, has come up with a new cryptography to decide where to meet. The ciphertext consists of the $ N $ character string $ S $, and the $ S_i $ character determines the direction of movement from the current location. The di...
#include <bits/stdc++.h> using namespace std; using int64 = long long; #define int int64 #define debug(x) cerr<<#x<<":"<<(x)<<endl; signed main() { int n;cin>>n; string s; cin>>s; int x=0,y=0; for(int i=0;i<s.size();++i){ if ('a' <= s[i] && s[i] <= 'm') ++x; if ('n' <= s[i] && s[i] <= 'z') --x; if ...
You have N items that you want to put them into a knapsack. Item i has value vi and weight wi. You want to find a subset of items to put such that: * The total value of the items is as large as possible. * The items have combined weight at most W, that is capacity of the knapsack. Find the maximum total value of i...
#include <bits/stdc++.h> using namespace std; using ll = long long; using P = pair<ll, ll>; int main() { cin.tie(0); ios::sync_with_stdio(false); ll N, W; cin >> N >> W; vector<ll> v(N), w(N); for (int i = 0; i < N; ++i) { cin >> v.at(i) >> w.at(i); } vector<vector<ll> > dp(N ...
Find the intersection of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$. Constraints * $1 \leq n, m \leq 200,000$ * $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$ * $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$ Input The input is given in the following format. $n$ $a_0 \; a_1 \; ....
#include<bits/stdc++.h> #define all(x) (x).begin(),(x).end() using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); set<int> a,b,c; int n,m; int x; cin>>n; for(int i=0;i<n;i++) { cin>>x; a.insert(x); } cin>>m; for(int i=0;i<m;i++) ...
Alice and Johnny are playing a simple guessing game. Johnny picks an arbitrary positive integer n (1 ≤ n ≤ 10^9) and gives Alice exactly k hints about the value of n. It is Alice's task to guess n, based on the received hints. Alice often has a serious problem guessing the value of n, and she's beginning to suspect t...
from collections import Counter minr = 1 maxr = 10 ** 9 + 1 t = int(raw_input()) for i in xrange(t): k = int(raw_input()) cnt = Counter() for j in xrange(k): op, num, ans = raw_input().split() ans = ans.upper() num = int(num) if op == '<': if ans == 'YES': ...
Spring is interesting season of year. Chef is thinking about different things, but last time he thinks about interesting game - "Strange Matrix". Chef has a matrix that consists of n rows, each contains m elements. Initially, the element aij of matrix equals j. (1 ≤ i ≤ n, 1 ≤ j ≤ m). Then p times some element aij is...
n,m,p=map(int,raw_input().split()) b=[] for x in xrange(p): a=map(int,raw_input().split()) b.append(a) b.sort() pos=0 for i in xrange(1,n+1): if b[pos][0]!=i: ans=m-1 else: count=0 prev=0 ans=m-1 while b[pos][0]==i and m!=1: count=count+1 i...
Chef loves games! But he likes to invent his own. Now he plays game "Digit Jump". Chef has sequence of digits S1, S2,..., SN,. He is staying in the first digit (S1) and want to reach the last digit (SN) in the minimal number of jumps. While staying in some digit x with index i (digit Si) Chef can jump into digits with...
import sys s = raw_input().strip() digits = [[] for i in xrange(10)] dist = [-1] * (len(s)) used = [False] * 10 for i in xrange(len(s)): digits[int(s[i])].append(i) dist[0] = 0 q = [0] while True: v = q.pop(0) cur = dist[v] if v == len(s)-1: print cur sys.exit() if cur ...
In the hidden country of Lapatrecta, an age old custom was followed to ensure that no outsider ever entered their country undetected. The security measure, though simple, was an effective one. Every person born in Lapatrecta had the initials of all his forefathers included in front of his name. Every once in a while, c...
N = int (raw_input()) words = [] maxDep = 0 def dfs(dic, depth): global maxDep if dic['__a'] > 1: if depth > maxDep: maxDep = depth for key in dic.keys(): if key!='__a': if dic[key]['__a'] > 1: dfs(dic[key], depth+1) dic = {} dic['__a'] = 0 for ...
NITMAS Fest is live. The members of the community are very busy. People from different colleges have come to compete. But, Naveen is very possessive about his girlfriend, Archana. He always remains close to his girlfriend. Couples (boys in a line and girls in another) have to stand in different rows in a line for a gam...
a=list(map(int,raw_input().split())) b=list(map(int,raw_input().split())) arr=[] for i in range(1,len(a)): for j in range(1,len(b)): arr.append(abs(a[i]-b[j])) arr=sorted(arr) print arr[0]
p { font-size:14px; text-align:justify; } Two positive integers n amd m, n greater than or equal to m, will be given as input. Make a code that generates all possible combinations of 1,2,3,...,n taking m integers at a time in "increasing order". Comparison between two combinations: a1,a2,a3,...,am b1,b2,b3,...,bm ...
import itertools n = int(raw_input()) m = int(raw_input()) ls = range(1, n + 1) op = list(itertools.combinations(ls, m)) for t in op: for x in t: print x, print
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. Ther...
t=int(input()) pre=[] curr=[] for i in range(t): s1=input() pre.append(s1) for i in range(t): s2=input() curr.append(s2) z=0 for i in range(t): if pre[i] in curr: curr.remove(pre[i]) pass else: z+=1 print(z)
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers. For a given list of pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) their WCD is arbit...
import java.util.*; import java.util.stream.*; import java.io.*; import java.math.*; public class Main { static boolean FROM_FILE = false; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { if (FROM_FILE) { t...
In the intergalactic empire Bubbledom there are N planets, of which some pairs are directly connected by two-way wormholes. There are N-1 wormholes. The wormholes are of extreme religious importance in Bubbledom, a set of planets in Bubbledom consider themselves one intergalactic kingdom if and only if any two planets ...
#include <bits/stdc++.h> using namespace std; const int N = 100010; int n; double p[N]; vector<int> adj[N]; int par[N]; double sum[N]; void dfs(int u, int pa) { par[u] = pa; for (int v : adj[u]) { if (v == pa) { continue; } dfs(v, u); sum[u] += (1. - p[v]); } } double preCalc() { double re...
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally: a_{1} ≤ a_{2}, a_{n} ≤ a_{n-1} and a_{i} ≤ max(a_{i-1}, ...
#include <bits/stdc++.h> using namespace std; const long long N = 2e5 + 5, inf = 1e18, mod = 998244353; long long n, dp[2][202][2], ps[2][202][2], a[N], PS[2][202][2]; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); dp[0][0][1] = 1; for (long long j = 0; j <= 200; j++) ps[0][j][1] = 1; cin >> n; ...
Santa has prepared boxes with presents for n kids, one box for each kid. There are m kinds of presents: balloons, sweets, chocolate bars, toy cars... A child would be disappointed to receive two presents of the same kind, so all kinds of presents in one box are distinct. Having packed all the presents, Santa realized ...
#include <bits/stdc++.h> using namespace std; const int maxn = 100005; pair<int, int> qq[maxn]; int q[maxn], s, o[maxn]; set<int> w[maxn], z; vector<pair<pair<int, int>, int> > r; int main() { int n, m, a, b, qa, qb; ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 0; i < n...
One fine day Sasha went to the park for a walk. In the park, he saw that his favorite bench is occupied, and he had to sit down on the neighboring one. He sat down and began to listen to the silence. Suddenly, he got a question: what if in different parts of the park, the silence sounds in different ways? So it was. Le...
#include <bits/stdc++.h> using namespace std; const int N = 1000005; namespace LCT { struct TNode { int ch[2], f; bool r; }; TNode t[N]; inline bool isroot(int pos) { return t[t[pos].f].ch[0] != pos && t[t[pos].f].ch[1] != pos; } inline void pushdown(int pos) { if (t[pos].r) { t[pos].r = 0; t[t[pos].ch[...
You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will...
#include <bits/stdc++.h> using namespace std; long long mod = 1000000007; vector<vector<int> > v(100001); vector<int> vis(100001); long long binpow(long long a, long long b) { long long res = 1; while (b > 0) { if (b & 1) res = (res * a) % mod; a = (a * a) % mod; b >>= 1; } return res % mod; } int d...
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2). You are given a sequence a consisting of n integers. You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the...
import java.util.Scanner; public class C1157 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int[] A = new int[N]; for (int n=0; n<N; n++) { A[n] = in.nextInt(); } StringBuilder output = new StringBui...
We call a function good if its domain of definition is some set of integers and if in case it's defined in x and x-1, f(x) = f(x-1) + 1 or f(x) = f(x-1). Tanya has found n good functions f_{1}, …, f_{n}, which are defined on all integers from 0 to 10^{18} and f_i(0) = 0 and f_i(10^{18}) = L for all i from 1 to n. It's...
#include <bits/stdc++.h> using namespace std; long long query(int i, long long x) { cout << "? " << i + 1 << ' ' << x << endl; long long r; cin >> r; return r; } pair<long long, long long> ans[1000]; mt19937_64 mrand(chrono::steady_clock::now().time_since_epoch().count()); double log_fac[2000]; double log_ncr(i...
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} ...
#include <bits/stdc++.h> using namespace std; const long long N = 4e5 + 5; long long a[N]; void solve() { int n; long long I; cin >> n >> I; for (int i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); long long k = (8 * I) / n; long long K = pow(2ll, min(20ll, k)); vector<long long> v; vector<long long> ...
The new pedestrian zone in Moscow city center consists of n squares connected with each other by n - 1 footpaths. We define a simple path as a sequence of squares such that no square appears in this sequence twice and any two adjacent squares in this sequence are directly connected with a footpath. The size of a simple...
#include <bits/stdc++.h> using namespace std; int n, k, root, d[200005], h[200005], res[200005]; vector<int> a[200005]; void dfs(int u, int p) { int tmp = 0; for (int i = 0; i < (int)a[u].size(); i++) { int v = a[u][i]; if (v == p) continue; d[v] = d[u] + 1; dfs(v, u); tmp = max(tmp, h[v]); } ...
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters. The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let'...
import sys def input(): str = sys.stdin.readline() return str[:-1] def unique(x, first, last): if first == last: return last result = first while first + 1 != last: first += 1 if(x[result] != x[first]): result += 1 x[result] = x[first] return resul...
There is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecuti...
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 Main { InputStream is; PrintWriter out; String INPUT = ""; private static final long M = 1000000007L; void solv...
Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can ...
import java.math.*; import java.io.*; import java.util.*; public class CNew { StringTokenizer st; BufferedReader in; PrintWriter ob; public static void main(String args[])throws IOException { new CNew().run(); } void run()throws IOException { in=new BufferedReader(new InputStreamReader(System.in)); ob=ne...
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said: —Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes....
#include <bits/stdc++.h> using namespace std; long long n, m, i, j; int a[50], x; char b[50]; bool f; int main() { cin >> n; i = 1; while (n > 0) { a[i] = n % 10; n = n / 10; i++; } sort(a + 1, a + i); if (a[1] == 0) { for (j = 2; j < i; j++) { if (a[j] > 0) { swap(a[1], a[j]);...
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realiz...
#include <bits/stdc++.h> using namespace std; const int N = 4e5 + 5; int a[N], t[N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; int ans = 0; for (int i = 0; i < n; i++) cin >> a[i]; for (int k = 0; k <= 24; k++) { for (int i = 0; i < n; i++) t[i] = a[i] % (1...
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i ≤ x ≤ r_i, and ((x mod a) mod b) ≠ ((x mod b) mod a). Calculate the answer for each query. Recall that y mod z is the remainder of the division of y by z...
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) t = int(input()) for i in range(t): a, b, q = map(int, input().split()) mi = min(a, b) ma = max(a, b) for j in range(q): l, r = map(int, input().split()) l = max(l, ma) if a == b or mi == 1 or...
Given an array a of length n, find another array, b, of length n such that: * for each i (1 ≤ i ≤ n) MEX(\\{b_1, b_2, …, b_i\})=a_i. The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set. If such array doesn't exist, determine this. Input The first line contains an ...
n=int(input()) arr=list(map(int,input().split())) flag=0 vis=[0]*(10**6+1) for i in range(n): if arr[i]>i+1: flag=1 vis[arr[i]]=1 if flag==1: print(-1) quit() b=[-1]*(n) for i in range(1,n): if arr[i-1]!=arr[i]: b[i]=arr[i-1] not_vis=[] for i in range(10**6+1): if vis[i]==0: ...
Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of...
from math import inf as inf from math import * from collections import * import sys import os input=sys.stdin.readline for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) b=[0]*31 fl="DRAW" for i in a: z=bin(i)[2:] z=z.zfill(31) for j in range(31): ...
Given a set of integers (it can contain equal elements). You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B). Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: * m...
t=int(input()) while t!=0: t-=1 n=int(input()) li=list(map(int,input().split())) dic={} dic2={} a=0 b=0 flag=0 ans=[0]*101 for i in li: if i not in dic and i not in dic2: dic[i]=1 else: ans[i]=1 dic2[i]=1 if i in dic...
You like playing chess tournaments online. In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 ...
#include <bits/stdc++.h> using namespace std; const long long md = 1e9 + 7; int an[310000]; char sn[310000]; int main() { int z; int n, m; int i, j, k; cin >> z; while (z--) { scanf("%d%d", &n, &k); scanf("%s", sn); bool flag = 1; int first, last; for (i = 0; i < n; i++) { if (sn[i] ...
You have n distinct points (x_1, y_1),…,(x_n,y_n) on the plane and a non-negative integer parameter k. Each point is a microscopic steel ball and k is the attract power of a ball when it's charged. The attract power is the same for all balls. In one operation, you can select a ball i to charge it. Once charged, all ba...
#include<bits/stdc++.h> using namespace std; int main() { long long a,b,c,d,e,f,g,h,i,j,k,l,m,n,x,y,z,t; cin>>t; while(t--) { cin>>a>>b; pair<long long,long long>pp[a+1]; map<long long,long long>mp[a+1]; for(i=1; i<=a; i++) { cin>>c>>d; p...
Consider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged. The road is constructed as follows: * the first row consist...
#include<bits/stdc++.h> //#define int long long #define ll long long #define p pair<int, int> #define endl '\n' const int INF = 1000000001; using namespace std; const int C = 998244353; vector<ll> fact, minus_fact; ll pow1(ll x, ll y, ll z=C){ if (y == 0){ return 1; } if (y % 2 == 0){ ret...
Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" — you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored...
import java.util.Scanner; public class Solution { private final static String voc = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static int[] toArray(String s) { while (s.length() > 1 && s.charAt(0) == '0') s = s.substring(1); int[] a = new int[s.length()]; for (int i = 0; i < a.le...
<image> While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from a_1, a_2, …, a_n to -a_1, -a_2, …, -a_n...
import os import sys from io import BytesIO, IOBase from collections import Counter import math as mt BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode ...
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
n=int(input()) a=list(map(int,input().split())) c=[] d=0 c.append(a[0]) for i in range(1,n): y=a[i]-a[i-1] if y>0 and a[i]>max(c): c.append(a[i]) d+=1 elif y<0 and a[i]<min(c): c.append(a[i]) d+=1 print(d) #print(c)
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friends...
#include <bits/stdc++.h> using namespace std; const long long N_max = 0; class graph { private: long long V; long long k, m; vector<pair<long long, long long>> L; vector<pair<long long, long long>> L2; public: graph(long long n) { V = n; } void add_edge(long long u, long long v) { L.push_back({u, v}); } ...
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon. The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some...
#include <bits/stdc++.h> using namespace std; int f[200000][3], N, K; char s1[200000], s2[200000]; bool ok; inline void dfs(int x, int y) { if (ok) return; int Nxt = x + K; if (Nxt > N) { ok = 1; return; } if (y == 1) { if (s2[Nxt] == '-' && f[x][1] + 1 < f[Nxt][2] && Nxt > f[x][1] + 1) { f[...
The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could ...
#include <bits/stdc++.h> using namespace std; void swap(int &x, int &y) { int t = x; x = y; y = t; } int main() { int n; cin >> n; int *p = new int[n]; vector<int> k; for (int i = 0; i < n; i++) { cin >> p[i]; k.push_back(p[i]); } sort(k.begin(), k.end()); int count = 0; for (int i = 0; ...
Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation. For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative ...
#include <bits/stdc++.h> using namespace std; int n; void EXEC() { cin >> n; for (int i = 0; i < n; ++i) { int s = 0; int t; for (int j = 0; j < n; ++j) { cin >> t; if (t != -1) s |= t; } cout << s << ' '; } cout << endl; } int main() { EXEC(); return 0; }
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages. Recent actions shows a list of n different threads ordered by the time of the latest message in the thread....
import java.util.Scanner; public class B270 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int[] A = new int[N]; for (int n=0; n<N; n++) { A[n] = in.nextInt(); } int pos = N-1; while (pos > 0...
Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles. Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the ...
#include <bits/stdc++.h> using namespace std; struct Point { int x, y; Point() {} Point(int x, int y) { this->x = x; this->y = y; } Point operator+(Point rhs) { return Point(x + rhs.x, y + rhs.y); } Point operator-(Point rhs) { return Point(x - rhs.x, y - rhs.y); } long long Dot(Point rhs) { retur...
It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x ...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; public class B { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] parts = br.rea...
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear a...
#include <bits/stdc++.h> using namespace std; const int max_n = 1e5 + 100; int t[4 * max_n]; int n; int max_on_seg(int v, int tl, int tr, int l, int r) { if (tl == l && tr == r) return t[v]; int m = (tl + tr) >> 1; if (r <= m) return max_on_seg(2 * v, tl, m, l, r); if (l > m) return max_on_seg(2 * v + 1, m + 1,...
John Doe offered his sister Jane Doe find the gcd of some set of numbers a. Gcd is a positive integer g, such that all number from the set are evenly divisible by g and there isn't such g' (g' > g), that all numbers of the set are evenly divisible by g'. Unfortunately Jane couldn't cope with the task and John offered...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e6 + 10; long long a[MAXN], d[MAXN], cnt[MAXN], ans, n, siz; void cut(long long x) { siz = 0; for (long long i = 1; i * i <= x; i++) { if (x % i == 0) { d[++siz] = i; if (x != i * i) d[++siz] = x / i; } } memset(cnt, 0, sizeof(c...
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom o...
import java.io.*; import java.util.*; public class P388C { public static StringTokenizer st; public static void nextLine(BufferedReader br) throws IOException { st = new StringTokenizer(br.readLine()); } public static String next() { return st.nextToken(); } pu...
Two teams meet in The Game World Championship. Some scientists consider this game to be the most intellectually challenging game in the world. You are given two strings describing the teams' actions in the final battle. Figure out who became the champion. Input The input contains two strings of equal length (between ...
import java.util.*; import static java.lang.System.out; import static java.lang.Math.*; public class T { public static void main(String... args) { Scanner in = new Scanner(System.in); String s1 = in.next(); String s2 = in.next(); int score = 0; for (int i = 0; i < s1.length()-1; i+=2) { String t1 = s1.su...
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. <image> The park can be represented as a rectangular n × m field. The park has k spiders, each spider at ...
import java.util.Arrays; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Comparator; import java.io.IOException; import java.util.StringTokenizer; import java.math.*; import java.util.*; public class ...
Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrang...
#include <bits/stdc++.h> using namespace std; template <typename T, size_t N> int SIZE(const T (&t)[N]) { return N; } template <typename T> int SIZE(const T &t) { return t.size(); } string to_string(const string s, int x1 = 0, int x2 = 1e9) { return '"' + ((x1 < s.size()) ? s.substr(x1, x2 - x1 + 1) : "") + '"'; ...
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measure...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer...
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Solution_505B { public static boolean[][][] colorMatrix; public static boolean[] used; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStr...
Polycarpus has a finite sequence of opening and closing brackets. In order not to fall asleep in a lecture, Polycarpus is having fun with his sequence. He is able to perform two operations: * adding any bracket in any position (in the beginning, the end, or between any two existing brackets); * cyclic shift — mov...
#include <bits/stdc++.h> using namespace std; const int maxn = 1000047; char s[maxn]; int n; vector<int> utried() { vector<int> lepsich(n); vector<int> por; int otv = 0; for (int i = 0; i < n; i++) { if (s[i] == '(') { por.push_back(i); lepsich[i] = 0; otv++; } } for (int i = 0; i ...
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i...
import sys factorials = [1] def newton(n, k): global factorials return factorials[n] / (factorials[k] * factorials[n - k]) def solve(x): if len(x) == 1: return 1 last = x.pop() - 1 n = sum(x) + last k = last return (solve(x) * newton(n, k)) % 1000000007 def preprocess(): for i in xrange(1, 1001)...
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend t...
n, d = map(int, raw_input().split()) friends = {} for _ in range(n): a,b = map(int, raw_input().split()) if a not in friends: friends[a] = 0 friends[a] += b friends = sorted([(k,friends[k]) for k in friends], key = (lambda x: x[0])) # import pudb;pu.db max_res = 0 start, end = 0,0 while end != len(...
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers. Input The first line of the input con...
# print ("Input digits and base for number one") n1, b1 = (int(x) for x in input().split()) # print ("Input all the digits") d1 = list(int(x) for x in input().split()) d1.reverse() # print ("Input digits and base for number two") n2, b2 = (int(x) for x in input().split()) # print ("Input all the digits") d2 = list(int...
You are given array ai of length n. You may consecutively apply two operations to this array: * remove some subsegment (continuous subsequence) of length m < n and pay for it m·a coins; * change some elements of the array by at most 1, and pay b coins for each change. Please note that each of operations may b...
#include <bits/stdc++.h> using namespace std; const long long INF = 3000000000000000000LL; long long dp[1000001][3]; void pf(long a, set<long long> &s) { long long i; for (i = 2; i * i <= a; ++i) { if (a % i == 0) { s.insert(i); while (a % i == 0) a /= i; } } if (a > 1) s.insert(a); } int ma...
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be n interesting minutes t1, t2, ..., tn. Yo...
line1 = raw_input() line2 = raw_input() data = line2.split(' ') def get_minute(data): temp = 0 for minute in data: if temp + 15 >= 90: return 90 if int(minute) - temp > 15: return temp + 15 temp = int(minute) return temp+15 if temp+15 < 90 else 90 prin...
A tree is an undirected connected graph without cycles. Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is cons...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.FileInputStream; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solu...
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room. Anatoly just made all his cockroaches to form a single line. As he is a perfectioni...
#include <bits/stdc++.h> using namespace std; const int maxn = 3e6 + 5; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; string s; cin >> n >> s; int swap[2] = {0}; int color[2][2] = {0}; for (int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] == 'r') color[0][0] += 1; if (i ...
Vasya plays the Plane of Tanks. The tanks in this game keep trying to finish each other off. But your "Pedalny" is not like that... He just needs to drive in a straight line from point A to point B on the plane. Unfortunately, on the same plane are n enemy tanks. We shall regard all the tanks as points. At the initial ...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); double ax, ay, bx, by; double dis(double x, double y) { return sqrt(x * x + y * y); } double get(double a, double w) { double v = 0; int num = 100; for (int i = 0; i <= 100; i++) { double x = ax + (bx - ax) * i / (double)num; doub...
Little Timofey has a big tree — an undirected connected graph with n vertices and no simple cycles. He likes to walk along it. His tree is flat so when he walks along it he sees it entirely. Quite naturally, when he stands on a vertex, he sees the tree as a rooted tree with the root in this vertex. Timofey assumes tha...
#include <bits/stdc++.h> using namespace std; const int MOD = (int)1e9 + 7; const int INF = (int)1e9; const long long LINF = (long long)1e18; const long double PI = acos((long double)-1); const long double EPS = 1e-9; inline long long gcd(long long a, long long b) { long long r; while (b) { r = a % b; a = b...
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, .... <image> The Monster will catch them if at any point they scream at the same tim...
import java.util.Scanner; public class A787 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int a = s.nextInt(); int b = s.nextInt(); int c = s.nextInt(); int d = s.nextInt(); boolean[] reached = new boolean[20000]; int k = 0; while (b + k * a < 20000) { reached[b...
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market. This morning, as us...
#include <bits/stdc++.h> const int N = 1e5; long long w[N]; long long c[N]; std::vector<std::pair<long long, int> > items; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); int n, m; std::cin >> n >> m; for (int i = 0; i < n; ++i) { std::cin >> w[i] >> c[i]; items.push_back(std::mak...
<image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's s...
#include <bits/stdc++.h> using namespace std; long long r; bool is_perfect_cube(long long n) { r = (long long)round(cbrt(n)); if (r * r * r == n) return true; return false; } int main() { int T; scanf("%d", &T); while (T--) { int a, b; scanf("%d %d", &a, &b); if (is_perfect_cube((long long)a * b...
Michael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs. Michael's day starts from charging his electric car for getting to the work and back. He spends 1000 burles on charge if he goes to the first job, and 2000 burles if ...
#include <bits/stdc++.h> using namespace std; const int MOD = (int)1e9 + 7; const int MOD2 = 1007681537; const int INF = (int)1e9; const long long LINF = (long long)1e18; const long double PI = acos((long double)-1); const long double EPS = 1e-9; inline long long gcd(long long a, long long b) { long long r; while (...
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai. Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in ...
#include <bits/stdc++.h> using namespace std; int main() { int n, k, b; scanf("%d%d%d", &n, &k, &b); stack<pair<int, int> > st; long long ans = (long long)n * b; for (int i = 0, a; i < n; i++) { scanf("%d", &a); if (st.size() && st.top().first == a) { st.top().second++; if (st.top().second...
You are given a connected undirected graph with n vertices and m edges. The vertices are enumerated from 1 to n. You are given n integers c1, c2, ..., cn, each of them is between - n and n, inclusive. It is also guaranteed that the parity of cv equals the parity of degree of vertex v. The degree of a vertex is the n...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; const int M = N * 25; int n, m; long long C[M], x, y, tar[N], dep[N], in[M]; int fir[N], ne[M], to[M], cnt = 1, fa[N], fan[N]; void add(int x, int y) { ne[++cnt] = fir[x]; fir[x] = cnt; to[cnt] = y; } void link(int x, int y) { add(x, y); add...
There is a rectangular grid of n rows of m initially-white cells each. Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and...
def main(): res,car=map(long,raw_input().split()) k=[] p=[] for i in xrange(res): p.append(raw_input()) ms=set(p) for i in ms: for cer,ver in enumerate(i): if ver=="#": k.append(cer) gs=set(k) for i in gs: if k.count(i)>1: ...
Everybody knows of [spaghetti sort](https://en.wikipedia.org/wiki/Spaghetti_sort). You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you... You come up with...
n = int(input()) l = [int(x) for x in input().split()] while len(l) > 1: if len([i for i in range(len(l)-1) if abs(l[i] - l[i+1]) > 1 ])>0: print ('NO') exit(0) l.remove(max(l)) print('YES')
Kuro has recently won the "Most intelligent cat ever" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games. Kuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot o...
#include <bits/stdc++.h> int c[50 + 5], f[50 + 5][50 + 5][50 + 5], C[50 + 5][50 + 5], F[50 + 5][2], p[50 + 5]; inline void rw(int& x, int y) { if ((x += y) >= 1000000007) x -= 1000000007; } int main() { int n, m, i, j, k, l, x, ans = 0; scanf("%d%d", &n, &m); for (i = 1; i <= n; ++i) scanf("%d", &c[i]); f...
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j. There are k ⋅ n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained b...
#include <bits/stdc++.h> using namespace std; int n, k; int joy[15]; int dp[505][5005]; int solve(int play, int cards) { for (int i = 0; i <= play; i++) for (int j = 0; j <= cards; j++) dp[i][j] = 0; for (int i = 1; i <= play; i++) for (int j = 1; j <= cards; j++) for (int l = 1; l <= min(k, j); l++) ...
Yesterday, Benny decided to buy something from a television shop. She created a list that consisted of small description of N orders. The description for an order number i is a string Si. The description may consist of uppercase/lowercase Latin letters, digits and a '$' sign. But, every time after the sign '$', Benny...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' import re import sys n = int(raw_input()) for i in range(n): str1 = raw_input() dollar = "$" space = " " str2 = str1.split(dollar)[1] str2="".join(str2.split()) l=[] sys.stdout....
You are converting an old code for a new version of the compiler. In the old code we have used "->" for pointers. But now we have to replace each "->" with a ".". But this replacement shouldn't be done inside commments. A comment is a string that starts with "//" and terminates at the end of the line. Input: At max...
while(True): try: str=raw_input() except: break new="." old="->" x=str.find("//") if(x==-1): print str.replace(old,new) else: print str[:x].replace(old,new)+str[x:]
Tapan and Divya have a rectangular shaped chocolate bar with chocolates labeled T, D and U. They want to split the bar into exactly two pieces such that: Tapan's piece can not contain any chocolate labeled D and similarly, Divya's piece can not contain any chocolate labeled T. All chocolates in each piece must be conn...
n,m,s=map(int,raw_input().split()) lst=[] for _ in range(n): lst.append(raw_input()) fac=n*m if n==1:print (2*m-1) elif m>=8: print n elif lst[0]!=lst[1]:print (n*m*fac-n*m) else:print (n*m*fac-fac)
Ikshu and his class Ikshu's class is very fond of playing games. Their teacher tied them with many ropes with each other, Such that each student is tied with exactly one rope. It means that if students 2 and 3 are connected and 2 is connected to 4 as well then 2,3 and 4 must be sharing the same rope. Now, teacher ask...
class DisjointSet(object): def __init__(self): self.leader = {} # maps a member to the group's leader self.group = {} # maps a group leader to the group (which is a set) def add(self, a, b): leadera = self.leader.get(a) leaderb = self.leader.get(b) if leadera is not Non...
Our friend Monk has an exam that has quite weird rules. Each question has a difficulty level in the form of an Integer. Now, Monk can only solve the problems that have difficulty level less than X . Now the rules are- Score of the student is equal to the maximum number of answers he/she has attempted without skipping a...
n, x = map(int, raw_input().split()) new_a = map(int, raw_input().split()) count = 0 skip = 0 for i in range(n): if(new_a[i] <= x and skip <= 1): count = count + 1 if(new_a[i] > x): skip = skip + 1 print count
Vicky, the Artist, had two lists A and B, such that B was a permutation of A. Vicky was very proud of these lists. Unfortunately, while transporting them from one exhibition to another, some numbers were left out of A. Can you find the missing numbers? If a number occurs multiple times in the lists, you must ensure tha...
n=input() a=map(int,raw_input().split()) m=input() b=map(int,raw_input().split()) a=sorted(a) b=sorted(b) i=0 j=0 ans=[] while i<len(a): if (a[i]==b[j]): i+=1 j+=1 else: if (len(ans)==0 or ans[-1]!=b[j]): ans.append(b[j]) j+=1 if (j!=len(b) and (len(ans)==0 or ans[-1]!=b[j])): ans.append(b[j]) for x in an...
There are N bikers present in a city (shaped as a grid) having M bikes. All the bikers want to participate in the HackerRace competition, but unfortunately only K bikers can be accommodated in the race. Jack is organizing the HackerRace and wants to start the race as soon as possible. He can instruct any biker to move ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' from sys import stdin import math from operator import indexOf def dist(a,b): return (((a[0]-b[0])*(a[0]-b[0])+((a[1]-b[1])*(a[1]-b[1])))) def main(): ...
The Mad King arrested Shil's comrades for participating in a rebellion against the King. Instead of punishing them with death, the King decided to play the Game of survival with them. The game is played as follows: All the N people are forced to stand in a line. Now the king randomly chooses any two persons standi...
n=input() a=map(int,raw_input().split()) i=a.index(max(a)) c=[i] l1=a[:i] l2=a[i+1:] max2=l2[-1] for x in xrange(n-i-2,-1,-1): if l2[x]>=max2: max2=l2[x] c.append(i+1+x) max=l1[0] for y in range(i): if l1[y]>=max: c.append(y) max=l1[y] for j in sorted(c): print j+1, else:print
Big Chandan is a dire lover of Biryani, especially Old Monk's Biryani. Today, he went over to have some of it. To his surprise, the waiter turns out be to be a coding geek and refuses to serves him unless Chandu solves his two- arrays problem, stated as: Given two non-increasing array of integers A,B i.e A[i] ≥ A[i...
'''def findMaxMonkiness(A, al, ah, B, bl, bh): if (al<ah) | (bl<bh): print(al) print(bl) print(ah) print(bh) amid=(al+ah)/2 bmid=(bl+bh)/2 if A[amid]<B[bmid]: print('less') print(amid) print(bmid) return ((findMa...
You are given a sequence A_1, A_2, ..., A_N and an integer K. Print the maximum possible length of a sequence B that satisfies the following conditions: * B is a (not necessarily continuous) subsequence of A. * For each pair of adjacents elements of B, the absolute difference of the elements is at most K. Constraint...
import typing class SegTree: def __init__(self, op: typing.Callable[[typing.Any, typing.Any], typing.Any], e: typing.Any, v: typing.Union[int, typing.List[typing.Any]]): self._op = op self._e = e if isinstance(v, int): v = [e] *...
Takahashi and Snuke came up with a game that uses a number sequence, as follows: * Prepare a sequence of length M consisting of integers between 0 and 2^N-1 (inclusive): a = a_1, a_2, \ldots, a_M. * Snuke first does the operation below as many times as he likes: * Choose a positive integer d, and for each i (1 \leq ...
#include <bits/stdc++.h> #define debug(...) fprintf(stderr, __VA_ARGS__) #ifndef AT_HOME #define getchar() IO::myGetchar() #define putchar(x) IO::myPutchar(x) #endif namespace IO { static const int IN_BUF = 1 << 23, OUT_BUF = 1 << 23; inline char myGetchar() { static char buf[IN_BUF], *ps = buf, *pt = buf; if...
Given are three integers N, K, and S. Find a sequence A_1, A_2, ..., A_N of N integers between 1 and 10^9 (inclusive) that satisfies the condition below. We can prove that, under the conditions in Constraints, such a sequence always exists. * There are exactly K pairs (l, r) of integers such that 1 \leq l \leq r \leq...
n, k, s = map(int, input().split()) if s == 10**9: ans = [10**9]*k+[1]*(n-k) else: ans = [s]*k+[s+1]*(n-k) print(*ans)