input
stringlengths
29
13k
output
stringlengths
9
73.4k
Problem description. Vipul is a hardworking super-hero who maintains the bracket ratio of all the strings in the world. Recently he indulged himself in saving the string population so much that he lost his ability for checking brackets (luckily, not permanently ).Being his super-hero friend help him in his time of hard...
for _ in range(input()): try: eval(raw_input()) print 'YES' except TypeError: print 'YES' except: print 'NO'
The Chef likes to stay in touch with his staff. So, the Chef, the head server, and the sous-chef all carry two-way transceivers so they can stay in constant contact. Of course, these transceivers have a limited range so if two are too far apart, they cannot communicate directly. The Chef invested in top-of-the-line t...
import math no_of_testcases = int(input()) for each in range(no_of_testcases): dist = int(input()) point_1 = map(int,raw_input().split()) point_2 = map(int,raw_input().split()) point_3 = map(int,raw_input().split()) point_12 =math.sqrt( math.pow((point_1[0] -point_2[0]),2) + math.pow((point_1[1]...
Frank explained its friend Felman the algorithm of Euclides to calculate the GCD of two numbers. Then Felman implements it algorithm int gcd(int a, int b) { if (b==0) return a; else return gcd(b,a%b); } and it proposes to Frank that makes it but with a little integer and another integer that has up to 250 d...
def gcd(a,b): while(b): a,b=b,a%b return a t=input() while(t): a,b=map(int,raw_input().split()) print(gcd(a,b)) t=t-1;
A Little Elephant from the Zoo of Lviv likes lucky strings, i.e., the strings that consist only of the lucky digits 4 and 7. The Little Elephant calls some string T of the length M balanced if there exists at least one integer X (1 ≤ X ≤ M) such that the number of digits 4 in the substring T[1, X - 1] is equal to the n...
n = input() for i in range(n): str = raw_input() l = len(str) megacounter = 0 counter = 0 i = 0 while(1): while(i<l and str[i]=='7'): i=i+1 counter=counter+1 if(i>=l): break megacounter = megacounter + (counter*(counter+1))/2 i=...
Given a string s. Can you make it a palindrome by deleting exactly one character? Note that size of the string after deletion would be one less than it was before. Input First line of the input contains a single integer T denoting number of test cases. For each test case, you are given a single line containing string...
import math import sys def checkpal(s): return s==s[::-1] for a in range(input()): s=raw_input() l=len(s) if(l==2): print "YES" else: if checkpal(s): print "YES" else: while s[0] == s[-1] and len(s)>2: s=s[1:-1] if checkpal(s[1:]) or ...
An established group of scientists are working on finding solution to NP hard problems. They claim Subset Sum as an NP-hard problem. The problem is to determine whether there exists a subset of a given set S whose sum is a given number K. You are a computer engineer and you claim to solve this problem given that all...
import sys for __ in range(input()) : n , k = map(int,sys.stdin.readline().split()) lists = map(int,sys.stdin.readline().split()) dp = [0]*(k+1) dp[0]=1 for i in lists : for j in range(k-i,-1,-1) : if dp[k] : break if dp[j] : dp[j+i] =...
You are given an array of n positive integers a_1, a_2, ..., a_n. You can perform the following operation any number of times: select several distinct indices i_1, i_2, ..., i_k (1 ≤ i_j ≤ n) and move the number standing at the position i_1 to the position i_2, the number at the position i_2 to the position i_3, ..., t...
#include <bits/stdc++.h> using namespace std; const int MAXN = 300000; map<int, int> mapa; map<pair<int, int>, vector<int>> pos; vector<int> g[MAXN]; int ptr[MAXN]; int used[MAXN]; void euler(int v, vector<int> &res) { used[v] = true; for (; ptr[v] < (int)(g[v]).size();) { ++ptr[v]; int u = g[v][ptr[v] - 1]...
There are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends. We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: * ...
#include <bits/stdc++.h> using namespace std; const int module = 1000000007; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, m, k; cin >> n >> m >> k; vector<set<int>> to(n, set<int>()); vector<pair<int, int>> edges(m); vector<int> nbr(n); for (int i = 0; i < m; ++i) { ...
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit. For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not. You have n cards with digits, and you want to use them to make as many phone n...
n = int(input()) s = input() k = s.count("8") l = n - k if k <= l//10: print(k) else: while k > l//10: k -= 1 l += 1 print(min(k, l//10))
Chouti thought about his very first days in competitive programming. When he had just learned to write merge sort, he thought that the merge sort is too slow, so he restricted the maximum depth of recursion and modified the merge sort to the following: <image> Chouti found his idea dumb since obviously, this "merge s...
#include <bits/stdc++.h> const int MAXN = 1e5 + 20; int n, k, M; int inv[MAXN], pre_inv[MAXN]; void math_pre() { inv[1] = 1; for (int i = 2; i <= ((n < 4) ? 4 : n); ++i) inv[i] = 1ll * (M - M / i) * inv[M % i] % M; for (int i = 1; i <= n; ++i) pre_inv[i] = (pre_inv[i - 1] + inv[i]) % M; } struct map { stati...
You are given q queries in the following form: Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i]. Can you answer all the queries? Recall that a number x belongs to segment [l, r] if l ≤ x ≤ r. Input The first l...
n = int(input()) A = [] for i in range(n): A = A+[input().split()] for a in A: if int(a[2]) < int(a[0]) or int(a[2]) > int(a[1]): print(a[2]) else: print(int(a[2])*(int(a[1])//int(a[2])+1))
Find the number of ways to divide an array a of n integers into any number of disjoint non-empty segments so that, in each segment, there exist at most k distinct integers that appear exactly once. Since the answer can be large, find it modulo 998 244 353. Input The first line contains two space-separated integers n...
#include <bits/stdc++.h> int bb[1 + 100000], dp[1 + 100000], ss[((100000 + 500 - 1) / 500)], dq[((100000 + 500 - 1) / 500)][500 + 1 + 500]; void update(int h) { int *qq = dq[h]; int i, t, c; t = 0; memset(qq, 0, (500 + 1 + 500) * sizeof *qq); for (i = (h + 1) * 500; i > h * 500; i--) { t += bb[i]; ...
In Byteland, there are two political parties fighting for seats in the Parliament in the upcoming elections: Wrong Answer Party and Time Limit Exceeded Party. As they want to convince as many citizens as possible to cast their votes on them, they keep promising lower and lower taxes. There are n cities in Byteland, co...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 100; int n, m, h[N], lev[N], Xor[N], cnt[N], deg[N]; vector<int> nxt[N], rnxt[N], vec[N]; set<int> s; queue<int> q; int main() { cin >> n >> m; for (int i = 1; i <= n; ++i) cin >> h[i]; for (int i = 1; i <= m; ++i) { int x, y; cin >> x >> y...
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on al...
m = int(input()) l = [0 for _ in range(m + 1)] for _ in range(m - 1): a,b = map(int, input().split()) l[a] += 1 l[b] += 1 if 2 in l: print("NO") else: print("YES")
An array of integers p_{1},p_{2}, …,p_{n} is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3,1,2], [1], [1,2,3,4,5] and [4,3,1,2]. The following arrays are not permutations: [2], [1,1], [2,3,4]. There is a hidden permutation of length n. ...
#include <bits/stdc++.h> using namespace std; const long long maxN = 2 * 100224; struct BIT { long long data[maxN] = {0}; void update(long long idx, long long val) { while (idx < maxN) { data[idx] += val; idx += idx & -idx; } } void update(long long l, long long r, long long val) { updat...
This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily...
# class SegmentTree(): # adapted from https://www.geeksforgeeks.org/segment-tree-efficient-implementation/ # def __init__(self,arr,func,initialRes=0): # self.f=func # self.N=len(arr) # self.tree=[0 for _ in range(2*self.N)] # self.initialRes=initialRes # for i in range(self....
You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. ...
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10; const int mod = 1e9 + 7; int head[N]; int dis[N], ecnt; int fa[N]; int cat[2005][2005]; long long gcd(long long a, long long b) { return a % b == 0 ? b : gcd(b, a % b); } long long qpow(long long base, long long n) { long long ans = 1; while (n...
There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1). You're given k subsets A_1, …, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 ≤ i_1 < i_2 < i_3 ≤ k, A_{i_1} ∩ A_{i_2} ∩ A_{i_3} = ∅. In one operation, you ...
#include <bits/stdc++.h> using namespace std; const int maxn = 3e5 + 10; int n, k; char s[maxn]; int pre[maxn << 1], sz[maxn << 1]; vector<int> op[maxn]; int find(int x) { return x == pre[x] ? x : pre[x] = find(pre[x]); } void merge(int x, int y) { int fx = find(x), fy = find(y); if (fy == 0) swap(fx, fy); if (fx...
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ...
import bisect def getsum(tree , i): s = 0 i += 1 while i>0: s += tree[i] i -= i & (-i) return s def updatebit(tree , n , i , v): i+= 1 while i <= n: tree[i] += v i += i & (-i) n = int(input()) x = list(map(int , input().split())) v = list(map(int , input().spli...
You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of...
#include <bits/stdc++.h> using namespace std; long long n; int tc = 0; int solve(); int main() { ios_base::sync_with_stdio(0); if (tc < 0) { cout << "TC!\n"; cin.ignore(1e8); } else if (!tc) cin >> tc; while (tc--) solve(); return 0; } int solve() { long long l, r; cin >> n >> l >> r; l--; ...
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions c...
#include <bits/stdc++.h> using namespace std; struct Edge { long long to, dis, next, cost; } edge[24050]; long long num = -1; bool vis[10010]; long long mincost; long long pre[10010], head[10010], cost[10010], last[10010], flow[10010], n, k, a[110], b[110], s, t, maxflow; long long to[110]; void add(long long f, ...
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will ...
#include <bits/stdc++.h> using namespace std; template <typename T> using minpq = priority_queue<T, vector<T>, greater<T>>; int n, k, a, b; long long t; vector<long long> ve[2][2]; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> k; for (int i = (0); i < (n); i++) { cin >> t >> a >> b; ...
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to...
import java.util.*; public class BadTriangle { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = s.nextInt(); } if (a[n -...
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid f...
l=[] for _ in range(int(input())): n=int(input()) a=[] for i in range(n): a.append(list(input())) if a[0][1]==a[1][0]: if a[n-1][n-2]==a[n-2][n-1]: if a[n-1][n-2]==a[0][1]: l.append("2") l.append("1 2") l.append("2 1") ...
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with tha...
import java.util.Scanner; public class HelpVasilisaTheWise { public static void main (String [] args) { Scanner in = new Scanner(System.in); int r1 = in.nextInt(); int r2 = in.nextInt(); int c1 = in.nextInt(); int c2 = in.nextInt(); int d1 = in.nextInt(); int ...
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare. In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words h...
#include <bits/stdc++.h> #define fst first #define snd second #define fore(i,a,b) for(int i=a,ThxDem=b;i<ThxDem;++i) #define pb push_back #define ALL(s) s.begin(),s.end() #define FIN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define SZ(s) int(s.size()) using namespace std; typedef long long ll; typedef pair<i...
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it. Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm: * the drive takes one positive number x...
def findIndexGE(prefixSumsMax,startSum,query): n=len(prefixSumsMax) b=n i=-1 while b>0: while i+b<n and startSum+prefixSumsMax[i+b]<query: i+=b b//=2 i+=1 return i def main(): t=int(input()) allans=[] for _ in range(t): n,m=readIntArr() ...
You are given an integer n. You have to apply m operations to it. In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once. You have to find the length of n after applying m operations. Since...
from os import path import sys,time from math import ceil, floor,gcd,log,log2 ,factorial from collections import defaultdict ,Counter , OrderedDict , deque from heapq import heapify , heappush , heappop from bisect import * # from functools import reduce from operator import mul from itertools import permutations maxx,...
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved. There is a process that takes place on arrays a and b of length n and length n-1 respectively. The process is an infinite sequence of operations. Each operat...
#include<bits/stdc++.h> #define pii pair<int,int> #define fi first #define sc second #define pb push_back #define ll long long #define trav(v,x) for(auto v:x) #define all(x) (x).begin(), (x).end() #define VI vector<int> #define VLL vector<ll> using namespace std; const int N = 1e6 + 100; const ll mod = 1e9 + 7; signed...
Some country is populated by wizards. They want to organize a demonstration. There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administr...
#include <bits/stdc++.h> using namespace std; int main() { double n, x, y, p, q, r; int a; cin >> n >> x >> y; p = y / 100; q = n * p; r = q - x; a = r; if (r > a) { cout << a + 1; } else if (a < 0) { cout << "0"; } else { cout << a; } }
You are given an equation: Ax2 + Bx + C = 0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order. Input The first line contains three integer numbers A, B and C ( - 105 ≤ A, B, C ≤ 105). Any coefficient may be equal to 0. Output In case of infinite root cou...
#include <bits/stdc++.h> using namespace std; int main() { double A, B, C; double D; cin >> A >> B >> C; double x1, x2; if (!A) { if (!B) { if (!C) { printf("-1"); return 0; } else { printf("0"); return 0; } } else { printf("1\n"); printf("...
In computer science, there is a method called "Divide And Conquer By Node" to solve some hard problems about paths on a tree. Let's desribe how this method works by function: solve(t) (t is a tree): 1. Chose a node x (it's common to chose weight-center) in tree t. Let's call this step "Line A". 2. Deal with all...
#include <bits/stdc++.h> struct edge { int to; edge* next; } E[6010], *ne = E, *first[3010]; void link(int a, int b) { *ne = (edge){b, first[a]}; first[a] = ne++; } int C[3010], cnt; bool tag[3010]; int dfs1(int i, int f) { int t; tag[i] = 1; for (edge* e = first[i]; e; e = e->next) if (e->to != f) { ...
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-". We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say tha...
#include <bits/stdc++.h> using namespace std; char s[100005]; int day[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; map<string, int> my; void check(char* s) { if (((s[0]) >= '0' && (s[0]) <= '9') && ((s[1]) >= '0' && (s[1]) <= '9') && ((s[3]) >= '0' && (s[3]) <= '9') && ((s[4]) >= '0' && (s[4]) <= '9') ...
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any bett...
#!/bin/python # -*- coding: utf-8 -*- n = int(input()) s = input() print(int(s.count('I') == 1) if 'I' in s else s.count('A'))
Advertising has become part of our routine. And now, in the era of progressive technologies, we need your ideas to make advertising better! In this problem we'll look at a simplified version of context advertising. You've got a text, consisting of exactly n words. A standard advertising banner has exactly r lines, eac...
#include <bits/stdc++.h> using namespace std; const int N = 1000100, L = 5000500, BufL = 220; char ch[N + L] = {}, buf[BufL] = {}; int n, r, c, l, a[N] = {}, p[N] = {}, f[N] = {}, g[N] = {}; int main() { gets(buf + 1); sscanf(buf + 1, "%d%d%d", &n, &r, &c); gets(ch + 1); l = strlen(ch + 1); for (int i = 1, to...
Everybody knows that we have been living in the Matrix for a long time. And in the new seventh Matrix the world is ruled by beavers. So let's take beaver Neo. Neo has so-called "deja vu" outbursts when he gets visions of events in some places he's been at or is going to be at. Let's examine the phenomenon in more deta...
#include <bits/stdc++.h> using namespace std; const int MAX = 100 + 10; const int Mod = (int)1e9 + 7; int n, m; int g[MAX][MAX], can[MAX][MAX]; vector<int> p[MAX][MAX]; int get(vector<int> &before, int kind, int could, int have) { int j; int now = 0, cc = have; for (; now < (int)before.size(); now++) { if (no...
We know that lucky digits are digits 4 and 7, however Vasya's got another favorite digit 0 and he assumes it also is lucky! Lucky numbers are such non-negative integers whose decimal record only contains lucky digits. For example, numbers 0, 47, 7074 are lucky, but 1, 7377, 895, -7 are not. Vasya has t important posi...
#include <bits/stdc++.h> using namespace std; set<long long> kharab = {1, 2, 3, 5, 6, 9, 10, 13, 17, 31, 34, 37, 38, 41, 43, 45, 46, 49, 50, 53, 57, 71, 83, 111, 123, 391, 403, 437, 457, 471, 483, 511, 523}; long long a[6]; vector<long long> D[43...
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like...
a, b = map(int, input().split()) c, s = a, 0 while a >= b: s += a // b a = (a // b) + (a % b) print(s + c)
Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; int inline in() { int x = 0, c; for (; (unsigned)((c = getchar()) - '0') >= 10;) { if (c == '-') return -in(); if (!~c) throw ~0; } do { x = (x << 3) + (x << 1) + (c - '0'); } while ((unsigned)((c = getchar()) - '0') < 10); ...
Sereja has painted n distinct points on the plane. The coordinates of each point are integers. Now he is wondering: how many squares are there with sides parallel to the coordinate axes and with points painted in all its four vertexes? Help him, calculate this number. Input The first line contains integer n (1 ≤ n ≤ ...
#include <bits/stdc++.h> using namespace std; const long double eps = 1e-12; const int maxn = 100000 + 1912; const int MX = 1e6; int n; pair<int, int> a[maxn]; vector<int> p[MX * 2 + 3]; long long res = 0; void ReadData() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d%d", &a[i].first, &a[i].second)...
To celebrate the opening of the Winter Computer School the organizers decided to buy in n liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles 0.5, 1 and 2 liters in volume. At that, there are exactly a bottles 0.5 in volume, b one-liter bottles and c of two...
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; import java.io.*; import java.util.*; import java.util.regex.Matcher; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputRead...
Ali is Hamed's little brother and tomorrow is his birthday. Hamed wants his brother to earn his gift so he gave him a hard programming problem and told him if he can successfully solve it, he'll get him a brand new laptop. Ali is not yet a very talented programmer like Hamed and although he usually doesn't cheat but th...
#include <bits/stdc++.h> using namespace std; inline int read() { static int r, sign; static char c; r = 0, sign = 1; do c = getchar(); while (c != '-' && (c < '0' || c > '9')); if (c == '-') sign = -1, c = getchar(); while (c >= '0' && c <= '9') r = r * 10 + (int)(c - '0'), c = getchar(); return sign *...
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s...
n = int(input()) a_sum = sum(map(int, input().split())) b_sum = sum(map(int, input().split())) c_sum = sum(map(int, input().split())) print(a_sum - b_sum) print(b_sum - c_sum)
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each ...
ll=lambda:map(int,input().split()) t=lambda:int(input()) ss=lambda:input() #from math import log10 ,log2,ceil,factorial as f,gcd #from itertools import combinations_with_replacement as cs #from functools import reduce #from bisect import bisect_right as br #from collections import Counter n=t() x,h=[],[] for _ in ran...
Geometric progression with the first element a and common ratio b is a sequence of numbers a, ab, ab2, ab3, .... You are given n integer geometric progressions. Your task is to find the smallest integer x, that is the element of all the given progressions, or else state that such integer does not exist. Input The fi...
#include <bits/stdc++.h> using std::sort; using std::swap; using std::unique; namespace fastIO { static char buf[(1 << 19)], *p1 = buf + (1 << 19), *pend = buf + (1 << 19); inline char nc() { if (p1 == pend) { p1 = buf; pend = buf + fread(buf, 1, (1 << 19), stdin); } return *p1++; } inline long long read(...
Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the i...
def f(x): if x == n: return "0" if x == 0: return "(" + str(X[0]) + "+" + f(1) + ")" ss = "(abs((t-" + str(x-1) + "))-abs((t-" + str(x) + ")))" tmp = (X[x] - X[x - 1]) // 2 re = (X[x] - X[x - 1]) - 2 * tmp X[x] -= re if t...
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Va...
import math nm = input().split() n = int(nm[0]) m = int(nm[1]) lis = [ 0 for i in range(m+1)] for _ in range(n) : inp = list(map(int, input().split())) inp.pop(0) for i in inp: lis[i]=1 prev = i if sum(lis)==m: print("YES") else: print("NO")
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but ...
#include <bits/stdc++.h> using namespace std; long long tree[1000000][2]; long long ar[1000000]; int a, b; long long query(int x, int l, int r, int s, int e, bool k) { if (l > e || r < s || s > e) return 0; if (l >= s && r <= e) return tree[x][k]; else { return query(x * 2, l, (l + r) / 2, s, e, k) + ...
You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds. Input The only line of the input contains a re...
import java.io.*; import java.util.*; import java.util.Map.Entry; public class Task_Rnd664_B { final static String input_file_name = "input/Rnd664_B.txt"; public static void main(String[] args) { //!!!!!!!!!!111 reader.init(true); //to server //reader.init(false); run(); wr.flush(); } public...
Long time ago, there was a great kingdom and it was being ruled by The Great Arya and Pari The Great. These two had some problems about the numbers they like, so they decided to divide the great kingdom between themselves. The great kingdom consisted of n cities numbered from 1 to n and m bidirectional roads between t...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; const int N = 1000, M = N * (N - 1) / 2; int dsu[N * 2]; int find(int i) { return dsu[i] < 0 ? i : (dsu[i] = find(dsu[i])); } bool join(int i, int j) { i = find(i); j = find(j); if (i == j) return false; if (dsu[i] > dsu[j]) dsu[i] = j...
In Walrusland public transport tickets are characterized by two integers: by the number of the series and by the number of the ticket in the series. Let the series number be represented by a and the ticket number — by b, then a ticket is described by the ordered pair of numbers (a, b). The walruses believe that a tic...
#include <bits/stdc++.h> using namespace std; int in() { int a; scanf("%d", &a); return a; } int gcm(int a, int b) { if (b > a) return gcm(b, a); if (a % b == 0) return b; else return gcm(b, a % b); } int calc_rev(int x) { int ret = 0; while (x) { int a = x % 10; ret = ret * 10 + a; ...
Nick has n bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda ai and bottle volume bi (ai ≤ bi). Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends x seconds to pour x units of soda...
#include <bits/stdc++.h> using namespace std; pair<int, int> dp[10005]; int a[105], b[105]; int main() { int n; scanf("%d", &n); int cap = 0, mx = 0; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); cap += a[i]; } for (int i = 0; i < n; i++) { scanf("%d", &b[i]); mx += b[i]; } for (int ...
Dasha is fond of challenging puzzles: Rubik's Cube 3 × 3 × 3, 4 × 4 × 4, 5 × 5 × 5 and so on. This time she has a cyclic table of size n × m, and each cell of the table contains a lowercase English letter. Each cell has coordinates (i, j) (0 ≤ i < n, 0 ≤ j < m). The table is cyclic means that to the right of cell (i, j...
#include <bits/stdc++.h> using namespace std; static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL; template <typename T, typename U> static void amin(T &x, U y) { if (y < x) x = y; } template <typename T, typename U> static void amax(T &x, U y) { if (x < y) x = y; } struct FFTCoeff...
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected ...
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.*; public class A { static long mod = 1000000007; public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(Syste...
There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: ...
#include <bits/stdc++.h> using namespace std; int main() { int t, m, num = 1; string com; int arg; vector<pair<pair<int, int>, int> > d; cin >> t >> m; for (int _n((t)-1), q(0); q <= _n; q++) { sort((d).begin(), (d).end()); cin >> com; if (com == "defragment") { if (d.size() > 0) { ...
Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation whi...
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D421 { InputStream is; PrintWriter out; int n; long a[]; private boolean oj = System.getProperty("ONLINE_JUDGE") != nu...
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment. Fortunately, chemical laws allow material transformations (yes, chemistry i...
#include <bits/stdc++.h> const double Pi = acos(-1.0); using namespace std; const int maxN = 100005; const long long inf = (long long)1e15; int n; long long b[maxN]; long long k[maxN]; long long req[maxN]; vector<int> G[maxN]; void dfs(int cur) { for (int i = 0; i < (int)G[cur].size(); i++) { int nxt = G[cur][i];...
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's p...
from sys import stdin def main(): password=raw_input() n=input() flag1=False flag2=False for i in xrange(n): str=raw_input() if str[0]==password[1]: flag1=True if str[1]==password[0]: flag2=True if flag1 and flag2 or str==password: ...
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card. She starts with 0 money on her account. In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, ...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class P893D { public static void main(String[] args) { FastScanner scan = new FastScanner(); int n = scan.nextInt(); int d = scan.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i...
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the gro...
def is_prime(a): return all(a % i for i in range(2, a)) n, k = map(int, input().split()) l = [int(x) for x in input().split()] if is_prime(k): if k in l: print(1) else: print(k) else: ll = [] for i in range(len(l)): if k % l[i] == 0: ll.append(l[i]) print(k ...
You and your friend are participating in a TV show "Run For Your Prize". At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positi...
input() a=list(map(int,input().split())) ans=0 for x in a: z=min(x-1,1000000-x) ans=max(z,ans) print(ans)
You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOExceptio...
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked an...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 7; const long long INF = 1e18 + 7; int a[maxn]; int aa[maxn]; int pre[maxn]; int b[maxn]; int main() { int i, j, m, n, t, z; int k; scanf("%d%d%d", &n, &m, &k); for (i = 1; i <= m; i++) { scanf("%d", &a[i]); aa[a[i]] = 1; } for (i ...
As you know Appu created aversion to Maths after that maths problem given by his teacher.So he stopped studying and began to do farming. He has some land where he starts growing sugarcane. At the end of the season he grew N sugarcanes. Is Appu satisfied??. No, He wants all his sugar canes to be of the same height. He g...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' num_of_sugarcanes = int(raw_input()) list_of_sugarcanes = map(int,raw_input().split()) max_of_sugarcanes = max(list_of_sugarcanes) def xyz (list_of_sugarcanes, max_sugar): for x i...
In the previous problem Chandu bought some unsorted arrays and sorted them (in non-increasing order). Now, he has many sorted arrays to give to his girlfriend. But, the number of sorted arrays are very large so Chandu decided to merge two sorted arrays into one sorted array. But he is too lazy to do that. So, he asked ...
def merge(a,b): c=[] l1=len(a) l2=len(b) i=0 j=0 while i<l1 and j<l2: if a[i]>b[j]: c.append(a[i]) i+=1 else: c.append(b[j]) j+=1 while i<l1: c.append(a[i]) i+=1 while j<l2: c.append(b[j]) j+=...
You are given an array A of size N, and Q queries to deal with. For each query, you are given an integer X, and you're supposed to find out if X is present in the array A or not. Input: The first line contains two integers, N and Q, denoting the size of array A and number of queries. The second line contains N space s...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' line1 = raw_input() arr_inp=[] for j in line1.split(' '): arr_inp.append(int(j)) line2 = raw_input() elemnt_array = {} for i in line2.split(' '): elemnt_array[int(i)] = 1 #elemnt_arr...
Golu is given a task of clearing coins fallen down on floor. Naughty being his modus operandi, he thought of playing a game while clearing coins. He arranges the coins like an M X N matrix with random heads (1) and tails (0). In every move, he chooses a sub-matrix of size L X B [such that max(L,B) >1] and interchange...
M,N=map(int,raw_input().split()) L=[] for i in range(M): L.append(map(int,raw_input().split())) if M+N==4 and (L==[[0,1],[1,1]] or L==[[1,0],[1,1]] or L==[[1,1],[1,0]] or L==[[1,1],[0,1]]) or L==[[1,0],[0,0]] or L==[[0,1],[0,0]] or L==[[0,0],[1,0]] or L==[[0,0],[0,1]]: print "-1" else: List=[] for ...
A certain business maintains a list of all its customers' names. The list is arranged in order of importance, with the last customer in the list being the most important. Now, he want to create a new list sorted alphabetically according to customers' last names, but among customers with the same last name he want the m...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' def fun(l): a=[] b=l[::-1] for j in range(len(b)): s=b[j].split(" ") if(len(s)>=2): a.append([s[-1].lower(),j]) else: a.append([s[0].lower(),j]) a.sort(key=lambda t...
Monk loves cakes! He visits the Binary Bakery to buy some of his favorite cheesecakes. The owner of the bakery, Bob, is a clever man. He does not want Monk to finish all his cheesecakes. Hence, he plays a game. The Monk is given N numbers and has to select K of these numbers. For each number that Monk chooses, he wil...
def count(num): tmp=num cnt=0 while(tmp!=0): ...
Description You are given two strings S and T, such that length of S is greater than the length of T. Then a substring of S is defined as a sequence of characters which appear consecutively in S. Find the total number of distinct substrings of M such that T is a substring of M Input Format One line containing strings...
a,b=raw_input().split() ans=[] i=0 while i<len(a): j=i while j<len(a): t=a[i:j+1] if b in t: if t not in ans: ans.append(t) j+=1 i+=1 print len(ans)
Roy is going through the dark times of his life. Recently his girl friend broke up with him and to overcome the pain of acute misery he decided to restrict himself to Eat-Sleep-Code life cycle. For N days he did nothing but eat, sleep and code. A close friend of Roy kept an eye on him for last N days. For every sing...
def main(): n = int(raw_input()) strings = [] string_streak = 0 total_streak = 0 for i in range(n): temp_string = raw_input() strings.append(temp_string) for string in strings: temp_string_streak = 0 temp_streak = 0 for char in string: if char == "E" or char == "S": if temp_streak > temp_string_...
Problem: Rani and Nandu decide to play a number game. Both play alternately, Rani playing the first move. In each of their moves, they can subtract a maximum of k and a minimun of 1 from n ( ie.each of them must subtract from n, any natural number less than or equal to k) , and the new value of n will be the result ...
for _ in xrange(input()): flag=True n,k=map(int,raw_input().split()) print "Nandu" if not (n-1)%(k+1) else "Rani"
Rakesh have learn about vowel in school and is given an assignment by his teacher in which he has to list all vowel together from the word's given to him,but he is busy in watching cricket match and want your help to solve the assignment. 5 vowel (a,e,i,o,u) and you should also take care of uppercase vowel (A,E,I,O,U)...
b="AEIOUaeiou" t=input() while t: t-=1 c="" a=raw_input() for x in a: if x in b: c+=x if (c==""): print "No" else: print c
Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A. The problem has N test cases. For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is `AC`,...
#include <bits/stdc++.h> using namespace std; int n,cnt[30]; char S[5]; int main() { scanf("%d",&n); for (int i=1;i<=n;i++) { scanf("%s",S); cnt[S[0]-65]++; } printf("AC x %d\n",cnt[0]); printf("WA x %d\n",cnt['W'-65]); printf("TLE x %d\n",cnt['T'-65]); printf("RE x %d\n",cnt['R'-65]); return 0; }
In this problem, we only consider strings consisting of lowercase English letters. Strings s and t are said to be isomorphic when the following conditions are satisfied: * |s| = |t| holds. * For every pair i, j, one of the following holds: * s_i = s_j and t_i = t_j. * s_i \neq s_j and t_i \neq t_j. For example, `a...
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); List<StringBuilder> list = rec('a', 'a', N - 1); for (StringBuilder sb : list) { System...
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation. Given are two integers A and B. If Takahashi can calculate A \times B, print the result; if he cannot, print `-1` instead. Constraints * 1 \leq A \leq 20 * 1 \leq B ...
import java.util.*; class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); if(a>=1&&a<=9&&b>=1&&b<=9){ System.out.println(a*b); }else{ System.out.println(-1); } } }
There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step. He can climb up one or two steps at a time. However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps. How many are there to climb ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ ll N,M,a,MOD=1e9+7; cin >> N >> M; vector<ll> X(N+5,0); for(int i=0;i<M;i++){ cin >> a; X[a]=-1; } X[0] = 1; if(X[1]!=-1)X[1] = 1; for(int i=2;i<N+1;i++){ if(X[i]==-1)continue; X[i] = ( (X[i-1]!=-1)*X[i-1] + (X[i-2]!=-1)*X[i...
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads. Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j...
#include<bits/stdc++.h> #define ll long long using namespace std; struct node { int u,v; ll w; bool operator<(const node &o)const{return w<o.w;} }e[6000005]; int n,cot=0,a[200005],fail[200005]; ll d; void add(int l,int r) { if(l>=r) return; int m=l+r>>1; ll mi=1e18,pos; for(int i=l;i<=m;i++)...
Ringo Mart, a convenience store, sells apple juice. On the opening day of Ringo Mart, there were A cans of juice in stock in the morning. Snuke buys B cans of juice here every day in the daytime. Then, the manager checks the number of cans of juice remaining in stock every night. If there are C or less cans, D new can...
from fractions import gcd T=input() def check(a,b,c,d): a-=b if a<0: return 0 if d<b: return 0 if d>=b: if c>=b-1: return 1 else: d=gcd(b,d) a%=d l=c+d-a r=b+d-a-1 # print l,r,d if l/d<r/d: return 0 else: return 1 # l<=a + t * d<=r for i in xrange(T): a,b,c,d=map(int,raw_input()....
AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd. Constraints * 1 ≤ a,b ≤ 10000 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the product is odd, print `Odd`; if it is even, print `Even`. E...
#include <bits/stdc++.h> using namespace std; int main(){ int a,b; cin>>a>>b; if((a*b)%2==0)cout<<"Even"; else cout<<"Odd"; return 0; }
We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand. When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb. The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per...
#include <bits/stdc++.h> using namespace std; #define MAX 100007 int r[MAX]; int a[MAX]; int b[MAX]; int k1[MAX]; int main(){ int x,k,q; cin >> x >> k; for(int i=1; i<=k; i++)cin >> r[i]; r[k+1]=INT_MAX; a[0]=0; b[0]=x; k1[0]=1; // printf("%d %d %d\n",a[0],b[0],k1[0]); for(int i=1; i<=k; i++){ int dt=r[i]-r...
There are N students and M checkpoints on the xy-plane. The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j). When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance. T...
import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.next()); int m = Integer.parseInt(sc.next()); int[] ax = new int[n]; int[] ay = new int[n]; int[] bx = new int[m]; int[] by = new int[m]; for(int i = 0; i<n; i++) { ...
Two students of AtCoder Kindergarten are fighting over candy packs. There are three candy packs, each of which contains a, b, and c candies, respectively. Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible. Not...
l=sorted(list(map(int,input().split()))) print("Yes" if l[0]+l[1]==l[2] else "No")
4 different points on the plane Read the coordinates of $ A (x_a, y_a) $, $ B (x_b, y_b) $, $ C (x_c, y_c) $, $ D (x_d, y_d) $ and read those 4 points Create a program that outputs YES if there is no dent in the quadrangle $ ABCD $ with the coordinates as the vertices, and NO if there is a dent. A quadrangle with a de...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String[] s = sc.next().split(","); double[] x = new double[6]; double[] y = new double[6]; for(int i=0;i<6;i++){ if(i<4){ ...
Sorting algorithms for sorting data are basic algorithms indispensable in computer science. For example, as shown in the figure below, the operation of "sorting the elements of an array of integer values ​​in ascending order" is alignment. <image> Many alignment algorithms have been devised, but one of the basic alg...
def bubble_sort(A, N): flag = True c = 0 i = 0 while flag: flag = False for j in range(N-1, i, -1): if A[j] < A[j-1]: A[j], A[j-1] = A[j-1], A[j] c += 1 flag = True i += 1 return c while True: N = int(raw_in...
PCK, which recycles Aizu's precious metal, Aizunium, has a network all over the country and collects Aizunium with many collection vehicles. This company standardizes the unit of weight and number of lumps for efficient processing. A unit called "bokko" is used for the weight of the lump. x Bocco's Aidunium weighs 2 x...
#include <iostream> #include <algorithm> #include <array> #include <math.h> #include <set> #include <stdlib.h> #include <string> #include <vector> #define INT_MAX 2000000000 #define INF 1000000000 #define MOD 1000000007 #define ll long long #define rep(i,a,b) for(i = (a); i < (b); i++) #define bitget(a,b) (((a) >> (b)...
problem If you write a positive integer in decimal notation (without leading 0) and look at the digit numbers in order, when the number increases and decreases alternately, the number is "zigza". Let's call it. For example, 2947 is a zigzag number because the digit numbers are in the order of 2 → 9 → 4 → 7 and increas...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; int mod=10000; struct Mod { public: int num; Mod() : Mod(0) { ; } Mod(long long int n) : num((n % mod + mod) % mod) { //static_assert(mod<INT_MAX / 2, "mod is too big, please make num 'long...
Problem KND is a student programmer at the University of Aizu. There are N towns around his town. He loves cream so he built a factory in a town to eat cream every day. The factory produces F liters of fresh cream daily. Every time you carry the cream, it will be damaged by the absolute difference between the temperat...
#include <bits/stdc++.h> using namespace std; #define dump(...) cout<<"# "<<#__VA_ARGS__<<'='<<(__VA_ARGS__)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define all(c) begin(c),end(c) #define mp mak...
You are the God of Wind. By moving a big cloud around, you can decide the weather: it invariably rains under the cloud, and the sun shines everywhere else. But you are a benign God: your goal is to give enough rain to every field in the countryside, and sun to markets and festivals. Small humans, in their poor vocabu...
#include<iostream> using namespace std; const int M = 1000000; int n; int sch[400][20]; bool dp[2][M]; int dy[] = {0,-1,0,1,0}, dx[] = {0,0,1,0,-1}; bool table[5][5]; int y,x; int main(){ while(cin >> n,n){ for(int i=0;i<n;i++){ for(int j=0;j<16;j++)cin >> sch[i][j]; } for(int i=0;i<M;i++)dp[0][i...
Example Input 2 1 1 2 2 Output 1
#include <bits/stdc++.h> using namespace std; const int INF = 1 << 29; struct UnionFind { vector< int > data; UnionFind(int sz) { data.assign(sz, -1); } int find(int k) { return (data[k] < 0 ? k : data[k] = find(data[k])); } void unite(int x, int y) { x = find(x); y = find(y); ...
Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections ...
#include<bits/stdc++.h> using namespace std; #define lp(i,n) for(int i=0;i<n;i++) int main(){ while(1){ int n; cin>>n; if(n==0) break; int a[50]; string memo; lp(i,n){ cin>>memo; a[i]=memo.size(); } lp(i,n){ int ans=0; int count=0,stats=0; for(int j=i;j<...
Edward R. Nelson is visiting a strange town for some task today. This city is built on a two-dimensional flat ground with several vertical buildings each of which forms a convex polygon when seen from above on it (that is to say, the buidlings are convex polygon columns). Edward needs to move from the point S to the po...
#include <iostream> #include <iomanip> #include <complex> #include <vector> #include <algorithm> #include <cmath> #include <array> #include <utility> #include <map> using namespace std; const double EPS = 1e-6; const double INF = 1e12; const double PI = acos(-1); #define EQ(n,m) (abs((n)-(m)) < EPS) #define X real() #d...
I have n tickets for a train with a rabbit. Each ticket is numbered from 0 to n − 1, and you can use the k ticket to go to p⋅ak + q⋅bk station. Rabbit wants to go to the all-you-can-eat carrot shop at the station m station ahead of the current station, but wants to walk as short as possible. The stations are lined up ...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; template<class T> using Table = vector<vector<T>>; const ld eps=1e-10; //// < "D:\D_Download\Visual Studio 2015\Projects\programing_contest_c++\Debug\a.txt" int K, R, L; l...
Taro is an elementary school student who has just learned multiplication. Somehow, he likes multiplication, so when he sees numbers, he wants to multiply. He seems to like to do the following for integers greater than or equal to 0. (Processing flow) * Procedure 1. If a certain integer n greater than or equal to 0 is ...
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <map> #include <sstream> using namespace std; string toString(int n){ ostringstream os; os << n; return os.str(); } int main(){ int Q; string N; cin >> Q; while(Q--){ cin >> N; int i; ...
Step up and down Kazuki, commonly known as Kerr, who attends JAG University, was invited by your friend this summer to participate in the ICPC (International Collegiate Potchari Contest). ICPC is a sports contest and requires a high degree of athletic ability. However, Mr. Kerr was always in front of the computer, and...
while 1: n = input() if n == 0: break F = raw_input().split() mode = 1 s = [0,0] ans = 0 for f in F: if f[0]=="l": s[0]^=1 if mode != s[0]: mode = -1 else: s[1]^=1 if mode != s[1]: mode = ...
Example Input 4 3 1 3 4 7 Output 6
#include<bits/stdc++.h> using namespace std; int N,K; int dp[2][1001][1001]; int dm[2][1001][1001]; int a[1000]; int main(){ scanf("%d %d",&N,&K); for(int i=0;i<N;i++)scanf("%d",&a[i]); sort(a,a+N); fill( (int*)dp[0], (int*)dp[1], 1e9); int ans=1e9; for(int T=1;T<=K;T++){ int t=T%2; int u=1-t; ...
problem Given $ N $ different natural numbers $ a_i $. I decided to make a pair by choosing a different natural number from the given natural numbers. Output one pair that can be created with a value difference that is a multiple of $ N -1 $. It should be noted that such a pair always exists. Example Input 5 1...
#include "bits/stdc++.h" using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int INF = 1e9; const ll LINF = 1e18; template<class S,class T> ostream& operator << (ostream& out,const pair<S,T>& o){ out << "(" << o.first << "," << o.second << ")"; return out; } template<c...
Problem A large-scale cluster † type supercomputer (commonly known as "SAKURA") cluster at Maze University consists of $ N $ computers (nodes) and $ M $ physical communication channels that can communicate with each other. .. In addition, each node is assigned an identification number from 1 to $ N $. This time, the ...
#include<bits/stdc++.h> using namespace std; #define int long long #define rep(i,n) for(int i=0;i<(n);i++) #define pb push_back #define all(v) (v).begin(),(v).end() #define fi first #define se second typedef vector<int>vint; typedef pair<int,int>pint; typedef vector<pint>vpint; template<typename A,typename B>inline...
Write a program of the Selection Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: SelectionSort(A) 1 for i = 0 to A.length-1 2 mini = i 3 for j = i to A.length-1 4 if A[j] < A[mini] 5 mini = j 6 swap A[i] and A[mini]...
#include <iostream> using namespace std; int main(void) { int n, an[100], cnt = 0; cin >> n; for(int i = 0; i < n; i++) cin >> an[i]; for(int i = 0; i < n; i++) { int mini = i; int tmp = an[i]; for(int j = i; j < n; j++) { if(an[j] < an[mini]) { mini = j; } } if(i != mini) { an[i] = an...
Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers). The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond. Note 解説 Input In the first line, the number of cards n (n ≤ 52) is given. In the following n line...
n=int(input()) cs = [ (s,k) for s in ['S','H','C','D'] for k in range(1,14) ] for _ in range(n): s,k=input().split() cs.remove((s,int(k))) for (s, k) in cs: print(s, k)