input
stringlengths
29
13k
output
stringlengths
9
73.4k
Your task is very simple. Given K numbers A1, A2, ..., AK. You need to find f(N) mod max(A1, A2, ..., AK) . f(N)=N! Input First line contains single integer T denoting the number of test cases.. First line of each test case contains two integers N and K. Next line contains K integers Ak Output For each test case,...
from math import* for i in range (input()): num ,k = map(int,raw_input().split()) a = factorial(num) arr = map(int,raw_input().split()) maxi = max(arr) print a%maxi
Problem Desrcription Shil likes to play with trees a lot.He is playing with an undirected tree containing N nodes.He wants to find out total number of unordered triplets (A,B,C) such that A is not connected to B, B is not connected to C and A is not connected to C by a direct edge (No two of A, B, C are mutually conne...
N=int(input()) D=[0]*N for i in range(N-1): a,b=map(int,raw_input().split()) a-=1;b-=1; D[a]+=1 D[b]+=1 ans=N*(N-1)*(N-2) ans/=6 ans-=(N-1)*(N-2) for i in D: if i>=2: ans+=(i*(i-1))/2 print ans
This is a simple game you must have played around with during your school days, calculating FLAMES of you and your crush! Given the names of two people, cancel out the common letters (repeated occurrence of a letter is treated separately, so 2A's in one name and one A in the other would cancel one A in each name), coun...
testcase = raw_input(); tc = int(testcase) while (tc > 0): flames = "FLAMES" #flames[0] = 'X' name1=list((raw_input()).replace(' ','')) name2=list((raw_input()).replace(' ','')) #ht = {} count =0 count1 = 0 i=0 while(i < len(name1)): j=0 while(j < len(name2)): if(name1[i] == name2[j]): ...
Now that Chef has finished baking and frosting his cupcakes, it's time to package them. Chef has N cupcakes, and needs to decide how many cupcakes to place in each package. Each package must contain the same number of cupcakes. Chef will choose an integer A between 1 and N, inclusive, and place exactly A cupcakes into ...
t = int(raw_input()) for ii in range(t): i = int(raw_input()) if i == 1 : print 1 elif i == 2 : print 2 elif i%2 == 0 : print (i/2 +1) else : print ( (i+1)/2)
You are given a simple code of a function and you would like to know what it will return. F(N, K, Answer, Operator, A[N]) returns int; begin for iK do for jN do AnswerAnswer operator Aj) return Answer end Here N, K, Answer and the value returned by the function F are integers;...
for q in range(int(raw_input())): n,k,ans=[int(u) for u in raw_input().split()] arr=[int(u) for u in raw_input().split()] op=raw_input().strip() if(k==0): print ans continue if(op=='OR'): for i in arr: ans=ans|i elif(op=='AND'): for j in ra...
Chef and his girlfriend are going to have a promenade. They are walking along the straight road which consists of segments placed one by one. Before walking Chef and his girlfriend stay at the beginning of the first segment, they want to achieve the end of the last segment. There are few problems: At the beginning ...
for _ in range(input()): n= int(raw_input()) att = map(int,raw_input().split()) ans = [] for i in range(n): ans.append(att[i]+i) print max(ans)
At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector А: * Turn the vector by 90 degrees clockwise. * Add to the vector a certain vector C. Operations could be performed in any order any number of times. ...
#include <bits/stdc++.h> using namespace std; long long ax, ay, bx, by, cx, cy; long long AX[4], AY[4], CX[4], CY[4]; bool judge_51nod(long long ax, long long ay, long long cx, long long cy) { long long zi1 = abs((bx - ax) * cx + (by - ay) * cy); long long zi2 = abs((by - ay) * cx - (bx - ax) * cy); long long mu ...
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from t...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> a(n); int ans = 0; for (int i = 0; i < n; i++) { cin >> a[i]; ans = max(ans, a[i]); } for (int i = ans; i < 1000; i++) { int cur = 0; for (int j = 0; j < n; j++) { cur += i - a[j] * 2; } i...
You are given a tree with n vertices; its root is vertex 1. Also there is a token, initially placed in the root. You can move the token to other vertices. Let's assume current vertex of token is v, then you make any of the following two possible moves: * move down to any leaf in subtree of v; * if vertex v is a ...
#include <bits/stdc++.h> using namespace std; int read() { char c = getchar(); int x = 0; while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + (c - '0'), c = getchar(); return x; } void MOD(int &x) { if (x >= 998244353) x -= 998244353; } int m; int l, nxt[1000010], head[100001...
This is an interactive problem! Ehab plays a game with Laggy. Ehab has 2 hidden integers (a,b). Laggy can ask a pair of integers (c,d) and Ehab will reply with: * 1 if a ⊕ c>b ⊕ d. * 0 if a ⊕ c=b ⊕ d. * -1 if a ⊕ c<b ⊕ d. Operation a ⊕ b is the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise...
#include <bits/stdc++.h> using namespace std; inline long long fpow(long long n, long long k, int p = 998244353) { long long r = 1; for (; k; k >>= 1) { if (k & 1) r = r * n % p; n = n * n % p; } return r; } inline long long inv(long long a, long long p = 998244353) { return fpow(a, p - 2, p); } inlin...
You are given a binary matrix A of size n × n. Let's denote an x-compression of the given matrix as a matrix B of size n/x × n/x such that for every i ∈ [1, n], j ∈ [1, n] the condition A[i][j] = B[⌈ i/x ⌉][⌈ j/x ⌉] is met. Obviously, x-compression is possible only if x divides n, but this condition is not enough. For...
import java.io.*; import java.util.*; public class Main { private static int MOD = 1000000007; public static void main(String[] args) throws Exception { InputStream inS = System.in; // InputReader sc = new InputReader(inS); PrintStream out = System.out; Scanner sc = new Sc...
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to de...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); const double eps = 1e-6; const int inf = 1e9; const long long llf = 1e18; const int mod = 1e9 + 7; const int maxn = 5e5 + 10; int n, m; int p[maxn]; vector<int> f[maxn]; vector<int> q; int main() { cin >> n >> m; for (int i = 1; i <= n; i++...
You are given a string s consisting of n lowercase Latin letters. Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from po...
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 * * @author alecs6k */ public class Main { public static void main(String[] args) { InputStream i...
You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game. The boss battle consists of n turns. During each turn, you will get several cards. Each card has two parameters: its cost c_i and damage d_i. You may play some of your cards during each turn i...
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class F { public static void main(String[] args) throws Exception { new F().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = f.nextInt();...
This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n. A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the st...
from collections import Counter n = int(input()) a = list(map(int, input().split())) l = [len(str(i)) for i in a] c = Counter(l) cl = [c[i] for i in range(1,11)] M = 998244353 pad = lambda a, d: a%d + (a - a%d) * 10 #print(a, l, c, cl) ans = 0 for i in a: il = len(str(i)) # let's calculate it again to avoid zi...
Alice is playing with some stones. Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones. Each time she can do one of two operations: 1. take one stone from the first heap and two stones from the second heap (...
t = int(input()) while t>0: x, y, z = [int(i) for i in input().split()] s = 0 f = -1 z = z//2 if y >= z: y = y - z s = z*2 + z else: s = y*2 + y f = 1 if f == -1: y = y//2 if x >= y: s = s + 2*y + y else: ...
You're given a simple, undirected, connected, weighted graph with n nodes and m edges. Nodes are numbered from 1 to n. There are exactly k centrals (recharge points), which are nodes 1, 2, …, k. We consider a robot moving into this graph, with a battery of capacity c, not fixed by the constructor yet. At any time, th...
#include <bits/stdc++.h> using namespace std; struct Edge { int x, y; long long val; } e[3 * 100055]; bool cmp(Edge x1, Edge x2) { return x1.val < x2.val; } int head[100055], to[6 * 100055], nex[6 * 100055]; long long w[6 * 100055]; int edge; inline void addEdge(int x, int y, long long z) { to[++edge] = y, w[edge...
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n. Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ...
#include <bits/stdc++.h> using namespace std; bool vis[200010]; void dfs(vector<long long int> arr[], long long int i, long long int temp) { vis[i] = true; for (long long int u : arr[i]) { if (!vis[u] and u != temp) dfs(arr, u, temp); } } int main() { long long int t; cin >> t; while (t--) { long lo...
Polycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size 1 × 1 × 1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1 × 1 × 1; each cell ...
#include <bits/stdc++.h> using namespace std; template <class T> istream& operator>>(istream& is, vector<T>& v) { for (T& x : v) is >> x; return is; } template <class T> ostream& operator<<(ostream& os, const vector<T>& v) { if (!v.empty()) { os << v.front(); for (int x = 1; x < v.size(); ++x) os << ' ' <...
Piet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules. The program will be a rectangular image consisting of col...
#include <bits/stdc++.h> using namespace std; static const int INF = 500000000; template <class T> void debug(T a, T b) { for (; a != b; ++a) cerr << *a << ' '; cerr << endl; } int w, h, n; char buf[55][55]; pair<int, int> moveTo[55][55][4][2]; int state[55][55][4][2]; int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1}...
James Bond has a new plan for catching his enemy. There are some cities and directed roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there. The city ...
#include <bits/stdc++.h> using namespace std; mt19937 gene(233); inline char GET_CHAR() { const int maxn = 131072; static char buf[maxn], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, maxn, stdin), p1 == p2) ? EOF : *p1++; } inline int getInt() { int res(0);...
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; int arr[n]; int arr1[m]; for (int i = 0; i < n; i++) { cin >> arr[i]; } for (int i = 0; i < m; i++) { cin >> arr1[i]; } int num = -1; for (int i = ...
BubbleSquare social network is celebrating 13^{th} anniversary and it is rewarding its members with special edition BubbleSquare tokens. Every member receives one personal token. Also, two additional tokens are awarded to each member for every friend they have on the network. Yet, there is a twist – everyone should end...
#include <bits/stdc++.h> #pragma GCC optimize(2) #pragma GCC optimize("Ofast") using namespace std; namespace Base { inline char gc(void) { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } template...
This is the hard version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved. You are given an array [a_1, a_2, ..., a_n]. Your goal is to find the length of the longest subarray of this array such that the...
#include <bits/stdc++.h> using namespace std; const long long inf = 1e9 + 69; const int MX = 5e5 + 5; const int LG = (int)log2(MX); const long long mod = 1e9 + 7; const int BLOCK = 450; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int n; vector<int> v, cnt; vector<int> q, inv; int val = 0; void ...
Alice had a permutation p_1, p_2, …, p_n. Unfortunately, the permutation looked very boring, so she decided to change it and choose some non-overlapping subranges of this permutation and reverse them. The cost of reversing a single subrange [l, r] (elements from position l to position r, inclusive) is equal to r - l, a...
#pragma GCC optimize ("Ofast") #include<bits/stdc++.h> using namespace std; void*wmem; char memarr[96000000]; template<class S, class T> inline S min_L(S a,T b){ return a<=b?a:b; } template<class T> inline void walloc1d(T **arr, int x, void **mem = &wmem){ static int skip[16] = {0, 15, 14, 13, 12, 11, 10, 9, 8, 7, ...
Please note the non-standard memory limit. There are n problems numbered with integers from 1 to n. i-th problem has the complexity c_i = 2^i, tag tag_i and score s_i. After solving the problem i it's allowed to solve problem j if and only if IQ < |c_i - c_j| and tag_i ≠ tag_j. After solving it your IQ changes and be...
#include <stdio.h> #include <map> #include <vector> int absi(int i) { if (i > 0) return i; else return -i; } int main() { int T; scanf("%d", &T); while (T--) { int n; long long ans = 0; scanf("%d", &n); std::vector<int> tag(n + 1); std::vector<int> s(n + 1); std::vector<long long> d(n + 1, 0); fo...
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circl...
import java.io.*; import java.util.*; public class c{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long s = sc.nextLong(); long[][] factors = getFactors(s); long tot = 0; for(int i = 0; i < factors.length; i++){ tot += factors[i][1]; } boolean res = isWinner(tot); ...
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming. It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file. Ever...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; public class java1 { public static void main(String[] args) {...
Polycarpus enjoys studying Berland hieroglyphs. Once Polycarp got hold of two ancient Berland pictures, on each of which was drawn a circle of hieroglyphs. We know that no hieroglyph occurs twice in either the first or the second circle (but in can occur once in each of them). Polycarpus wants to save these pictures o...
#include <bits/stdc++.h> using namespace std; int lenA, lenB; int A[1000004]; int B[1000004]; int idxB[1000004]; int main() { scanf("%d %d", &lenA, &lenB); for (int i = 0, _n = (lenA); i < _n; ++i) scanf("%d", A + i); memset(idxB, -1, sizeof(idxB)); for (int j = 0, _n = (lenB); j < _n; ++j) { scanf("%d", B ...
Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the si...
import java.util.Scanner; public class P7 { public static void main(String[] arg) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int tot = a*c; int cont = 0; while(tot > 0){ tot = tot -b;...
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string s, ...
from collections import Counter import string import math import sys def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(number_of_variables): if number_of_variables==1: return int(sys.stdin.readline()) if number_of_variables>=2: return map(int,sys.stdin.readline(...
The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the...
#include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:36777216") template <class T> inline T &RD(T &); template <class T> inline void OT(const T &); inline long long RD() { long long x; return RD(x); } inline char &RC(char &c) { scanf(" %c", &c); return c; } inline char RC() { char c; ...
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
import java.util.HashMap; import java.util.Scanner; public class A { public static void main(String[] args) { HashMap<Integer, Integer> setH = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> setA = new HashMap<Integer, Integer>(); Scanner s = new Scanner(System.in); int n...
<image> Input The first line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be a letter of English alphabet, lowercase or uppercase. The second line of the input is an integer between 0 and 26, inclusive. Output Output the required string. Examples Input AprilFool 14...
#include <bits/stdc++.h> using namespace std; template <typename T> int size(T& a) { return (int)a.size(); } template <typename T> T sqr(T a) { return a * a; } bool isLowercase(char ch) { return ch >= 'a' && ch <= 'z'; } bool isUppercase(char ch) { return !isLowercase(ch); } char toLowercase(char ch) { if (isUppe...
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another. (Cultural note: standing in huge and disorganized queues for hours is a native ...
#include <bits/stdc++.h> using namespace std; int s[5555], b[5555]; bool mark[5555], moze[5555]; int main() { int n, x, i, j, t, q, br, of, bb; scanf("%d%d", &n, &x); for (i = 0; i <= n; i++) mark[i] = false; for (i = 1; i <= n; i++) { scanf("%d", &s[i]); mark[s[i]] = true; } br = 0; of = 0; q =...
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
x=input() x=x.replace("+","") x=sorted(x) for i in range(1,2*len(x)-1,2): x.insert(i,"+") x=''.join(x) print(x)
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types: 1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j ...
#include <bits/stdc++.h> using namespace std; const int maxn = 5000 + 10; int a[maxn]; int b[maxn]; int c[maxn]; int cnt[maxn]; int n, m; bool mark[maxn]; int q[maxn][5]; bool Bomb; int main() { cin >> n >> m; for (int i = 1; i <= m; i++) { cin >> q[i][1]; if (q[i][1] == 1) { cin >> q[i][2] >> q[i][3]...
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 ≤ i ≤ n) day, the price for one barrel of honey is going to is xi kilos of raspberry. Unfortunately, the b...
#include <bits/stdc++.h> using namespace std; int main() { int n, c; int m; int dif; int ans; while (scanf("%d %d", &n, &c) == 2) { vector<int> num; for (int i = 0; i < n; i++) { scanf("%d", &m); num.push_back(m); } dif = ans = 0; for (int i = 1; i < num.size(); i++) { if...
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partiti...
#include <bits/stdc++.h> using namespace std; int n, m; int visit[111111]; vector<int> v[111111], mark[111111]; int dfs(int t) { vector<int> v1; int i; for (i = 0; i < v[t].size(); i++) { int u = v[t][i]; if (visit[mark[t][i]] == 0) { visit[mark[t][i]] = 1; int w = dfs(u); if (w == 0) ...
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends. Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal ...
import java.util.Scanner; /** * Created by zephyr on 5/30/14. */ public class GIft { public static void main(String args[]){ System.out.println(gift()); } public static String gift(){ Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); int x100 = 0; ...
Andrew plays a game called "Civilization". Dima helps him. The game has n cities and m bidirectional roads. The cities are numbered from 1 to n. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities v1, v2, ..., vk, that there is a r...
#include <bits/stdc++.h> using namespace std; const int maxn = 3e5; int n, m; int f[maxn]; int diameter[maxn]; int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); } vector<int> G[maxn]; int d1[maxn], d2[maxn]; int vis[maxn], t; queue<int> q; int bfs1(int u, int d[]) { t++; q.push(u); d[u] = 0; vis[u] = ...
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player. Your task is to write a program that...
l=list(map(int,input().split())) x=sum(l) if(x%5==0 and x!=0): print(int(x/5)) else: print(-1)
New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi. As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a...
#include <bits/stdc++.h> using namespace std; const int N = 1005; inline int read() { int x = 0, w = 1; char ch = 0; while (ch < '0' || ch > '9') { ch = getchar(); if (ch == '-') w = -1; } while (ch <= '9' && ch >= '0') { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x * w; ...
In this problem you will meet the simplified model of game King of Thieves. In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way. <image> An interesting feature of the game is that you can design your own levels...
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); for (int i = 0; i < n; i++) { for (int j = 1; j < n; j++) { boolean f = true; for(int k = 0; k < 5; k++) if(i + k * j < n && s.ch...
Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one. GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x...
def solve(): a = raw_input() b = raw_input() c = raw_input() acount = [0] * 26 for char in a: acount[ord(char) - ord('a')]+=1 bcount = [0] * 26 for char in b: bcount[ord(char) - ord('a')]+=1 ccount = [0] * 26 for char in c: ccount[ord(char) - ord('a')]+=1 bres = 0 cres = 0 ...
You are given a sequence of n integers a1, a2, ..., an. Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible. The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence. The poor...
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.InputMismatchException; /** * Built using ...
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: * Include a perso...
#include <bits/stdc++.h> using namespace std; int main() { int m = 0, a = 0; for (int i = 0; i < 100; i++) { string s; getline(cin, s); if (s[0] == '+') { m++; continue; } if (s[0] == '-') { m--; continue; } int c = 1; int t = 0; for (int j = 0; j < s.size...
Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point. Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to ...
#include <bits/stdc++.h> using namespace std; class Solver621D { public: void run(); }; void Solver621D::run() { vector<string> formulas = {"x^y^z", "x^z^y", "(x^y)^z", "y^x^z", "y^z^x", "(y^x)^z", "z^x^y", "z^y^x", "(z^x)^y"}; vector<function<complex<double>(complex<double>, co...
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities. Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting ea...
#include <bits/stdc++.h> using namespace std; template <typename T> std::ostream &operator<<(std::ostream &out, vector<T> &v) { for (typename vector<T>::size_type i = 0; i < v.size(); ++i) out << v[i] << " "; out << "\n"; return out; } template <typename T> std::ostream &operator<<(std::ostream &out, set<T> &...
In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from 1 to 109. At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. Aft...
n, k = input().split(' ') n = int(n) k = int(k) d = input().split(' ') i = 0 while True: i += 1 p = int((i) * (i+1) / 2) if k <= p : print(d[k-(p-i)-1]) break
You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj). At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get? Let p and q be two permutations of the numbers 1, 2, ..., n. p i...
#include <bits/stdc++.h> using namespace std; int SET(int n, int pos) { return n = n | (1 << pos); } int RESET(int n, int pos) { return n = n & ~(1 << pos); } int CHECK(int n, int pos) { return (bool)(n & (1 << pos)); } int bigMod(int n, int power, int MOD) { if (power == 0) return 1; if (power % 2 == 0) { int ...
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edg...
#include <bits/stdc++.h> using namespace std; int break_point() { char c; while ((c = getchar()) != '\n') ; return 0; } template <typename T> void read_integer(T &r) { bool sign = 0; r = 0; char c; while (1) { c = getchar(); if (c == '-') { sign = 1; break; } if (c != ' ' &...
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s. ...
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min; public class A implements Runnable{ // SOLUTION!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! ...
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z". The testtube is divided into n consecutive re...
#include <bits/stdc++.h> using namespace std; long long MOD = 1e9 + 7; int inf = 2e9; long long INF = 8e18; int fre[26][5001]; int ts[5001]; int ff[5001]; int fac[5001]; int nf[5001]; string s; long long fe(long long x, int e) { long long r = 1; while (e) { if (e & 1) r = (r * x) % MOD; x = (x * x) % MOD; ...
Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it? Input The input contains a single integer n (0 ≤ n ≤ 2000000000). Output Output a single integer. Examples Input 11 Output 2 Input 14 Output 0 Input 61441 Output 2 Input 571576 Output 10 Input 2128506 Output 3
a=str(hex(int(input()))) b=0 for i in range(2,len(a)): if a[i]=="0" or a[i]=="4" or a[i]=="6" or a[i]=="9" or a[i]=="a" or a[i]=="d": b+=1 elif a[i]=="8" or a[i]=="b": b+=2 print(b)
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path. You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times. Solve...
l,r= map(int,raw_input().split()) if r-l<10: three = 0 two = 0 for i in range (l,r+1): if i%3 == 0: three += 1 if i%2 == 0: two += 1 if three==0 and two==0: print (l) exit() if three>=two: print (3) else : print (2) else: print (2)
There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine the mi...
#include <bits/stdc++.h> using namespace std; using i64 = long long; class A830 { private: i64 cost(i64 a, i64 b, i64 c) { return abs(a - b) + abs(b - c); } public: void solve(istream& in, ostream& out) { int n, k, p; in >> n >> k >> p; vector<int> a(n), b(k); for (int i = 0; i < n; ++i) { ...
Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points a, b, c. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c....
str=raw_input() a=str.split() def len(x1,y1,x2,y2): return (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1) for x in xrange(0,6): a[x]=int(a[x]) if(len(a[0],a[1],a[2],a[3])==len(a[2],a[3],a[4],a[5]) and ((a[5]-a[3])*(a[2]-a[0])!=(a[4]-a[2])*(a[3]-a[1]))): print 'Yes' else: print 'No'
Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :) Rick and Morty like to go to the ridge High Cry for crying loudly — there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this...
#include <bits/stdc++.h> using namespace std; const long long N = 2e5 + 5; stack<pair<long long, long long> > q; long long n, a[N], go[N]; struct cell { long long max_l, max_r, or_l, or_r; }; bool d[N][35]; cell b[N]; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for (long...
Let's consider the following game. We have a rectangular field n × m in size. Some squares of the field contain chips. Each chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right. The player may choose a chip and make a move with it. The move ...
#include <bits/stdc++.h> using namespace std; int m, n, mn, ans, cnt, p[5005][4]; char c[5005]; int v[5005], vw; int f(char c) { switch (c) { case 'L': return 0; case 'R': return 1; case 'U': return 2; case 'D': return 3; } } int solve(int x) { for (int i = 0; i < mn; ++i) ...
You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. ...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; set<int> g[N], disconn; vector<int> ans_vec, temp, temper; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; int x, y; while (m--) { cin >> x >> y; g[x].insert(y); g[y].insert(x); } vect...
BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!). Main feature of services offered by BigData Inc. is the access availability guarantee even under the ci...
import java.io.*; import java.util.*; public class MainC { static final StdIn in = new StdIn(); static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n=in.nextInt(), m=in.nextInt(), h=in.nextInt(); int[] u = in.readIntArray(n, 0); List<Integer>[] graph = ne...
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ...
n = int(input()) k = str(input()) Max = 0 for i in range(n-1): t=k[i]+k[i+1] z=0 for j in range(0,n-1): s=k[j]+k[j+1] if (s==t): z=z+1 #print(z) if (z>Max): Max=z res=t print(res)
Allen and Bessie are playing a simple number game. They both know a function f: \{0, 1\}^n → R, i. e. the function takes n binary arguments and returns a real value. At the start of the game, the variables x_1, x_2, ..., x_n are all set to -1. Each round, with equal probability, one of Allen or Bessie gets to make a mo...
#include <bits/stdc++.h> using namespace std; int N, R, vals[1 << 18]; double sum = 0; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(18); cin >> N >> R; for (int i = 0; i < (1 << N); i++) { cin >> vals[i]; sum += vals[i]; } cout << sum / (1 << N) << '\n'; f...
The bloodiest battle of World War II has started. Germany and its allies have attacked the Soviet union army to gain control of the city of Stalingrad (now Volgograd) in the south-western Soviet Union.The war has become intensive and the soviet union's 64th army is fighting against the germans. General "Vasily Chuikov"...
import math #import decimal from * def func(x1,y1,x2,y2,x3,y3): area = x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2) if area < 0.0: area = -area area = area*(0.5) return area t = int(raw_input()) while t > 0: st = raw_input() st = st.split(' ') x1 = float(st[0]) y1 = float(st[1]) x2 = float(st[2]) y2 = floa...
Ramesh and Suresh were in the same class and got home work from their mathematics teacher. The Homework consists of N strings and each string consists of only digits. The task which they need to perform is that they need to divide the string into 4 integers such that their sum is maximum. Note: Each integer should be...
T=input() best=-1 bound=10**12 boundS=str(bound) def findBest(s,off,n,sofar): #print "looking for best fo",s[off:],n remain=len(s)-off if remain<n: return global best if n==1: if remain>13: return if s[off]=="0": if len(s)-off>1: return if remain==13 and s[off:]!=boundS: return val=sofar+int(s[...
Problem Description Given a list of integers, find and display all even numbers from the end of the list. Input Format Each line of input begins with an integer N indicating the number of integer n that follow which comprises a list. Output Format All even numbers from the end of the list, each separated by a sin...
while True: try: s = raw_input() except: break if len(s.rstrip().lstrip())==0: break ser = map(int, s.split()) srr = ser[1:][::-1] found = False for x in srr: if x % 2 == 0: found = True print x, if not found: ...
Draco Malfoy and Hermione Granger have gotten into a "battle of brains". Draco was foolish enough to challenge her to a Arithmancy problem. Septima Vector, Arithmancy teacher at Hogwarts, has agreed to give them both a problem which they should solve overnight. The problem is as follows :- Firstly, a function F (fro...
t=int(raw_input()) def z(x): i=5 c=0 while x/i>=1: c+=n/i i*=5 return c for i in range(t): n=int(raw_input()) print z(n)
Given 2 numbers n1 and n2, following operations can be performed: 1) Decrement n1 by 1(if n1>1) 2) Decrement n2 by 1(if n2>1) 3) Incremenet n1 by 1 4) Incremenet n2 by 1 Find the maximum possible value of gcd(n1,n2) with atmost k operations. Note: Any of the 4 operations counts for one operation. gcd(n1,n2) refers to G...
t=input() from fractions import gcd for x in range(t): n1=input() n2=input() k=input() ans=0 for i in range(-k, k+1): if i+n1<1: continue absi=abs(i) for j in range(-k+absi, k-absi+1): if j+n2<1: continue y=gcd(n1+i, n2+j) if y>ans: ans=y print ans
The time has arrived when the world is going to end. But don't worry, because the new world yuga will start soon. Manu (carrier of mankind) has been assigned the job to carry all the necessary elements of current yuga to the upcoming yuga. There are N stones arranged in a straight line. In order to fulfill the task, M...
def func(s,val): cfc=0 x=0 length=len(s) for i in range(length): if x+s[i]<=val: x+=s[i] else: cfc+=1 x=s[i] return cfc+1 t=input() for i in range(t): l1=map(int,raw_input().strip().split()) n=l1[0] j=l1[1] route=map(int,raw_input().strip().split()) s=[] minimum=0 for k in range(1,n): x=rou...
Professor Sharma gives the following problem to his students: given two integers X( ≥ 2) and Y( ≥ 2) and tells them to find the smallest positive integral exponent E such that the decimal expansion of X^E begins with Y. For example, if X = 8 and Y= 51, then X^3 = 512 begins with Y= 51, so E= 3. Professor Sharma has a...
i=1 for _ in xrange(input()): a,b=map(int,raw_input().split()) n=1 x=1 while True: x=x*a if str(b) == str(x)[:len(str(b))]: break n=n+1 print "Case %d:"%i, n i+=1
The russian intelligence agency KGB make an encryption technique to send their passwords. Originally the password is of 3 characters. After encryption the password is converted into 3 numbers A-B-C. Now, Sherlock wants to decrypt the password encryption technique of KGB. Sherlock knows that every number has only 2 po...
T = int(raw_input()) for ti in xrange(T): a,b,c = map(int,raw_input().split()) if a%3: s1 = 'X' else: while a%3==0: a /= 3 if a==1: s1 = 'K' else: s1 = 'X' if b%5: s2 = 'Y' else: while b%5==0: b /= 5 if b==1: s2 = 'G' else: s2 = 'Y' if c%2: s3 = 'Z' else: while c%2==0: c ...
Jiro is a fun loving lad. His classmates are very competitive and are striving for getting a good rank, while he loves seeing them fight for it. The results are going to be out soon. He is anxious to know what is the rank of each of his classmates. Rank of i'th student = 1+ (Number of students having strictly grea...
n = int(raw_input()) m = map(int, raw_input().split()) for i in range(0,len(m)): count =1 for j in range(0,len(m)): if(m[i]<m[j]): count+=1 print count,
PowerShell had N natural numbers. He wanted to test Xenny's speed in finding the sum and difference of several numbers. He decided to ask Xenny several questions. In each question, he gave him two positive integers L and R. He asked him to find the sum of all integers from index L to index R (inclusive) and the differ...
n,q=map(int,raw_input().split()) b=map(int,raw_input().split()) bb=[0] for i in xrange(n): bb.append(bb[len(bb)-1]+b[i]) for i in xrange(q): l,r=map(int,raw_input().split()) print bb[r]-bb[l-1],2*b[r-1]-bb[r]+bb[l-1]
Given is a string S, where each character is `0`, `1`, or `?`. Consider making a string S' by replacing each occurrence of `?` with `0` or `1` (we can choose the character for each `?` independently). Let us define the unbalancedness of S' as follows: * (The unbalancedness of S') = \max \\{ The absolute difference be...
#include<bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=a;i<=b;i++) #define ROF(i,a,b) for(int i=a;i>=b;i--) const int N=1e6+7,INF=0x3f3f3f3f,sgn[]={-1,1}; char a[N]; int n,s[N],nxt[N]; int solve(int x,int cnt=0){ int w=0; FOR(i,1,n){ if(a[i]=='?'&&cnt+2+nxt[i]<=x)cnt+=2; w=min(w,s[i]+cnt); } ...
Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten. Constraints * 1 \leq N < 10^{100} * 1 \leq K \leq 3 Input Input is given from Standard Input in the following format: N K Output Print the count. Examples Input 100 1 Output 19 Inpu...
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 * * @author varunvats32 */ public class Main { public static void main(String[] args) { InputStre...
Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once. The i-th dish (1 \leq i \leq N) he ate was Dish A_i. When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points. Additionally, when he eats Dish i+1 just after eating Dish i (1 \...
#include <bits/stdc++.h> using namespace std; int n,a[201],b[201],c[201]; int main() { scanf("%d",&n); int sum=0; for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=1;i<=n;i++) scanf("%d",&b[i]),sum+=b[i]; for(int i=1;i<n;i++) scanf("%d",&c[i]); for(int i=1;i<n;i++) if(a[i]+1==a[i+1]) sum+=c[a[i]]; prin...
You are given a simple connected undirected graph G consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. Edge i connects Vertex a_i and b_i bidirectionally. It is guaranteed that the subgraph consisting of Vertex 1,2,\ldots,N and Edge 1,2,\ldots,N-1 is a spanning t...
#include<bits/stdc++.h> using namespace std; typedef long long LL; const int N=20,mod=1000000007; int add(int a,int b,int p=mod){return a+b>=p?a+b-p:a+b;} int sub(int a,int b,int p=mod){return a-b<0?a-b+p:a-b;} int mul(int a,int b,int p=mod){return (LL)a*b%p;} void sadd(int &a,int b,int p=mod){a=add(a,b,p);} void ss...
There are N integers a_1, a_2, ..., a_N not less than 1. The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P. Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N. Constraints * 1 \leq N \leq 10^{12} * 1 \leq P \leq 10^{12} Input Input is...
import math import collections # 試し割法 N, P = map(int, input().split()) def trial_division(n): # 素因数を格納するリスト factor = [] # 2から√n以下の数字で割っていく tmp = int(math.sqrt(n)) + 1 for num in range(2, tmp): while n % num == 0: n //= num factor.append(num) # リストが空ならそれは素数 ...
You are given an integer sequence A of length N and an integer K. You will perform the following operation on this sequence Q times: * Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one ...
N, K, Q = map(int, input().split()) X = list(map(int, input().split())) r = 10**18 for y in X: tmp = [] tmp2 = [] for x in X: if x < y: tmp.sort() tn = len(tmp) if len(tmp) > K-1: tmp2 += tmp[:tn-K+1] tmp = [] continue ...
Joisino is planning to open a shop in a shopping street. Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those ...
// C - Shopping Street #include <bits/stdc++.h> using namespace std; using vi = vector<int>; using vvi = vector<vi>; #define rp(i,s,e) for(int i=(int)(s);i<(int)(e);++i) int main(){ int n; cin>>n; vvi F(n, vi(10)); rp(i, 0, n) rp(j, 0, 10) cin>>F[i][j]; vvi P(n, vi(10+1)); rp(i, 0, n) rp(j, 0, 10+1) cin>>P[i][j];...
Mole decided to live in an abandoned mine. The structure of the mine is represented by a simple connected undirected graph which consists of N vertices numbered 1 through N and M edges. The i-th edge connects Vertices a_i and b_i, and it costs c_i yen (the currency of Japan) to remove it. Mole would like to remove som...
#include<bits/stdc++.h> using namespace std; inline int read() { int res=0,fh=1; char ch=getchar(); while((ch>'9'||ch<'0')&&ch!='-')ch=getchar(); if(ch=='-')fh=-1,ch=getchar(); while(ch>='0'&&ch<='9')res=res*10+ch-'0',ch=getchar(); return fh*res; } const int maxn=16; int n,m,mxs,sum[(1<<16)+12],a[maxn][maxn]; ...
Snuke has decided to play a game, where the player runs a railway company. There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke Line stops at station 0 and every d-th station thereafter, where d is a predetermined constant for each train. For example, if d = 3, the train stops at station 0, 3, 6...
#include <bits/stdc++.h> #define ll long long #define INF 999999999 #define MOD 1000000007 #define rep(i,n) for(int i=0;i<n;i++) using namespace std; typedef pair<int,int>P; const int MAX_N = 100005; vector<P> lens[100005]; int bit[MAX_N+1],n,m; //i番目までの和を計算する int sum(int i) { int s = 0; while(i>0){ s += bit[i...
We have a string X, which has an even number of characters. Half the characters are `S`, and the other half are `T`. Takahashi, who hates the string `ST`, will perform the following operation 10^{10000} times: * Among the occurrences of `ST` in X as (contiguous) substrings, remove the leftmost one. If there is no occ...
#import<iostream> using namespace std; string s;int c,f; int main(){ cin>>s; for(int i=0;i<s.size();i++){ if(s[i]=='S')f++; else if(f>0)f--,c+=2; } cout<<s.size()-c<<endl; }
There is a 120 minute videotape with standard recording. When I set the VCR counter to 00:00:00 with the tape completely rewound and recorded in standard recording mode, I got a certain counter value. Enter this counter value (hours, minutes, seconds), find the length of the remaining tape (recordable time), and create...
#include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <cmath> #include <stack> #include <vector> #include <map> #include <set> #include <queue> #include <list> #include <iostream> #include <climits> #include <cfloat> using namespace std; void printTime(int sec) { printf("%02d:%02d:%02d...
You want to go on a trip with a friend. However, friends who have a habit of spending money cannot easily save travel expenses. I don't know when my friends will go on a trip if they continue their current lives. So, if you want to travel early, you decide to create a program to help your friends save in a planned mann...
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class Main{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; void run(){ for(;;){ int l=sc.nextInt(); if(l==0){ break; } int...
A trick of fate caused Hatsumi and Taku to come to know each other. To keep the encounter in memory, they decided to calculate the difference between their ages. But the difference in ages varies depending on the day it is calculated. While trying again and again, they came to notice that the difference of their ages w...
#include<bits/stdc++.h> // Shrotening #define fst first #define snd second #define pb push_back // Loop #define FOR(i,a,b) for(auto i=(a);i<(b);++i) #define RFOR(i,a,b) for(auto i=(a);i>=(b);--i) #define REP(i,a) for(long i=0;i<(a);++i) #define RREP(i,a) for(long i=(a);i>=0;--i) #define EACH(i,a) for(auto (i)=(a).b...
There are N stations in the city where JOI lives, and they are numbered 1, 2, ..., and N, respectively. In addition, there are M railway lines, numbered 1, 2, ..., and M, respectively. The railway line i (1 \ leq i \ leq M) connects station A_i and station B_i in both directions, and the fare is C_i yen. JOI lives nea...
#include<iostream> #include<algorithm> #include<vector> #include<queue> #include<functional> using namespace std; #define ll long long const ll linf = 1e15; struct edge{ int to; ll cost; }; struct node{ int from; ll cost; bool operator<(const node &n1) const { return n1.cost < cost; } }...
A new type of mobile robot has been developed for environmental earth observation. It moves around on the ground, acquiring and recording various sorts of observational data using high precision sensors. Robots of this type have short range wireless communication devices and can exchange observational data with ones ne...
#include<cmath> #include<queue> #include<cstdio> #include<string> #include<cassert> #include<algorithm> #define rep(i,n) for(int i=0;i<(n);i++) #define sq(x) ((x)*(x)) #define sqsum(x,y) (sq(x)+sq(y)) using namespace std; struct path{ int n,t[1001],x[1001],y[1001]; }; struct event{ // ロボットの接触イベント double t; ...
You are working for an amusement park as an operator of an obakeyashiki, or a haunted house, in which guests walk through narrow and dark corridors. The house is proud of their lively ghosts, which are actually robots remotely controlled by the operator, hiding here and there in the corridors. One morning, you found th...
#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 std; int h, w, n;...
Two coordinates (a1, a2) and (b1, b2) on a two-dimensional grid of r × c are given. The cost of moving from a cell (e, f) to one of the cells (e + 1, f), (e-1, f), (e, f + 1), (e, f-1) is 1. And. You can also move between (e, c-1) and (e, 0), and between (r-1, f) and (0, f) at a cost of 1. At this time, find the number...
#include<iostream> #include<cmath> using namespace std; #define rep(i, n) for (int i = 0; i < int(n); ++i) const int MOD = 100000007; long long nck[1111][1111]; int main() { rep (i, 1111) nck[i][0] = 1; rep (i, 1110) rep (j, 1110) { nck[i + 1][j + 1] = (nck[i][j] + nck[i][j + 1]) % MOD; } int r, c...
<!-- Problem G --> Let's Move Tiles! You have a framed square board forming a grid of square cells. Each of the cells is either empty or with a square tile fitting in the cell engraved with a Roman character. You can tilt the board to one of four directions, away from you, toward you, to the left, or to the right, ...
#include <iostream> #include <string> #include <cstdio> #include <vector> #include <numeric> #include <cstdlib> #include <cctype> using namespace std; #define ALL(v) begin(v),end(v) #define REP(i,n) for(int i=0;i<(n);++i) #define RREP(i,n) for(int i=(n)-1;i>=0;--i) typedef long long LL; typedef vector<int> vint; con...
Nathan O. Davis is a student at the department of integrated systems. Today he learned digital quanti- zation in a class. It is a process that approximates analog data (e.g. electrical pressure) by a finite set of discrete values or integers. He had an assignment to write a program that quantizes the sequence of real ...
#include <cstdio> #include <iostream> #include <sstream> #include <fstream> #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 <cfloa...
KM country has N kinds of coins and each coin has its value a_i. The king of the country, Kita_masa, thought that the current currency system is poor, and he decided to make it beautiful by changing the values of some (possibly no) coins. A currency system is called beautiful if each coin has an integer value and the...
#include <iostream> #include <vector> #include <algorithm> #include <iomanip> #include <cmath> using namespace std; const double INF = 1e18; const int lim = 200000; int main(){ int n; cin >> n; vector<int> a(n); for(int i=0; i<n; i++) cin >> a[i]; vector<double> dp(lim+1, 0); for(int i=0; i<n; i++){ vector<d...
You happened to get a special bicycle. You can run with it incredibly fast because it has a turbo engine. You can't wait to try it off road to enjoy the power. You planned to go straight. The ground is very rough with ups and downs, and can be seen as a series of slopes (line segments) when seen from a lateral view. T...
#include<cmath> #include<cstdio> #include<vector> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; const long double EPS=1e-8; const long double PI=acos(-1); struct point{ long double x,y; point():x(0),y(0){} point(long double x,long double y):x(x),y(y){} point operator-(const point &a)const{ return...
You are practicing a juggle that involves in a number of square tiles. They all look the same in their size, but actually there are three different kinds of the tiles, A, B and X. The kind of a tile can be distinguishable by its mass. All the tiles of the same kind have exactly the same mass. The mass of type A tiles i...
#include<bits/stdc++.h> using namespace std; double EPS=1e-9; struct L{ double a,b,c; L(double A,double B,double C){ a=A; b=B; c=C; } L(){} }; struct P{ double x,y; P(double X,double Y){ x=X; y=Y; } P(){} }; inline bool operator < (const P &a,const P &b){ if(a.x!=b.x){ return a.x<b.x; }else return...
G: Destiny Draw- problem Mr. D will play a card game. This card game uses a pile of N cards. Also, the pile cards are numbered 1, 2, 3, ..., N in order from the top. He can't afford to be defeated, carrying everything that starts with D, but unfortunately Mr. D isn't good at card games. Therefore, I decided to win b...
#include <bits/stdc++.h> using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int, int> PII; typedef long long LL; typedef pair<LL, LL> PLL; #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(), (a).rend() #define PB push_back #define EB emplace_ba...
For skilled programmers, it is very easy to implement a sorting function. Moreover, they often avoid full sorting to reduce computation time if it is not necessary. Here, we consider "rough sorting" which sorts an array except for some pairs of elements. More formally, we define an array is "$K$-roughly sorted" if an a...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; #define ll long long #define ull unsigned long long #define rep(i,n,N) for(ll i=n;i<=N;++i) #define rap(i,n,N) for(ll i=n;i>=N;--i) #define mp make_pair #define pb push_back #define pob pop_back #define pf push_front #define pof pop_front #define...
Problem There is a bundle of $ n $ cards, with $ i $ written on the $ i $ th card from the bottom. Shuffle this bundle as defined below $ q $ times. * When looking at the bundle from below, consider a bundle $ x $ made by stacking odd-numbered cards on top, and a bundle $ y $ made by stacking even-numbered cards on ...
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} struct FastIO{ FastIO(){ cin.tie(0); ios::sync_with_stdio(0); } }fastio_beet; //IN...
For a given polygon g, print "1" if g is a convex polygon, "0" otherwise. Here, in a convex polygon, all interior angles are less than or equal to 180 degrees. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n-1) are sides of the polygon. The line segment con...
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; double x[10010],y[10010]; double ans; int pd; int n; int main(){ cin>>n; for(int i=1;i<=n;i++){ cin>>x[i]>>y[i]; x[i+n]=x[i],y[i+n]=y[i]; } for(int j=1;j<=n-1;j++){ double xx=x[j],yy=y[j]...