input
stringlengths
29
13k
output
stringlengths
9
73.4k
You are managing a mobile phone network, and want to offer competitive prices to connect a network. The network has n nodes. Your competitor has already offered some connections between some nodes, with some fixed prices. These connections are bidirectional. There are initially m connections the competitor is offerin...
#include <bits/stdc++.h> using namespace std; const int maxn = 5e5 + 10; int n, m, k, par[maxn], h[maxn], p[maxn], bound[maxn], ga[maxn], gb[maxn], fa[maxn], fb[maxn], w[maxn]; bool marked[maxn]; vector<int> g[maxn], newVers; int root(int v) { return (par[v] == v ? v : par[v] = root(par[v])); } void merge(int v, in...
It is the year 2969. 1000 years have passed from the moon landing. Meanwhile, the humanity colonized the Hyperspace™ and lived in harmony. Until we realized that we were not alone. Not too far away from the Earth, the massive fleet of aliens' spaceships is preparing to attack the Earth. For the first time in a while,...
#include <bits/stdc++.h> using namespace std; int read() { int ans = 0, flag = 1; char ch = getchar(); while (ch > '9' || ch < '0') { if (ch == '-') flag = -flag; ch = getchar(); } while (ch >= '0' && ch <= '9') { ans = ans * 10 + ch - '0'; ch = getchar(); } return ans * flag; } const int ...
Ivan is collecting coins. There are only N different collectible coins, Ivan has K of them. He will be celebrating his birthday soon, so all his M freinds decided to gift him coins. They all agreed to three terms: * Everyone must gift as many coins as others. * All coins given to Ivan must be different. * Not l...
#include <bits/stdc++.h> long long n, m, k, l; long long ans; int main() { scanf("%lld%lld%lld%lld", &n, &m, &k, &l); ans = (l + k) / m; if ((l + k) % m != 0) ++ans; if (ans * m > n) puts("-1"); else printf("%lld\n", ans); }
As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to differen...
#include <bits/stdc++.h> using namespace std; int a[1100]; int main() { int n, m, h, sum, i, j; double ss; while (scanf("%d%d%d", &n, &m, &h) != EOF) { for (sum = 0, i = 1; i <= m; i++) { scanf("%d", &a[i]); sum += a[i]; } if (sum < n) { printf("-1.0\n"); continue; } ss...
Fedya and Sasha are friends, that's why Sasha knows everything about Fedya. Fedya keeps his patience in an infinitely large bowl. But, unlike the bowl, Fedya's patience isn't infinite, that is why let v be the number of liters of Fedya's patience, and, as soon as v becomes equal to 0, the bowl will burst immediately. ...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; class node { public: node* l; node* r; node* p; int time, ltime, rtime, speed, rspeed; long long sum, lsum; node(int time, int speed) : time(time), speed(speed) { l = r = p = NULL; ltime = rtime = time; rspeed = speed; ...
This is an interactive problem. Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake". Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is ...
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; using ll = long long; using llu = long long unsigned; using ld = long double; const ld EPS = 1e-9; inline int cmp(ld first, ld second = 0, ld tol = EPS) { return (first <= second + tol) ? (first + tol < second) ? -1 : 0 : 1; } const int MOD = 1...
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example, * f(599) = 6: 599 + 1 = 600 → 60 → 6; * f(7) = 8: 7 + 1 = 8; * f(9) = 1: 9 + 1 = 10 → 1; * f(10099) = 101: 10099 + 1 = 10100 → 1010 → 101. ...
def f(n): n = n + 1 while n % 10 == 0: n = n // 10 return n n = int(input()) ctr = 0 nums = {} while n not in nums: # print(n) nums[n] = True ctr += 1 n = f(n) print(ctr)
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle. After a long time thinking, Tolik's uncle hasn't any...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; int r1 = 1, r2 = n; while (r1 <= r2) { int c1 = 1, c2 = m; if (r1 == r2) { while (c1 <= c2) { cout << r1 << " " << c1 << "\n"; if (c1 != c2) cout << r2 << " " << c2 << "\n"; c1++, c2--; ...
You are given an array a_1, a_2, ... , a_n and two integers m and k. You can choose some subarray a_l, a_{l+1}, ..., a_{r-1}, a_r. The cost of subarray a_l, a_{l+1}, ..., a_{r-1}, a_r is equal to ∑_{i=l}^{r} a_i - k ⌈ (r - l + 1)/(m) ⌉, where ⌈ x ⌉ is the least integer greater than or equal to x. The cost of empty...
#include <bits/stdc++.h> using namespace std; const int N = 300005; const long long inf = 5e17, mx = 6e15; inline long long read() { long long x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0'...
It's Petya's birthday party and his friends have presented him a brand new "Electrician-n" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him. Construction set "Electrician-n" consists of 2n - 1 wires and 2n light bulbs. Each bulb has its own unique index that is an ...
#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") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("O3") using namespace std; const long long N = 2e5 + 5; const long long M = 3e5 + 5; ...
There are n friends living on a circular street. The friends and their houses are numbered clockwise from 0 to n-1. Initially person i has a_i stones. The friends want to make the distribution of stones among them perfectly balanced: everyone should possess the same number of stones. The only way to change the distri...
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import static java.util.Arrays.fill; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public ...
This is an interactive problem. Khanh has n points on the Cartesian plane, denoted by a_1, a_2, …, a_n. All points' coordinates are integers between -10^9 and 10^9, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a permutation p_1, p_2,...
#include <bits/stdc++.h> using namespace std; vector<pair<long long, int>> A; int s(int x, int y, int z) { int r; printf("2 %d %d %d\n", x, y, z); fflush(stdout); scanf("%d", &r); return r; } long long Q(int x, int y, int z) { long long r = 0; printf("1 %d %d %d\n", x, y, z); fflush(stdout); scanf("%l...
New Year is getting near. So it's time to change handles on codeforces. Mishka wants to change his handle but in such a way that people would not forget who he is. To make it work, he only allowed to change letters case. More formally, during one handle change he can choose any segment of his handle [i; i + l - 1] and...
#include <bits/stdc++.h> using namespace std; template <typename _T> inline void read(_T &f) { f = 0; _T fu = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') { fu = -1; } c = getchar(); } while (c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getch...
One day in the IT lesson Anna and Maria learned about the lexicographic order. String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi, and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of the string a. The le...
import java.io.*; import java.lang.Math; import java.util.*; public class Main { public static Scanner in; public static PrintStream out; public static void test() { String s = in.nextLine(); long k = in.nextLong(); int n = s.length(); int cnt[] = new int[27]; long substr_cnt[] = new long[27]; int...
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤...
for x in range(int(input())): n=int(input()) a=list(map(int,input().split())) b=[] i=0 count=0 s=0 while i<n: if a[i]%2==0: count=1 s=i break else: b.append(i) i+=1 if count==1: print(1) print(s+1) ...
Denis came to Nastya and discovered that she was not happy to see him... There is only one chance that she can become happy. Denis wants to buy all things that Nastya likes so she will certainly agree to talk to him. The map of the city where they live has a lot of squares, some of which are connected by roads. There...
#include <bits/stdc++.h> using namespace std; int mod = 998244353; const int M = 1e6 + 10; const int N = 1e5 + 10; inline long long read() { long long b = 1, sum = 0; char c = getchar(); while (!isdigit(c)) { if (c == '-') b = -1; c = getchar(); } while (isdigit(c)) { sum = sum * 10 + c - '0'; ...
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t. You can perform the following operation on s any number of times to achieve it — * Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1.....
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Prob6 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(...
The only difference between easy and hard versions is on constraints. In this version constraints are lower. You can make hacks only if all versions of the problem are solved. Koa the Koala is at the beach! The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shor...
#include <bits/stdc++.h> using namespace std; long long ara[300005], tmp[300005]; int main() { long long test, t, i, j, k, a, b, c, x, y, z, n, m; scanf("%lld", &test); for (t = 1; t <= test; t++) { scanf("%lld", &n); scanf("%lld%lld", &z, &m); for (i = 1; i <= n; i++) scanf("%lld", &ara[i]); for ...
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w...
for _ in range(int(input())): n,k = map(int,input().split()) s = input() l = [-1]*k f = 0 for i in range(len(s)): if s[i] != "?": if l[i%k] == -1: l[i%k] = int(s[i]) else: if l[i%k] != int(s[i]): f = 1 if f...
Alice and Bob have decided to play the game "Rock, Paper, Scissors". The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in...
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missile...
import java.util.*; public class MissileSilos { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int s = sc.nextInt(); List<Edge>[] edges = new List[n + 1]; for (int i = 0; i <= n; i++) { List<Edge> temp = new ArrayList<Edge>();...
You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the...
import sys for iter in range(int(sys.stdin.readline())): n, m = map(int, sys.stdin.readline().split()) s = input() balance = [0] * (n + 1) for i in range(n): if s[i] == '+': balance[i + 1] = balance[i] + 1 else: balance[i + 1] = balance[i] - 1 max_prefix, min...
You are given an integer k and an undirected tree, consisting of n vertices. The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of thi...
#include <bits/stdc++.h> #define maxn 5086 using namespace std; const int p = 998244353; int n, m; int f[maxn][maxn], g[maxn], siz[maxn]; vector<int> v[maxn]; int x, y; inline void add(int &x, int y){ x += y; if(x >= p) x -= p; } void dfs(int i, int fa){ siz[i] = 1, f[i][0] = 1; for(int j = 0;j < v[i].size();...
Nastia has an unweighted tree with n vertices and wants to play with it! The girl will perform the following operation with her tree, as long as she needs: 1. Remove any existing edge. 2. Add an edge between any pair of vertices. What is the minimum number of operations Nastia needs to get a bamboo from a tr...
#include <bits/stdc++.h> using namespace std; const int N = 100005; set<int> graph[N]; int parent[N]; int visited[N]; vector<pair<int, int>> dels; vector<pair<int, int>> adds; void setupp(int v, int p){ parent[v] = p; for(auto x : graph[v]){ if(x != p) setupp(x, v); } } void setup(in...
Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arra...
mod = 1000000007 f = [1] * 200001 for i in xrange(2, 200001): f[i] = f[i-1] * i % mod invf = [1] * 200001 invf[-1] = pow(f[-1], mod - 2, mod) for i in xrange(200000, 2, -1): invf[i-1] = invf[i] * i % mod def C(n, k): if k < 0 or k > n: return 0 return f[n] * invf[k] * invf[n-k] % mod def solve(m...
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row — the row which has exac...
n=int(input()) l=[list(map(int,input().split())) for i in range(n)] z=[[False]*n for i in range(n)] summ=0 for i in range(n): for j in range(n): if i==j and z[i][j]==False: summ+=l[i][j] z[i][j]=True elif i==n//2 and z[i][j]==False: summ+=l[i][j] z[i][...
We've got a rectangular n × m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall. In this problem <image> is a remai...
#include <bits/stdc++.h> using namespace std; const int N = 1505; char adj[N][N]; int vis[N][N], dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int n, m; bool dfs(int x, int y, int markx, int marky) { for (int i = 0; i < 4; i++) { int xx = x + dir[i][0], yy = y + dir[i][1]; int imarkx = markx, imarky = marky...
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions. An in...
#include <bits/stdc++.h> using namespace std; int s0[100010], s1[100010], sn; inline int lowbit(int n) { return n & (-n); } void add(int seg[], int x, int c) { for (int i = x; i <= sn; i += lowbit(i)) seg[i] += c; } int sum(int seg[], int x) { int i, ans = 0; for (i = x; i > 0; i &= i - 1) ans += seg[i]; return...
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program re...
n = int(input()) ab = [0,0] for i in range(n): t,x,y = map(int,input().split()) ab[t-1]+=x-y print('LIVE' if ab[0]>=0 else 'DEAD') print('LIVE' if ab[1]>=0 else 'DEAD')
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for t...
#include <bits/stdc++.h> using namespace std; const int INF = 2147483647; const long long LLINF = 9223372036854775807LL; int main() { int n, m, k; scanf("%d%d%d", &n, &m, &k); double ans = 1; for (int i = 0; i <= k; ++i) ans *= (m - i + .0) / (n + i + 1.); ans = 1 - ans; ans = max(0., ans); printf("%.15lf...
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves fir...
//package com.congli.codeforces; import java.io.*; import java.util.*; public class CrocChamp2013R2Div2C { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { CrocChamp2013R2Div2C test = new CrocChamp2013R2Div2C(); test.start(); } pu...
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (...
#include <bits/stdc++.h> using namespace std; const int N = 11; const int M = 2050; const int pr = 1993; const int mod = 1000000031; vector<long long> st[N]; set<long long> dif; int l[N], r[N]; long long hs[M], deg[M], ls[M * M]; void proc(int id, string s) { int n = (int)s.size(); for (int i = 0; i < n; i++) { ...
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear a...
import java.io.*; import java.util.*; /* */ public class P1 { static FastReader sc=null; public static void main(String[] args) { PrintWriter out=new PrintWriter(System.out); sc=new FastReader(); int n=sc.nextInt(); int a[]=sc.readArray(n); for(int i=0;i<n;i++)a[i]--; int counts[]=new int[n]...
You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle. A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the r...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; int dp[40000]; std::map<long long, long long> freq; int main(int argc, char const *argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); int a; cin >> a; string second; cin >> second; for (int i = 0; i < second.length(); ++i) { ...
George is a cat, so he loves playing very much. Vitaly put n cards in a row in front of George. Each card has one integer written on it. All cards had distinct numbers written on them. Let's number the cards from the left to the right with integers from 1 to n. Then the i-th card from the left contains number pi (1 ≤ ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1000000 + 3; int bit1[MAXN]; int bit2[MAXN]; int p[MAXN]; int at[MAXN]; bool is[MAXN]; inline int lb(int x) { return x & (-x); } void update(int x, int add, int n, int bit[]) { while (x <= n) { bit[x] += add; x += lb(x); } } int query(int x, int...
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the app...
def pitagoras(k): casos_possiveis = [] for n in range(1,k): m = int((k**2 - n**2)**(0.5)) if((n**2 + m**2) == k**2): casos_possiveis.append([n, m]) return casos_possiveis def possivelRepresntar(k): for n in range(1, k): m = int((k**2 - n**2)**(0.5)) if ((n **...
You are given an n × m grid, some of its nodes are black, the others are white. Moreover, it's not an ordinary grid — each unit square of the grid has painted diagonals. The figure below is an example of such grid of size 3 × 5. Four nodes of this grid are black, the other 11 nodes are white. <image> Your task is to...
#include <bits/stdc++.h> using namespace std; int mat[405][405]; int n, m; string s; int hangr[405][405], hangl[405][405]; int lieu[405][405]; void Init() { cin >> n >> m; for (int i = 1; i <= n; i++) { cin >> s; for (int j = 0; j < m; j++) mat[i][j + 1] = s[j] - '0'; } for (int i = 1; i <= n; i++) { ...
Pieguy and Piegirl are playing a game. They have a rooted binary tree, that has a property that each node is either a leaf or has exactly two children. Each leaf has a number associated with it. On his/her turn a player can choose any two leafs that share their immediate parent, remove them, and associate either of th...
#include <bits/stdc++.h> const int N = 256; int n, a[N], l[N], r[N]; int size[N]; void dfs(int x) { if (a[x] != -1) { size[x] = 0; return; } dfs(l[x]); dfs(r[x]); size[x] = size[l[x]] + size[r[x]] + 1; if (size[r[x]] & 1) std::swap(l[x], r[x]); } inline int merge(int lhs, int rhs, int dir) { if (l...
Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unluc...
import java.io.*; import java.util.*; import java.math.*; public class Main{ static class Trial implements Comparable<Trial>{ boolean[] t; int r; Trial(boolean[] t, int r){ this.t = t; this.r = r; } public int compareTo(Trial b){ return th...
After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number x to the basket, Misha should answer the quest...
#include <bits/stdc++.h> using namespace std; template <class T> bool setmax(T &_a, T _b) { if (_b > _a) { _a = _b; return true; } return false; } template <class T> bool setmin(T &_a, T _b) { if (_b < _a) { _a = _b; return true; } return false; } template <class T> T gcd(T _a, T _b) { ret...
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? No...
import java.awt.*; import java.io.*; import java.util.*; public final class CliqueProblem { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(in, out); solver.solve(); in.c...
Kyoya Ootori wants to take the train to get to school. There are n train stations and m one-way train lines going between various stations. Kyoya is currently at train station 1, and the school is at station n. To take a train, he must pay for a ticket, and the train also takes a certain amount of time. However, the tr...
#include <bits/stdc++.h> const int N = 100005; using namespace std; inline int Getint() { register int x = 0, f = 1; register char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } ...
Stewie the Rabbit explores a new parallel universe. This two dimensional universe has the shape of a rectangular grid, containing n lines and m columns. The universe is very small: one cell of the grid can only contain one particle. Each particle in this universe is either static or dynamic. Each static particle always...
#include <bits/stdc++.h> void Get(int &T) { char C; bool F = 0; for (; C = getchar(), C < '0' || C > '9';) if (C == '-') F = 1; for (T = C - '0'; C = getchar(), C >= '0' && C <= '9'; T = T * 10 + C - '0') ; F && (T = -T); } char S[1005][1005]; int N, M; void Init() { Get(N); Get(M); for (int i =...
Kleofáš is participating in an n-thlon - a tournament consisting of n different competitions in n different disciplines (numbered 1 through n). There are m participants in the n-thlon and each of them participates in all competitions. In each of these n competitions, the participants are given ranks from 1 to m in suc...
#include <bits/stdc++.h> using namespace std; int n, m, sum; int a[101]; long double f[101000], s[101000], ans; int main() { cin >> n >> m; if (m == 1) { printf("1.0000000000000000\n"); return 0; } f[0] = m - 1; int now = 0; for (int i = 1; i <= n; i++) scanf("%d", &a[i]), sum += a[i]; for (int i ...
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other wi...
#include <bits/stdc++.h> using namespace std; int main() { unsigned long long int d, l, v1, v2; float t; cin >> d >> l >> v1 >> v2; t = (l - d) / (v1 + v2); cout << fixed << setprecision(10) << (double)(l - d) / (v1 + v2); return 0; }
After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters. Each morning, Bessie travels to school along a sidewalk consisting of m + n...
#include <bits/stdc++.h> using namespace std; const int N = 100020; const int mod = 1000000007; int n; int m; int last[26]; int res[2000100]; int sum[2000100]; int k; string s; int main() { cin >> n >> k; cin >> s; n += (s.size()); res[0] = 1; sum[1] = 1; for (int i = 1; i <= n; i++) if (i <= (s.size())...
It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can c...
import java.util.*; import java.io.*; public class c { public static void main(String[] args) throws Exception { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); long[] aPos = new long[2]; long[] bPos = new long[2]; long[] bin = new long[2]; Str...
As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the midd...
#include <bits/stdc++.h> using namespace std; const long long N = 100100; const long long Mod1 = 1e9 + 7; const long long Mod2 = Mod1 - 1; long long a[N]; long long add(long long x, long long y, long long Mod) { x %= Mod; y %= Mod; return (x + y) % Mod; } long long sub(long long x, long long y, long long Mod) { ...
During the chemistry lesson Andrew learned that the saturated hydrocarbons (alkanes) enter into radical chlorination reaction. Andrew is a very curious boy, so he wondered how many different products of the reaction may be forms for a given alkane. He managed to solve the task for small molecules, but for large ones he...
#include <bits/stdc++.h> using namespace std; int n, m, tot; vector<int> e[100005]; map<vector<int>, int> h; map<int, int> f[100005]; set<int> s; inline void addEdge(int u, int v) { e[u].push_back(v); } inline int R() { char c; int res, sign = 1; while ((c = getchar()) > '9' || c < '0') if (c == '-') sign = -...
Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character — non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to...
import java.util.Scanner; public class C { static int[]s; static int[][]a; static boolean[][][]calculated; static int L; static int[][][]d; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String ss = sc.next(); L = ss.length(); s ...
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some verte...
#include <bits/stdc++.h> using namespace std; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { if (0) return; cout << name << " : " << arg1 << "\n"; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { if (0) return; const char* comma = strchr...
Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated n Mr. Meeseeks, standing in a line numbered from 1 to n. Each of them has his own color. i-th Mr. Meeseeks' color is ai. Rick and Morty are gathering their army and they want to divide Mr. Meeseeks into s...
#include <bits/stdc++.h> using namespace std; const int nmax = 100010; const int inf = (int)1e8; int n, a[nmax], last[nmax], distinct; int ans[nmax]; struct Node { Node *left, *right; int sum; Node() { left = right = NULL; sum = 0; } int getSum(Node *v) { return (v ? v->sum : 0); } void update() { t...
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kep...
#include <bits/stdc++.h> using namespace std; int a[200005]; long long pre[200005]; int main() { int n, k; scanf("%d%d", &n, &k); int i; for (i = 1; i <= n; i++) { scanf("%d", &a[i]); pre[i] = pre[i - 1] + a[i]; } int kk = k; if (k > (n + 1) / 2) { k = k - (n + 1) / 2; k = n / 2 + 1 - k; ...
n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed. You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using ii = pair<ll, ll>; using vi = vector<ll>; using vb = vector<bool>; using vvi = vector<vi>; using vii = vector<ii>; using vvii = vector<vii>; constexpr int INF = 2000000000; constexpr ll LLINF = 9000000000000000000; struct ...
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is e...
#include <bits/stdc++.h> using namespace std; const long long int M = 1e6 + 5, M2 = 2e6, SM = 600; const long long int inf = 1e18, mod = 98765431; const long long int LG = 18; const long long int Z = 26; long long int n, k; long long int a[M], t[M]; int main() { ios::sync_with_stdio(false); cin >> n >> k; k++; ...
Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each ro...
import java.io.*; import java.util.*; public class Main implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; int time = 0; int[] st, lz; void solve() { int n = scn.nextInt(); int[] par = new int[n]; par[0] = -1; for(int i = 1; i < n; i++) { par[i] = scn.nextInt() - 1; } in...
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of tree...
#include <bits/stdc++.h> using namespace std; const int H = 1e5; int a[H], s[H]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int h; cin >> h; for (int i = 0; i <= h; i++) cin >> a[i]; s[0] = a[0]; for (int i = 1; i <= h; i++) s[i] = s[i - 1] + a[i]; bool ok = false; for (int ...
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: * A <image> BC * B <image> AC * C <image> AB * AAA <image> empty string Note that a substring is one or more consecutive characters. For give...
#include <bits/stdc++.h> #pragma GCC target("pclmul") using ul = std::uint32_t; using ull = std::uint64_t; using li = std::int32_t; using ll = std::int64_t; using uss = std::uint8_t; const ul maxn = 1e5; char str[maxn + 2]; ul scb[maxn + 1]; ul sca[maxn + 1]; ul tcb[maxn + 1]; ul tca[maxn + 1]; ul q; int main() { std...
Instructors of Some Informatics School make students go to bed. The house contains n rooms, in each room exactly b students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to n. Initially,...
#include <bits/stdc++.h> using namespace std; const int MOD = 1000000007; const int INF = 0x3f3f3f3f; const long long LL_INF = 0x3f3f3f3f3f3f3f3f; const double PI = acos(-1); const double EPS = 1e-10; const int N = 1000010; long long n, d, b; long long s[N]; long long pref[N]; int main() { ios_base::sync_with_stdio(f...
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her. The three friends are very smart so they passed all the challenges very quickly and finally reached the destination...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 7, mz = 1e9 + 7; char s[N]; int p[5][255]; int main() { int n; cin >> n; int len[5]; for (int i = 1; i <= 3; i++) { scanf("%s", s); len[i] = strlen(s); for (int j = 0; j < len[i]; j++) { p[i][s[j]]++; if (p[i][s[j]] > p[i]...
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times: * if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; * if th...
import java.util.*; import java.io.*; import java.math.BigInteger; import java.text.*; public class Main { static long mod = (long)1e9 + 7; static long mod1 = 998244353; static FastScanner f; static PrintWriter pw = new PrintWriter(System.out); static Scanner S = new Scanner(System.in); static l...
Benny is a little pig. She usually goes to school, but the summer is coming which is also the time of getting the grade card report of all the N + 1 subjects. Benny has a M grade point system. Hence, all the scores for any subject are not less than 1 and not greater than M. During this year of education, Benny got N ...
cases = int(raw_input()) for case in xrange(cases): N, M, X = (int(i) for i in raw_input().split()) scores = [int(i) for i in raw_input().split()] req = (N+1)*X - sum(scores) if req>M: print 'Impossible' elif req<=0: print 1 else: print req
NOTE: All quotes are for clarity You are given one n x m grid and q queries. Each cell of grid will have a value assigned to it. Each query will be of type "x y d". Read below on how you have to process them. For each query, the grid is initially plain white. Now, for query "x y d" the cell (x, y) will be colored bla...
n, m, q = [int(x) for x in raw_input().split()] totl=0 grid=[] visit=[] for i in range(0,n):#rows grid.append([int(y) for y in raw_input().split()]) def loop(x,y,dif,mx,my,count): cval=grid[x][y]; count=1 visit[x][y]+=1 if(x>0 and visit[x-1][y]==0): val=grid[x-1][y] if(abs(cval-val)<=dif): count+=1 loop(...
Suresh is a fan of Mario. But being a programmer he decided to modify the game. In one module he needs your help. He modified the game as follows: There are N stones on the way indexed from 1 to N. Every stone having index i is associated with points equal to i^th fibonacci number. That is if there are 5 stones then th...
def fib(n): f=[] f.append(1) f.append(1) for i in range(2,n): p=f[i-1] q=f[i-2] f.append(p+q) #print f return sum(f) temp=map(int,raw_input().split()) n=temp[0] arr=map(int,raw_input().split()) a=[] c1=fib(n) print c1-sum(arr)
Somnath is a Grammar Nazi. He keeps pointing out others’ grammatical mistakes. However, for a given sentence, he tries to remember all the unique words only so that he can be more efficient with his annoying habit. You wish to join his team to help him with his obsession for Queen’s Language. Given a sentence S, find t...
for _ in range(int(raw_input())): s = set(raw_input().strip().split()) print len(s)
Manish like to play with bits, so he was recently gifted with a puzzle book on bits arithmetic by one of his friend on his birthday. Manish couldn't solve any of the puzzles from the book and needs your help to solve one. Given two integers m & n .Find the number of combinations of bit-size 'n' in which there are no '...
import sys tc=int(raw_input()) for x in range(0,tc) : (k, n) = map(int,raw_input().split()) s = [0]*(500) s[k] = 1 # T(k, k) = 1 for i in range(k + 1, n + 1): s[i] = 2*s[i-1] + pow(2, (i - k - 1)) - s[i-1-k] a = s[n] print pow(2,n)-a
rakesh loves to play number games. when He was surfing on google he found one of the game. The theme of the game is to find the shortest way that he can make the number equal to 1. He can only perform only three operations they are -1, /2, /3. As the level of game increased and he was facing difficulty to solve the lar...
for _ in xrange(input()): n=input() ans=0 while n>1: if n%3==0: n/=3 elif n%2==0: n/=2 else: n-=1 ans+=1 print ans
Problem Statement: Nash, a high school student studies the concepts of Functions(Mathematics), for the first time.After learning the definitions of Domain and Range, he tries to find the number of functions possible,given the number of elements in domain and range.He comes to you for help.Can you help him with this? I...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' test = raw_input() test = int(test) for i in range(test): l = raw_input() l = l.split() a = int(l[0]) b = int(l[1]) x = b**a print x%1000000007
Shil likes Round numbers very much . A number is called Round number if its non-negative and its first and last digits are same. For example 0 , 3 , 343 and 50005 are round numbers whereas 1000 is not a round number. Shil has an array A1 , A2 .. AN . He wants to answer Q queries of following two type : 1 l r : F...
def update(x,v): while x<=N: bit[x]+=v x += x&-x def query(x): total = 0; while x>0: total+=bit[x] x -= x&-x return total (N,Q) = [int(s) for s in raw_input().strip().split(" ")] S = [s for s in raw_input().strip().split(" ")] X = [] bit = [0 for j in range(N+1)] for i in range(N): if S[i][0]==S[i][-1]: ...
There is a magical shop owned by The Monk, which consists of magical potions. On the first day there are A number of potions. Let, potions[I] denote the number of potions present in the shop on the I^th day. potions[I] = potions[I-1] * potions[I-1] You, Monk's favorite student love to play around with various type...
a,b=map(int,raw_input().split()) s=raw_input() m,n=[0]*(len(s)),[0]*(len(s)) ans=j=sum=0 #m[j]=a #j+=1 for i in range(len(s)): if s[i]=='1' and i==0: #ans=pow(,2,b) sum+=a%b m[j]=a #print m[j],i j+=1 elif s[i]=='0' and i==0: m[j]=a j+=1 elif s[i]=='1': m[j]=pow(m[j-1],2,b) sum+=m[j]%b #print m[j]...
Link to Russian translation the problem You are given a number N. How many zeroes does N! end on? Input The first line contains one integer T - number of test cases. The following T lines contain one integer each - N. Output For each test case output one integer per line - the answer for this question. Constraints ...
t=int(raw_input()) for i in xrange(t): n=int(raw_input()) res=0 while n!=0: res+=n/5 n=n/5 print res
Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1. Constraints * 0 \leq N \...
n = int(input()) a = list(map(int,input().split())) cumsum_a = a.copy() for i in range(n-1, -1, -1): cumsum_a[i] += cumsum_a[i+1] ans = 0 node = 1 for i in range(n + 1): if a[i] > node: ans = -1 break ans += node if i < n: node = min(2 * (node - a[i]), cumsum_a[i + ...
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i. Consider painting each of these edges white or black. There are 2^{N-1} such ways to paint the edges. Among them, how many satisfy all of the following M restrictions? * The i-th (1 \leq i \leq M) restriction...
#include <bits/stdc++.h> using namespace std; using PP = pair<int, int>; int n, m; vector<PP> G[50]; int p[50], q[50]; long ps[50][50]; void rec(int st, int from, int prev, long path) { ps[st][from] = path; for (PP e : G[from]) { int to = e.first; int id = e.second; if (to == prev) continue; path ...
AtCoder's head office consists of N rooms numbered 1 to N. For any two rooms, there is a direct passage connecting these rooms. For security reasons, Takahashi the president asked you to set a level for every passage, which is a positive integer and must satisfy the following condition: * For each room i\ (1 \leq i \...
#二部グラフにできるのか #ここからよ #実は奇サイクルを含まない=二部グラフとなる #それぞれのレベルで奇サイクルかどうか #二部グラフを考えて残りでもどんどん二部グラフを考えるイメージ #最終的には1or2の状態で残る N=int(input()) ans=[[0]*N for j in range(N)] #nはvecの長さ #次の通路のレベル def dfs(n,vec,level): global ans #print(vec) #print(n) l=vec[:n//2] r=vec[n//2:] for i in l: for j in r: ...
Find the number, modulo 998244353, of sequences of length N consisting of 0, 1 and 2 such that none of their contiguous subsequences totals to X. Constraints * 1 \leq N \leq 3000 * 1 \leq X \leq 2N * N and X are integers. Input Input is given from Standard Input in the following format: N X Output Print the nu...
#include <iostream> #include <algorithm> #include <iomanip> #include <vector> #include <queue> #include <set> #include <map> #define N_MAX 6002 using namespace std; typedef long long ll; const ll MOD = 998244353; ll inv[N_MAX],fac[N_MAX],finv[N_MAX]; void init(){ fac[0]=fac[1]=1; finv[0]=finv[1]=1; inv[1]...
In some other world, today is Christmas. Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing: * A level-0 burger is a patty. * A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) b...
import java.util.*; class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); long X = sc.nextLong(); HashMap<Integer, Long> map = new HashMap<Integer, Long>(); long Nlen = 5; map.put(1, Nlen); for(int i = ...
There is a tree with N vertices numbered 1 through N. The i-th edge connects Vertex x_i and y_i. Each vertex is painted white or black. The initial color of Vertex i is represented by a letter c_i. c_i = `W` represents the vertex is white; c_i = `B` represents the vertex is black. A cat will walk along this tree. More...
#include <bits/stdc++.h> using namespace std; vector<int> edge[100050]; int n; char fuck[100050]; bool intree[100050]; void build(int pos,int lst) { if(fuck[pos] == 'W') intree[pos] = 1; for(auto v : edge[pos]) if(v != lst) { build(v,pos); intree[pos] |= intree[v]; } } int deg[100050]; int val[100050]...
Snuke has come up with the following problem. > You are given a sequence d of length N. Find the number of the undirected graphs with N vertices labeled 1,2,...,N satisfying the following conditions, modulo 10^{9} + 7: > > * The graph is simple and connected. > * The degree of Vertex i is d_i. > When 2 \leq N, 1...
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZER...
Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier. He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though. Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Ot...
x,a,b=map(int,input().split()) print("dangerous" if (a+x)<b else "delicious" if a>=b else "safe")
As a New Year's gift, Dolphin received a string s of length 19. The string s has the following format: `[five lowercase English letters],[seven lowercase English letters],[five lowercase English letters]`. Dolphin wants to convert the comma-separated string s into a space-separated string. Write a program to perform th...
#include<cstdio> #include<cstring> int main() { char str[20]; scanf("%s",str); str[5]=' '; str[13]=' '; puts(str); return 0; }
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion. All strings that can be obtained in this way can be evaluated as formulas. ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); String str[] = line.split(""); ...
Dr .: Peter, I've finally done it. Peter: See you again? What kind of silly invention is this time? Dr .: I finally came up with a revolutionary way to process mathematical formulas on a computer. Look at this table. Ordinary notation | Dr.'s "breakthrough" notation --- | --- 1 + 2 | 1 2 + 3 * 4 + 7 | 3 4 * 7 + 10 /...
#include<iostream> #include<cstdio> #include<string> #include<stack> #include<cstdlib> using namespace std; int main(){ string r; while(getline(cin,r)){ r+=' '; int mark = -1,range = 1; stack <double> num; char ord = 'k'; for(int i=0; i<r.size(); i++){ if(r[i] == ' '){ if(mark != -1){ ...
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development. For such a store manager, you decided to create a program that displays the number of e...
#include <iostream> using namespace std; int main() { int n, t, s[10], i, j; while (cin >> n && n) { for (i = 0; i < 10; i++) s[i] = 0; for (i = 0; i < n; i++) { cin >> t; s[t]++; } for (i = 0; i < 10; i++) { if (s[i] == 0) cout << "-" << endl; else { for (j = 0; j < s[i]; j++) ...
In the year 30XX, an expedition team reached a planet and found a warp machine suggesting the existence of a mysterious supercivilization. When you go through one of its entrance gates, you can instantaneously move to the exit irrespective of how far away it is. You can move even to the end of the universe at will with...
#include <bits/stdc++.h> using namespace std; #define _MACRO(_1, _2, _3, NAME, ...) NAME #define _repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define _rep(i,n) _repl(i,0,n) #define rep(...) _MACRO(__VA_ARGS__, _repl, _rep)(__VA_ARGS__) #define pb push_back #define all(x) begin(x),end(x) #define uniq(x) sort(all(x)),...
An bydrocarbon is an organic compound which contains only carbons and hydrogens. An isomer is a compound that has the same number of carbons but different structures. Heptane, for example, is a hydrocarbon with 7 carbons. It has nine isomers. The structural formula of three are shown in Figure 1. Carbons are represente...
#include<bits/stdc++.h> using namespace std; int main(){ while(1){ int n; cin >> n; if(cin.eof())break; int c=0; int x=0; for(int i=0;i<n/2;i++){ int f=1; for(int j=0;j<i;j++){ f*=3; } c+=f*2; x=f; //cout << c << endl; } if(n%2&&n!=1)c+=x*3; if(...
After long studying how embryos of organisms become asymmetric during their development, Dr. Podboq, a famous biologist, has reached his new hypothesis. Dr. Podboq is now preparing a poster for the coming academic conference, which shows a tree representing the development process of an embryo through repeated cell div...
#include<iostream> #include<string> #include<set> #include<iterator> #include<algorithm> #include<vector> using namespace std; typedef basic_string<bool> BS; const BS T=BS(1,true); const BS F=BS(1,false); char str[999]; char *p; struct Cell{ Cell *l,*r; BS bs; set<BS> sbs; int num,den; Cell():l(),r(),num(...
Given several points on a plane, let’s try to solve a puzzle connecting them with a zigzag line. The puzzle is to find the zigzag line that passes through all the given points with the minimum number of turns. Moreover, when there are several zigzag lines with the minimum number of turns, the shortest one among them sh...
#include<bits/stdc++.h> #define MAX 2500 #define inf 1<<29 #define linf 1e18 #define eps (1e-8) #define mod 1000000007 #define pi M_PI #define f first #define s second #define mp make_pair #define pb push_back #define all(a) (a).begin(),(a).end() #define pd(a) printf("%.10f\n",(double)(a)) #define FOR(i,a,b) for(int i=...
Problem The appearance of the sky is different from usual. A variety of colorful hot-air balloons covered the sky. Today is a hot-air balloon tournament. It seems that all the participants will compete for the scored ball dropped from the hot-air balloon. I decided to predict the winner because it was a big deal. * N...
#include <iostream> #include <vector> #include <fstream> #include <cstdio> #include <algorithm> #include <cmath> #include <map> #include <queue> #include <set> #include <functional> #include <ctime> #include <numeric> #include <unordered_set> #include <unordered_map> using namespace std; #define fst first #define snd...
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces. Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, t...
while True: n = int(raw_input()) if n==0: break lst = [0] * n for i in xrange(n): lst[i] = 1 << i isFailed = True calender = {} for i in xrange(n): a = map(int, raw_input().split()) for j in xrange(1, a[0]+1): if a[j] not in calender: calender[a[j]] = [] calender[a[j]].app...
A dial lock is a kind of lock which has some dials with printed numbers. It has a special sequence of numbers, namely an unlocking sequence, to be opened. You are working at a manufacturer of dial locks. Your job is to verify that every manufactured lock is unlocked by its unlocking sequence. In other words, you have ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define each(itr,v) for(auto itr:v) #define pb push_back #define all(x) (x).be...
The trafic on the Internet is increasing these days due to smartphones. The wireless carriers have to enhance their network infrastructure. The network of a wireless carrier consists of a number of base stations and lines. Each line connects two base stations bi-directionally. The bandwidth of a line increases every y...
#include<iostream> #include<sstream> #include<queue> using namespace std; const int N = 51; class E{ public: int a[N]; E(){ for(int i=0;i<N;i++)a[i]=0; } E(int n){ for(int i=0;i<N;i++)a[i]=0; } E(int n,int val){ for(int i=0;i<N;i++)a[i]=val; } E(int n,int v,int s){ for(int i=0;i<N;i++)a...
Problem D: Exportation in Space In an era of space travelling, Mr. Jonathan A. Goldmine exports a special material named "Interstellar Condensed Powered Copper". A piece of it consists of several spheres floating in the air. There is strange force affecting between the spheres so that their relative positions of them ...
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <cmath> #include <cstring> #include <complex> using namespace std; const double EPS = 1e-10; const double INF = 1e12; #define EQ(n,m) (abs((n)-(m)) < EPS) #define X real() #define Y imag() typedef complex<double> P; typedef vector<P...
Mr. A wants to get to the destination on the Yamanote line. After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also,...
"山手線" a, b, c = map(int, input().split()) flag = True if a+b == 60 and c > a: # 必ず辿りつけない print(-1) else: right = 0 left = a i = 0 while True: # print('left : ', left) # print('right : ', right) # print('c : ', c) if left >= c and c >= right: print(c) ...
Problem statement AOR Ika got a cabbage with $ N $ leaves. The leaves of this cabbage are numbered $ 1, \ ldots, N $ in order from the outside, and the dirtiness of the $ i $ th leaf is $ D_i $. The larger this value is, the worse the degree of dirt is. AOR Ika-chan decided to use the cabbage leaves for cooking, so sh...
#include <bits/stdc++.h> using namespace std; #define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repl(i,0,n) #define mp(a,b) make_pair((a),(b)) #define pb(a) push_back((a)) #define all(x) (x).begin(),(x).end() #define uniq(x) sort(all(x)),(x).erase(unique(all(x)),end(x)) #define fi first #define se...
N: Mail order Mr. Komozawa bought building blocks toys from Makai mail order. The building blocks are in the shape of a cube with a side length of 1, and are stacked on squares divided into $ H $ pieces vertically and $ W $ pieces horizontally. Seen from the side, $ A_1, A_2, A_3, \ dots, A_H $ blocks were stacked i...
#include <bits/stdc++.h> using namespace std; priority_queue<int, vector<int>, greater<int> > a; priority_queue<int, vector<int>, greater<int> > b; int main(){ int h, w; cin >> h >> w; int tmp; for(int i = 0;i < h;i++){ cin >> tmp; a.push(tmp); } for(int i = 0;i < w;i++){ cin >> tmp; b.pus...
Problem There are coins with front and back sides and dice with rolls from $ 1 $ to $ N $. Gacho decided to play the following games using these. The game starts with a score of $ 0 $ and proceeds as follows. 1. Roll the dice $ 1 $ and add the number of rolls to the score. 2. If the current score is $ K $ or more, ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; constexpr ll MOD = 998244353; ll power(ll x, ll n){ x %= MOD; ll res = 1; while(n > 0){ if(n&1){ res *= x; res %= MOD; } x *= x; x %= MOD; n >>= 1; } return res; } ...
Find common tangent lines of two circles $c1$ and $c2$. Constraints * $-1,000 \leq c1x, c1y, c2x, c2y \leq 1,000$ * $1 \leq c1r, c2r \leq 1,000$ * $c1$ and $c2$ are different Input Center coordinates ($cix$, $ciy$) and radii $cir$ of two circles $c1$ are $c2$ are given in the following format. $c1x \; c1y \; c1r$ ...
// #include {{{ #include <iostream> #include <cassert> #include <cstring> #include <cstdlib> #include <cstdio> #include <cctype> #include <cmath> #include <ctime> #include <queue> #include <set> #include <map> #include <stack> #include <string> #include <bitset> #include <vector> #include <complex> #include <algorithm>...
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique. * insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the cor...
from collections import defaultdict def main(): q = int(input()) d = defaultdict(int) for _ in range(q): para = input().split() if para[0] == "0": d[para[1]] = int(para[2]) elif para[0] == "1": print(d[para[1]]) main()
The Kalakeyas were a powerful, ferocious and cruel clan of Danavas. They were known to be really strong and they did not have any war strategy. They would just attack the enemy randomly and overpower them with sheer number of soldiers. However, we all know that Baahubali and Bhallaladeva defeated the Kalakeyas by follo...
import math as m no=int(raw_input()) out=[] inp=[] for i in range(no): a,b= map(int,raw_input().split()) inp.append([a,b]) for inputar in inp: a=inputar[0] b=inputar[1] if(a/2<b): out.append(-1) continue sol=[i for i in range(1,a+1)] if(b==0): out.append(sol) ...
You are given a string of lower case characters. You have to find the character with the most frequency. In case there are 2 such characters, consider the one with lower ASCII value. After this replace the character with the maximum frequency with '?' (without quotes). Then, print the resulting string. You have to do t...
T=input(); for t in range(T) : S=raw_input(); maxc=0; char=-1; for i in range(26) : c=S.count(chr(97+i)); if c>maxc : maxc=c; char=i; S=S.replace(chr(97+char),'?') print S;