input
stringlengths
29
13k
output
stringlengths
9
73.4k
Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given. Circle inside a rectangle Cons...
import java.util.Scanner; class Main{ public static void main(String[] args){ Scanner stdIn = new Scanner(System.in); int W = stdIn.nextInt(); int H = stdIn.nextInt(); int x = stdIn.nextInt(); int y = stdIn.nextInt(); int r = stdIn.nextInt(); if (x+r<=W && y+r<=H && x-r>=0 && y-r>=0){ Syst...
Now that we have recovered all our data, we can return to hacking in to the hacker's system. Our sources tell us that this hacker's lust for power is so great that it is reflected in everything he does, everything he creates. Perhaps this knowledge can become his weakness in our hands, his thirst for power laying a tra...
#! /usr/bin/python # imports import sys import StringIO class Problem(object): def __init__(self, reader): self.reader = reader def run(self): test_case_count = int(self.reader.readline().strip()) for test_case in range(test_case_count): t...
Pakistan Team is obsessed with match fixing. Their bookie Asif is writing a letter to them and wants nobody else to be able to read it. They use a simple substitution cipher to encode his message. Each letter in the message is replaced with its corresponding letter in a substitution alphabet. A substitution alphabet is...
def main(): from string import ascii_lowercase as al t = input() for i in xrange(t): string = raw_input().strip() d = {} ans = "" indx = 0 for _ in string: try: ans += d[_] except: d[_] = al[indx] ...
Given a positive integer K > 2, with prime factorization: K = p1^a1 * p2^a2 ... * pn^an Compute the following: S = a1*p1 + a2*p2 ... + an*pn. Input A list of Output For each integer compute the super factor sum and output it on a single line. Example Input: 6 7 Output: 5 7
from fractions import gcd import sys import cStringIO from Queue import Queue import random def rho(n): if n%2 == 0: return 2 x = y = random.randrange(2, 1000000) d = 1 c = random.randrange(2, 1000000) while d==1: x = ((x*x)+c)%n y = ((y*y)+c)%n y = ((y*y)+c)%n ...
A number is called as a lucky number if its decimal representation contains only the lucky digits, 4 and 7. e.g. 47, 744, 4 are lucky numbers, whereas 5, 17, 467 are not. Recently, Na2a found a magic stone. With the help of this stone, he can multiply a number by any lucky number. Also, the magic stone can be used any ...
n=input() a=[] a=map(int,raw_input().split()) for i in range (n): c2=0 c5=0 #print i temp=a[i] while temp%2==0: c2=c2+1 temp=temp/2 temp=a[i] while temp%5==0: c5=c5+1 temp=temp/5 ans=a[i] while c5>c2: ans=ans*4 c2=c2+2 print ans
The following graph G is called a Petersen graph and its vertices have been numbered from 0 to 9. Some letters have also been assigned to vertices of G, as can be seen from the following picture: Let's consider a walk W in graph G, which consists of L vertices W1, W2, ..., WL, such that Wi is connected with Wi + ...
def digit(c,present): if c=='A': if present=='i': return "5" else: return "0" elif c=='B': if present=='i': return "6" else: return "1" elif c=='C': if present=='i': return "7" else: return "2" elif c=='D': if present=='i': return "8" else: return "3" elif c=='E': if prese...
Soma is a fashionable girl. She absolutely loves shiny stones that she can put on as jewellery accessories. She has been collecting stones since her childhood - now she has become really good with identifying which ones are fake and which ones are not. Her King requested for her help in mining precious stones, so she ...
test=int(raw_input()) a=0 while(a<test): a=a+1 count=0 j= raw_input() s= raw_input() for letter in s: if (letter in j): count=count+1 print count
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2'). You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa). For e...
#include <bits/stdc++.h> using namespace std; long long sz; bool valido(const long long &p) { return (p < sz); } int main() { string s, r, b, o; cin >> s; sz = int(s.size()); for (long long i = 0; i < sz; i++) { if (s[i] == '1') r += s[i]; else b += s[i]; } bool a = false; for (long lo...
You are given an array a of length n that consists of zeros and ones. You can perform the following operation multiple times. The operation consists of two steps: 1. Choose three integers 1 ≤ x < y < z ≤ n, that form an arithmetic progression (y - x = z - y). 2. Flip the values a_x, a_y, a_z (i.e. change 1 to 0...
#include <bits/stdc++.h> using namespace std; int n; int a[100055]; int main() { cin >> n; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); } vector<pair<int, int> > res; for (int i = 1; i + 2 <= n; i++) if (a[i]) { a[i] ^= 1; int add = 1; for (int j = i + 1; j <= n; j++) { ...
Egor came up with a new chips puzzle and suggests you to play. The puzzle has the form of a table with n rows and m columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip), p...
#include <bits/stdc++.h> using namespace std; struct Node { int a, b, c, d; } temp; queue<Node> q1, q2; string s1[305][305], s2[305][305]; int main() { int n, m; int ans = 0, m1 = 0, m2 = 0; int num1 = 0, num0 = 0; scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { ...
Vasya has a tree consisting of n vertices with root in vertex 1. At first all vertices has 0 written on it. Let d(i, j) be the distance between vertices i and j, i.e. number of edges in the shortest path from i to j. Also, let's denote k-subtree of vertex x — set of vertices y such that next two conditions are met: ...
/** * Date: 13 Nov, 2018 * Link: * * @author Prasad-Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java...
One Saturday afternoon Egor was playing his favorite RPG game. While discovering new lands and territories, he came across the following sign: <image> Egor is a passionate player, but he is an algorithmician as well. That's why he instantly spotted four common letters in two words on the sign above — if we permute th...
#include <bits/stdc++.h> using namespace std; const int Maxn = 100005; int T, n, k, ct, pnt, a[Maxn], mini[Maxn], from[Maxn]; bool type, vis[Maxn]; vector<int> tmp, Ve[Maxn]; void work(void) { pnt = 0; a[0] = type ? 0x3f3f3f3f : -0x3f3f3f3f; mini[1] = 0; for (int i = 1; i <= n; i++) { int pos = lowe...
The king of Berland organizes a ball! n pair are invited to the ball, they are numbered from 1 to n. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from 1 to k, inclusive. Let b_i be the color of the man's ...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n, k; cin >> n >> k; vector<array<int, 2>> ats; for (int i = 1; i <= k; i++) for (int j = i + 1; j <= k; j++) { ats.push_back({i, j}); ats.push_back({j, i}); if (ats...
Input The input contains a single integer a (1 ≤ a ≤ 99). Output Output "YES" or "NO". Examples Input 5 Output YES Input 13 Output NO Input 24 Output NO Input 46 Output YES
import math k = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] n = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] a = int(input()) if a < ...
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
n = int(input()) l = [] se = set() for _ in range(n): st = input() s = st[0:1] l.append(s) se.add(s) su = 0 for s in se: c = l.count(s) if c>1: x = c//2 y = c-x su += ((x*(x-1))+(y*(y-1)))//2 print(su)
After a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the curren...
#include <bits/stdc++.h> using namespace std; struct Edge { int src, dst; long long cost; Edge(int a, int b, long long c) : src(a), dst(b), cost(c) {} bool operator<(const Edge &rhs) const { return cost < rhs.cost; } }; struct UnionFind { vector<int> data, last; vector<vector<pair<int, int> > > history; U...
The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without chang...
#include <bits/stdc++.h> using namespace std; string s, s1; bool check(string ans) { int pos = 0; for (int i = 0; i < ans.size(); i++) { if (ans[i] == s1[pos]) { pos++; } } if (pos == s1.size()) return true; else return false; } int main() { cin >> s >> s1; int ans = 0; for (int i ...
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
n = int(input()) s = input() for i in range(s.count('n')): print(1, end = ' ') for i in range(s.count('z')): print(0, end = ' ')
Constanze is the smartest girl in her village but she has bad eyesight. One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto...
s=input() a=s.count('m') f=True ans=0 if(a>0): f=False a=s.count('w') if(a>0): f=False n=len(s) if(f==True): dp=[0]*(n+1) dp[0]=1 dp[1]=1 for i in range(2,n+1): if(s[i-1]==s[i-2] and (s[i-1]=='u' or s[i-1]=='n')): dp[i]=(dp[i-1]+dp[i-2])%1000000007 else: ...
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not. Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c...
def inp(): return [int(s) for s in input().split()] if __name__ == '__main__': for i in range(int(input())): s = input() output = '' if len(s) == 1 and s[0] == '?': s = 'a' for j in range(len(s)): if s[j] != '?': output += s[j] ...
This problem is different with easy version only by constraints on total answers length It is an interactive problem Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask tw...
#include <bits/stdc++.h> using namespace std; int charcnt[1000]; int main() { ios::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; if (n == 1) { cout << "? 1 1" << endl; char firstch; cin >> firstch; cout << "! " << firstch; return 0; } else if (n == 2) { cout << "? 1 1" << e...
Kuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done, and he is discussing with the team about the score distribution for the round. The round consists of n problems, numbered from 1 to n. The problems are ordered in increasing order of difficulty,...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") using namespace std; constexpr int maxn = 5e3 + 100; int n, m, ans[maxn]; int main() { scanf("%d %d", &n, &m); if (n == 1) return puts(m == 0 ? "1" : "-1"); if (n == 2) return puts(m == 0 ? "1 2" : "-1"); ans[1] = 1; ans[2] = 2; for (int i = 3; i <= n; ...
Piet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules. The program will be a rectangular image consisting of col...
#include <bits/stdc++.h> using namespace std; const int maxn = 262, hm = 52 * 52, maxt = 200; const long long INF = 1000; const long double EPS = 1E-9, EPS2 = 1E-8; const long double M_PIS = 3.14159265358979323846264338327950288; unsigned char color[hm]; string s[maxn]; pair<int, int> deltas[4]; pair<int, int> pix[hm][...
Note that the only differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if all versions are solved. Slime is interested in sequences. He defined good positive integer sequences p of length n as follows: * For each k>1 that presents in p, there should be at ...
#include <bits/stdc++.h> char obuf[1 << 21], *oS = obuf, *oT = oS + (1 << 21) - 1; struct Flusher_ { ~Flusher_() { (fwrite(obuf, 1, oS - obuf, stdout), oS = obuf, void()); } } flusher_; template <class T> inline void print(T x) { if (x < 0) (*oS++ = ('-'), oS == oT ? (fwrite(obuf, 1, oS - obuf, stdout), oS...
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him. Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card c...
#include <bits/stdc++.h> using namespace std; const int MaxN = int(2e5); const long double pi = 3.1415926535897932384626433832795; char s[MaxN]; int main() { while (gets(s)) { int len = strlen(s); int tmp = (len - 2) / 2 + len % 2; int one = 0, two = 0; for (int i = (0); i <= (len - 1); i++) { o...
This is an interactive problem. Omkar has just come across a duck! The duck is walking on a grid with n rows and n columns (2 ≤ n ≤ 25) so that the grid contains a total of n^2 cells. Let's denote by (x, y) the cell in the x-th row from the top and the y-th column from the left. Right now, the duck is at the cell (1, ...
#include <bits/stdc++.h> using namespace std; const long long inf = 2000000000000000000LL; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long t, i, j, k, l, m, n, o, p, q, temp, ans = 0, flag = 0, mod = 1000000007; cin >> n; long lon...
— Hey folks, how do you like this problem? — That'll do it. BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows: 1. He chooses two piles (i, j) such that 1 ≤ i, j ≤ n and i ≠ j. 2. All candies from pile i are...
for _ in range(int(input())): n, k = list(map(int,input().split())) arr = list(map(int,input().split())) arr.sort() i, j = 0, 1 c = 0 while j<n: temp = arr[i] + arr[j] if temp <= k: t = k-arr[j] t = t//arr[i] c += t j += 1 print(c)
You are given a matrix a of size n × m consisting of integers. You can choose no more than \left⌊m/2\right⌋ elements in each row. Your task is to choose these elements in such a way that their sum is divisible by k and this sum is the maximum. In other words, you can choose no more than a half (rounded down) of eleme...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization("unroll-loops") const long long int inf = 9e18; const long double pi = 2 * acos(0.0); using namespace std; long long int power(long long int a, long long int n) { if (n == 0) { return 1; } long l...
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap! In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a playe...
#include<bits/stdc++.h> typedef long long ll; const int N = 5e5 + 50; struct point_t { int x, y, id; inline bool operator<(const point_t &rhs) const { if (x != rhs.x) return x < rhs.x; if (y != rhs.y) return y < rhs.y; return id < rhs.id; } } p[N]; int n, m, o, tot, buc[N], t[N]; bool vis[N], lose[N]; inl...
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. <image> There are n books standing in a row on the shelf, the i-th book has color a_i. You'd like to rearrange the books to make the shelf look beautif...
n = int(input()) a = [int(x) - 1 for x in input().split()] l = [-1 for _ in range(n + 1)] r = [-1 for _ in range(n + 1)] freq = [0 for _ in range(n + 1)] dp = [0 for _ in range(n + 1)] for i in range(n): if(l[a[i]] == -1): l[a[i]] = i r[a[i]] = i for i in range(n - 1, -1, -1): dp[i] = dp[i + 1] freq[a[i...
Touko's favorite sequence of numbers is a permutation a_1, a_2, ..., a_n of 1, 2, ..., n, and she wants some collection of permutations that are similar to her favorite permutation. She has a collection of q intervals of the form [l_i, r_i] with 1 ≤ l_i ≤ r_i ≤ n. To create permutations that are similar to her favorit...
// do a test using namespace std; #include <bits/stdc++.h> #define N 25005 #define M 100005 int n,m; int a[N]; int lmin[N],rmax[N]; int suc[N][2],pre[N][2]; int ans; void work(int l,int r){ for (int i=l;i<=r;++i){ for (int &j=rmax[i];j<=r;++j) if (a[j]>a[i]){ int &t=suc[i][0]; if (a[j]<a[t]) ans+=(pr...
Annie has gotten bored of winning every coding contest and farming unlimited rating. Today, she is going to farm potatoes instead. Annie's garden is an infinite 2D plane. She has n potatoes to plant, and the i-th potato must be planted at (x_i,y_i). Starting at the point (0, 0), Annie begins walking, in one step she c...
#include <bits/stdc++.h> #define l2 array<ll,2> using namespace std; typedef long long ll; const int N = 800100; multiset<ll> lft, rgt; ll ans = 0; l2 pts[N]; int n; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); #ifdef _LOCAL freopen("in.txt","r",stdin); #endif // _LOCAL cin >> n; for (int i...
Two players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue. We'll describe ...
#include <bits/stdc++.h> using namespace std; int n, m, xx1, yy1, xx2, yy2; int main() { cin >> n >> m; cin >> xx1 >> yy1 >> xx2 >> yy2; int dx = abs(xx1 - xx2), dy = abs(yy1 - yy2); if (dx > dy) { swap(dx, dy); } int mx; if (dx == 0) { mx = 4; } else if (dx == 1) { mx = 5; } else { mx...
The Little Elephant loves sortings. He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such that l ≤ i ...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; i++) { scanf("%d", &v[i]); } long long ans = 0; for (int i = 0; i < n - 1; i++) { ans += max(0, v[i] - v[i + 1]); } cout << ans << '\n'; return 0; }
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ...
//import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //import java.io.OutputStream; import java.io.PrintWriter; //import java.util.Scanner; import java.util.Arrays; import java.util.StringTokenizer; //import jdk.nashorn.internal.runtime.reg...
Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards i...
import java.io.IOException; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @...
Two players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid l...
import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the to...
Vasily the bear has got a large square white table of n rows and n columns. The table has got a black border around this table. <image> The example of the initial table at n = 5. Vasily the bear wants to paint his square table in exactly k moves. Each move is sequence of actions: 1. The bear chooses some square in...
#include <bits/stdc++.h> using namespace std; inline bool EQ(double a, double b) { return fabs(a - b) < 1e-9; } long long add(long long a, long long b) { long long ret = a + b; if (ret >= 7340033) ret -= 7340033; return ret; } long long subtract(long long a, long long b) { long long ret = a - b; if (ret < 0) ...
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: * Its elements are in increasing o...
n=int(input()) for i in range(n,n+n): print(i,end=' ')
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number ...
#include <bits/stdc++.h> using namespace std; const int N = 100001; int n; int a[N]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", a + i); long long lo = *max_element(a, a + n), hi = 1e13; while (lo < hi) { long long mid = (lo + hi) >> 1; long long tot = 0; for (int i = 0; i ...
There is a tree consisting of n vertices. The vertices are numbered from 1 to n. Let's define the length of an interval [l, r] as the value r - l + 1. The score of a subtree of this tree is the maximum length of such an interval [l, r] that, the vertices with numbers l, l + 1, ..., r belong to the subtree. Considerin...
#include <bits/stdc++.h> using namespace std; int A[100100]; int B[100100]; vector<int> L[100100]; int T[100100]; int prof[100100]; void update(int idx, int t) { idx++; while (idx < 100100) { T[idx] += t; idx += idx & -idx; } } int query(int idx) { idx++; int ret = 0; while (idx) { ret += T[idx]...
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add...
#include <bits/stdc++.h> int main() { std::string l; std::getline(std::cin, l); int a = 0; for (int i = 0; i < l.length(); i++) { if (l[i] == '|') { a++; } else { break; } } bool kot = false; if (l[a] == '+') { kot = true; } else { kot = true; } int a1 = 0; for (int...
During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check. Each participant is identified by some unique positive i...
#include <bits/stdc++.h> #pragma comment(linker, "/stack:256000000") using namespace std; int a[100100]; int main() { int n, x, k; cin >> n; for (int(i) = 0; (i) < (n); (i)++) { scanf("%d %d", &x, &k); if (a[k] < x) { printf("NO"); return 0; } if (a[k] == x) { ++a[k]; } } ...
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have a...
#include <bits/stdc++.h> const int N = 1001010; using namespace std; int Next[N], Pre[N], id[N], a[N], i, j, n, tmp, vis[N]; long long ans; bool cmp(int x, int y) { return a[x] < a[y]; } int main() { scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%d", &a[i]), id[i] = i, Next[i] = i + 1, Pre[i] = i - 1; sort...
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of...
#include <bits/stdc++.h> using namespace std; int make1(int n, int m, int a, int b) { int wk = 0; while (n > 0) { n--; wk += a; } return wk; } int make2(int n, int m, int a, int b) { int wk = 0; while (n > 0) { n -= m; wk += b; } return wk; } int make3(int n, int m, int a, int b) { int...
A traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the i-th rest point the distance from the start equals xi, and its picturesqueness e...
#include <bits/stdc++.h> using namespace std; namespace IO { template <class T> inline void readin(T& x) { char c; bool f = 0; while ((c = getchar()) < '0' || '9' < c) f |= (c == '-'); for (x = (c ^ 48); '0' <= (c = getchar()) && c <= '9'; x = (x << 1) + (x << 3) + (c ^ 48)) ; if (f) x = -x; } temp...
Nowadays, most of the internet advertisements are not statically linked to a web page. Instead, what will be shown to the person opening a web page is determined within 100 milliseconds after the web page is opened. Usually, multiple companies compete for each ad slot on the web page in an auction. Each of them receive...
#include <bits/stdc++.h> using namespace std; long double L[5], R[5]; int main() { int n; cin >> n; long double ans = 0; long double cte = 1; for (int i = 0; i < n; i++) cin >> L[i] >> R[i], cte *= (R[i] - L[i] + 1); for (int num = 1; num <= 10000; num++) { for (int k = 1; k < (1 << n); k++) { lon...
Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game. There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of ...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; template <class T> inline void scan_d(T &ret) { char c; int flag = 0; ret = 0; while (((c = getchar()) < '0' || c > '9') && c != '-') ; if (c == '-') { flag = 1; c = getchar(); } while (c >= '0'...
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively. Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connec...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class WorkFile { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = In...
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. <image> There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ....
#include <bits/stdc++.h> using namespace std; int main() { int N; scanf("%d", &N); int a[N], b[N]; for (int i = 0; i < N; i++) { scanf("%d%d", &a[i], &b[i]); } int fst = b[0], sum = a[0], rslt = 0; for (int i = 1; i < N; i++) { if (b[i] < fst) { rslt += sum * fst; fst = b[i], sum = a[i...
Pasha and Akim were making a forest map — the lawns were the graph's vertexes and the roads joining the lawns were its edges. They decided to encode the number of laughy mushrooms on every lawn in the following way: on every edge between two lawns they wrote two numbers, the greatest common divisor (GCD) and the least ...
#include <bits/stdc++.h> using namespace std; vector<int> primes; long long gcd(long long a, long long b) { if (b > a) return gcd(b, a); while (b) { long long mod = a % b; a = b; b = mod; } return a; } void gen_primes(int n) { vector<int> bit(n + 1, 1); primes.push_back(2); int lim = sqrt(n) +...
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections. The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob...
import java.io.*; import java.util.*; public class Main { void solve(Scanner in, PrintWriter out) { long n = in.nextLong(); out.println(n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * n * (n - 1) * (n - 2) * (n - 3) * (n - 4)); } void run() { try ( Scan...
Codeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contribution — an integer number, not necessarily positive. There are n registered users and the i-th of them has contribution ti. Limak is a little polar bear and he's new into competi...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; const int N = 2e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7; int n, k, a[N]; long long b, c; int get(int x) { return (x % 5 + 5) % 5; } int count(int x) { return (x - get(x)) / 5; } int main() { ios_base::sync_with_stdio(0...
Kolya is developing an economy simulator game. His most favourite part of the development process is in-game testing. Once he was entertained by the testing so much, that he found out his game-coin score become equal to 0. Kolya remembers that at the beginning of the game his game-coin score was equal to n and that he...
n = int(input()) for i in range((n//1234567) + 1): for j in range((n//123456) + 1): t = n - i * 1234567 - j * 123456 if t >= 0 and t % 1234 == 0: print("YES") exit() print("NO")
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are abou...
#include <bits/stdc++.h> using namespace std; const long long mod = 1e7 + 7; int main() { long long n, q1; cin >> n >> q1; queue<pair<int, int>> q; vector<int> timer(n + 1), mapi(n + 1); int total = 0, count = 0; vector<int> inValid(n + 1); while (q1--) { int x1, x2; cin >> x1 >> x2; if (x1 ==...
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first. There are n stacks of photos. Each stack con...
import java.io.*; import java.util.*; import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import static java.util.Arrays.sort; public class family_photos { static BufferedReader in; static PrintWriter out;...
Igor likes hexadecimal notation and considers positive integer in the hexadecimal notation interesting if each digit and each letter in it appears no more than t times. For example, if t = 3, then integers 13a13322, aaa, abcdef0123456789 are interesting, but numbers aaaa, abababab and 1000000 are not interesting. Your...
#include <bits/stdc++.h> using namespace std; const int HASH = 100003; const int MaxN = 1000000; struct HASHMAP { int head[HASH], next[MaxN], Hcou; unsigned long long key[MaxN]; long long val[MaxN]; void init() { Hcou = 0; memset(head, -1, sizeof(head)); } void insert(unsigned long long k, long long...
Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be pas...
#include <bits/stdc++.h> const int N = 1e5 + 7; using namespace std; vector<int> ans, a[N]; int us[N], need[N]; int x, i, j, k, n, m; void dfs(int x) { us[x] = 1; for (int i = 0; i < a[x].size(); ++i) if (us[a[x][i]] == 1) { cout << -1; exit(0); } else if (us[a[x][i]] == 2) continue; e...
Bankopolis, the city you already know, finally got a new bank opened! Unfortunately, its security system is not yet working fine... Meanwhile hacker Leha arrived in Bankopolis and decided to test the system! Bank has n cells for clients' money. A sequence from n numbers a1, a2, ..., an describes the amount of money ea...
#include <bits/stdc++.h> using namespace std; const long long N = (long long)1e5 + 6, M = 10, mod = (long long)0; long long a[N], n, seg[N << 2][M], ch[N << 2][M]; void pull(long long v) { long long l = v << 1, r = l | 1; for (long long j = 0; j < 10; ++j) seg[v][j] = seg[l][j] + seg[r][j]; } void build(long long v...
It's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood. <image> The neighborhood consists of n houses in a straight line, labelled 1 to n from left to right, all an equal distance apart. Everyone in this neighborhood lov...
#include <bits/stdc++.h> using namespace std; map<long long, long long> onLeft, onRight; pair<long long, long long> onMiddle; bool possible(long long n, long long k, long long limit) { onLeft.clear(); onRight.clear(); onLeft[0LL] = onRight[0LL] = 0LL; onMiddle = make_pair(2LL, n - 1LL); long long maxInterval,...
Lech got into a tree consisting of n vertices with a root in vertex number 1. At each vertex i written integer ai. He will not get out until he answers q queries of the form u v. Answer for the query is maximal value <image> among all vertices i on path from u to v including u and v, where dist(i, v) is number of edges...
#include <bits/stdc++.h> using namespace std; const int maxn = 5e4 + 20; const int sq = 256; const int qs = maxn / sq + 5; const int maxb = 10; vector<int> adj[maxn], tmp; int x[maxn]; int a[maxn], ans[maxn][qs]; int l[maxn * maxb], r[maxn * maxb], t[maxn * maxb], mx[maxn * maxb]; int tah = 1, par[maxn], p[maxn], h[max...
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go. Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of ...
import java.util.Scanner; public class Main20200817 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] line1 = scanner.nextLine().split(" "); String[] line2 = scanner.nextLine().split(" "); scanner.close(); int length = Integer.pars...
Masha's little brother draw two points on a sheet of paper. After that, he draws some circles and gave the sheet to his sister. Masha has just returned from geometry lesson so she instantly noticed some interesting facts about brother's drawing. At first, the line going through two points, that brother drew, doesn't...
#include <bits/stdc++.h> using namespace std; struct pt { long double x, y; pt(long double x = 0, long double y = 0) : x(x), y(y) {} const pt operator-(const pt &a) const { return pt(x - a.x, y - a.y); } const pt operator+(const pt &a) const { return pt(x + a.x, y + a.y); } const pt operator*(const long doubl...
Let's consider the following game. We have a rectangular field n × m in size. Some squares of the field contain chips. Each chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right. The player may choose a chip and make a move with it. The move ...
import java.io.*; public class E implements Runnable{ BufferedReader in; int n, m; char[] a; int[] left, right, up, down; int[] l, r, u, d; int max, cnt, cur; void dfs(int ind){ cur++; if (cur > max){max = cur; cnt = 1;} else if (cur== max)cnt++; if (l[ind] > -1) r[l[ind]] = r[ind]; if (r[...
Let us define two functions f and g on positive integer numbers. <image> <image> You need to process Q queries. In each query, you will be given three integers l, r and k. You need to print the number of integers x between l and r inclusive, such that g(x) = k. Input The first line of the input contains an integ...
/** * Created by Baelish on 2/15/2018. */ import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); g = new int[(int)1e6+50]; Arrays.fill(g, -1...
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is: Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the ...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int TESTS = 1; while (TESTS--) { int i, n; cin >> n; if (n < 6) cout << "-1" << endl; else { cout << "1 3" << endl << "1 2" << endl << "1 4" << endl; fo...
Some company is going to hold a fair in Byteland. There are n towns in Byteland and m two-way roads between towns. Of course, you can reach any town from any other town using roads. There are k types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least s differ...
import java.util.*; import java.io.*; //import java.text.*; public class Main{ final long MOD = (long)1e9+7, IINF = (long)1e19; final int MAX = (int)500001, MX = (int)1e7+1, INF = (int)1e9; // DecimalFormat df = new DecimalFormat("0.00000000"); // final double EPS = 1e-8; FastReader in; PrintWrit...
Agent 007 is on a secret mission in country "Codeland" on which he was transferring data in form of binary string to secret base of MI6. One day agents of country Codeland detect some ambiguity in system as they find that someone is leaking their data. When Agent 007 get to know about this, he become more careful and ...
''' # 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!' t=input() while t>0: t-=1 s=raw_input() n=input() x=(n*(n+1))/2 if x%2==0: print s.count("1") #print s else: print s.count("0")
“All Hail The King.” Middle aged, and overqualified highschool chemistry teacher Walter White has been diagnosed with lung cancer. To make sure his family is financially secure, he teams up with a former student Jesse Pinkman and turns to a life of crime to make and distribute the purest crystal meth on the streets. ...
for _ in range(int(raw_input())): n=int(raw_input()) a=map(int,raw_input().split()) a=sorted(a,reverse=True) add=0 i=0 l=len(a) while i<l: add=add+(a[i]*a[i+1]) i+=2 print add
Mack gives Daisy two strings S1 and S2-consisting only of characters- 'M' and 'D' , and asks her to convert S1 to S2 in exactly N moves. In a single move, Daisy has two choices: Exchange any one 'M' with a 'D', or Exchange any one 'D' with a 'M'. You need to help Daisy if it's possible to transform S1 to S2 in exactl...
def solve(s1, s2, k): count = 0 for i in xrange(len(s2)): if s1[i] != s2[i]: count += 1 if count > k: return False if count == k or (k-count) % 2 == 0: return True return False T = input() for i in xrange(T): s1, s2, N = raw_input().strip().split(" ") N = int(N) if solve(s1, s2, N): print "Yes" e...
Valentina is looking for a new game to play with her friends. She asks her mom Marcia for an idea. After a moment Marcia described to girls the following simple game. Girls are divided into n teams, indexed 1 through n. Each girl chooses a lowercase letter, one of 'a' - 'z'. Of course, some girls can choose the same l...
for _ in range(int(raw_input())): n,s=raw_input().split() n=int(n) p={} for i in s: if p.has_key(i): p[i]+=1 else: p[i]=1 a=[] for i in range(n): s=raw_input() ct=0 for j in s: ct+=p.get(j,0) a.append([ct,-len(s)...
Milly is feeling bored during her winter vaccations, so she has decided to do some random fun on some arrays. She will take K number of arrays of same same size N. She will make all possible non-empty subsets of these arrays. She will make a Set S made up of the same-sized subsets of these arrays while considering the ...
from operator import add, mul def read_ints(): return map(int, raw_input().split()) def sum(it): return reduce(add, it, 0) def getpow(a, x, mod): if x == 0: return 1 t = getpow(a, x / 2, mod) if x % 2 == 0: return t * t % mod return t * t * a % mod def main(): T = read_ints()[0] for t in xrange(T): N...
On the way to Dandi March, Gandhijee carried a mirror with himself. When he reached Dandi, he decided to play a game with the tired people to give them some strength. At each turn of the game he pointed out a person and told him to say a number N(possibly huge) of his choice. The number was called lucky if that equals ...
t=int(raw_input()) for i in range(t): a=raw_input() if(a[::-1]!=a): print "NO" elif(('2'in a)or('3'in a)or('4'in a)or('5'in a)or('6'in a)or('7'in a)or('9'in a)): print "NO" else: print "YES"
Julius Cipher is a type of cipher which relates all the lowercase alphabets to their numerical position in the alphabet, i.e., value of a is 1, value of b is 2, value of z is 26 and similarly for the rest of them. Little Chandan is obsessed with this Cipher and he keeps converting every single string he gets, to the ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t = int(raw_input()) dc = { "a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9, "j":10, "k":11, "l":12, "m":13, "n":14, "o":15, "p":16, "q":17, "r":18, "s"...
Today RK wants to play a game based on his awesome name.In this game RK gives you a string consists only of characters "R" and "K".Your task is to find the number of substrings of the given string, containing exactly M characters "R" and number of substrings containing exactly N characters "K". Note : String a1 is a s...
test=int(input()) for i in range(0,test): k,l = raw_input().split(' ') k=int(k) l=int(l) d, c, r = {0 : 1}, 0, 0 e,f,g={0:1},0,0 for x in raw_input(): c += x == 'R' f += x == 'K' r += d.get(c - k, 0) g += e.get(f-l,0) d[c] = d.get(c, 0) + 1 e[f]=e.get(f,0)+1 print (str(r)+" "+str(g))
Square Inc. processes thousands of transactions daily amounting to millions of dollars. They also have a daily target that they must achieve. Given a list of transactions done by Square Inc. and a daily target your task is to determine at which transaction does Square achieves the same. Input: First line contain...
import bisect; n=input(); A=map(int,raw_input().split()); V,su=[],0; for i in A: su+=i; V.append(su); for i in xrange(int(raw_input())): z=int(raw_input()); x=bisect.bisect_left(V,z); if x==n: print -1 else: print x+1
Description IIT Gandhinagar has a day-care centre for the children of its faculty and staff. As it is IIT Gandhinagar’s culture to do things differently, the morning roll-call here is conducted in a unique manner. The kids stand in a circle and the teacher proceeds around the circle clockwise, spelling each name on th...
n=input() arr=[-1]*(n+1) N=n p=1 while n: a=input() if (a%n==0): ans=n else: ans=a%n y=0 for x in range(p,N+1): if (arr[x]==-1): ans-=1 if (ans==0): y=x break # print "HEre"+str(ans)+str(y) if (ans): for x in range(1,p): # print x,ans,y,arr[x] # y+=1 if (arr[x]==-1): ans-=1 if...
We have 3N cards arranged in a row from left to right, where each card has an integer between 1 and N (inclusive) written on it. The integer written on the i-th card from the left is A_i. You will do the following operation N-1 times: * Rearrange the five leftmost cards in any order you like, then remove the three le...
#include<cstdio> #include<algorithm> #include<iostream> #include<cstring> using namespace std; const int maxn=2005; int a[3*maxn],maxx[maxn][maxn],maxval[maxn],nxtval[maxn]; void chmax(int &x,int y) { x=max(x,y); return; } void upd(int val,int t,int x,int y) { if(val==-1) return; int nxt=max(maxx[x][y],...
Let us define the FizzBuzz sequence a_1,a_2,... as follows: * If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}. * If the above does not hold but 3 divides i, a_i=\mbox{Fizz}. * If none of the above holds but 5 divides i, a_i=\mbox{Buzz}. * If none of the above holds, a_i=i. Find the sum of all numbers among the first...
N = int(input()) s = sum([i for i in range(1, N+1) if ((i%3)!=0) and ((i%5)!=0)]) print(s)
In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month. Constraints * Both 2019-M_1-D_1 and 20...
import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); int c = scan.nextInt(); int d = scan.nextInt(); int ans=1; if(a==c){ans=0;} System....
There is a stack of N cards, each of which has a non-negative integer written on it. The integer written on the i-th card from the top is A_i. Snuke will repeat the following operation until two cards remain: * Choose three consecutive cards from the stack. * Eat the middle card of the three. * For each of the other ...
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include<queue> #include<map> using namespace std; #define N 200012 typedef long long ll; struct node{ll x,y;friend bool operator<(node a,node b){return (a.x^b.x)?a.x<b.x:a.y<b.y;}}; int n,a[N]; map<node,ll>dp[22][22]; ll cal(int ...
There is a very long bench. The bench is divided into M sections, where M is a very large integer. Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action: * We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied s...
#pragma GCC optimize("O3") #include <bits/stdc++.h> // #include <ext/pb_ds/assoc_container.hpp> // using namespace __gnu_pbds; // gp_hash_table<int, int> mapka; using namespace std; #define PB push_back #define MP make_pair #define LL long long #define int LL #define FOR(i,a,b) for(int i = (a); i <= (b); i++) #define ...
Takahashi is practicing shiritori alone again today. Shiritori is a game as follows: * In the first turn, a player announces any one word. * In the subsequent turns, a player announces a word that satisfies the following conditions: * That word is not announced before. * The first character of that word is the same a...
#include <bits/stdc++.h> using namespace std; int n; string w; set<string>ss; int main(){ cin>>n; char c; for(int i=0;i<n;i++){ cin>>w; if(ss.count(w)==0){ if(i!=0&&c!=w[0]){ cout<<"No"; return 0; } c=w[w.size()-1]; ss.insert(w); } else{ cout<<"No"; return 0; } } cout<<"Yes"; r...
There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region. The front and back sides of these cards can be distinguished, and initially every card faces up. We will perform the following op...
#include <bits/stdc++.h> using namespace std; int main(){ long long n,m; cin>>n>>m; if(n==2 || m==2) cout<<0<<endl; else cout<<max(max((n-2),(long long)1)*max((m-2),(long long)1),(long long)0)<<endl; return(0); }
Rng is going to a festival. The name of the festival is given to you as a string S, which ends with `FESTIVAL`, from input. Answer the question: "Rng is going to a festival of what?" Output the answer. Here, assume that the name of "a festival of s" is a string obtained by appending `FESTIVAL` to the end of s. For ex...
# Problem A - XXFESTIVAL # input S = input() # inititliazation s_len = len(S) ans = S[:(s_len - 8)] # output print(ans)
You have N items and a bag of strength W. The i-th item has a weight of w_i and a value of v_i. You will select some of the items and put them in the bag. Here, the total weight of the selected items needs to be at most W. Your objective is to maximize the total value of the selected items. Constraints * 1 ≤ N ≤ 10...
n, W = [int(_) for _ in raw_input().split()] wvs = [[int(_) for _ in raw_input().split()] for i in xrange(n)] p = {0: 0} for w, v in wvs: for d, dv in p.items(): p[d + w] = max(p.get(d + w, 0), dv + v) m = -1 for d, dv in sorted(p.items()): if dv <= m: del p[d] con...
There are N persons, conveniently numbered 1 through N. They will take 3y3s Challenge for N-1 seconds. During the challenge, each person must look at each of the N-1 other persons for 1 seconds, in some order. If any two persons look at each other during the challenge, the challenge ends in failure. Find the order i...
#include "iostream" #include "math.h" using namespace std; int N; int num; int main() { cin >> N; if (N == 2) { cout << "-1\n"; return 0; } if (N % 2 == 1) { for (int i = 1; i <= N; i++) { for (int j = 0; j < N-1; j++) { num = i + j+1; if (num > N) { num %= N; } cout << num << " "; ...
Write a program which computes the digit number of sum of two integers a and b. Constraints * 0 ≤ a, b ≤ 1,000,000 * The number of datasets ≤ 200 Input There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF. ...
import sys import math for x in sys.stdin.readlines(): a, b = map(int, x.strip().split()) print int(math.log10(a + b)) + 1
I conducted an exit poll of the shopping amount at a department store. Create a program that takes the shopping amount data as input, calculates the average shopping amount per person, and outputs it. The number of people surveyed shall be 100,000 or less, and the shopping amount per person shall not exceed 1 million y...
#include<iostream> using namespace std; int main() { long long int a, b; int n,m; cin >> n; a = 0; for (int i = 1; i <= n; i++) { cin >> m; a = a + m; } cout << a / n << endl; }
There is a game called Packet Monster. A game that catches, raises, fights and exchanges monsters, and is very popular all over Japan. Of course, in my class. That's why I also raise monsters so that I can play with everyone in this game, but sadly there is no opponent to play against. I'm not the type who is good at t...
#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-9; //// < "D:\D_Download\Visual Studio 2015\Projects\programing_contest_c++\Debug\a.txt" int main() { w...
problem Information I want to paint a rectangular veneer board to make a signboard for the promotion of the Olympic Games. Some rectangular masking tapes are pre-attached to the veneer board where I do not want to paint. We decided to paint each area with a different color. For example, in the case of Figure 5-1 we us...
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <cmath> #include <queue> #include <vector> #define min(a,b) (((a) < (b)) ? (a) : (b)) #define max(a,b) (((a) > (b)) ? (a) : (b)) #define abs(x) ((x) < 0 ? -(x) : (x)) #define INF 0x3f3f3f3f #define delta 0.85 #define eps 1e-...
In 2012, human beings have been exposed to fierce onslaught of unidentified mysterious extra-terrestrial creatures. We have exhaused because of the long war and can't regist against them any longer. Only you, an excellent wizard, can save us. Yes, it's time to stand up! The enemies are dispatched to the earth with bei...
#include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; int main() { //vector<bool> close(1<<(5*5), false); vector<int> close((1<<(5*5))/32, 0); vector<int> cls(1000000); for (int n; scanf("%d", &n), !(n==0); ){ vector<vector<int> > pats(33); vector<vector<in...
People in Silverland use square coins. Not only they have square shapes but also their values are square numbers. Coins with values of all square numbers up to 289 (= 172), i.e., 1-credit coins, 4-credit coins, 9-credit coins, ..., and 289-credit coins, are available in Silverland. There are four combinations of coins...
#include <iostream> #include <cstring> using namespace std; int dp[310]; int main(){ memset(dp, 0, sizeof(dp)); dp[0] = 1; for(int i=1; i < 17; i++){ for(int j=1; j < 300; j++){ if(j < i*i) continue; dp[j] += dp[j-i*i]; } } int n; while(cin >> n, n){...
An open-top box having a square bottom is placed on the floor. You see a number of needles vertically planted on its bottom. You want to place a largest possible spheric balloon touching the box bottom, interfering with none of the side walls nor the needles. Java Specific: Submitted Java programs may not use "java.a...
#include <algorithm> #include <numeric> #include <map> #include <vector> #include <cmath> #include <iostream> #include <queue> #include <tuple> #include <set> #include <complex> #include <iomanip> using namespace std; typedef long double D; const D INF = 1e12, EPS = 1e-8; typedef complex<D> P; #define X real() #def...
Problem Jennifer and Marian presented Carla with the string S. However, Carla is not happy to receive the string S. I wanted the string T. The three decided to work together to change the string S to the string T. Jennifer first sorts the letters in any order. Marian then exchanges the lowercase letters of the two ...
#include <iostream> #include <cstdio> #include <cassert> #include <cstring> #include <vector> #include <valarray> #include <array> #include <queue> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <algorithm> #include <cmath> #include <complex> #include <random> using namespace ...
You are addicted to watching TV, and you watch so many TV programs every day. You have been in trouble recently: the airtimes of your favorite TV programs overlap. Fortunately, you have both a TV and a video recorder at your home. You can therefore watch a program on air while another program (on a different channel) ...
#include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <functional> #include <sstream> #include <complex> #include <stack> #include...
Masa Kita, who entered the University of Tokyo, joined a circle called TSG (University of Tokyo Super Gamers). This circle exhibits games at the Komaba Festival every year, and Masa Kita decided to create and display the games as well. The game created by Kitamasa is a common falling block puzzle game such as the fol...
#include<iostream> #include<cstring> #define rep(i,n) for(int i=0;i<n;i++) using namespace std; string g[12]; bool vis[12][12]; bool clr[12][12]; const int dy[] = {-1,0,1,0}, dx[] = {0,1,0,-1}; int dfs(int y,int x,int col){ if(g[y][x] != col)return 0; if(vis[y][x])return 0; vis[y][x] = true; int res = 1; r...
Example Input 2 3 1 3 1 0 Output 2
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pa...
Problem Statement A magician lives in a country which consists of N islands and M bridges. Some of the bridges are magical bridges, which are created by the magician. Her magic can change all the lengths of the magical bridges to the same non-negative integer simultaneously. This country has a famous 2-player race ga...
#include <bits/stdc++.h> using namespace std; const long long INF=1LL<<60; const int MAXN=1005; int n, m, S1, S2, T; char s[100]; struct edge{ int to; long long w; bool type; edge(int to=0, long long w=0, bool type=false):to(to),w(w),type(type) {} }; vector<edge> G[MAXN]; long long dist[MAXN][MAXN]; pri...
Falling Block Puzzle Block drop You are playing a falling block puzzle. As shown in the figure below, the field of this puzzle has a shape in which cubic cells are arranged in 2 squares x 2 squares in each row, and the rows are infinitely arranged on the top. <image> Each cell either has one block that fits snugly ...
#include <bits/stdc++.h> using namespace std; #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) typedef long long LL; int main(){ int h,n; char c; while(1){ cin >> h >> n; if(h==0) return 0; vector<vector<vector<int> > > field(h+2*n+1,vector<vector<int> >(2,vector<int>(2,0))); ...