input
stringlengths
29
13k
output
stringlengths
9
73.4k
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are n bosses in this tower, numbered from 1 to n. The type of the i-th boss is a_i. If the i-th boss is easy then its type is a_i = 0, otherwise this boss is hard and its type is a_i = 1. During one session, eith...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t, n; cin >> t; while (t--) { cin >> n; long long arr[n]; long long dp[n][2][2]; for (int i = 0; i < n; i++) { cin >> arr[i]; } dp[0][0][0] = arr[0]; dp[0][0][1] = ...
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size n × n is called prime if ...
import java.io.*; import java.util.*; import java.util.Arrays.*; public class PrimeSquare { public static void main(String[] args) throws IOException { Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=in.nextInt(); while(t-->0) { ...
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya brought home string s with the length of n. The string only consists of lucky digits. The di...
#include <bits/stdc++.h> using namespace std; struct state { int total, ss, se, ee, size; state() : total(0), ss(0), se(0), ee(0), size(0) {} inline static state build_base(const char& c, const char& startchar) { state s; s.total = 1, s.size = 1; if (c == startchar) { s.ss = 1; } else { ...
You have n stacks of blocks. The i-th stack contains h_i blocks and it's height is the number of blocks in it. In one move you can take a block from the i-th stack (if there is at least one block) and put it to the i + 1-th stack. Can you make the sequence of heights strictly increasing? Note that the number of stacks...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Random; import java.util.StringTokenizer; im...
This winter is so... well, you've got the idea :-) The Nvodsk road system can be represented as n junctions connected with n - 1 bidirectional roads so that there is a path between any two junctions. The organizers of some event want to choose a place to accommodate the participants (junction v), and the place to set u...
#include <bits/stdc++.h> using namespace std; const int N = 1e5, M = INT_MIN / 3, C = 1e9; bool flag[N]; int sz[N], dep[N], depw[N], depm[N], ans, u, v; struct edge { int to, w, next; bool operator<(const edge &e) const { return depm[to] < depm[e.to]; } }; vector<edge> g[N]; void get_nodes(int u, int fa, int *vi) {...
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance. This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is eit...
from math import * from collections import Counter,defaultdict,deque I =lambda:int(input()) M =lambda:map(int,input().split()) LI=lambda:list(map(int,input().split())) for _ in range(I()): n=I() s=input() dc=0 kc=0 d=defaultdict(int) for i in s: dc+=i=="D" kc+=i=="K" g=...
As you know, lemmings like jumping. For the next spectacular group jump n lemmings gathered near a high rock with k comfortable ledges on it. The first ledge is situated at the height of h meters, the second one is at the height of 2h meters, and so on (the i-th ledge is at the height of i·h meters). The lemmings are g...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int mod = 1e9 + 7; const int maxn = 1e5 + 10; const double eps = 1e-8; struct node { int w, v, id; bool operator<(const node& p) const { if (w != p.w) return w < p.w; else return v < p.v; } } a[maxn]; int n, k, h; ...
You are given a directed graph G with n vertices and m arcs (multiple arcs and self-loops are allowed). You have to paint each vertex of the graph into one of the k (k ≤ n) colors in such way that for all arcs of the graph leading from a vertex u to vertex v, vertex v is painted with the next color of the color used to...
import java.io.*; import java.util.*; public class CyclicColoring { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; ArrayList<Integer>[] g, gr; int[] color; static final int NON_VISITED = Integer.MAX_VALUE; int gcd(int a, int b) { return b == 0 ? a : gcd(b,...
The Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows. Initially, the ...
#include <bits/stdc++.h> using namespace std; long long fpm(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...
Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet. Overall the galaxy has n...
#include <bits/stdc++.h> using namespace std; int n, m, a, b, w, start = 0, k; long long int MAX = 1e18; vector<vector<int> > wait(100005); vector<vector<pair<int, int> > > adj(100005); void binarySearch(int v, long long int& d) { if (wait[v].size() == 0) { return; } int low = 0, high = wait[v].size() - 1, mi...
Furlo and Rublo play a game. The table has n piles of coins lying on it, the i-th pile has ai coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to: * choose some pile, let's denote the current number of coins in it as x; * choose some integer y (0 ≤ y < x; x1 / 4 ≤ y ≤ x1 / 2) a...
#include <bits/stdc++.h> using namespace std; long long x, a[] = {3, 15, 81, 6723, 50625, 2562991875LL}; int sg[] = {0, 1, 2, 0, 3, 1, 2}, n, ans = 0; int main() { cin >> n; while (n--) { cin >> x; ans ^= sg[lower_bound(a, a + 6, x) - a]; } cout << (ans ? "Furlo" : "Rublo") << endl; return 0; }
The sequence is called ordered if it is non-decreasing or non-increasing. For example, sequnces [3, 1, 1, 0] and [1, 2, 3, 100] are ordered, but the sequence [1, 3, 3, 1] is not. You are given a sequence of numbers. You are to find it's shortest subsequence which is not ordered. A subsequence is a sequence that can be...
import java.io.*; import java.util.*; /** * Created by peacefrog on 12/4/15. * Time : 9:57 PM */ public class CF27C { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; PrintWriter out; long timeBegin, timeEnd; public void runIO() throws IOException { timeBegin = Syste...
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; scanf("%d%d", &n, &m); vector<int> vec(n); int a, b; scanf("%d%d", &a, &b); vec[0] = a * b; for (int i = 1; i < n; i++) { scanf("%d%d", &a, &b); vec[i] = vec[i - 1] + a * b; } int l = 0; for (int i = 0; i < m; i++) { in...
I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself. I would like to create a new graph in such a way that: * The new graph consists of the same number o...
#include <bits/stdc++.h> using namespace std; void printList(list<int>* list) { cout << "list : "; for (__typeof((*list).begin()) li = ((*list).begin()); li != (*list).end(); ++li) { cout << *li << ","; } cout << endl; } void printT_VPII(vector<pair<int, int> > v) { cout << "list : "; for (__type...
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it. Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time...
m, n = map(int, input().split()) a = sorted([int(x) for x in input().split()]) b = sorted([int(x) for x in input().split()]) for i in range(100): if (i >= a[-1] and i < b[0] and i >= 2 * a[0]): print(i) break else: print(-1)
Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9. Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine ...
import java.util.Scanner; public class Main2 { public static void main(String args[]){ Scanner sc = new Scanner(System.in); String s = sc.nextLine(); long counter = 1; int count = 1; int sum = Character.digit(s.charAt(0), 10); for(int i = 1 ; i < s.length() ; i++){ sum += Character.digit(s.charAt(i), 1...
You are given a permutation p. Calculate the total number of inversions in all permutations that lexicographically do not exceed the given one. As this number can be very large, print it modulo 1000000007 (109 + 7). Input The first line contains a single integer n (1 ≤ n ≤ 106) — the length of the permutation. The s...
#include <bits/stdc++.h> using namespace std; long long f[1000005], b[1000005], bit[1000005], _n, _len; void update(long long i, long long val) { while (i <= _n) { bit[i] += val; i += (i & (-i)); } } long long query(long long i) { long long sum = 0; while (i > 0) { sum += bit[i]; i -= (i & (-i))...
In order to ensure confidentiality, the access to the "Russian Code Cup" problems is password protected during the problem development process. To select a password, the jury can generate a special table that contains n columns and the infinite number of rows. To construct a table, the first row is fixed, and all the ...
#include <bits/stdc++.h> using namespace std; const int N = 200005; const int M = 105; struct Query { int k, x, y; inline void input() { scanf("%d %d %d", &k, &x, &y); y--; } } query[N]; int n, q, value[N], a[N], m = 0; int cnt[M][N]; int prefix[M][N]; int sum[M][N]; int temp[N]; inline int lowbit(int x) ...
DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a ...
#include <bits/stdc++.h> using namespace std; int vis[1000], q[1000], node[1000], n, a[1000][1000], m; long double ans = 0; void solve(int u) { int l = 0, r = 1; q[r] = u; int to = 0; long double maxn = 0; for (int i = 1; i <= n; i++) if (a[i][u]) { if ((double)(node[u] + node[i] * 1.0) / (double)a[...
After you had helped Fedor to find friends in the «Call of Soldiers 3» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all...
from sys import stdin from collections import defaultdict def main(): stdin.readline() num = {} stat = lambda word: (word.count('r'), len(word), num.setdefault(word, len(num))) essay = list(map(stat, stdin.readline().lower().split())) queue = [] for word in essay: queue.append(word) n_synonym ...
In a far away galaxy there are n inhabited planets numbered with numbers from 1 to n. One day the presidents of all the n planets independently from each other came up with an idea of creating the Galaxy Union. Now they need to share this wonderful idea with their galaxymates, that’s why each president is busy working ...
#include <bits/stdc++.h> using namespace std; int n, m, k; bool debug = false; int W; struct root { int id; long long edge, ss; vector<int> subNodes; }; vector<pair<int, long long>> mp[200005]; vector<root> rs; int v[200005]; int cpoint[200005]; long long sumNode[200005], countNode[200005], dd[200005], toOthe...
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation. In...
#include <bits/stdc++.h> using namespace std; int const maxn = 35; int const maxk = 205; int p[maxn]; double ans[maxn][maxn][maxk]; int to(int x, int l, int r) { if (x < l || x > r) return x; return l + r - x; } double solve(int n, int i, int j, int k) { if (k == 0) { if (p[i] > p[j]) return 1.0; el...
Life in Bertown has become hard. The city has too many roads and the government spends too much to maintain them. There are n junctions and m two way roads, at which one can get from each junction to any other one. The mayor wants to close some roads so that the number of roads left totaled to n - 1 roads and it were s...
#include <bits/stdc++.h> using namespace std; int dp[1 << 10][1 << 10]; int use[1 << 10][1 << 10]; int g[10][10]; struct node { int s1, s2; }; queue<node> q; int n, m, k; int p1[20], p2[20]; void bfs() { memset(use, 0, sizeof(use)); for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { if (g[i][...
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; int p, q; int rev(int x) { int ret = 0; while (x) { ret *= 10; ret += x % 10; x /= 10; } return ret; } bool vis[4000000 + 10]; void init() { vis[1] = 1; for (int i = 2; i <= 4000000; i++) if (!vis[i]) for (int j = i + i; j <= 4000000; j += ...
Welcoming autumn evening is the best for walking along the boulevard and n people decided to do so. The boulevard can be represented as the axis Ox. For every person there are three parameters characterizing the behavior: ti, si, fi — the moment of time when the i-th person starts walking, the start point and the end ...
n = input() lines = [map(int, raw_input().split()) for i in xrange(n)] def greets(id1, id2): if id1 == id2: return False t1, s1, f1 = lines[id1] t2, s2, f2 = lines[id2] d1 = (f1>s1) - (f1<s1) d2 = (f2>s2) - (f2<s2) l1 = abs(f1-s1) l2 = abs(f2-s2) # one direction if d1...
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015. Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016. Limak wants to prove how responsible a bear he is. He is going to regularly save candies for ...
s=input().split() l1=[52,52,52,52,53,53,52] l2=[31,29,31,30,31,30,31,31,30,31,30,31] count=0 if s[2]=="month": x=int(s[0]) for i in range(len(l2)): if x<=l2[i]: count+=1 print(count) else: for i in range(len(l1)): if int(s[0])==i+1: print(l1[i]) break
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star. A "star" figure having n ≥ ...
#include <bits/stdc++.h> using namespace std; int main() { double n, r, s, ans; cin >> n >> r; double a = atan(1) * 2 / n; ans = r * r * n * sin(2 * a) * sin(a) / sin((n * 2 - 3) * a); printf("%.10f\n", ans); return 0; }
A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert a grams of sand into b grams of lead, the second one allows you to convert c grams of lead into d grams of gold a...
import java.util.*; public class A { public static void main(String[] args) { new A(new Scanner(System.in)); } public A(Scanner in) { Fract one = new Fract(1L, 1L); boolean passed = false; Fract cur = one; Fract[] vs = new Fract[3]; for (int i=0; i<3; i++) {...
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S. Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvio...
#include <bits/stdc++.h> using namespace std; struct tocka { long long int x, y; bool operator<(const tocka &p) const { if (x == p.x) return y < p.y; return x < p.x; } }; vector<tocka> v, gornji, donji, convex; long long int ccw(tocka a, tocka b, tocka c) { return (a.x * (b.y - c.y) + b.x * (c.y - a.y) ...
Scott Lang is at war with Darren Cross. There are n chairs in a hall where they are, numbered with 1, 2, ..., n from left to right. The i-th chair is located at coordinate xi. Scott is on chair number s and Cross is on chair number e. Scott can jump to all other chairs (not only neighboring chairs). He wants to start a...
#include <bits/stdc++.h> using namespace std; int X[5010], A[5010], B[5010], C[5010], D[5010]; long long f[5010][5010]; long long _Min(long long x, long long y) { return x < y ? x : y; } int main() { int n, sp, tp, i, j; scanf("%d%d%d", &n, &sp, &tp); for (i = 1; i <= n; i++) scanf("%d", &X[i]); for (i = 1; i <...
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end...
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class TC2A { public static void main(String[] args) { FastScanner in = new FastScanner(); in.nextInt(); String ...
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwis...
import java.util.*; import java.io.*; public class B { public static void main(String[] args) throws Exception { BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); String input; StringTokenizer tok; int x1, x2, x3, y1, y2, y3; input = bi.readLine(); ...
You have n devices that you want to use simultaneously. The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power. You have a si...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; /* * * Comments Here * */ public class C69_fixed { static BufferedReader br; static BufferedWriter bw; static StringTokenizer st; public st...
Given a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n. Input The first line contains two integers n and k (2 ≤ n ≤ 100000, 1 ≤ k ≤ 20). Output If it's impossible to find the representation of n as a product of k...
#!/usr/bin/env python from math import sqrt dic = {} def kfact(n, k): if (n, k) in dic: return dic[(n, k)] if k == 1: return [n] for i in range(2, int(sqrt(n)) + 1): if n % i == 0: if kfact(n // i, k - 1): result = [i] + kfact(n // i, k - 1) ...
Ivan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number x is really big if the difference between x and the sum of its digits (in decimal representation) is not less than s. To prove that these numbers may have different speci...
#include <bits/stdc++.h> using namespace std; priority_queue<long long int, vector<long long int>, greater<long long int> > t; vector<long long int> p[200005], s(5000005, 0), d(5000005, 0); map<pair<long long int, long long int>, long long int> mp; set<pair<long long int, long long int> > q; long long int mxn = 200005;...
Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex i is equal to ai. Ilya believes that the beauty of the vertex x is the greatest common div...
import java.util.*; import java.io.*; public class c implements Runnable { static PrintWriter out; static int[] arr; static int n; static ArrayList<Integer>[] adjs; static int[] ans; static int count = 100; public void main() throws Throwable { FastScanner in = new FastScanner(Syste...
Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice". ...
import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; public class OneTwoThree { public static void main(String[] args) { new OneTwoThree(System.in, System.out); } private static class Solver impl...
You are given a complete undirected graph with n vertices. A number ai is assigned to each vertex, and the weight of an edge between vertices i and j is equal to ai xor aj. Calculate the weight of the minimum spanning tree in this graph. Input The first line contains n (1 ≤ n ≤ 200000) — the number of vertices in th...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 7; const int MOD = 1e9 + 7; const double eps = 1e-8; const double Pi = acos(-1.0); const double E = exp(1.0); inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); ...
Let's suppose you have an array a, a stack s (initially empty) and an array b (also initially empty). You may perform the following operations until both a and s are empty: * Take the first element of a, push it into s and remove it from a (if a is not empty); * Take the top element from s, append it to the end ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Vector; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.Stack; import java.util.ArrayList; import...
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...
#include <bits/stdc++.h> using namespace std; const int maxn = 3; const long double eps = 1e-12; int n, ted; bool bad; long double x[maxn], y[maxn], r[maxn], dis, tmp, a, b, A, B, C; vector<pair<long double, long double> > t[maxn], fin[maxn], v; long double gdis(long double x1, long double y1, long double x2, ...
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One night Petya was sleeping. He was dreaming of being the president of some island country. The count...
#include <bits/stdc++.h> using namespace std; template <class T> inline void sc(T &x) { register int c = getchar(); x = 0; int neg = 0; for (; ((c<48 | c> 57) && c != '-'); c = getchar()) ; if (c == '-') { neg = 1; c = getchar(); } for (; c > 47 && c < 58; c = getchar()) { x = (x << 1) + (...
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem. There are n displays placed along a road, and the i-th of them can display a text with font size s_i only. Maria Stepanovna wants to rent such t...
mod = 1000000007 MOD = 998244353 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) it = lambda : tuple(map(int, input().split())) ls = lambda : list(input()) n=ii() l=il() c=il() mn=10**20 f...
Once Algorithm guru gave a simple problem to his students.He gave a list of n integers say, A={a1,a2,a3...an} and another integer, x representing the expected sum. He said students to select numbers from array list(0 or more numbers) such that the sum of these numbers is as close as possible but not exceeding to the su...
t=input() while t: t-=1 n,k=map(int,raw_input().split()) a=map(int,raw_input().split()) pos=[False]*(k+1) current=[False]*(k+1) for x in a: y=x while y<=k: current[y]=True y+=x pos=list(current) pos[0]=True i=0 while i<=k: if (current[i]): j=i while j<=k: if (current[i] and current[j] ...
In Byteland,conversion of numbers between different bases has always been a herculian task.They always make errors in these conversions. People in Byteland always write one of the digits wrong when they convert a number to a new base and write it down. For example, when they convert the number 56 into binary (base 2...
def base3Modifier(base3List,iteration): localBase3=list(base3List) bitLoc=int(iteration/2) bitRemainder=iteration%2 if(bitRemainder==0): if(localBase3[bitLoc]=='2'): localBase3[bitLoc]='1' elif(localBase3[bitLoc]=='1'): localBase3[bitLoc]='0' else: localBase3[bitLoc]='2' else: if(localBase3[bitLoc...
Captain Jack Sparrow and Davy Jones are having a furious sword fight to gain the key to the chest containing Davy Jones' heart. Jack wants to kill Davy Jones and live forever as the captain of The Flying Dutchman. On the other hand, Davy Jones wants to save himself from death. A string is hanging between them. With ea...
def py_2(): t = input() for tt in xrange(t): freq = [0]*26 s = raw_input() slen = len(s) for i in xrange(slen): #print ord(s[i])-97 freq[ord(s[i])-97] += 1 c = 0 for i in xrange(26): if freq[i]%2: c += 1 if c==0: print 'JACK' elif c%2: print 'JACK' else: print 'DAVY JONES' py_2...
You're playing a video game, in which you will get an achievement if you complete all of the levels consecutively without dying. You can play the levels in any order, and each time you play a level you'll either complete it or die. Each level has some probability that you'll complete it, and takes some amount of time. ...
flag=1 for i in range(input()): n=input() a=map(int,raw_input().split()) b=map(int,raw_input().split()) pd=[x1*(x2**2) for (x1,x2) in zip(a,b)] i=0 dic={} for j in pd: dic[i]=j i+=1 print "Case #"+str(flag)+":" , for w in sorted(dic,key=dic.get,reverse=True): print w, print"" flag+=1
Link to Russian translation of the problem. Kevin has an array A of N integers, but he doesn't like it - he only likes an array if all its neighboring elements are different (e.g. he likes the array [2,4,2,5,3,2,4], but not [1,2,3,3,4]). Kevin can reverse any contiguous subarray of his array any number of times. For ...
n=int(raw_input()) arr=map(int,raw_input().split()) look=[0]*(max(arr)+1) look_count=[0]*(max(arr)+1) for i in xrange(len(arr)): look_count[arr[i]]+=1 for i in xrange(len(arr)-1): if arr[i]==arr[i+1]: look[arr[i]]+=1 mx=max(look) if max(look_count)>(n+1)/2: print -1 else: print max(mx,(sum(look)+1)/2)
A modified KP number is a positive whole number n with d digits, such that when we split its square into two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d−1 digits, the sum of the pieces is equal to the original number (i.e. l + r = n). Note: r may have leading ...
def kaprekar(i): if i == 1: return True s = i**2 s = str(s) length = len(s) if len(s) <= 1: return False temp = int(s[0:length/2]) + int(s[length/2:]) if temp == i: return True else: return False a = input() b = input() l = [] for i in range(a,b+1): if...
Panda is fond of numbers. Given a number, he subtracts it with squares of any one particular digit of that number to get new numbers. This operation can be applied any number of times (possibly zero) till he obtains a pandatic number. If he is able to reach to a pandatic number then he wins. A pandatic number is a numb...
tc = int(raw_input()) while(tc): n = int(raw_input()) if n == 90 or n == 91: print "No" elif n<13: if n==1 or n==4: print "Yes" else: print "No" else: print "Yes" tc = tc -1
Rose loves to play games. This problem is about a game he recently played. In the game there are N locations, numbered 0 through N-1. Each location has one entrance and one exit. You are given an array aka A with N elements.For each i, A[i] describes the exit from location i. If A[i] is a number between 0 and N-1, incl...
t=input() while t>0: n=input() s=map(int,raw_input().strip().split()) d={} #print s i=0 while i!=-1 and (i not in d): d[i]=1 i=s[i] #print i if i==-1: print "Win" else: print "Lose" t=t-1
Jack is a great mathematician. He loves to solve series. Now Stuart gave a series to Jack and said you have to solve the problem by making a computer program. But Jack doesn't know, how to code. The series is: 1 + (a1).(x)^1 + (a2).(x)^2 + (a3).(x)^3 +........+(an).(x)^n And the problem is find the sum of the a1 + ...
for t in range(int(raw_input())): n = int(raw_input()) print 2**n - 1
The end sem exams at are over. Sneh is the class teacher of class X/C. She now has the hectic task of preparing the report card of her class. Since Sneh is a computer teacher she tried to infuse some fun into his task. Sneh knew that there are n students in class and they had k subjects. Subjects are numbered from 1 t...
(N,K) = map(int,str(raw_input()).split()) marks = [] for i in range(N): marks.append(map (int, str(raw_input()).split())) def worst(subjects): candidates = range(N) for subject in subjects: if len(candidates) == 1: return candidates[0] + 1 min = 100 new_candidates = [] for candidate in candidates: if...
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx. You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other? Constraints...
#include <iostream> #include <cstdio> #include <cstring> #include <set> using namespace std; #define N typedef long long ll; ll ans=0; int ch[1000005][27],cnt,len,tot=1,ed[1000005],siz[1000005],fa[1000005],f[1000005][27],id[1000005]; char s[1000005]; void add(char s[]) { int len=strlen(s); int x=1; for(int i=len-1;...
A positive integer X is said to be a lunlun number if and only if the following condition is satisfied: * In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1. For example, 1234, 1, and 334 are lunlun numbers, while ...
k=int(input()) q=["1","2","3","4","5","6","7","8","9"] x=9 for i in q: if x>100000: break x+=1 a=i[-1] for j in ([-1,0,1]): bb=int(a)+j if bb<10 and bb>=0: q.append(i+str(bb)) print(q[k-1])
Given is a tree G with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. Consider painting the edges in G with some number of colors. We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different. Among the colo...
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e5 + 5; int n, k; int deg[N], ans[N]; vector<pair<int, int> > g[N]; void dfs(int u, int par, int c) { for(auto &it:g[u]) { if(it.first == par) co...
You are given a 4-character string S consisting of uppercase English letters. Determine if S consists of exactly two kinds of characters which both appear twice in S. Constraints * The length of S is 4. * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: S ...
#include <bits/stdc++.h> using namespace std; int main() { char s[4]; for(int i=0;i<4;++i) cin >> s[i]; sort(s,s+4); if(s[0]==s[1]&&s[2]==s[3]&&s[1]!=s[2]) cout << "Yes" << endl; else cout << "No" << endl; }
Find the largest integer that can be formed with exactly N matchsticks, under the following conditions: * Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9). * The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectiv...
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int[] A = new int[M]; for (int i = 0; i < M; i...
You are given a permutation of 1,2,...,N: p_1,p_2,...,p_N. Determine if the state where p_i=i for every i can be reached by performing the following operation any number of times: * Choose three elements p_{i-1},p_{i},p_{i+1} (2\leq i\leq N-1) such that p_{i-1}>p_{i}>p_{i+1} and reverse the order of these three. Cons...
#include<cstdio> #include<algorithm> using namespace std; int n,a[300005]; int main(){ scanf("%d",&n); for(int i=1;i<=n;++i)scanf("%d",&a[i]); for(int i=1,j=1;i<=n;i=j=j+1){ while(1){ if(j+1>n||a[j+1]!=j+1)break; if(j+2>n||a[j+2]==j+2)break; j+=2; } for(int k=i;k<=j;++k) if(a[k]<i||a[k]>j) retu...
There are N holes in a two-dimensional plane. The coordinates of the i-th hole are (x_i,y_i). Let R=10^{10^{10^{10}}}. Ringo performs the following operation: * Randomly choose a point from the interior of a circle of radius R centered at the origin, and put Snuke there. Snuke will move to the hole with the smallest ...
""" @ 凸包をつくる > 凸包内部の点に属する領域は、半径Rの円からするともはやないものとして考えて良い > というかこの多角形自体点として考えていい! @ 凸包の頂点vについて > vの両隣との傾きだけあればよい > その間の角度 / 360が答え """ from math import gcd, atan, pi, degrees def cross3(a, b, c): return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0]) def convex_hull(ps): qs = [] N = len(ps...
Process the Q queries below. * You are given two integers A_i and M_i. Determine whether there exists a positive integer K_i not exceeding 2 × 10^{18} such that A_i^{K_i} ≡ K_i (mod M_i), and find one if it exists. Constraints * 1 \leq Q \leq 100 * 0 \leq A_i \leq 10^9(1 \leq i \leq Q) * 1 \leq M_i \leq 10^9(1 \leq ...
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<map> #define SF scanf #define PF printf using namespace std; long long power(long long x,long long num,long long mod){ long long res=1; while(num){ if(num&1){res=res*x;res%=mod;} x*=x; x%=mod; num>>=1...
You are in charge of controlling a dam. The dam can store at most L liters of water. Initially, the dam is empty. Some amount of water flows into the dam every morning, and any amount of water may be discharged every night, but this amount needs to be set so that no water overflows the dam the next morning. It is know...
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 { static InputStream is; static PrintWriter out; static String INPUT = ""; static void solve() { int n = ...
You are given a string S consisting of digits between `1` and `9`, inclusive. You will insert at most K commas (`,`) into this string to separate it into multiple numbers. Your task is to minimize the maximum number among those produced by inserting commas. Find minimum possible such value. Constraints * 0 ≦ K < |S|...
#include<iostream> using namespace std; string s; int K,L,N; int dp[1<<17][101]; int main() { cin>>K>>s; N=s.size(); L=N/(K+1); if(N%(K+1)==0) { string ans=s.substr(0,L); for(int i=L;i<N;i+=L)ans=max(ans,s.substr(i,L)); cout<<ans<<endl; } else if(K<100) { int A=N%(K+1); for(int i=0;i<=N;i++)for(int j=...
Write a program which prints the central coordinate $(p_x, p_y)$ and the radius $r$ of a circumscribed circle of a triangle which is constructed by three points $(x_1, y_1)$, $(x_2, y_2)$ and $(x_3, y_3)$ on the plane surface. Constraints * $-100 \leq x_1, y_1, x_2, y_2, x_3, y_3 \leq 100$ * $ n \leq 20$ Input Inpu...
#include <stdio.h> #include <math.h> using namespace std; int main(){ int n; double x1,x2,x3,y1,y2,y3,ox,oy,r; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%lf %lf %lf %lf %lf %lf",&x1,&y1,&x2,&y2,&x3,&y3); ox=((y2-y1)*((y3*y3-y1*y1)+(x3*x3-x1*x1))-(y3-y1)*((y2*y2-y1*y1)+(x2*x2-x1*x1)))/ (2*((x3-x1)*(y2...
A prime number n (11, 19, 23, etc.) that divides by 4 and has 3 has an interesting property. The results of calculating the remainder of the square of a natural number (1, 2, ..., n -1) of 1 or more and less than n divided by n are the same, so they are different from each other. The number is (n -1) / 2. The set of n...
#include <bits/stdc++.h> #define reps(v, f, l) for (int v = (f), v##_ = (l); v < v##_; ++v) #define rep(v, n) reps(v, 0, n) #define lep(v, n) reps(v, 1, n + 1) using namespace std; typedef long long int lint; static inline int in(){ int x; scanf("%d", &x); return x; } static inline lint inl(){ lint x; scanf("%lld",...
One of the games that uses the Hyakunin Isshu tag is "Buddhist turning". It is a simple game that uses only picture cards, so it is widely enjoyed. There are various derivative types of rules, but the shaved turn considered here is performed by N participants according to the following rules. * Use a total of 100 card...
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true) { int n = sc.nextInt(); if (n == 0) { break; } int[] hand = new int[n]; int pool = 0; String card = sc.next(); for(int i=0;i<10...
problem You are playing with J using the Midakuji. The Amida lottery consists of n vertical bars and m horizontal bars. The vertical bars are numbered from 1 to n in order from the left, and the vertical bar i The positive integer si is written at the bottom of. <image> Figure 3-1 Example of Amidakuji (n = 4, m = 5,...
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)n; ++i) #define REP(i,n...
Jon is the leader of killifish. Jon have a problem in these days. Jon has a plan to built new town in a pond. Of course new towns should have a school for children. But there are some natural enemies in a pond. Jon thinks that the place of a school should be the safest place in a pond for children. Jon has asked by so...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; public class Main { static FastScanner sc = new FastScanner(); public static void main(String[] args) throws Exception { PrintWriter writer = ...
Mr. Schwarz was a famous powerful pro wrestler. He starts a part time job as a warehouseman. His task is to move a cargo to a goal by repeatedly pushing the cargo in the warehouse, of course, without breaking the walls and the pillars of the warehouse. There may be some pillars in the warehouse. Except for the locatio...
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.PriorityQueue; import java.util.Scanner; public class Main { public static final int MAX = 7; public static boolean is_ok(int x, int y...
Example Input 4 4 1 2 3 1 3 3 2 3 3 2 4 3 Output 1 3
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> l_l; typedef pair<int, int> i_i; #define EPS (1e-7) #define INF (1e9) #define PI (acos(-1)) //const ll mod = 1000000007; struct UnionFind { vector<int> par; vector<int> rank; vector<ll> Size; UnionFind(int n = 1) {...
P "Today is the recording of a program of a liver test project." O-type Chieri "Ki, Kimo no good ..." Kanako Shimura "Is Chieri-chan okay?" Akane Tsukino "As expected, Mr. P! It's a wonderful commentary that clearly shows the situation in one line! Come on! Let's run toward the fireball!" P "The rules are simple, w...
#include <iostream> #include <vector> using namespace std; typedef pair<int, int> i_i; int N; i_i pp; void dfs(int u, int p, vector<vector<int> >& G, vector<int>& num) { num[u] = 1; for (int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if (v == p) continue; dfs(v, u, G, num); num[u] += num[v]; if (num...
In a forest, there lived a spider named Tim. Tim was so smart that he created a huge, well-structured web. Surprisingly, his web forms a set of equilateral and concentric N-sided polygons whose edge lengths form an arithmetic sequence. <image> Figure 1: An example web of Tim Corresponding vertices of the N-sided pol...
#include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace ...
JAVA (Japan Aerospace Voyage Agency) launched a spacecraft in 2003 as part of its space development project. One of the purposes of launching this spacecraft is to approach the asteroid Ishikawa and collect samples of its surface material. Despite various accidents, the spacecraft reached Ishikawa and finally returned ...
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <queue> #include <utility> #define EPS 1e-10 using namespace std; typedef long long ll; struct Point{ double x,y; Point(double x = 0.0,double y = 0.0): x(x),y(y) {} Point operator + (Point p){ ...
Honestly, a rabbit does not matter. There is a rabbit playing a stage system action game. In this game, every stage has a difficulty level. The rabbit, which always needs challenges, basically wants to play more difficult stages than he has ever played. However, he sometimes needs rest too. So, to compromise, he admit...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef vector<int> VI; typedef vector<VI> VVI; const double PI = 3.14159265358979323846; const double EPS = 1e-12; const int INF = numeric_limits<int>::max() / 2; const int NEG_INF = numeric_limits<int>::min() / 2; const l...
D - Medical Inspection Problem Statement The government has declared a state of emergency due to the MOFU syndrome epidemic in your country. Persons in the country suffer from MOFU syndrome and cannot get out of bed in the morning. You are a programmer working for the Department of Health. You have to take prompt mea...
#include<iostream> #include<bitset> #include<vector> #include<numeric> #include<algorithm> using namespace std; typedef bitset<300000/10> BS; BS absbs; BS is[3000]; vector<int> idx; int a[32345],b[32345]; int rec(const BS &bs,int nth,int r){ if(r<0)return r; if(bs==absbs)return r; while((is[idx[nth]]&~bs).non...
A pitch-black room When I woke up, Mr. A was in a pitch-black room. Apparently, Mr. A got lost in a dungeon consisting of N rooms. You couldn't know which room A got lost in, but fortunately he got a map of the dungeon. Let's show A the way to go and lead to a bright room. It is known that M of the N rooms are pitch ...
#include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> #include <queue> using RoomInfo = std::pair<long long, long long>; //どの部屋に残っているか using Node = std::pair<RoomInfo, int>; // first, second:cost namespace std { template <> class hash<std::pair<long long, long long>> { pu...
Intersections of Crossing Path City are aligned to a grid. There are $N$ east-west streets which are numbered from 1 to $N$, from north to south. There are also $N$ north-south streets which are numbered from 1 to $N$, from west to east. Every pair of east-west and north-south streets has an intersection; therefore the...
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define rep(i,n) FOR(i,0,n) #define pb emplace_back typedef long long ll; typedef pair<int,int> pint; int ans[101][101]; vector<int> g[10001]; bool used[10001]; const int dx[]={1,0,-1,0},dy[]={0,1,0,-1}; int main(){ int n,a...
I: Add Problem Statement Mr. T has had an integer sequence of N elements a_1, a_2, ... , a_N and an integer K. Mr. T has created N integer sequences B_1, B_2, ... , B_N such that B_i has i elements. * B_{N,j} = a_j (1 \leq j \leq N) * B_{i,j} = K \times B_{i+1,j} + B_{i+1,j+1} (1\leq i \leq N-1, 1 \leq j \leq i) ...
#include <bits/stdc++.h> #define ll long long #define maxn 150005 /*rem*/ #define mod 65537 #define db double #define vi vector<int> #define pb push_back #define mp make_pair #define pi pair<int, int> #define fi first #define se second using namespace std; ll ksm(ll a, ll b) { if (!b) return 1; ll ns = ksm(a, b >...
The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$. Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$. Constraints ...
# -*- coding: utf-8 -*- N = int(input()) p = [0 for _ in range(N+1)] p[0], p[1] = map(int, input().split()) for n in range(2, N+1): p[n] = list(map(int, input().split()))[1] M = [[0]*(N+1) for _ in range(N+1)] for n in range(N+1): M[n][n] = 0 for l in range(2, N+1): for i in range(1, N-l+2): j =...
For given two sides of a triangle a and b and the angle C between them, calculate the following properties: * S: Area of the triangle * L: The length of the circumference of the triangle * h: The height of the triangle with side a as a bottom edge Input The length of a, the length of b and the angle C are given in...
import math pi=math.pi a,b,si=map(float,input().split()) S=(1/2)*a*b*math.sin(math.radians(si)) c2=a*a+b*b-2*a*b*math.cos(math.radians(si)) L=a+b+math.sqrt(c2) h=(2*S)/a print(S) print(L) print(h)
A valid parentheses sequence is a non-empty string where each character is either '(' or ')', which satisfies the following constraint: You can find a way to repeat erasing adjacent pairs of parentheses '()' until it becomes empty. For example, '(())' and '()((()()))' are valid parentheses sequences, but ')()(' an...
def f(s): balance = 0 max_balance =0 for i in range(len(s)): if s[i] == '(': balance +=1 if s[i] == ')': balance -=1 max_balance = max(max_balance,balance) return max_balance for _ in range(input()): k = "" for i in range(f(str(raw_input()))): k = '('+k+')' pr...
After a long time, Chef has finally decided to renovate his house. Chef's house has N rooms in it numbered from 1 to N. Each room is currently painted in one of the red, blue or green colors. Your are given configuration of colors of his house by a string S consisting of N characters. In this string, color red will be ...
for _ in xrange(input()): l = [] n = input() s = raw_input() l.append(s.count('R')) l.append(s.count('G')) l.append(s.count('B')) l.remove(max(l)) print sum(l)
Note: For Turbo C++, select "Text" as your language Problem description: ProCon Junior gives you chance to earn points for admission in IIIT Delhi. So, it is not easy to get points. If you solve this problem you are one more step closer to earn points. Solve this problem and earn points. Problem: In IIIT Delhi we play ...
x=input() for i in range(x): y=input() ln=[] d=dict() for j in range(y): n=raw_input() st=n.split() name=st[0] sc=int(st[1]) if name in ln: new=d[name]+sc d[name]=new else: d[name]...
Chef has the string s of length n consisted of digits 4 and 7. The string s is called balanced if there exits such integer x (1 ≤ x ≤ n) that the number of digits 4 in substring s[1; x) is equal to the number of digits 7 in substring s(x; n], where s[1; x) is the substring from the 1st digit to (x-1)th digit of s, and ...
mod = 1000000007 fact = [1] for i in xrange(1,5003): fact.append((i*fact[i-1])%mod) inv = [] for j in xrange(5003): nv = pow(fact[j] , mod-2 , mod) inv.append(nv) for j in xrange(int(raw_input())): l = raw_input() four = l.count('4') seven = l.count('7') if (four == 0 or seven == 0 ): ...
An integer is said to be a palindrome if it is equal to its reverse. For example, 79197 and 324423 are palindromes. In this task you will be given an integer N, 1 ≤ N ≤ 1000000. You must find the smallest integer M ≥ N such that M is a prime number and M is a palindrome. For example, if N is 31 then the answer is 1...
import math n=input() if n&1==0: n+=1 found=0 def checkPrime(x): if x<=1: return 0 if x%2==0: return 0 else: root=int(math.sqrt(x))+1 for i in range(3,root,2): if x%i==0: return 0 else: return 1 while not fou...
Given the lengths of the edges of a tetrahedron calculate the radius of a sphere inscribed in that tetrahedron (i.e. a sphere tangent to all the faces). Input An integer t, 1 ≤ t ≤ 30, denoting the number of test cases, followed by t lines, each containing 6 integers describing the lengths of the edges of a tetrahedr...
# tetra.py def area(a,b,c): s = 0.5*(a+b+c) answer = ( s * (s-a) * (s-b) * (s-c) )**0.5 return answer def determinant( x ): # assumes x is a square matrix if len(x)==1: return x[0][0] if len(x)==2: return x[0][0]*x[1][1] - x[0][1]*x[1][0] row = [0]*(len(x)-1) # expand ...
There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string. Your task is to find a sequence of operations after which one of the strings ...
#include <bits/stdc++.h> using namespace std; void compute(deque<pair<char, int> > ds, deque<pair<char, int> > dt, vector<array<int, 2> > &ans, int flg) { int swp = 0; int totlens = 0; int totlent = 0; for (auto x : ds) { totlens += x.second; } for (auto x : dt) { totlent += x.second; ...
The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the qu...
import java.util.*; import java.io.*; import java.math.*; public class Main9 { static class Pair { int x; int y; Pair(int x,int y) { this.x=x; this.y=y; } } static int mod=1000000007; public static int[] sort(int[] a) { int n=a.length; ArrayList<Integer> ar=new ArrayList<>(); for(int i=0;i<a...
You are given a straight half-line divided into segments of unit length, which we will call positions. The positions are numbered by positive integers that start with 1 from the end of half-line, i. e. 1, 2, 3 and so on. The distance between the positions is the absolute difference between the respective numbers. Lah...
#include <bits/stdc++.h> using namespace std; struct person { int acc, pos; bool thr, moved; }; struct property { int mrange, trange, ipos; } P[3]; struct state { person P[3]; int to_int() { int res(0); for (int i = 0; i < 3; ++i) { if (P[i].pos >= 64) throw logic_error("@L21"); res = (res...
This is an interactive problem. Chouti was tired of studying, so he opened the computer and started playing a puzzle game. Long long ago, the boy found a sequence s_1, s_2, …, s_n of length n, kept by a tricky interactor. It consisted of 0s and 1s only and the number of 1s is t. The boy knows nothing about this seque...
#include <bits/stdc++.h> using namespace std; int s[101010]; int ask(int x, int y) { printf("? %d %d\n", x, y); fflush(stdout); scanf("%d", &x); return x; } void ok(int n) { int i; printf("! "); for (i = 1; i <= n; i++) printf("%d", s[i]); fflush(stdout); } int main() { int n, t, now, i, shd = 0, tmp,...
Ivan loves burgers and spending money. There are n burger joints on the street where Ivan lives. Ivan has q friends, and the i-th friend suggested to meet at the joint l_i and walk to the joint r_i (l_i ≤ r_i). While strolling with the i-th friend Ivan can visit all joints x which satisfy l_i ≤ x ≤ r_i. For each joint...
#include <bits/stdc++.h> using namespace std; int b[500005], ans[500005]; struct Base { int a[23], pos[23]; Base() { for (int i = 0; i < 23; i++) a[i] = 0; } void up(int &a, int b) { if (b > a) a = b; } void ins(int x, int r) { for (int i = 22; ~i; i--) if (x >> i & 1) { if (a[i]) ...
In Morse code, an letter of English alphabet is represented as a string of some length from 1 to 4. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1". Because there are 2^1+2^2+2^3+2^4 = 30 strings with le...
#include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; const int INF = 0x3f3f3f3f; const long long LINF = 0x3f3f3f3f3f3f3f3f; int N, n, SA[3003], lcp[3003], arr[3003], rsa[3003]; long long D[3003][3003], T[3003]; char S[3003]; void SuffixArray() { int i, j, k; int m = 2; vector<int> cnt(max(...
Codefortia is a small island country located somewhere in the West Pacific. It consists of n settlements connected by m bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to a or b seconds. It's guaranteed that one can go between any...
#include <bits/stdc++.h> using namespace std; const int N = 80, N2 = (1 << 18) + 1; int cnt, n, m, A, B, fa[N], sz[N], bl[N], dis[N][N2], inq[N][N2], ans[N]; queue<pair<int, int> > q; vector<pair<int, int> > g[N]; int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); } int main() { ios::sync_with_stdio(0); ...
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}. Less for...
import sys input = lambda: sys.stdin.readline().strip() from math import log2 n = int(input()) ls = list(map(int, input().split())) Sum = [0] for i in ls: Sum.append(Sum[-1]+i) q = int(input()) for i in range(q): a, b = map(int, input().split()) print((Sum[b]-Sum[a-1])//10)
Let us define a magic grid to be a square matrix of integers of size n × n, satisfying the following conditions. * All integers from 0 to (n^2 - 1) inclusive appear in the matrix exactly once. * [Bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all elements in a row or a column must be the sa...
n = int(input()) for i in range(n): printlist = [] m=i//4 k=i%4 for j in range(n): printlist.append(str(4*n*m+4*j+k)) print(' '.join(printlist))
You are fed up with your messy room, so you decided to clean it up. Your room is a bracket sequence s=s_{1}s_{2}... s_{n} of length n. Each character of this string is either an opening bracket '(' or a closing bracket ')'. In one operation you can choose any consecutive substring of s and reverse it. In other words,...
#include <bits/stdc++.h> #pragma GCC optimize "trapv" using namespace std; const int INF = 1e9; void _print(long long t) { cerr << t; } void _print(int t) { cerr << t; } void _print(string t) { cerr << t; } void _print(char t) { cerr << t; } void _print(long double t) { cerr << t; } void _print(double t) { cerr << t; }...
You are given a Young diagram. Given diagram is a histogram with n columns of lengths a_1, a_2, …, a_n (a_1 ≥ a_2 ≥ … ≥ a_n ≥ 1). <image> Young diagram for a=[3,2,2,2,1]. Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a 1 × 2 or 2 × 1 recta...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { ...
Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t. Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k ≥ 2 and 2k non-empty strings s_1, t_1, s_...
s = input() mp = [ [0 for i in range(26)] for _ in range(len(s))] for i in range(len(s)) : mp[i][ord(s[i]) - ord('a')] += 1 if i > 0 : for j in range(26) : mp[i][j] += mp[i - 1][j] for _ in range(int(input())) : l, r = map(int, input().split()) sc = 0 for i in range(26) : ...
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last diffe...
#include <bits/stdc++.h> using namespace std; const int N = 5050; int min_depth[N], max_depth[N]; void prec() { for (int n = 1; n <= 5000; n++) { int nn = n - 1, h = 0, cnt = 1; while (nn) { h++; cnt *= 2; min_depth[n] += min(nn, cnt) * h; nn -= min(nn, cnt); } max_depth[n] = n...
You are playing another computer game, and now you have to slay n monsters. These monsters are standing in a circle, numbered clockwise from 1 to n. Initially, the i-th monster has a_i health. You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monste...
from sys import stdin, stdout import io, os input = stdin.buffer.readline def inp(): return int(input()) def arrinp(): return [int(x) for x in input().split()] l = [] def main(): t = inp() for _ in range(t): n = inp() A, B = zip(*[list(map(int, input().split())) for i in range(n)]) ...
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: 1. Each vertex should be labeled by exactly one number 1, 2 or 3; ...
// Don't place your source in a package import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new F...