input
stringlengths
29
13k
output
stringlengths
9
73.4k
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n. Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. So his recent chat list can be represented wit...
#include <bits/stdc++.h> char _; using namespace std; void PRINT(int x, int y) { for (int i = y - 1; i >= 0; i--) { cout << ((0u == (x & (1 << i))) ? 0u : 1u); } cout << endl; } vector<string> vec_splitter(string s) { s += ','; vector<string> res; while (!s.empty()) { res.push_back(s.substr(0, s.fin...
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≀ t ≀ 1000) β€” the ...
t=int(input()) for _ in range(t): n,k=map(int,input().split()) if k%(n-1)==0: temp=k//(n-1) print(n*(temp-1)+n-1) else: temp=k//(n-1) print(n*temp+k%(n-1))
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar! An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≀ x,y,z ≀ n), a_{x}+a_{y} β‰  a_{z} (not necessarily distinct). You are given one integer ...
t=int(input()) for i in range(0,t): n=int(input()) L=[1]*n print(*L)
No matter what trouble you're in, don't be afraid, but face it with a smile. I've made another billion dollars! β€” Boboniu Boboniu has issued his currencies, named Bobo Yuan. Bobo Yuan (BBY) is a series of currencies. Boboniu gives each of them a positive integer identifier, such as BBY-1, BBY-2, etc. Boboniu has a ...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1, c = getchar(); while (c < 48) c == '-' && (f = -1), c = getchar(); while (c > 47) x = x * 10 + c - '0', c = getchar(); return x * f; } const int MAXN = 100005; std::vector<int> adj[MAXN]; int s[MAXN], c[MAXN], q[MAXN]; int n, cn...
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large). Killjoy's account is already infected and has a rating equal to x. Its rating is constant. There are n accounts except hers, number...
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code70 { public static void main(String[] args) { InputReader in = new InputReader(System....
Chef Monocarp has just put n dishes into an oven. He knows that the i-th dish has its optimal cooking time equal to t_i minutes. At any positive integer minute T Monocarp can put no more than one dish out of the oven. If the i-th dish is put out at some minute T, then its unpleasant value is |T - t_i| β€” the absolute d...
from sys import stdin, stdout t=int(stdin.readline()) for _ in range(t): n=int(stdin.readline()) arr=list(map(int,stdin.readline().split())) arr.sort() dp=[[10**9 for _ in range(2*n)] for _ in range(n)] for i in range(0,n): for j in range(1,2*n): if i==0: dp[i][j]=min(dp[i][j-1],abs(arr[i]-j)) else: ...
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows: * he wrote the number a_1 to the left side (at the beginning of the whiteboard); * he wrote the number a_2 to the right side (at the end of the whiteboard); * then as far to the left as possible ...
#include <bits/stdc++.h> using namespace std; #define IO ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0); #define int long long #define double long double #define vi vector<int> #define vvi vector<vi> #define pii pair<int, int> #define vii vector<pii> #de...
Suppose you are living with two cats: A and B. There are n napping spots where both cats usually sleep. Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically: * Cat A changes its napping place in order: n, n - 1, n - 2, ..., 3, 2, 1, n, n - 1, ... In other words, a...
def main(): t = int(input()) for _ in range(t): n, k = list(map(int, input().split())) k -= 1 if n % 2 == 0: print(k % n + 1) else: med = int(n*0.5) print((k+int((k/med)))%n+1) main()
Joseph really likes the culture of Japan. Last year he learned Japanese traditional clothes and visual arts and now he is trying to find out the secret of the Japanese game called Nonogram. In the one-dimensional version of the game, there is a row of n empty cells, some of which are to be filled with a pen. There is ...
#pragma GCC optimize("-Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") // #include <atcoder/all> // #include <bits/stdc++.h> #include <complex> #include <queue> #include <set> #include <unordered_set> #include <list> #include <chrono> #include <ra...
You are given two integers a and b. In one turn, you can do one of the following operations: * Take an integer c (c > 1 and a should be divisible by c) and replace a with a/c; * Take an integer c (c > 1 and b should be divisible by c) and replace b with b/c. Your goal is to make a equal to b using exactly k ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class Main{ static FastReader fs=new FastReader(); static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ ...
You are given n points on the plane. You need to delete exactly k of them (k < n) so that the diameter of the set of the remaining n - k points were as small as possible. The diameter of a set of points is the maximum pairwise distance between the points of the set. The diameter of a one point set equals zero. Input ...
#include <bits/stdc++.h> using namespace std; class Edge { public: int v, u, d; Edge(int _v, int _u, int _d) : v(_v), u(_u), d(_d) {} const bool operator<(const Edge &b) const { return d < b.d; } }; class Coor { public: int x, y; Coor() {} Coor(int _x, int _y) : x(_x), y(_y) {} Coor &operator-=(const Co...
Imagine the Cartesian coordinate system. There are k different points containing subway stations. One can get from any subway station to any one instantly. That is, the duration of the transfer between any two subway stations can be considered equal to zero. You are allowed to travel only between subway stations, that ...
#include <bits/stdc++.h> using namespace std; const int N = 200005, INF = 200000000; int n, kk; pair<int, int> s[N]; struct Node { int x, y, t; } a[N]; inline int lowbit(int x) { return x & -x; } struct BIT { int sz, c[N]; BIT() { memset(c, 191, sizeof(c)); } void add(int x, int v) { while (x <= sz) c[x] = ...
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its su...
#include <bits/stdc++.h> using namespace std; template <class T> inline T Max(T a, T b) { if (a > b) return a; else return b; } template <class T> inline T Min(T a, T b) { if (a < b) return a; else return b; } template <class T> inline T gcd(T a, T b) { if (a < 0) return gcd(-a, b); if (b < ...
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been pa...
def nC3(n): return n*(n-1)*(n-2)/6 def nC2(n): return n*(n-1)/2 k = input() s = [] n = 3 while k >= nC3(n+1): n += 1 ans = range(n) k -= nC3(n) while k > 0: n = 2 while k >= nC2(n+1): n += 1 ans.append(n) k -= nC2(n) n = len(ans) print n for i in range(n): buf = '' f...
The m-floor (m > 1) office of international corporation CodeForces has the advanced elevator control system established. It works as follows. All office floors are sequentially numbered with integers from 1 to m. At time t = 0, the elevator is on the first floor, the elevator is empty and nobody is waiting for the ele...
#include <bits/stdc++.h> using namespace std; struct Point { int t, x, y, nom; Point(int t = 0, int x = 0, int y = 0, int nom = 0) {} const bool operator<(const Point& q) const { return t < q.t; } const bool operator>(const Point& q) const { return t > q.t; } }; int n, m, sa[500500]; long long ans[500500]; set<...
You've got a non-decreasing sequence x1, x2, ..., xn (1 ≀ x1 ≀ x2 ≀ ... ≀ xn ≀ q). You've also got two integers a and b (a ≀ b; aΒ·(n - 1) < q). Your task is to transform sequence x1, x2, ..., xn into some sequence y1, y2, ..., yn (1 ≀ yi ≀ q; a ≀ yi + 1 - yi ≀ b). The transformation price is the following sum: <image>...
#include <bits/stdc++.h> using namespace std; long long pow(long long b, long long e, long long m) { long long t = 1; for (; e; e >>= 1, b = b * b % m) e & 1 ? t = t * b % m : 0; return t; } template <class T> inline bool chkmin(T &a, T b) { return a > b ? a = b, true : false; } template <class T> inline bool c...
Bike is a smart boy who loves math very much. He invented a number called "Rotatable Number" inspired by 142857. As you can see, 142857 is a magic number because any of its rotatings can be got by multiplying that number by 1, 2, ..., 6 (numbers from one to number's length). Rotating a number means putting its last s...
#include <bits/stdc++.h> using namespace std; long long pp; int n, x, pr[110000]; long long mo(long long a) { if (a >= 0 && a < pp) return a; a %= pp; if (a < 0) a += pp; return a; } long long ksm(long long a, int b) { long long ans = 1; while (b) { if (b & 1) ans = mo(ans * a); a = mo(a * a); b...
Victor and Peter are playing hide-and-seek. Peter has hidden, and Victor is to find him. In the room where they are playing, there is only one non-transparent wall and one double-sided mirror. Victor and Peter are points with coordinates (xv, yv) and (xp, yp) respectively. The wall is a segment joining points with coor...
#include <bits/stdc++.h> using namespace std; class vec { public: double x, y; vec() {} vec(double tx, double ty) { x = tx, y = ty; } vec operator+(const vec &t) { return vec(x + t.x, y + t.y); } vec operator-(const vec &t) { return vec(x - t.x, y - t.y); } double operator*(const vec &t) { return x * t.y -...
Jeff loves regular bracket sequences. Today Jeff is going to take a piece of paper and write out the regular bracket sequence, consisting of nm brackets. Let's number all brackets of this sequence from 0 to nm - 1 from left to right. Jeff knows that he is going to spend ai mod n liters of ink on the i-th bracket of th...
#include <bits/stdc++.h> using namespace std; const long long inft = 1000000009LL * 12324; const int mod = 1000000007; const int MAXN = 42; int a[MAXN], b[MAXN]; long long M[MAXN][MAXN], A[MAXN][MAXN], T[MAXN][MAXN]; void solve() { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < (n); ++i) scanf("%d", &a[i]);...
You have a rooted tree consisting of n vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to n. Then we represent the color of vertex v as cv. The tree root is a vertex with number 1. In this problem you need to answer to m queries. Each query is des...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class TreeAndQueries { static class Query { ...
User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below. 1. At first, the score is 0. 2. For each block of contiguous "o"s with length x the score increases by x2. 3. F...
#include <bits/stdc++.h> using namespace std; const long long int INF = numeric_limits<long long int>::max(); int main() { int x = 28691, y = 28312; cin >> x >> y; pair<long long int, int> ans(-INF, -1); if (y > 0) { for (int y_groups = 1; y_groups <= y; ++y_groups) if (x >= y_groups - 1) { in...
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat. One day the director of the F ...
#include <bits/stdc++.h> using namespace std; char str[2]; int n, m, a[101000], b[101000], ans, l[101000], v[101000], s[101000]; int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) { scanf("%s%d", str, &b[i]); a[i] = (str[0] == '+' ? 1 : -1); } for (int i = 1; i <= m; i++) { if (a[i] < ...
DZY owns 2m islands near his home, numbered from 1 to 2m. He loves building bridges to connect the islands. Every bridge he builds takes one day's time to walk across. DZY has a strange rule of building the bridges. For every pair of islands u, v (u β‰  v), he has built 2k different bridges connecting them, where <image...
#include <bits/stdc++.h> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; const int mod = 1051131, inv_2 = (mod + 1) >> 1; inline int read() { int s = 0, f = 1; char ch = getchar(); while (!...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
n=int(input()) p=list(map(int,input().split())) q=list(map(int,input().split())) d=[] for i in range(1,p[0]+1): d+=[p[i]] for i in range(1,q[0]+1): if(q[i] not in d): d+=[q[i]] if(len(d)==n): print("I become the guy.") else: print("Oh, my keyboard!")
The "Road Accident" band is planning an unprecedented tour around Treeland. The RA fans are looking forward to the event and making bets on how many concerts their favorite group will have. Treeland consists of n cities, some pairs of cities are connected by bidirectional roads. Overall the country has n - 1 roads. We...
#include <bits/stdc++.h> using namespace std; int const N = 6e3 + 10; int n, r[N]; vector<int> adj[N]; int lis[N]; int ans; void dfs(int v, int par) { int idx = lower_bound(lis, lis + n, r[v]) - lis; ans = max(ans, idx + 1); int tmp = lis[idx]; lis[idx] = r[v]; for (int i = 0; i < adj[v].size(); i++) { in...
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (...
import java.util.Scanner; /** * * @author Mohammad Dehghan */ public class ACM { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int x, y, s; x = scanner.nextInt(); y = scanner.nextI...
A duck hunter is doing his favorite thing, hunting. He lives in a two dimensional world and is located at point (0, 0). As he doesn't like walking for his prey, he prefers to shoot only vertically up (because in this case, the ducks fall straight into his hands). The hunter doesn't reload the gun immediately β€” r or mor...
#include <bits/stdc++.h> using namespace std; int n, d; struct Node { int mx, ad; } seg[200010 * 12]; pair<int, int> inp[200010]; map<int, int> dis; int inv[200010 * 4]; int cn = 0; int cmi = 0; int lav = -1; int cl = 0; void assignV(int ed) { typeof(dis.begin()) it = dis.upper_bound(lav); for (; it != dis.end() ...
Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this! Let us remind you...
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const double PI = acos(-1.0); const double E = exp(1.0); const int M = 2e6 + 5; int prime[M]; int huiwen[M]; int sum[M]; void getprime() { for (int i = 2; i < M; ++i) { sum[i] = sum[i - 1]; if (!prime[i]) { prime[++prime[0]] = ...
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practi...
#include <bits/stdc++.h> using namespace std; int v[2000000]; int acc[2000000]; int n; int solve(int a, int b) { if (v[a] == v[b]) { for (int i = a; i < b + 1; i++) v[i] = v[a]; return (b - a) / 2; } int sz = (b - a + 1); for (int i = a; i < a + sz / 2; i++) v[i] = v[a]; for (int i = a + sz / 2; i < b...
A tree is a connected undirected graph with n - 1 edges, where n denotes the number of vertices. Vertices are numbered 1 through n. Limak is a little polar bear. His bear family prepares a New Year tree every year. One year ago their tree was more awesome than usually. Thus, they decided to prepare the same tree in th...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -1; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; return x * f; } const int MAXN = 200010; const int INF = 2147364800; int N, tax[11], L[11...
Blake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special. You are given an array a of length n. The characteristic of this array is the value <image> β€” the sum of the pro...
#include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; const int N = 2e5 + 5; const int M = 1e6 + 5; const long long INF = 1e18; long long values[N]; struct Line { long long k, m; Line(long long _k = 0, long long _m = 0) { k = _k; m = _m; } long long Get(long long val) { return k *...
You are given an array a with n elements. Each element of a is either 0 or 1. Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a). Input The first line contains two integers n and k (1 ≀...
#include <bits/stdc++.h> using namespace std; const int tam = 100010; const int MOD = 1000000007; const int MOD1 = 998244353; const double DINF = 1e100; const double EPS = 1e-9; const double PI = acos(-1); int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; cin >> n >> k; vector<int> ar...
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
n, m = [int(s) for s in input().split()] for i in range(n): a = [str(s) for s in input().split()] if 'C' in a or 'Y' in a or 'M' in a: m = -1 break else: pass print('#Color') if m == -1 else print('#Black&White')
In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right. The company workers have a very complicated work schedule. At the beginning of a work day all ...
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.HashMap; import java.util.TreeMap; import java.util.TreeSet; public class Hanger { class Segment implement...
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k β‰₯ 0, 0 < r ≀ 2k. Let's call that representation prairie partition of x. For example, the prairie partitions of 12, 17, 7 and 1 are: 12 = 1 + 2 + 4 + 5, 17 = 1 + 2 + 4 + 8 + 2, ...
#include <bits/stdc++.h> using namespace std; int n, num[101]; long long a; int check(long long mid) { int mmin = mid, ret = num[0] - mid; for (int i = 1; i < 101; ++i) { ret = max(ret, 0); if (i & 1) ret += num[i]; else { ret += (num[i] - mmin); mmin = min(mmin, num[i]); } } r...
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec". Now Mike asks himself: what...
import java.io.*; import java.util.*; public class Main{ static int mod=(int)1e9+7; public static void main(String[] args) throws IOException { Writer out=new Writer(System.out); Reader in=new Reader(System.in); // int ts=in.nextInt(); int ts=1; outer: while(ts-->0) { int n=in.nextInt(); Stri...
Alice and Bob got very bored during a long car trip so they decided to play a game. From the window they can see cars of different colors running past them. Cars are going one after another. The game rules are like this. Firstly Alice chooses some color A, then Bob chooses some color B (A β‰  B). After each car they upd...
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Map; import java.util.Set; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; public class MC { static BufferedR...
You are given a directed graph, consisting of n vertices and m edges. The vertices s and t are marked as source and sink correspondingly. Additionally, there are no edges ending at s and there are no edges beginning in t. The graph was constructed in a following way: initially each edge had capacity ci > 0. A maximum ...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; struct edge { int f, t, g; } w[N]; int n, m, s, t, head[N], nxt[N]; void add(int f, int t, int g, int ig) { static int cnt = 1; w[++cnt] = (edge){f, t, g}; nxt[cnt] = head[f]; head[f] = cnt; w[++cnt] = (edge){t, f, ig}; nxt[cnt] = head[...
A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from ...
# -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random """ created by shhuan at 2017/10/4 19:43 """ a, b, f, k = map(int, input().split()) if b < f or f+b < a: print(-1) exit(0) r = a-f res = 0 fuel = b for i in range(k): if i % 2 == 0: # 0...
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make ...
#include <bits/stdc++.h> using namespace std; int marks[128]; bool can_be_typed(string &, map<char, vector<pair<int, int> > > &); double distance(int, int, int, int); int main() { ios::sync_with_stdio(false); int n, m, x; cin >> n >> m >> x; map<char, vector<pair<int, int> > > key_position; vector<pair<int, i...
Opposite to Grisha's nice behavior, Oleg, though he has an entire year at his disposal, didn't manage to learn how to solve number theory problems in the past year. That's why instead of Ded Moroz he was visited by his teammate Andrew, who solemnly presented him with a set of n distinct prime numbers alongside with a s...
#include <bits/stdc++.h> using namespace std; inline int read() { register int x = 0; register char ch = getchar(); while (ch < '0' || ch > '9') ch = getchar(); while (ch >= '0' && ch <= '9') x = (x << 3) + (x << 1) + (ch ^ 48), ch = getchar(); return x; } const int N = 63; int n, cnt; long long a[N], c[N...
Firecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement. Little Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve. A wonder strikes Tommy. How many regions are formed by the circl...
from math import sqrt class vector: def __init__(self, _x = 0, _y = 0): self.x = _x self.y = _y def len(self): return sqrt(self.x ** 2 + self.y ** 2) def len_sq(self): return self.x ** 2 + self.y ** 2 def __mul__(self, other): if (type(self) == type(other)): return self.x * other.x + self.y * other.y ...
Japate, while traveling through the forest of Mala, saw N bags of gold lying in a row. Each bag has some distinct weight of gold between 1 to N. Japate can carry only one bag of gold with him, so he uses the following strategy to choose a bag. Initially, he starts with an empty bag (zero weight). He considers the bags...
#include <bits/stdc++.h> using namespace std; namespace NTT { const int EXP = 23; const unsigned long long EXP_MULT = 119, NTT_MOD = (EXP_MULT << EXP) + 1; unsigned long long rt[EXP + 1], invrt[EXP + 1]; bool built; unsigned long long modPow(unsigned long long a, unsigned long long p) { return p ? modPow((a) * (a) % ...
There are n distinct points on a coordinate line, the coordinate of i-th point equals to x_i. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset co...
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") const long long mod = 1000 * 1000 * 1000 + 7; const long long inf = 1ll * 1000 * 1000 * 1000 * 1000 * 1000 * 1000 + 7; co...
It is the final leg of the most famous amazing race. The top 'n' competitors have made it to the final. The final race has just begun. The race has 'm' checkpoints. Each team can reach any of the 'm' checkpoint but after a team reaches a particular checkpoint that checkpoint gets closed and is not open to any other tea...
def possible(time): match = [-1 for i in xrange(m)] vis = [0 for i in xrange(n)] ret, tim = 0, 42 def dfs(u): vis[u] = tim for t, i in G[u]: if t <= time: if match[i] == -1 or (vis[match[i]] != tim and dfs(match[i])): match[i] = u return True else: break return False for i in xrange(n...
Daenerys Targaryen set her eyes on The Kingdom of The North which is ruled by the House Stark. There is a huge market in the Castle of Winterfell that sells products of all prices starting from 1 coin i.e. there are products worth Rs 1, 2, 3 . . . 10^17 . Ned Stark is the Lord of Winterfell. He gives Daenerys some co...
t = input() ls = 10**17 for _ in xrange(t): n = input() num = [int(i) for i in raw_input().split()] num.sort() x = 0 for i in num: if(i<=x+1): x+=i x+=1 if(x>ls): print -1 else: print x
Platypus Perry is on a mission again. This time, Dr. Heinz Doofenshmirtz has plotted a bomb in the centre of Danville town. He wishes to rebuild the town. We need to defuse the bomb for Perry. As always, Dr. Heinz has given perry the key combination to defuse the bomb, but unfortunately Perry has not been able to get ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' T=input() for t in xrange(T): l=raw_input().split() #a=(int)l[0] #print l[0]*2 b=int(l[1]) index=0 for i in range(len(l[0])-len(l[1])+1): x=int(l[0][index:index+len(l[1])]) pr...
Joffrey Baratheon is the king of all seven kingdoms. His birthday is coming very soon. So he invited all lords, ladies and kings of the all kingdoms. So Joffrey send a unique secret code X with all invitations. When any person want to attend the birthday party of the Joffrey, he/she must tell his/her secret code to th...
import math t=input() c=0 A=[] if t>=1 and t<=10: for i in range(0,t): n=input() c=0 A=[] if n>=1 and n<=100000: s=raw_input().split() if len(s)==n: for j in range(0,len(s)): k=int(s[j]) if k>=1 and k<=ma...
You are given a cost matrix of dimensions m X n. The problem of finding the minimal path from top-left corner to some cell in the matrix is well studied. Here, we are gonna add a little twist. To refresh your memory, the total cost of a path is sum total of cost of all cells visited in the path. Only 2 moves are all...
from collections import deque for _ in xrange(input()): R, C = map(int, raw_input().split()) li = [] for _ in xrange(R): li.append(raw_input().split()) res = [] for i in xrange(R): t = [] for j in xrange(C): t.append([]) res.append(t) res[...
Monk and his P-1 friends recently joined a college. He finds that N students have already applied for different courses before him. Courses are assigned numbers from 1 to C. He and his friends will follow the following conditions when choosing courses:- They will choose the course i (1 ≀ i ≀ C), for which the value o...
import heapq def solve(c, iqs, piqs): res = [] q = [(0, i, 0, (0, 0)) for i in range(len(iqs) + 1, c + 1)] q += [(iq, i, 1, (0, iq)) for i, iq in enumerate(iqs, 1)] heapq.heapify(q) for iq in piqs: _, course, student_count, last_iqs = q[0] res.append(course) student_count +=...
Have you ever been a part of the exciting game Passing the Parcel ? Sid is on a school picnic with his classmates. The teacher decides to make the whole class play the game of Passing the Parcel. Since the winner of the game gets lots of chocolates and ice cream as his/her prize, all the students are over-excited abo...
num = int(raw_input()) song = raw_input() students = list(range(1,num+1)) ballpointer = 0 # problem while len(students) > 1: for lyrics in song: if len(students) == 1: break if lyrics == 'b': del students[ballpointer] if lyrics == 'a': ballpointer += 1 ...
Roy has a string S of length N. String S is made of lower case English alphabets. He likes sorted strings. So he wonders how many substrings of S are sorted. Given the string S, your task is to count the number of sorted substrings of S. A string s is lexicographically sorted if si ≀ si+1 where 1 ≀ i ≀ N-1 (con...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' t=int(raw_input()) while t: t-=1 n=int(raw_input()) s=raw_input() sort=1 c=0 for i in range(1,n): if(s[i]>=s[i-1]): sort+=1 else: c+= (sort*(sort+1...
Given a string s and m queries. For each query delete the K-th occurence of a character x. Input: The first line contains the string s followed by an integer m. The string consists of lowercase letters. After that m lines follow each line containing the integer K and the character x. Output: Print the string after al...
s = raw_input() s = list(s) ln = len(s) di = {} ind = 0 for i in s: if i in di: t = di[i] t.append(ind) di[i] = t else: di[i] = [ind] ind+=1 #print di m = input() while m: m-=1 k,x = raw_input().split() k = int(k) k -= 1 t = di[x] t.pop(k) di[x] = t temp = '$'*ln temp = list(temp) for i in di: t = ...
In his childhood, Utkarsh had a Graph having N nodes and N-1 edges. It was always possible to go from any node to any other node via a path. Now after so many years he has discovered the same Graph in the store room of his house. But many edges of the Graph are now destroyed. Formally now Utkarsh has only M edges of...
import math x,y=map(int,raw_input().split()) for i in range(y): z=raw_input() print (((x*(x-1))/2)-(x-1))
Takahashi loves the number 7 and multiples of K. Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.) If the sequence contains no multiples of K, print `-1` instead. Constraints * 1 \leq K \leq 10^6 * K is an integer. Input Input is giv...
n=int(input()) f=0 for i in range(n): f=f*10+7 f%=n if f==0: print(i+1) break else:print(-1)
You are going to eat X red apples and Y green apples. You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C. Before eating a colorless apple, you can paint it red or green, and it will count as a red o...
import java.io.*; import java.util.*; import java.lang.*; public class Main { int mod = 1000000007; static FastScanner sc = new FastScanner(); public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); int x = sc.nextInt(); int y = sc.nextInt(); int a = sc.nextIn...
In 2937, DISCO creates a new universe called DISCOSMOS to celebrate its 1000-th anniversary. DISCOSMOS can be described as an H \times W grid. Let (i, j) (1 \leq i \leq H, 1 \leq j \leq W) denote the square at the i-th row from the top and the j-th column from the left. At time 0, one robot will be placed onto each s...
#pragma GCC optimize ("Ofast") #include<bits/stdc++.h> using namespace std; #define MD (1000000007U) struct Modint{ unsigned val; Modint(){ val=0; } Modint(int a){ val = ord(a); } Modint(unsigned a){ val = ord(a); } Modint(long long a){ val = ord(a); } Modint(unsigned long long a){ ...
You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative. You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used. You planned to make an apple pie using all of the apples, ...
n,l=map(int,input().split()) if l <= 0: if -1 * l >= n: n -= 1 else: l += 1 n -= 1 print(int(n*(2*l+n-1)/2))
In order to pass the entrance examination tomorrow, Taro has to study for T more hours. Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A). While (X \times t) hours pass in World B, t hours pass in World A. How many hours will pass in World A while Taro studies fo...
[a,b]=map(int, input().split()) print(a/b)
There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.) What is the area of this yard excluding the roads? Find it. Constraints * A is an ...
a, b = map(int, input().split()) print(a*b - b - (a-1))
We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left. According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is...
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) #define int long long signed main(){ int a,b,c,d,e,f,g,h,i; cin>>a>>b>>c>>d>>e>>f>>g>>h>>i; int j=a-b,k=b-c; if(j==d-e&&k==e-f&&j==g-h&&k==h-i)puts("Yes"); else puts("No"); return 0; }
We have a grid with H rows and W columns of squares. We will represent the square at the i-th row from the top and j-th column from the left as (i,\ j). Also, we will define the distance between the squares (i_1,\ j_1) and (i_2,\ j_2) as |i_1 - i_2| + |j_1 - j_2|. Snuke is painting each square in red, yellow, green or...
H,W,D = map(int,input().split()) d = ['R','Y','G','B'] ans = [[] for i in range(H)] for i in range(H): for j in range(W): x,y = i+j, i-j k = (x % (2*D)) // D k += ((y % (2*D)) // D) * 2 ans[i].append(d[k]) for row in ans: print(''.join(row))
Mr.X, who the handle name is T, looked at the list which written N handle names, S_1, S_2, ..., S_N. But he couldn't see some parts of the list. Invisible part is denoted `?`. Please calculate all possible index of the handle name of Mr.X when you sort N+1 handle names (S_1, S_2, ..., S_N and T) in lexicographical ord...
#include<iostream> #include<string> #include<algorithm> using namespace std; string s[11111],t; int n; int F(string a,string b){ bool ok[2]={0,0}; for(int i=0;i<a.size();i++){ if(i==b.size()){ok[0]=1;break;} if(a[i]=='?')if('z'>b[i]){ok[0]=1;break;} if(a[i]>b[i]){ok[0]=1;break;} if(a[i]<b[i])break; }//倧きい可能...
We have a graph with N vertices, numbered 0 through N-1. Edges are yet to be added. We will process Q queries to add edges. In the i-th (1≦i≦Q) query, three integers A_i, B_i and C_i will be given, and we will add infinitely many edges to the graph as follows: * The two vertices numbered A_i and B_i will be connected...
#include <bits/stdc++.h> using namespace std; typedef long long LL; #define mod 1000000007 #define INF_LL 1145141919810364 #define MAX_N 200005 #define MAX_Q 200005 int N, Q; LL A[MAX_Q], B[MAX_Q], C[MAX_Q]; void input() { cin >> N >> Q; for (size_t i = 0; i < Q; i++) { scanf("%lld %lld %lld", &A[i], &B[i...
In cryptography, Caesar cipher is one of the simplest and most widely known encryption method. Caesar cipher is a type of substitution cipher in which each letter in the text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 1, 'a' would be replaced by 'b', 'b' would...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); final char[] THE = {'t', 'h', 'e'}; final char[] THIS = {'t', 'h', 'i', 's'}; final char[] THAT = {'t', 'h', 'a', 't'}; while(sc.hasNext()){ char[] charset = sc.nextLine().toCharArr...
Create a program that inputs the test result data of the visual acuity test and outputs the number of people who apply to each judgment based on the following visual acuity judgment table for each of the left and right eyesight. Judgment | Sight --- | --- A | 1.1 or above B | 0.6 or more and less than 1.1 C | 0.2 or m...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] a = new int[2]; int[] b = new int[2]; int[] c = new int[2]; int[] d = new int[2]; double x, y; while(sc.hasNext()){ x = sc.nextDouble(); y = sc.nextDouble(); i...
It is known that each weight of 1 gram, 3 gram, 9 gram, and 27 gram can be weighed from 1 gram to 40 gram in 1 gram increments using a balance. For example, if you put a weight of 3 grams and a weight you want to weigh on one plate of the balance and a weight of 27 grams and 1 gram on the other plate, the weight of the...
#include<iostream> #include<string> using namespace std; int main() { int w; cin >> w; string ans; while (true) { if (w == 0) { cout << ans << endl; char ch; cin >> ch; return 0; } else if (w % 3 == 1) { ans = '+' + ans; w--; } else if (w % 3 == 2) { ans = '-' + ans; w++; } else ans =...
problem A city in Canada where JOI lives is divided into a grid pattern by w roads that extend straight in the north-south direction and h roads that extend straight in the east-west direction. The w roads in the north-south direction are numbered 1, 2, ..., w in order from the west. In addition, h roads in the east-...
#include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <cstring> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <functional> #include <sstream> #include <complex> #inclu...
Currently, people's entertainment is limited to programming contests. The activity of the entertainment club of a junior high school to which she belongs is to plan and run a programming contest. Her job is not to create problems. It's a behind-the-scenes job of soliciting issues from many, organizing referees, and pro...
#include<iostream> #include<cstdio> #include<set> #include<map> #include<cmath> #include<cstdlib> #include<algorithm> #include<cstring> #include<cassert> #include<string> #include<vector> #include<queue> #define mp make_pair #define pb push_back #define fi first #define se second #define INF 100000005 #define rep(i,n) ...
A fisherman named Etadokah awoke in a very small island. He could see calm, beautiful and blue sea around the island. The previous night he had encountered a terrible storm and had reached this uninhabited island. Some wrecks of his ship were spread around him. He found a square wood-frame and a long thread among the w...
#include<iostream> #include<vector> #include<cmath> using namespace std; struct LineInfo{ double a, b, c; }; struct Point{ double x, y; }; vector<Point> Input(int, double, char); Point InputInner(double, double, char); vector<LineInfo> GetAllLine(const vector<Point>&, const vector<Point>&); LineInfo GetLine(co...
Example Input 2 10 10 Output 40.00000000
#include<iostream> #include<vector> #include<algorithm> #include<cmath> using namespace std; #define rep(i,n) for(int i=0;i<(n);i++) void chmax(double &l, double r){if(l<r)l=r;} int main(){ int n; cin>> n; vector<double> r(n); rep(i, n) cin>> r[i]; vector<double> x(n); rep(i, n){ x[i]=r[i]; rep(j...
Problem Given a sequence A with n elements, a sequence B with m elements, q queries each consisting of an integer c. For each query The absolute value of the difference between the sum of all [la, ra] in sequence A and the sum of all [lb, rb] in sequence B is c. La, ra, lb, rb (0 ≀ la ≀ ra ≀ ra ≀ Find the number of co...
#include<bits/stdc++.h> using namespace std; using int64 = long long; namespace FastFourierTransform { using C = complex< double >; void DiscreteFourierTransform(vector< C > &F, bool rev) { const int N = (int) F.size(); const double PI = (rev ? -1 : 1) * acos(-1); for(int i = 0, j = 1; j + 1 < N; ...
Your computer is a little old-fashioned. Its CPU is slow, its memory is not enough, and its hard drive is near to running out of space. It is natural for you to hunger for a new computer, but sadly you are not so rich. You have to live with the aged computer for a while. At present, you have a trouble that requires a ...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; //Compress Files public class Main{ int INF = 1<<29; void run(){ Scanner sc = new Scanner(System.in); for(;;){ int n = sc.nextInt(), m = sc.nextInt(); if((n|m)==0)break; int[] a = new int[n], b = new i...
Natsuki and her friends were taken to the space by an alien and made friends with a lot of aliens. During the space travel, she discovered that aliens’ hands were often very different from humans’. Generally speaking, in a kind of aliens, there are N fingers and M bend rules on a hand. Each bend rule describes that a f...
#include <iostream> #include <set> #include <vector> #include <string> #include <map> #include <algorithm> #include <cstring> #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) begin(x),end(x) using namespace std; #define MAX_V 1024 vector<int> g[MAX_V], rg[MAX_V], vs; bool used[MAX_V]; int cmp[MAX_V]; vo...
For a positive integer a, let S(a) be the sum of the digits in base l. Also let L(a) be the minimum k such that S^k(a) is less than or equal to l-1. Find the minimum a such that L(a) = N for a given N, and print a modulo m. Input The input contains several test cases, followed by a line containing "0 0 0". Each tes...
#include <bits/stdc++.h> #define rep(i,n) for(int i=0;i<(int)(n);i++) #define rep1(i,n) for(int i=1;i<=(int)(n);i++) #define all(c) c.begin(),c.end() #define pb push_back #define fs first #define sc second #define show(x) cout << #x << " = " << x << endl #define chmin(x,y) x=min(x,y) #define chmax(x,y) x=max(x,y) using...
Problem Statement Nathan O. Davis is a student at the department of integrated systems. Today's agenda in the class is audio signal processing. Nathan was given a lot of homework out. One of the homework was to write a program to process an audio signal. He copied the given audio signal to his USB memory and brought ...
#include "iostream" #include "climits" #include "list" #include "queue" #include "stack" #include "set" #include "functional" #include "algorithm" #include "string" #include "map" #include "unordered_map" #include "unordered_set" #include "iomanip" #include "cmath" #include "random" #include "bitset" #include "cstdio" ...
Example Input 3 Output 1
#include "iostream" #include "climits" #include "list" #include "queue" #include "stack" #include "set" #include "functional" #include "algorithm" #include "string" #include "map" #include "unordered_map" #include "unordered_set" #include "iomanip" #include "cmath" #include "random" #include "bitset" #include "cstdio" ...
In the building of Jewelry Art Gallery (JAG), there is a long corridor in the east-west direction. There is a window on the north side of the corridor, and $N$ windowpanes are attached to this window. The width of each windowpane is $W$, and the height is $H$. The $i$-th windowpane from the west covers the horizontal r...
#include<bits/stdc++.h> #define MOD 1000000007LL using namespace std; typedef long long ll; typedef pair<int,int> P; int n,w,h; int x[101]; int xi[101]; int main(void){ scanf("%d%d%d",&n,&h,&w); for(int i=0;i<n;i++){ scanf("%d",&x[i]); } for(int i=0;i<n;i++){ xi[i]=i*w; if(i%2==0){ xi[i]+=x[i]; }else{...
Problem The great devil Sacagna was still attacked by her natural enemy cat today. I bought a secret weapon because I couldn't do it all the time. This secret weapon can block the cat's path of movement by creating huge rocks that keep cats away from you. Now, Sacagna and one cat are in a rectangular closed section ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> P; int dx[8] = { 1, 0, -1, 0, 1, 1, -1, -1 }; int dy[8] = { 0, 1, 0, -1, 1, -1, 1, -1 }; vector<int> G[100000]; int dir[100000]; int vis[100000]; void dfs(int v, int p, int d) { dir[v] |= 1 << d; vis[v] = 1; for(auto c : G[...
For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0...
from heapq import heappush, heappop def dijkstra(G, s): n = len(G) fixed = set() d = {} for i in range(n): d[i] = 9999999999999999999999999999999999999 d[s] = 0 heap = [(0, s)] while len(fixed) < n: du, u = heappop(heap) for v in G[u]: if v in fixed: ...
Write a program which calculates the area and perimeter of a given rectangle. Constraints * 1 ≀ a, b ≀ 100 Input The length a and breadth b of the rectangle are given in a line separated by a single space. Output Print the area and perimeter of the rectangle in a line. The two integers should be separated by a si...
l = map(int,raw_input().split() ) men = l[0] * l[1] shu = (l[0] + l[1]) * 2 print(str(men) + " " + str(shu))
A regular octagon with vertices X1, X2,..., X8 is provided. A frog starts jumping from the vertex X1. It may jump to any of the two adjacent vertices in one jump except from X5. When it reaches X5, it stops and stays there. Let P(n) be the number of distinct paths of exactly n jumps ending at X5. Given the value of n, ...
a=[] i=2 a.insert(0,0) a.insert(1,2) while i<101: n=4*a[i-1]-2*a[i-2] a.append(n) i=i+1 #def f(n): # if n == 0: # return 0 # elif n == 1: # return 2 # else: # return 4*f(n-1) -2*f(n-2) t=input() i=0 while i<t: n=input() if n%2==0: n=n/2-1 print a[n] else: print...
In the University College of JNTUK Vizianagaram external lab examinations were being conducted. Management has decided to strictly prohibit the mal practices for that the management has decided to arrange cardboards of size nx2 to place in between two successive systems. The construction of cardboard can be done only b...
#!/usr/bin/python # -*- encoding: utf-8 -*- # pylint: disable=invalid-name,missing-docstring,bad-builtin from sys import stdin def main(): arr = [0]*(1000001) arr[0] = arr[1] = 1 for x in xrange(2, 1000001): arr[x] = (arr[x - 1] + arr[x - 2]) % 1000000007 dstream = map(int, stdin.read().split()...
Problem description Nineteen years after the conclusion of events of Harry Potter and the Deathly Hallows, Harry Potter is now a Ministry of Magic employee. His youngest son Albus Severus Potter struggle with the weight of a family legacy he never wanted. As past and present fuse ominously, both father and son learn th...
import random import math for test_Case in range(int(raw_input())): potion = raw_input() count_potion = [0]*26 for c in potion: count_potion[ord(c)-ord('a')]+=1 count_ingr = [0]*26 n = int(raw_input()) for i in range(n): temp = raw_input()...
Everybody loves magic, especially magicians who compete for glory on the Byteland Magic Tournament. Magician Cyael is one such magician. Cyael has been having some issues with her last performances and today she’ll have to perform for an audience of some judges, who will change her tournament ranking, possibly increasi...
from sys import stdin for trial in xrange(int(stdin.readline())): N = int(stdin.readline()) S = [map(int,stdin.readline().split()) for i in range(N)] dp = [[0 for i in xrange(N)] for j in xrange(N)] for i in xrange(1,N): dp[i][0] = dp[i-1][0]+S[i][0] for i in xrange(1,N): dp[0][i] = dp[0][i-1]+S[0]...
The chef has a recipe he wishes to use for his guests, but the recipe will make far more food than he can serve to the guests. The chef therefore would like to make a reduced version of the recipe which has the same ratios of ingredients, but makes less food. The chef, however, does not like fractions. The original rec...
from fractions import gcd as g def gcdN(l): l.sort() temp=l[0] for i in l[1:]: temp=g(temp,i) return temp # print gcdN([12,6,3,4,2]) for testcases in xrange(int(raw_input())): temp=map(int,raw_input().split()) n=gcdN(temp[1:]) for i in temp[1:]: print (i/n), print ''
Let's define a good tree: It is a tree with k * n nodes labeled from 0 to k * n - 1 Node i and node j are not adjacent, for all 0 <= i, j < k * n such that i div k = j div k (here div means integer division. E.g. 7 div 2 = 3) Given n and k, how many different good trees are there? Input Two integers n(1 <= n <= 10...
# a dive into the deep, a lot of concepts here # Kirchoff's Matrix Tree Theorem, Laplacian matrix, cofactors, a revision into # determinants # Revision: replacing a row by itself minus a multiple of another row: # doesn't change determinant # k=3, A = # 0,0,0,1,1,1,1,1,1.......1 # 0,0,0,1,1,1,1,1,1.......1 # 0,0...
Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed! Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denote...
def sum(x): ans = 0 for i in x: ans ^= i return ans i = lambda: [*map(int, input().split())] n, m = i() a = i() b = i() if sum(a) != sum(b): print("NO") quit() print("YES") one = sum(a[1:]) ^ b[0] print(one, end = " ") for i in b[1:]: print(i, end = " ") print() st = "" for i in range(m...
As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space. Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and ...
#include <bits/stdc++.h> using namespace std; long long int n, a[300005], q; long long int b[300005]; long long int ans[300005]; vector<pair<long long int, long long int> > qur[560]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; cin >>...
The company X has n employees numbered from 1 through n. Each employee u has a direct boss p_u (1 ≀ p_u ≀ n), except for the employee 1 who has no boss. It is guaranteed, that values p_i form a tree. Employee u is said to be in charge of employee v if u is the direct boss of v or there is an employee w such that w is i...
#include <bits/stdc++.h> using namespace std; template <class T> using vv = vector<vector<T>>; template <class T> ostream &operator<<(ostream &os, const vector<T> &t) { os << "{"; for (int(i) = 0; (i) < (t.size()); ++(i)) { os << t[i] << ","; } os << "}" << endl; return os; } template <class T, size_t n> ...
The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the pat...
#include <bits/stdc++.h> const long long mod = (long long)1e9 + 7; using namespace std; long long n; vector<long long> vc; vector<vector<pair<long long, long long>>> adj; long long ans; long long dfs(long long s, long long p) { long long m1, m2; m1 = m2 = 0; for (auto i : adj[s]) { if (p != i.first) { l...
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, …, d_k, such that 1 ≀ d_i ≀ 9 for all i and d_1 + d_2 + … + d_k = n. Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d...
n = int(input()) f = 0 for i in range(9,0,-1): if n%i==0: f = 1 break if f == 0: print(1) print(n) else: print(n//i) print(*(n//i*str(i).split()))
Asya loves animals very much. Recently, she purchased n kittens, enumerated them from 1 and n and then put them into the cage. The cage consists of one row of n cells, enumerated with integers from 1 to n from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were n - 1 ...
import java.io.*; import java.util.*; public class E implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(); DisJointSet dj = new DisJointSet(n); for (int i = 0; i < n - 1; i++) { int u = scn.nextInt() - 1, v = scn.nextInt() - 1; dj.union(u, v);...
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat. Assume that we have a cat with a number x. A perfect longcat is a cat with a number equal 2^m - 1 for some non-ne...
// Change Of Plans BABY.... Change Of Plans // import java.io.*; import java.util.*; import static java.lang.Math.*; public class catFurierTransform { static void MainSolution() { n = ni(); int c = 0; StringBuilder sb = new StringBuilder(); while (!check(n)) { if ((c &...
Nauuo is a girl who loves playing games related to portals. One day she was playing a game as follows. In an nΓ— n grid, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. We denote a cell on the intersection of the r-th row and c-th column as (r,c). A porta...
#include <bits/stdc++.h> using namespace std; int n; int r[2 * 1005], berHoy[2][1005], dhhuke[2 * 1005]; vector<int> ans; int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 1; i <= n; i++) dhhuke[i] = i, dhhuke[i + n] = i; for (int i = 1; i <= n; i++) { cin >> r[i]; berHoy[0][r[i]] = i; ...
Tokitsukaze and CSL are playing a little game of stones. In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if...
#include <bits/stdc++.h> using namespace std; vector<long long> nums; long long repetidos() { sort(nums.begin(), nums.end()); long long rta = 0, ant = -1; for (auto x : nums) { if (x == ant) { rta++; } ant = x; } return rta; } bool falla(int n) { for (int i = 1; i < n - 1; i++) { if (n...
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard n Γ— n in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r, c) can threat squares (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (...
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.StringTokenizer; public class E { private void solve() throws IOException { int T = nextInt(); for (int i = 0; i < T; i++) { i...
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with? Input The first...
import java.util.Scanner; public class AniaAndMinimizing { public static void main(String arg[]) { Scanner scr = new Scanner(System.in); int s = scr.nextInt(); int k = scr.nextInt(); String str = scr.next(); char n[] = str.toCharArray(); for(int i=0;i<s && k>0;i++) { if(i==0) { if(s==1...
The only difference between easy and hard versions is constraints. Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you. There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins....
#include <bits/stdc++.h> using namespace std; int n; set<pair<int, int>> byp; int p[200000]; int m[200000]; int sorted[200000]; bool cmp(int i, int j) { if (m[i] < m[j]) return true; if (m[i] > m[j]) return false; return p[i] > p[j]; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int...
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent. Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, y...
#include <bits/stdc++.h> using namespace std; int a[10000], b[10000], c[10000]; int last[10000]; vector<int> front[10000]; priority_queue<int, vector<int>, greater<int>> q; int main() { int n, m, k; cin >> n >> m >> k; for (int i = 1; i <= n; i++) { cin >> a[i] >> b[i] >> c[i]; last[i] = i; } int u, v...