input
stringlengths
29
13k
output
stringlengths
9
73.4k
For given two segments s1 and s2, print the distance between them. s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. Input The entire input looks like: q (the number of queries) 1st query 2nd query ... qth...
/// // File: cgl_2_d.cpp // Author: ymiyamoto // // Created on Mon Oct 23 00:28:22 2017 // #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> using namespace std; #define EPS 1e-10 #define equals(x, y) (fabs(x - y) < EPS) struct vector_t { double x; double y; vector_t(double a, double ...
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and reverse specified elements by a list of the following operation: * reverse($b, e$): reverse the order of $a_b, a_{b+1}, ..., a_{e-1}$ Constraints * $1 \leq n \leq 1,000$ * $-1,000,000,000 \leq a_i \leq 1,000,000,000$ * $1 \leq ...
#include <iostream> #include <cstring> #include <vector> #include <cstdio> #include <stack> #include<queue> #include<list> #include<algorithm> int main() { int n,q,b,e; std::cin>>n; std::vector<int> S; for(int i = 0; i < n; i++) { int hoge; std::cin>>hoge; S.push_back(hoge)...
The auditorium of Stanford University is made up of L*R matrix (assume each coordinate has a chair). On the occasion of an event Chef was called as a chief guest. The auditorium was filled with males (M) and females (F), occupying one chair each. Our Chef is very curious guy, so he asks the gatekeeper some queries. The...
# cook your code here n,m,t=map(int,raw_input().split()) a=[[0 for i in range(m)]for i in range(n)] b=[[0 for i in range(m)]for i in range(n)] q=[] m_max=0 f_max=0 for i in range(n): q.append(raw_input()) for j in range(m): if i==0 or j==0: if q[i][j]=='M': a[i][j]=1 ...
The Titanic ship is sinking. The nearest ship has answered the SOS call, and come to rescue the people. Everyone is anxious to get to safety. Unfortunately, the new ship may not have enough room to take everyone to safe land. This adds to the anxiety of people. To avoid stampede, there has to be some rescue plan. You...
#!/usr/bin/python "Solve the Rescue problem at CodeChef" def main(): testcases = int(raw_input()) for testcase in xrange(testcases): capacity, men, women, children = map(int, raw_input().split()) max_women = min(women, (men << 1)) max_children = min((men + max_women) << 2, int(capacity * 0.8)) children_rescue...
Problem description. Tima wants to contest for Mr. Ignus. But there are many obstacles which Tima must cross to become Mr. Ignus. Tima has qualified and passed all the tests and there remains a last test for him to complete successfully. The task is as follows : There are n judges. The ith judge have A[i] coins wi...
t=int(raw_input()) for _ in range(t): s=int(raw_input()) if s>0: arr=map(int,raw_input().split()) dp=[0]*s dp[0]=arr[0] if s>1: dp[1]=max(arr[0],arr[1]) if s>2: for i in range(2,s): dp[i]=max(dp[i-2]+arr[i], dp[i-1]) ...
Problem description. Jojo is so good at multiplying that she can multiply two 15-digits integers within 5 seconds. After practicing for years, she decided to approach the Limca Book of Records. As a jury member you are given the task to decide if she is eligible enough for holding the record. But before you test her, y...
print input() * input()
After IOI Ilya decided to make a business. He found a social network called "TheScorpyBook.com". It currently has N registered users. As in any social network two users can be friends. Ilya wants the world to be as connected as possible, so he wants to suggest friendship to some pairs of users. He will suggest user u ...
a = int (raw_input()) c= [] d= [] for i in range(a): now = raw_input() c.append(now) d.append(int(now,2)) i=0 for k in xrange(a): for j in xrange(k+1,a): if c[k][j]!='1': if int(d[k])&int(d[j]): i= i+2 print i
After Chef successfully built a modern (L, K)-window on the attic wall he decided to expand the notion of the (L, K)-window in some other areas. Now he considers a rectangular grid that contains only zeroes and ones and has size N x M. He considers the (L, K)-window here as any submatrix of size L x K that contains onl...
#!/usr/bin/python mainlis=[] maxv=1000000080798150871 for i in range(0,1000,1): mainlis.append([]) varlis=mainlis[i] for j in range(0,3,1): varlis.append(0) test=input() while test >0: string=raw_input() lis=string.split() n=int(lis[0]) m=int(lis[1]) l=int(lis[2]) k=int(lis[3]) for i in range(...
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room. The bu...
t,f,lw,hw,q = map(int,input().split()) while(q): t1,f1,t2,f2=map(int,input().split()) if(t1==t2): print(abs(f1-f2)) else: ans=abs(t1-t2) if((f1>=lw and f1<=hw) or (f2>=lw and f2<=hw)): ans+=abs(f1-f2) print(ans) elif(f1<lw and f2 <lw) : ans+=(abs(lw-f1)+abs(lw-f2)) print(an...
Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked m neighbours of Ada about clients w...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; scanf("%d%d", &n, &m); long long ret = 0; vector<vector<int>> a(m); int pos[100002][11]; for (int i = 0; i < m; i++) { int aa; for (int j = 0; j < n; j++) { scanf("%d", &aa); a[i].push_back(aa); pos[aa][i] = j; ...
Vova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0. Each heater has a va...
//package Contest515div3; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class mainB { public static Scanner enter = new Scanner(System.in); public static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args...
Alice is a big fan of volleyball and especially of the very strong "Team A". Volleyball match consists of up to five sets. During each set teams score one point for winning a ball. The first four sets are played until one of the teams scores at least 25 points and the fifth set is played until one of the teams scores ...
#include <bits/stdc++.h> using namespace std; const int N = 20; int ans[N][2]; void update(int w, int l, int L, int R, int a, int b) { int st = 0; for (int i = L; i <= R; i++) { if (i < l) st = 1; else st = 0; int val = min(st == 1 ? a : b, ans[i][st] - 2); ans[i][1 - st] = val; if (...
Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit. Vasya has n problems to choose from. They are numbered from 1 to n. The difficulty of the i-th problem is d_i. Moreover, the problems are given in the increasing order by the...
#include <bits/stdc++.h> using namespace std; template <typename Tp> inline void read(Tp &x) { static char c; static bool neg; x = 0, c = getchar(), neg = false; for (; !isdigit(c); c = getchar()) { if (c == '-') { neg = true; } } for (; isdigit(c); c = getchar()) { x = x * 10 + c - '0'; ...
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule s, which can be represented as a binary string, in which the i-th symb...
def findNeedSubstring(s): n = len(s) rst = '' tmp = 0 for i in range(1, n-1, 1): if(s[0:i] == s[n-i:n]): rst = s[0:i] # this is the longest substring that prefix = suffix tmp = i return s[tmp: n] def polyHash(s): rst = [0] * (len(s) + 1) h...
You are given an array a consisting of n integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0. You may choose at most one consecutive subarray o...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } const long long mod = 1e9 + 7; long long modpow(long long a, long long e) { if (e == 0) return 1; long long x = modpow(a * a % mod, e >> 1); return e & 1 ? x * a % mod : x; } int n; long long dp...
Alice is the leader of the State Refactoring Party, and she is about to become the prime minister. The elections have just taken place. There are n parties, numbered from 1 to n. The i-th party has received a_i seats in the parliament. Alice's party has number 1. In order to become the prime minister, she needs to b...
#include <bits/stdc++.h> using namespace std; vector<int> v; int main() { int n; cin >> n; int s = 0; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; s += a[i]; } v.push_back(0); int sum = a[0]; for (int i = 1; i < n; i++) { if (a[0] >= 2 * a[i]) { sum += a[i]; v.push_back...
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
for z in range (int(input())): a=list(map(int,input().split())) print(sum(a)//2)
Polycarp is reading a book consisting of n pages numbered from 1 to n. Every time he finishes the page with the number divisible by m, he writes down the last digit of this page number. For example, if n=15 and m=5, pages divisible by m are 5, 10, 15. Their last digits are 5, 0, 5 correspondingly, their sum is 10. You...
q = int(input()) for i in range(q): n, m = input().split(" ") n = int(n) m = int(m) if n == m: print(m%10) continue inicial = m aux = (m%10) m += inicial while (m%10) != (inicial%10) and m <= n: aux += (m%10) m += inicial m = m-inicial ...
Alice got a new doll these days. It can even walk! Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column. However, the d...
#include <bits/stdc++.h> using namespace std; long long m, n, flag, x = 1, y = 1, k; const int maxn = 1e5 + 5; vector<long long> line[maxn]; vector<long long> col[maxn]; struct node { int x, y; } last; bool fun(int x, int y) { if (last.x == x && last.y == y) return true; return false; } void run(long long ans) { ...
This is the harder version of the problem. In this version, 1 ≤ n ≤ 10^6 and 0 ≤ a_i ≤ 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend...
/** * @author derrick20 */ import java.io.*; import java.util.*; public class SendBoxesToAlice { public static void main(String args[]) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); long[] arr = sc.next...
You are given two integers a and b. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by 1; during the second operation you choose one of these numbers and increase it by 2, and so on. You choose the number of these operations yourself. For example, if...
cum_sum = [0]*47000 cum_sum[1]=1 for i in range(2,47000): cum_sum[i] = cum_sum[i-1]+i n = int(input()) for i in range(n): a,b = map(int,input().split()) delta = max(a,b) - min(a,b) cnt = cum_sum.index([el for el in cum_sum if el <= delta][-1]) eq = a+b+cum_sum[cnt] while (eq%2!=0 or eq//2 <...
You are given a string s consisting of lowercase Latin letters. Let the length of s be |s|. You may perform several operations on this string. In one operation, you can choose some index i and remove the i-th character of s (s_i) if at least one of its adjacent characters is the previous letter in the Latin alphabet f...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10; int n, m, k; string s; bool check(const string& s, int j) { return (j > 0 && s[j - 1] + 1 == s[j]) || (j < n - 1 && s[j + 1] + 1 == s[j]); } void solve() { for (int i = 25; i >= 0; i--) { for (int k = 0; k < n + 20; k++) { for (int j...
Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He w...
#include <bits/stdc++.h> using namespace std; long long mod2 = 1e9 + 7; long long mod = 998244353; const long long N = 2e3 + 12; bool vis[2005][2005]; int n, k, a[10][2005]; string s[] = {"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"}, ...
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble. There is a set S containing very important number...
/** * @author vivek * programming is thinking, not typing */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { private static void solveTC(int __) { /* For Google */ // ans.append("Case #").append(__).append(": "); ...
This is the hard version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
t=int(input()) for _ in range(t): n=int(input()) arr=list(input().rstrip("\n")) arr1=list(input().rstrip("\n")) arr=[int(x) for x in arr] arr1=[int(x) for x in arr1] #print(arr,n) result=[] if arr == arr1: print(0) else: if n == 1: print("1 1") ...
Mr. Chanek just won the national chess tournament and got a huge chessboard of size N × M. Bored with playing conventional chess, Mr. Chanek now defines a function F(X, Y), which denotes the minimum number of moves to move a knight from square (1, 1) to square (X, Y). It turns out finding F(X, Y) is too simple, so Mr. ...
#include <bits/stdc++.h> using namespace std; namespace modular { const int mod = 1000000007; inline int add(int x, int y) { return x + y >= mod ? x + y - mod : x + y; } inline int dec(int x, int y) { return x - y < 0 ? x - y + mod : x - y; } inline int mul(int x, int y) { return 1ll * x * y % mod; } } // namespace mo...
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: * Choose m such that 1 ≤ m ≤ 1000 * Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java...
You have given an array a of length n and an integer x to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be q. If q is divisible by x, the robot adds x copies of the integer q/x to the end of the array, and moves on to the next element. Note ...
import java.io.*; import java.util.StringTokenizer; public class A_StrangeList { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static final PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); private static Strin...
You are given n rectangles, each of height 1. Each rectangle's width is a power of 2 (i. e. it can be represented as 2^x for some non-negative integer x). You are also given a two-dimensional box of width W. Note that W may or may not be a power of 2. Moreover, W is at least as large as the width of the largest recta...
#include <bits/stdc++.h> using namespace std; int main() { long t; cin>>t; while(t--){ long n,w; cin>>n>>w; long tmp; long count[20]={0}; for(long i=0;i<n;i++){ cin>>tmp; count[long(log2(tmp))]++; } // for(long i=19;i>=0;i--) // cout<<count[i]<<" "; long space_left=w,largest=-1; long heig...
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet. The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot re...
#include <bits/stdc++.h> #include <string> using namespace std; bool susp() { int n; cin >> n; string days; cin >> days; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (days[j] == days[i] && days[j - 1] != days[i]) return false; }...
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2). In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider t...
import java.util.*; import java.io.*; import java.math.*; /** * @author Naitik * */ public class Main { static FastReader sc=new FastReader(); static long dp[][]; static int mod=1000000007; static int max; static long bit[]; static long seg[]; static long A[]; static PrintWriter out=new Prin...
Vasya plays the Geometry Horse. The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is kno...
#include <bits/stdc++.h> using namespace std; struct st { int x; int c; }; int pr(st a, st b) { return a.c < b.c; } st a[1005]; long long b[1005]; int i, j, k, n, m, x, y; long long res, t, z; int main() { cin >> n; for (i = 0; i < n; i++) { cin >> a[i].x >> a[i].c; } sort(a, a + n, pr); cin >> m; f...
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that. Let's consider a set of fun...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class d123 { public static void debug(Object... obs) { System.out.println(Arrays.deepToString(obs)); } static long...
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one. The council of the elders has recently decided to ...
#include <bits/stdc++.h> using namespace std; vector<pair<long long, long long> > vec[300005]; long long d[300005], r[300005], cost[300005]; long long val = 300005, temp; long long rev; void dfs(int node, int parent, int dist, int inv) { d[node] = dist; r[node] = inv; for (int i = 0; i < vec[node].size(); i++) { ...
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an. Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar. Polycarpus took a piece of...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); vector<int> digitos(long long n, int dig) { vector<int> res; while (n > 0) { res.push_back(n % 2); n /= 2; } while (res.size() < dig) res.push_back(0); reverse(res.begin(), res.end()); return res; } int main() { int n; w...
Manao is working for a construction company. Recently, an order came to build wall bars in a children's park. Manao was commissioned to develop a plan of construction, which will enable the company to save the most money. After reviewing the formal specifications for the wall bars, Manao discovered a number of controv...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; long MODULAR = 1000000009; public void solve() throws ...
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number....
#f = open("A.in", "r+") #a = f.readline().strip() n = int(input()) a = raw_input().strip() a = [int(x) for x in a.strip().split()] cnt = 0; ok = True aSet = set(a) for i in aSet: if i == 0: continue if a.count(i) == 2: cnt += 1 elif a.count(i) > 2: ok = False print(-1) break; if ok: print(cnt)
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning....
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10, P = 1e9 + 7; int t, n, tt[N], cnt, tmp; long long sum, f[N], fac[N]; void freo() { freopen("throw.in", "r", stdin); freopen("throw.out", "w", stdout); } void prep() { t = 1; f[1] = fac[0] = 1; f[2] = 2; for (int i = 0; ++i < N; fac[i] = f...
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xeni...
#include <bits/stdc++.h> using namespace std; long long t[400000]; long long a[1 << 17]; void build_segment_tree(long long v, long long tl, long long tr, bool op) { if (tl == tr) { t[v] = a[tl]; return; } long long tm = tl + (tr - tl) / 2; build_segment_tree(2 * v, tl, tm, !op); build_segment_tree(2 *...
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the le...
import java.util.*; public class Main { private static final long MOD = 1000000007; public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); int taskCount = scan.nextInt(); scan.nextLine(); for (int taskIndex = 0; taskIndex < taskCoun...
One day a bear lived on the Oxy axis. He was afraid of the dark, so he couldn't move at night along the plane points that aren't lit. One day the bear wanted to have a night walk from his house at point (l, 0) to his friend's house at point (r, 0), along the segment of length (r - l). Of course, if he wants to make thi...
#include <bits/stdc++.h> using namespace std; template <class T> inline T sqr(T x) { return x * x; } const double EPS = 1e-6; const int INF = 0x3fffffff; const long long LINF = INF * 1ll * INF; const double PI = acos(-1.0); using namespace std; int sign(double x) { return x < -EPS ? -1 : x > EPS; } struct Point { d...
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; const int maxn = 1e5 + 123; vector<int> v[maxn]; int n, m, High[maxn]; bool mark[maxn]; int Dfs(int Vert, int Dad) { mark[Vert] = true; vector<int> now; now.clear(); for (__typeof(v[Vert].begin()) i = v[Vert].begin(); i != v[Vert].end(); ++i) if (!mark[*i]) { ...
Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital ...
#include <bits/stdc++.h> using namespace std; int i, j, k, m, n, q, x, y; int u[1090][1090], d[1090][1090], l[1090][1090], r[1090][1090]; int a[1090][1090]; void precacu() { int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) if (a[i][j]) { if (a[i - 1][j]) u[i][j] = u[i - 1][j];...
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
n = int(input()) for _ in range(n): a,b = map(int,input().split()) if a!=b: print ('Happy Alex') exit() print ('Poor Alex')
There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: * Red-green tower is consisting of some number of levels; * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level — of n...
#include <bits/stdc++.h> using namespace std; const int mod = 1000000007ll; int r, g; long long dp[2][300000]; int main() { scanf("%d %d", &r, &g); int h = 1; while (((h + 1) * (h + 2)) / 2 <= r + g) h++; int N = min(r, g); dp[0][0] = 1; for (int k = 1; k <= h; k++) { for (int n = 0; n <= N; n++) { ...
Dohyun is running a grocery store. He sells n items numbered by integers from 1 to n. The i-th (1 ≤ i ≤ n) of them costs ci dollars, and if I buy it, my happiness increases by hi. Each item can be displayed only for p units of time because of freshness. As Dohyun displays the i-th item at time ti, the customers can buy...
#include <bits/stdc++.h> using namespace std; const int MAXD = 20000; const int MAXB = 4000; int N, P, Q, ans[MAXD + 5], back[MAXB + 5][MAXB + 5], forw[MAXB + 5][MAXB + 5]; vector<pair<int, int> > que[MAXD + 5], itm[MAXD + 5]; void apply(int d, int m[][MAXB + 5], int *i) { for (auto p : itm[d]) { for (int c = 1; ...
One day Om Nom found a thread with n beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly. <image> Om Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regul...
#include <bits/stdc++.h> using namespace std; const int INF = INT_MAX; const long long INFL = LLONG_MAX; const long double pi = acos(-1); int N, K; string s; int ans[1001001]; int z[1001001]; int main() { ios_base::sync_with_stdio(0); cout.precision(15); cout << fixed; cout.tie(0); cin.tie(0); cin >> N >> K...
Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called GukiZiana. For given array a, indexed with integers from 1 to n, and number y, GukiZiana(a, y) represents maximum value of j - i, such that aj = ai = y. If there is no y as an element in a, then GukiZiana(a, y) is eq...
#include <bits/stdc++.h> using namespace std; const long long inf = LLONG_MAX; int n, q, sq, len, ord, ii, jj, val, mx, mn, mxpos, mnpos; long long lazy[1000]; vector<pair<long long, long long> > S[1000]; inline int getseg(int pos) { return pos / sq + (pos % sq != 0); } void prop(int as) { for (int i = 0; i < S[as].s...
You are given a box full of mirrors. Box consists of grid of size n × m. Each cell of the grid contains a mirror put in the shape of '\' or ' / ' (45 degree to the horizontal or vertical line). But mirrors in some cells have been destroyed. You want to put new mirrors into these grids so that the following two conditio...
#include <bits/stdc++.h> using namespace std; const int N = 205, M = N * N; int n, m, l, mod, fa[M], id[M], fl; long long ans, a[N][N]; char s[N][N]; long long mypow(long long x, int y) { long long z = 1; while (y) { if (y & 1) (z *= x) %= mod; y >>= 1; (x *= x) %= mod; } return z; } long long det()...
Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the ro...
import java.util.*; public class Rules { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a = in.nextInt(); double maxSpeed = in.nextInt(); double len = in.nextInt(); double delayDist = in.nextInt(); double delaySpeed = in.nextInt(); double timeToDela...
You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line...
#!/usr/bin/env python3 import datetime def main(args): hh, mm = list(map(int, input().split(':'))) a = int(input()) mm += a hh += (mm // 60) mm %= 60 hh %= 24 print(f"{hh:02d}:{mm:02d}") return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
Limak is a little grizzly bear. He will once attack Deerland but now he can only destroy trees in role-playing games. Limak starts with a tree with one vertex. The only vertex has index 1 and is a root of the tree. Sometimes, a game chooses a subtree and allows Limak to attack it. When a subtree is attacked then each ...
#include <bits/stdc++.h> const int maxN = 5e5 + 7; const int maxH = 60; int n, fa[maxN]; double f[maxN][maxH]; inline int read() { int x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = ...
The term of this problem is the same as the previous one, the only exception — increased restrictions. Input The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ...,...
#include <bits/stdc++.h> using namespace std; const int N6 = 1e6 + 6, N3 = 1e3 + 6, oo = 1e9 + 9, base = 1e9 + 7; const long long ool = 1e18 + 9; int n; long long k, a[N6], ans, b[N6]; pair<long long, int> d[N6]; int main() { ios_base ::sync_with_stdio(0); cin.tie(0); cin >> n >> k; for (int i = 1; i <= n; ++i)...
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two...
#include <bits/stdc++.h> using namespace std; const long long MOD = 1000000007; const long long INF = 1000000000; template <class T> inline void read(T &x) { char c; int flag = 1; while ((c = getchar()) < '0' || c > '9') if (c == '-') flag *= -1; x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x =...
R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met anoth...
import sys,heapq #sys.stdin=open("data.txt") input=sys.stdin.readline n,a,b=map(int,input().split()) if a<b: a,b=b,a if b==0: # 1 01 001 0001 ... is optimal, plus a long series of 0's print((n-1)*a) else: # pascal's triangle thing pascal=[[1]*20005] for i in range(20004): n...
This problem has unusual memory constraint. At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared n papers with the income of some company for some time periods. Note that the income can be positive, zero or negative. Igor and Zhenya placed the papers in a row and dec...
#include <bits/stdc++.h> #pragma warning(disable : 4996) using namespace std; int IT_MAX = 1 << 19; const int MOD = 100000000; const int INF = 1034567891; const long long LL_INF = 1234567890123456789ll; const double PI = 3.141592653589793238; const double ERR = 1E-10; int in[4050]; int sum[4050]; int dp[4050][95][95]; ...
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string...
n,m=map(int,input().split()) m1,m2,m3=[m+1]*n,[m+1]*n,[m+1]*n for i in range(n): s=input() for j, c in enumerate(s): z=min(j, m-j) if c>='0' and c<='9': m1[i]=min(m1[i],z) else: if c>='a' and c<='z': m2[i]=min(m2[i],z) else: ...
<image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0
import sys import itertools def f(x): a = x[0] | x[1] b = x[2] ^ x[3] c = x[1] & x[2] d = x[0] | x[3] e = a & b f = c ^ d g = e | f return g def main(): a = [] for i in xrange(4): a.append(int(raw_input().strip())) x = 8 * a[0] + 4 * a[1] + 2 * a[2] + a[3] d ...
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7...
s = list(raw_input()) cur = 0 ans = 0 mod = pow(10,9)+7 for i in range(len(s)-1,-1,-1): if s[i]=='a': ans = (ans+cur)%mod if cur: cur *= 2 cur %= mod else: cur += 1 print ans
It is known that passages in Singer house are complex and intertwined. Let's define a Singer k-house as a graph built by the following process: take complete binary tree of height k and add edges from each vertex to all its successors, if they are not yet present. <image> Singer 4-house Count the number of non-empty ...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; int n; long long c[500][500]; long long dp[500][500]; int main() { scanf("%d", &n); for (int i = 0; i <= 400; i++) { for (int j = 0; j <= i; j++) { if (j == 0 || j == i) c[i][j] = 1; else c[i][j] = (c[i - 1][j - 1...
Mojtaba and Arpa are playing a game. They have a list of n numbers in the game. In a player's turn, he chooses a number pk (where p is a prime number and k is a positive integer) such that pk divides at least one number in the list. For each number in the list divisible by pk, call it x, the player will delete x and a...
#include <bits/stdc++.h> using namespace std; int su[1000005]; long long prim[1000005]; int tot = 0; int n; long long arr[1005]; map<long long, long long> vis; map<long long, long long>::iterator it; map<long long, long long> SG; void shai() { for (int i = 2; i <= 1000000; i++) if (su[i] == 0) { prim[++tot]...
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's an...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int a, b, c; cin >> a >> b >> c; if (n == 1) { cout << 0; return 0; } cout << min(a, b) + min(min(a, b), c) * (n - 2); }
Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy start...
#include <bits/stdc++.h> using namespace std; string s, a, b; string ans[2][2] = {{"fantasy", "backward"}, {"forward", "both"}}; bool check() { int pos = s.find(a); if (pos == string::npos) return false; pos = s.find(b, pos + a.length()); return pos != string::npos; } int main() { ios::sync_with_stdio(false);...
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had ...
#include <bits/stdc++.h> using namespace std; signed main() { ios::sync_with_stdio(0); string seq; cin >> seq; vector<string> f(10); for (int i = 0; i < 10; ++i) { cin >> f[i]; } for (int i = 0; i + 8 <= 80; i += 10) { for (int j = 0; j < 10; ++j) { if (f[j] == seq.substr(i, 10)) { c...
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles. Here are some definitions of graph theory. An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices....
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; void set_io(string s) { ios_base::sync_with_stdio(0); cin.tie(0); freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } vector<int> d(200001); map<int, vector<int> > cc; int cc_count(0), n, m; vector<bool> vis(2...
On one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game. It is well known that one month on this planet consists of n^2 days, so calendars, represented as square matrix n by n are extremely popular. Weather conditions are even more unusual. Due to the unique composition o...
#include <bits/stdc++.h> using namespace std; const int mod = 998244353; int pw[1000005], fac[1000005], inv[1000005]; int ksm(int a, int p) { int ans = 1; while (p) { if (p & 1) ans = 1ll * ans * a % mod; a = 1ll * a * a % mod; p >>= 1; } return ans; } int C(int n, int m) { if (n < m) return 0; ...
Our Tom is doing what he is best at, COOKING A BARBECUE for his guests. He has invited all of us, and taking the help of his apprentice to smoke the barbecues. The Tom has got BBQ sticks, each can take N fillings, and he presents N distinctly filled sticks in front his guests forming a N*N matrix But here is the probl...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' n=int(raw_input()) while(n>0): n-=1 a=int(raw_input()) ans=2**(a-2)+1 print ans
In Poornima college, PIET CS Deparment is shifting from basement to the third floor. The HOD of the department is trying to finding the number ways to reach the third floor. You are given the number of stairs, and you have to help HOD to find out number of ways in which he can climb the stairs. The HOD is capable of cl...
fibo = [1,2] def gen() : for i in range(2,150) : fibo.append(fibo[i-1]+fibo[i-2]) gen() for __ in range(input()) : print fibo[input()-1]%(1<<64)
Chandu has been appointed as the superintendent of a jail having N prisoners . Prisoner are numbered form 1 to N. Today he has been specially invited to execute the prisoners. All the prisoners are arranged in circle and he starts executing them in clock-wise direction. He always starts with first prisoner and skips ...
st1=int(raw_input()) while(st1!=0): ans=1 n=int(raw_input()) k=2 for i in range(n): ans=(ans+k-1)%(i+1)+1 print(ans) st1=st1-1
As the league stage of the world cup has come to its end, its time to calculate the highest points earned in the league stage by a team. There are many teams playing in the world cup. A team is awarded 3 points for a win, 1 point for a tie and it loses 1 point if they lose a match. You have received data of N  teams ...
res = list() n = int(raw_input()) for i in range(n): num = list(map(int, raw_input().split())) res.append(num[0]*3+num[1]*1-num[2]) print(max(res))
Problem Description Apparently, the key that would take Alice home from her Wonderland adventure is a magic pass code hidden in numbers. Help her find it! It's the one with the highest sum of its digits! Input Format Input consists of several integer n, each separated by a newline character. Output Format Output ...
alls = [] while True: failed = False try: s = raw_input() except: failed = True break if len(s.rstrip().lstrip())==0: failed = True break alls.append(s) if len(alls)> 0: winner = '' maxs = 0 for y in alls: csum = sum(int(x) for x...
Nikki's latest work is writing an story of letters. However, she finds writing story so boring that, after working for three hours, she realized that all she has written are M long words consisting entirely of letters A and B. Having accepted that she will never finish the story in time, poor Nikki has decided to at le...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' n = int(raw_input()) count = 0 for i in range(n): inputStr = raw_input() inputStrArr = inputStr.split() stack = [] for j in inputStr: #print j #print sta...
Ramesh is a hard-working employee.Seeing his dedication towards his work his boss decided to promote him. Ramesh was overjoyed on getting to know this.But soon he realized he needed to shift to another Town X. Ramesh needed to transport his n boxes to Town X for which he contacted the company "Packers and Movers".This ...
import sys n, m = [int(x) for x in sys.stdin.readline().split()] weights = [int(x) for x in sys.stdin.readline().split()] trucks = [int(x) for x in sys.stdin.readline().split()] weights.sort(reverse=True) trucks.sort(reverse=True) w = 0 t = 0 count = 1 while (weights): #print(w, len(weights)) if t == len(truc...
You are given an array A1,A2...AN. You have to tell how many pairs (i, j) exist such that 1 ≤ i < j ≤ N and Ai XOR Aj is odd. Input and Output First line T, the number of testcases. Each testcase: first line N, followed by N integers in next line. For each testcase, print the required answer in one line. ...
t=input() for j in range(t): n=input() res=sum(int(i)%2 for i in raw_input().split()) print res*(n-res)
There are N temples in a straight line and K monks who want to spread their enlightening power to the entire road of temples. All the monks have an enlightenment value, which denotes the range of enlightenment which they can spread in both the directions. Since, they do not want to waste their efficiency on trivial th...
def is_enlightened(xs, k, power): last_position = xs[0] + power k -= 1 for x in xs: if x > last_position + power: last_position = x + power k -= 1 return k >= 0 def solve(xs, k): xs.sort() start = 0 end = ((xs[0] + xs[-1]) / 2) + 1 found = end while ...
Xsquare loves to play with the coins very much. Today , he has N stacks of coins . Each stack of coins has some non zero height Hi equal to the number of coins on that stack ( considering all the coins are identical and each coin has a height of 1 unit ) . In one move, Xsquare can select any number of consecutive sta...
t = int(raw_input()) for i in range(t): (n, k) = map(int, raw_input().strip().split(' ')) arr = map(int, raw_input().strip().split(' ')) mask = [0]*n for i in range(n): if arr[i]<=k: mask[i]=1 i=0 ans=0 while i<n: if mask[i]==0: i+=1 else: temp=0 while i<n and mask[i]!=0: temp+=arr[i] ...
We have N boxes numbered 1 to N, and M balls numbered 1 to M. Currently, Ball i is in Box A_i. You can do the following operation: * Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box. Since the balls are very easy to break, you cannot move Ball i more th...
#include<bits/stdc++.h> using namespace std; typedef long long LL; const int N=100000,INF=(1<<30)-1; int n,m,cm,a[N+9],b[N+9],c[N+9]; struct side{ int y,next; }e[N*2+9]; int lin[N+9],cs; void Ins(int x,int y){e[++cs].y=y;e[cs].next=lin[x];lin[x]=cs;} void Ins2(int x,int y){Ins(x,y);Ins(y,x);} int deg[N+9][2]; v...
Raccoon is fighting with a monster. The health of the monster is H. Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health. Raccoon wins when the monster's health becomes 0 or below. If Raccoon can win without using...
#include <bits/stdc++.h> using namespace std; int main() { int h, n, a; cin >> h >> n; for (int i = 0; i < n; i++) { cin >> a; h -= a; } cout << (h <= 0 ? "Yes" : "No") << endl; }
Given is a permutation P of \\{1, 2, \ldots, N\\}. For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R. Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}. Constraints * 2 \le N \le 10^5 * 1 \le P_i \le N * P_i \neq P_j (i \neq j) * All values...
#include<bits/stdc++.h> #define ll long long using namespace std; template <typename T> void read(T &x){ x=0;char ch=getchar();int fh=1; while (ch<'0'||ch>'9'){if (ch=='-')fh=-1;ch=getchar();} while (ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar(); x*=fh; } int n,x,w[100010],le[100010],ho[100010]; ll ans; int main(){ ...
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i. At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation: * Choose a vertex ...
import java.util.*; public class Main { public static List<Integer> link[]; public static int[] d; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); link = new ArrayList[N]; for (int i=0; i<N; i++) { link[i] = new...
Takahashi has an N \times N grid. The square at the i-th row and the j-th column of the grid is denoted by (i,j). Particularly, the top-left square of the grid is (1,1), and the bottom-right square is (N,N). An integer, 0 or 1, is written on M of the squares in the Takahashi's grid. Three integers a_i,b_i and c_i desc...
/* [caddi2018] F - Square */ #include <algorithm> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; typedef long long...
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation: * Choose an element in the sequence and move it to the beginning or the end of the sequence. Find the minimum number of op...
#include <bits/stdc++.h> using namespace std; const int N=200005; int n,a[N],b[N],dp[N]; int main(){ scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&a[i]),b[a[i]]=i; int ans=0; for (int i=1;i<=n;i++){ int p=b[a[i]-1]; dp[i]=dp[p]+1; ans=max(ans,dp[i]); } printf("%d",n-ans); return 0; }
You are given an integer N. Consider an infinite N-ary tree as shown below: <image> Figure: an infinite N-ary tree for the case N = 3 As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. ...
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long int lli; int main(){ int n,q; cin >> n >> q; for(int i=0; i<q; i++){ lli x,y; cin >> x >> y; if(n==1){ cout << min(x, y) << endl; continue; } x--...
There are N balls in a row. Initially, the i-th ball from the left has the integer A_i written on it. When Snuke cast a spell, the following happens: * Let the current number of balls be k. All the balls with k written on them disappear at the same time. Snuke's objective is to vanish all the balls by casting the ...
#include <iostream> #include <cstring> #include <cstdio> using namespace std; const int M = 2e5 + 10; int a[M] , vis[M] , cnt[M]; int main() { int n , m; scanf("%d%d" , &n , &m); int ans = n; for(int i = 1 ; i <= n ; i++) { scanf("%d" , &a[i]); cnt[a[i]]++; int pos = a[i] - cnt[a...
N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament. For some reasons, the tournament may not be "fair" for all the contestants. That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The struct...
#include <bits/stdc++.h> using namespace std; template <class T> using V = vector<T>; template <class T> using VV = V<V<T>>; int n; VV<int> g; int dfs(int v) { V<int> st; for (int u: g[v]) { st.push_back(dfs(u)); } sort(st.begin(), st.end()); int g = 0; for (int d: st) { g = ...
Snuke loves permutations. He is making a permutation of length N. Since he hates the integer K, his permutation will satisfy the following: * Let the permutation be a_1, a_2, ..., a_N. For each i = 1,2,...,N, |a_i - i| \neq K. Among the N! permutations of length N, how many satisfies this condition? Since the ans...
#include <cstdio> #include <iostream> #include <algorithm> #define N 4010 #define P 924844033 using namespace std; int n,k,t; int a[N]; int vis[N][2]; long long fac[N],g[N]; long long Ans; long long f[N][N][2]; int main(){ scanf("%d%d",&n,&k); for(int i=1;i<=n;i++) for(int j=0;j<2;j++) if(!vis[i][j]){ ...
If the strings are consecutive, you can replace the characters with a rule to shorten the string. For example, for the string AAAA, the expression @ 4A will compress one character. Create a program that restores the character string compressed by this rule to the original character string. However, it is assumed that t...
while True: try: s = raw_input() except EOFError: break i=0 hirabun = '' while i <len(s): if s[i] != '@': hirabun += s[i] i += 1 elif s[i] == '@' and i+2 < len(s): hira_part = s[i+2]*int(s[i+1]) hirabun += hira_...
Mr. A came to Aizu for sightseeing. You can overlook the Aizu Basin from the window of the hotel where you stayed. As I was looking at the scenery, I noticed a piece of the photo on the floor. Apparently I took the outside view from the window. "Which area did you take?" A asked, holding the photo so that the view outs...
#include<iostream> #include<algorithm> #include<vector> #include<stack> #include<map> #include<set> #include<queue> #include<cstdio> #include<climits> #include<cmath> #include<cstring> #include<string> #include<sstream> #include<numeric> #include<cassert> #define f first #define s second #define mp make_pair #define ...
If you visit Aizu Akabeko shrine, you will find a unique paper fortune on which a number with more than one digit is written. Each digit ranges from 1 to 9 (zero is avoided because it is considered a bad omen in this shrine). Using this string of numeric values, you can predict how many years it will take before your ...
#include <bits/stdc++.h> using namespace std; #define rep(i, j, n) for(int i=j;i<n;++i) #define all(i) i.begin(),i.end() #define rall(i) i.rbegin(),i.rend() #define INF 1e9 const int mod = 1e9 + 7; typedef long long i64; typedef pair<int, int> pi; template <class T> using vt = vector<T>; template <class T> using vvt...
Compute A + B. Constraints * -1000 ≤ A, B ≤ 1000 Input The input will consist of a series of pairs of integers A and B separated by a space, one pair of integers per line. The input will be terminated by EOF. Output For each pair of input integers A and B, you must output the sum of A and B in one line. Example ...
#include<iostream> #include <cstdio> using namespace std; int main() { int a, b; while (scanf("%d %d", &a, &b) != EOF) printf("%d\n", a + b); return 0; }
RJ Freight, a Japanese railroad company for freight operations has recently constructed exchange lines at Hazawa, Yokohama. The layout of the lines is shown in Figure B-1. <image> Figure B-1: Layout of the exchange lines A freight train consists of 2 to 72 freight cars. There are 26 types of freight cars, which are d...
#include <bits/stdc++.h> using namespace std; int calc(string s) { set<string> sset; int n = s.size(); for(int i=0; i<n; i++) { string fst(s, 0, i), snd(s, i, n-i); string rfst(fst.rbegin(), fst.rend()), rsnd(snd.rbegin(), snd.rend()); sset.insert(fst+snd); sset.insert(...
One of the tasks students routinely carry out in their mathematics classes is to solve a polynomial equation. It is, given a polynomial, say X2 - 4X + 1, to find its roots (2 ± √3). If the students’ task is to find the roots of a given polynomial, the teacher’s task is then to find a polynomial that has a given root. ...
#include <vector> #include <algorithm> #include <cstdio> #include <cmath> using namespace std; bool gauss(vector<vector<long double> > &a){ if(a.empty())return false; int n=a.size(); for(int i=0;i<n;i++){ if(!a[i][i]){ int j=i+1; for(;j<n;j++){ if(a[j][i]){ for(int k=i;k<=n;k++)a[i][k]+=a[j][k]; ...
A grid of r × c is given. Numbers from 1 to 8 are written on some squares on the grid. <image> It is necessary to connect the squares with numbers and the squares with other numbers with a line. For the squares with numbers written on them, it is necessary to connect lines with other squares as many as the number wr...
#include <iostream> #include <cstdio> #include <vector> #include <list> #include <cmath> #include <fstream> #include <algorithm> #include <string> #include <queue> #include <set> #include <map> #include <complex> #include <iterator> #include <cstdlib> #include <cstring> #include <sstream> #include <stack> #include <cli...
The mayor of Amida, the City of Miracle, is not elected like any other city. Once exhausted by long political struggles and catastrophes, the city has decided to leave the fate of all candidates to the lottery in order to choose all candidates fairly and to make those born under the lucky star the mayor. I did. It is a...
#include <iostream> #include <utility> #include <vector> #define llint long long using namespace std; typedef pair<llint, llint> P; llint n, m, a; vector<P> vec[1005]; int main(void) { while(1){ cin >> n >> m >> a; if(n == 0 && m == 0 && a == 0) break; for(int i = 1; i <= 1000; i++) vec[i].clear(); llint...
Ninjas are professional spies in the Middle Age of Japan. They have been popular in movies and games as they have been described with extraordinary physical abilities and unrealistic abilities. You are absorbed in one of ninja games, Ninja Legend. In this game, you control in an exceptionally talented ninja named Mast...
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; //Ninja Legend public class Main{ int h, w, N, INF = 1<<29; char[][] map; int[][] d = {{-1,0},{0,1},{1,0},{0,-1}}, adj, id, dp; int get(int S, int la...
Angry Birds is a mobile game of a big craze all over the world. You were convinced that it was a waste of time to play the game, so you decided to create an automatic solver. <image> You are describing a routine that optimizes the white bird's strategy to defeat a pig (enemy) by hitting an egg bomb. The white bird fo...
// OBツ嘉ッツ嘉債宿2011 Day3 I : White Bird #include <iostream> #include <vector> #include <cmath> using namespace std; const double EPS = 1e-8; int main(){ int N, V, X, Y; int L[50], B[50], R[50], T[50]; while(cin >> N >> V >> X >> Y){ vector<double> vd; int low = Y, high = 1000000007; for(int i=0;i<N;i++){ c...
Mr. Haskins is working on tuning a database system. The database is a simple associative storage that contains key-value pairs. In this database, a key is a distinct identification (ID) number and a value is an object of any type. In order to boost the performance, the database system has a cache mechanism. The cache ...
#include <algorithm> #include <queue> #define REP(i,n) for(int i=0; i<(int)(n); i++) #include <cstdio> #include <unordered_set> inline int getInt(){ int s; scanf("%d", &s); return s; } using namespace std; int main(){ const int n = getInt(); const int m = getInt(); std::unordered_set<int> s; vector<int> v(n...
In Manhattan, roads run where the x or y coordinate is an integer. Both Sunuke-kun's house and Sumeke-kun's house are on the road, and the straight line distance (Euclidean distance) is just d. Find the maximum value that can be considered as the shortest distance when traveling along the road from Sunuke-kun's house t...
#include<iostream> #include<vector> #include<utility> #include<algorithm> #include<string> #include<cstdio> #include<queue> #include<functional> #include<tuple> #include<iomanip> #include<stack> #include<cmath> #define ll long long using namespace std; int main() { double d,m; cin >> d; m = sqrt(2)*d; if (sqrt(d*d -...
Example Input 2 4 %.@\$ ..\$\$ Output Yes
#include <bits/stdc++.h> using namespace std; #define F first #define S second #define pi M_PI #define R cin>> #define Z class #define ll long long #define ln cout<<'\n' #define in(a) insert(a) #define pb(a) push_back(a) #define pd(a) printf("%.10f\n",a) #define mem(a) memset(a,0,sizeof(a)) #define all(c) (c).begin(),(...
D: Sontaku (Surmise) Some twins like even numbers. Count how many even numbers are in $ N $ integers $ A_1, A_2, A_3, \ dots, A_N $. input The integer $ N $ is given on the first line. On the second line, $ N $ integers $ A_1, A_2, A_3, \ dots, A_N $ are given, separated by blanks. output Output an even number. ...
#include <bits/stdc++.h> #define r(i,n) for(int i=0;i<n;i++) #define int long long using namespace std; typedef pair<int,int>P; #define fi first #define se second signed main(){ int n,s=0; cin>>n; while(n--){ int a; cin>>a; if(a%2==0)s++; } cout<<s<<endl; }