task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Plotting functions (variation) (PLOT1)
Given a function y=f(x) in RPN-notation plot it with stars (*) and then (!) its derivation with crosses (+) for 0 ≤ x ≤ 20 with Δx=1 in a diagram with 21×21 points (0 ≤ x,y ≤ 20). Empty fields are marked with dots (.). For plotting the real number y should be rounded to integer (-0.5 → -1, -0.4 → 0, 0.4 → 0, 0.5 → 1). The function and its derivation are continuous between 0 and 20.
The function definition uses only the following characters: 0123456789x.+-*/^
'^' means 'power of'. Items are separated by space.
Input
In the first line the number N of functions, then N lines with one function.
Output
The plot of each function and its derivation in 21 lines.
Example
Input:
1
x 1 -
Output:
.....................
....................*
...................*.
..................*..
.................*...
................*....
...............*.....
..............*......
.............*.......
............*........
...........*.........
..........*..........
.........*...........
........*............
.......*.............
......*..............
.....*...............
....*................
...*.................
+++++++++++++++++++++
.*................... | 32,300 |
PRIMITIVEROOTS (PROBLEM4)
Introduction to Primitive Roots
a
primitive root modulo
n
is any number
g
with the property that any number
coprime
to
n
is
congruent
to a power of
g
modulo
n
.
The number 3 is a primitive root modulo 7. because
Problem Statement
Given a number n as input you’ve to find the (product all the primitive roots of n) % n if n is prime.
Input
The first line consists of T the number of test cases followed by T lines. Each line consists of a prime number n.
Output
For each test case print the test case number followed by ‘
:
’ followed by (product of all primitive roots of n) % n. If it is not a prime then print “
NOTPRIME
”
Input Specifications
1 ≤ T ≤ 100
3 ≤ n ≤ 10000
Example
Input:
3
6
7
9
Output:
1:NOTPRIME
2:1
3:NOTPRIME
Description for test case #2:
The primitive roots of 7 are 3 and 5. The product % 7 = 15 % 7 =1 | 32,301 |
Adventure in Moving (AVDM)
To help you move from Waterloo to the big city, you are considering renting a moving truck. Gas prices being so high these days, you want to know how much the gas for such a beast will set you back.
The truck consumes a full litre of gas for each kilometre it travels. It has a 200 litre gas tank. When you rent the truck in Waterloo, the tank is half full. When you return it in the big city, the tank must be at least half full, or you'll get gouged even more for gas by the rental company. You would like to spend as little as possible on gas, but you don't want to run out along the way.
Input
Input is all integers. The first integer is the distance in kilometres from Waterloo to the big city, at most 10000. Next comes a set of up to 100 gas station specifications, describing all the gas stations along your route, in non-decreasing order by distance. Each specification consists of the distance in kilometres of the gas station from Waterloo, and the price of a litre of gas at the gas station, in tenths of a cent, at most 2000.
Output
Output is the minimum amount of money that you can spend on gas to get you from Waterloo to the big city. If it is not possible to get from Waterloo to the big city subject to the constraints above, print "Impossible".
Example
Input:
500
100 999
150 888
200 777
300 999
400 1009
450 1019
500 1399
Output:
450550 | 32,302 |
Barn Allocation (BARN)
Farmer John recently opened up a new barn and is now accepting stall
allocation requests from the cows since some of the stalls have a
better view of the pastures.
The barn comprises N (1 ≤ N ≤ 100,000) stalls conveniently numbered
1..N; stall i has capacity C
i
cows (1 ≤ C
i
≤ 100,000). Cow i
may request a contiguous interval of stalls (A
i
, B
i
) in which to
roam (1 ≤ A
i
≤ N; A
i
≤ B
i
≤ N), i.e., the cow would like to
wander among all the stalls in the range A
i
..B
i
(and the stalls
must always have the capacity for her to wander).
Given M (1 ≤ M ≤ 100,000) stall requests, determine the maximum
number of them that can be satisfied without exceeding stall
capacities.
Consider both a barn with 5 stalls that have the capacities shown
and a set cow requests:
Stall id: 1 2 3 4 5
+---+---+---+---+---+
Capacity: | 1 | 3 | 2 | 1 | 3 |
+---+---+---+---+---+
Cow 1 XXXXXXXXXXX (1, 3)
Cow 2 XXXXXXXXXXXXXXX (2, 5)
Cow 3 XXXXXXX (2, 3)
Cow 4 XXXXXXX (4, 5)
FJ can't satisfy all four cows, since there are too many requests
for stalls 3 and 4.
Noting that Cow 2 requests an interval that includes stalls 3 and
4, we test the hypothesis that cows 1, 3, and 4 can have their
requested stalls. No capacity is exceeded, so the answer for this
set of data is 3 – three cows (1, 3, and 4) can have their requests
satisfied.
Input
Line 1: Two space-separated integers: N and M
Lines 2..N+1: Line i+1 contains a single integer: C
i
Lines N+2..N+M+1: Line i+N+1 contains two integers: A
i
and B
i
Output
Line 1: The maximum number of requests that can be satisfied
Example
Input:
5 4
1
3
2
1
3
1 3
2 5
2 3
4 5
Output:
3 | 32,303 |
GRADE POINT AVERAGE (GPA1)
Every student of a college has to write 3 internal assessments and 1 final exam on each semester for all the 6 subjects. Each internal assessment mark is out of 20 and the final exam mark is out of 100. The best two of three assessment marks is chosen and those marks are considered to be out of 45. The final exam mark is considered to be out of 50. The remaining 5 marks is allotted based on the percentage of attendance of the student.
Attendance mark allotment
Below 51% attendance – 5 marks
Below 61% attendance – 4 marks
Below 71% attendance – 3 marks
Below 81% attendance – 2 marks
Below 91% attendance – 1 mark
else – No mark for those sincere students
Some students even bunk the assessments. If he bunks then instead of the mark ‘ab’ symbol is used which denotes “absent”. But no one bunks the final exam.
No attendance is taken during exam days
For each subject there’ll be some credit allotted by the department based on the importance of the subject.
Total marks in a particular subject = best two out of three assessments (45%) + attendance mark (5%) + Final exam (50%)
Points out of 10:
%Total mark in a subject Points
>= 91 10
>= 81 9
>= 71 8
>= 61 7
> 50 6
== 50 5
< 50 0
If the student scores 0 point in any of the subjects then he’s declared as FAILED else he’s declared as PASSED.
Mr. Chintumani, a professor of Computer Science department of the college designed a software program to calculate the GRADEPOINTAVERAGE (GPA) of the student and to determine whether the student is “PASSED” or “FAILED"
GPA = sum of (credit * points) for all the subjects / total number of credits of all the subjects
Input
The first line consists of an integer n, the number of students in the class. Then n test cases follows, in each test case the first line consists of 6 integers a, b, c, d, e and f, the credits of the 6 subjects. Then for the next 6 lines, each line (each subject) consists of 5 numbers (the first three numbers are the assessment marks out of 20, the fourth is the final exam mark and the fifth is the percentage of attendance).
Output
Assume you are Prof. Chintumani and print the result and GPA (rounded to two decimal places) per line for each student in the format as given in the example output.
Example:
Input:
1
1 1 1 2 2 3
19 18 20 70 70
17.33 15 16.66 66 70.66
ab ab ab 0 100
ab ab 10 78 78
17 18.33 19.5 64 87
14 8 ab 60 45
Output:
FAILED, 6.30
Explanation of the test case:
There is only 1 student
In the Subject 0, he got 19, 18 and 20 as internal marks, considering best two of three his internals score is 43.875/45.
His final exam score is 35/50.
His attendance mark is 3.
So the total marks he got in that subject is 81.875 which leads to 9 points.
Similarly he gets.
Subject 1: 74.2387 → 8 points
Subject 2: 0 → 0 points
Subject 3: 52.25 → 6 points
Subject 4: 75.5588 → 8 points
Subject 5: 59.75 → 6 points
GPA = (9*1 + 8*1 + 0*1 + 6*2 + 8*2 + 6*3 ) / (1+1+1+2+2+3) = 6.30
Since he got 0 points in at least one of the subjects he has FAILED
The output format is “RESULT,
gpa” without double quotes. | 32,304 |
Ancient Pocket Calculator (POCALC1)
Adam likes pocket calculators, especially the early ones. As one of his favorite calculators is about 40 years old, he is not sure how long he will be able to use it. So he had the ingenious idea to develop a simulator that behaves exactly like his calculator. This simulator must be able to read a sequence of keystrokes from the calculator's keypad, process the appropriate calculations and print the calculator's output. As Adam needs only basic arithmetic, the following keys will be sufficient: digits 0 to 9, decimal point, operators +, -, x and : (for division), the equal sign for calculating and displaying a result and the [C] key for reseting the calculator and clearing the display, i.e. the display is set to "0.". Calculations are done from left to right without any operator precedence.
You may call Adam's calculator a headstrong comtemporary, because of its special behaviour:
There is no invalid sequence of keystrokes. You can press arbitrary keys one after another, the calculator always knows how to handle it. If more than one operator key (including [=]) is pressed directly after another, only the last of these operators will be processed - all previous ones (in that continuous sequence) are ignored.
If more than 8 digit keys are pressed for the input of a single number, only the first 8 digits will be processed - all following digits are ignored. If the actual display value is zero, the typing of the zero key will have no effect, it's just ignored like successive keystrokes of the same operator. If a floating point value is typed in, a leading zero directly before the decimal point may be left out, but will be displayed just the same. If the decimal point key is pressed within a number that already has a decimal point typed in or if the input of a number (as a sequence of digit keys) is terminated by a decimal point, that has no effect.
Input
Input starts with a positive integer t (t<1000) in a single line, the number of testcases. Then t lines follow, each line giving the description of an arbitrary sequence of keystrokes on the calculator's keypad. Every key is enclosed by square brackets, all keystrokes are separated by a single space. The number of keystrokes per sequence is less than 500 and every sequence will be terminated by [=].
Output
For each sequence of keystrokes print the result the calculator will show on the display after the complete sequence of keystrokes has been processed. The size of the display is 8 digits plus an optional "-"-sign in front of the leftmost digit and a decimal point that will always appear, even if the result is an integer value. If a value has more than 8 decimal digits, it has to be rounded to fit into 8 digits. As the calculator's display is filled from right to left, the output has to be adjusted to the right.
If the absolute value of a number rounded to an integer needs more than 8 digits, scientific notation is used. Same case, if the absolute value of a number is larger than 10
-100
, but rounding to 8 digits would result in displaying zeros only. If the absolute value is not larger than 10
-100
, it results to zero.
In scientific notation a number is expressed as a product of a decimal part and a power of 10. The decimal part has always exactly one non-zero digit before the decimal point, an optional "-" sign in front of the leftmost digit and upto 4 digits after the decimal point, rounded if necessary. If the exponent is negative, a "-" follows, otherwise a space. Then follow two digits representing the exponent; a leading zero is shown in the exponent, if necessary.
Notice that there are two cases, where the calculator will display "Error." instead of showing a result. If a (final or interim) result has a rounded absolute value of at least 10
100
or if you divide by zero. After an error has occured, all following keystrokes are ignored unless [C] is pressed.
For more clarity of the calculator's behaviour and the required input and output format please look at the examples below.
Example
Input:
12
[3] [+] [4] [x] [5] [=]
[1] [:] [6] [=]
[4] [.] [8] [-] [x] [+] [-] [+] [x] [-] [.] [=]
[4] [.] [8] [-] [x] [+] [-] [+] [x] [.] [=]
[+] [+] [+] [+] [+] [+] [1] [=] [=] [=]
[9] [8] [C] [-] [7] [6] [5] [4] [3] [2] [1] [0] [1] [2] [3] [4] [=]
[1] [=] [2] [=] [3] [=]
[5] [:] [9] [8] [7] [8] [9] [8] [9] [8] [7] [8] [8] [:] [4] [5] [6] [7] [8] [9] [=]
[-] [9] [9] [9] [9] [9] [9] [9] [9] [-] [-] [-] [-] [8] [8] [8] [8] [8] [8] [=]
[2] [.] [3] [.] [4] [.] [5] [=]
[0] [0] [0] [0] [0] [=]
[.] [:] [.] [=]
Output:
35.
0.1666667
4.8
0.
1.
-76543210.
3.
1.108-13
-1.0089 08
2.345
0.
Error. | 32,305 |
Messy Phone List (PHONMESS)
Adam has a lot of friends and therefore he stored a lot of phone numbers in his phone database. As his telephone doesn't belong to the latest generation, its database is somewhat simple. In fact, all entries are stored line by line, exactly in the way Adam once typed them in, no matter what format he used. Unfortunately he changed the format from time to time, unable or too lazy to remember how he did it the last time. So, after years have passed (Adam likes his phone and doesn't want to replace it by a modern one), his phone number list has become really messed up and he wants to do some clean up. Your task is to write a program that will do that clean up for him.
Every entry consists of three parts: telefon number, first name and last name of one of Adam's friends. The order of these parts may vary. An entry may start with the phone number, following the name or vice versa, phone number and name always separated by exactly one space. The order of the two parts of the name may also vary. Either it is first name before last name, separated by a space, or it is last name before first name, separated by a comma.
A phone number may contain an optional leading area code, separated by a "-" or a "/" from the local code. If an area code is missing, the area code of Adam's hometown is assumed. Area code and local code both consist of at least three and at most ten digits. There may be additional optional spaces in between for better readability. For the final list the phone numbers have to be normalized. A normalized phone number consists of the area code and the local code, separated by "-" without any spaces.
A name consists of any letters of the English alphabet. Capital letters and small letters may be mixed, as Adam didn't pay attention to that when he typed in the entries. First name and last name each are at least one and at most 20 characters long. For the final list all names have to be normalized. A normalized name consists of only small letters, except the first one being a capital letter. All following explanations refer to normalized numbers and names.
If two different persons have the same phone number, that will be considered as being an error - none of these entries must appear in the final list. If two entries are equal, they must appear only once in the final list. If a person is listed with different phone numbers, this person has changed phone numbers over the years and will only appear with the latest of the listed numbers, that does not have to be removed because of the reason stated above.
Input
Input starts with a positive integer t (t<50) in a single line, then t testcases follow. Every testcase starts with one line containing a positive integer n (n<1000), the number of phone list entries, and - separated by a space - the area code of Adam's hometown. Then n lines follow, each line representing one entry in the phone list.
Output
For each testcase first print the number k of entries in the final list in a single line. Then k lines must follow, the cleaned up phone list. Each line is a single entry that has to look exactly like this: [first name] [last name]: [phone number]. Square brackets only for clarity. The list has to be sorted in alphabetical order according to last names (primary key) and - if necessary - first names (secondary key).
Example
Input:
2
10 0608
Sastre,Carlos 030/64 736 666
Voigt,Jens 07401-4498
A Winokurow 0289-334405
Jan ULLRICH 089-77 98 00 9
089/779 8009 Ullrich,Jan
LANCE Armstrong 0608 / 220 4 768 86
Jan Ullrich 089/7798 005
02 89 / 33 44 05 Contador,A
ArmStrong,Lance 220476886
Ullrich,JaN 0289 / 334405
5 012
Becker,Franz 1200344
Becker,Boris 034/50005
Boris Becker 012 / 50 005
5000 5 Boris Becker
Franz Beckenbauer 332323
Output:
4
Lance Armstrong: 0608-220476886
Carlos Sastre: 030-64736666
Jan Ullrich: 089-7798005
Jens Voigt: 07401-4498
3
Franz Beckenbauer: 012-332323
Boris Becker: 012-50005
Franz Becker: 012-1200344 | 32,306 |
Maximum Subset of Array (MAXSUB)
Given an array find the sum of the maximum non-empty subset of the array and also give the count of the subset. A subset of an array is a list obtained by striking off some (possibly none) numbers.
A non-empty subset implies a subset with at least 1 element in it.
Input
First line contains an integer T which is the number of integers. Following this T-cases exist.
Each case starts with a line containing an integer n which is the number of elements in the array.
The next line contains n-integers which contain the value of this subset.
Constraints
T ≤ 20
n ≤ 50,000
Each element in the array ≤ 1,000,000,000
Output
For each test case output the value of the maximum subset and the count of the subsets modulo 1000,000,009
Example
Input:
2
5
1 -1 1 -1 1
6
-200 -100 -100 -400 -232 -450
Output:
3 1
-100 2 | 32,307 |
No Squares Numbers (NOSQ)
A square free number is defined as a number which is not divisible by any square number.
For example, 13, 15, 210 are square free numbers, where as 25 (divisible by 5*5), 108 (divisible by 6*6), 18 (divisible by 3*3) are not square free numbers. However number 1 is not considered to be a square and is a squarefree number.
Now you must find how many numbers from number a to b, are square free and also have a digit d inside it.
For example for in the range 10 to 40 te squarefree numbers having digit 3 are 13, 23, 30, 31, 33, 34, 35, 37, 38, 39
Input
The first line contains an integer T, which is the number of test-cases
Then follow T lines, each containing 3 integers a, b and d.
1 <= T <= 20,000
1 <= a <= b <= 100,000
0 <= d <= 9
Output
Print one integer which is the required number as described in the problem statement.
Example
Input:
3
10 40 3
1 100 4
1 100000 7
Output:
10
9
26318 | 32,308 |
Nacci Fear (NACCI)
We all know about the classical Fibonacci series, Fibonacci series is F(n) = F(n-1) + F(n-2). For this question we call it a 2-Nacci series as a new element is calculated as the sum of the last 2 terms of the series. For Fibonacci we assume F(0)=0 and F(1)=1. We define as new series N-Nacci where F(n) is the sum of the last n terms and here we assume that F(0)=0, F(1)=1, F(2)=2 ... F(n-1) = (n-1). Your task is to calculate the last K digits of the Lth term of the N-Nacci series (no leading zeros needed).
Constraints
2 ≤ N ≤ 30
K ≤ 8
L ≤ 1000000000
Input
The first line of the input denotes the number of test cases t (at most 10). Each line denotes a test case consisting of N, K, L.
Output
For each test case print the last K digits of the Lth term of the N-Nacci series.
Example
Input:
4
2 1 5
3 6 12
4 1 10
4 2 10
Output:
5
778
6
16 | 32,309 |
Party Switching (PSWITCH)
Seraph is a smart boy who, one day at the time of his birthday he was wearing a lot of lights for the event. The number of lights is installed for as many as N, which are numbered 1 through N. lights are connected to a controller that has 4 buttons. Each button functions as follows:
if this button is pressed, then all light will change the state from OFF to ON or from ON to OFF.
if this button is pressed, then the odd-numbered light will change its state.
if this button is pressed, then the even-numbered light will change its state.
if this button is pressed, all lights are numbered 3K +1 will change its state.
In the controller, there are counter C that count number of button will be pressed. when the initial state, the state of all the lights are ON and the counter C is set to 0. After that you will be given information of light at the end of the show, and you have to count how many kinds of configuration according to the information provided.
Input
The first line containing N (10 <= N <= 100) that indicates number of lamps. The second line is C (1 <= C <= 1000) that indicate the final value of the counter. The third line is lists the number of ON lights at the end of the show, each number separated by a space and the end of the line given the value -1. The fourth line is lists the number of OFF light at the end of the show, each number separated by a space and the end of the line given the value -1.
Output
The possible configurations at the end of the event. There should be no repetitive configuration and output must be in lexicographical. If there is no configuration, print "Impossible".
Example
Input:
10
1
-1
7 -1
Output:
0000000000
0101010101
0110110110
Explanation
There is 10 lamps in that event and you have to press the button once, and at the end of event, lamp number 7 must be OFF.
0 mean that lamp is OFF, 1 mean that lamp is ON. | 32,310 |
Modern Pocket Calculator (POCALC2)
Adam likes pocket calculators, not only the
early ones
, but also the modern ones with a two line LCD-display and mathematically correct operator precedence. The upper (input-)line shows the expression you typed in, the (output-)line below shows the result immediately after the [=] key has been pressed. Given the calculator's input-line, the program's task is to produce its output-line. Using the calculator's [S-D] key, the display switches between fractional and decimal representation of the result, so output must contain both representations.
Input
Input starts with a positive integer t (t<1000) in a single line, then t testcases follow. Every testcase consists of either three lines or a single line, representing the expression in the calculator's input-line, followed by a blank line. An expression contains n numbers (0 < n < 10) with exactly one operator (+, -, x, :) between any two numbers and exactly one space to separate number and operator. There will be no invalid expression and no undefined operation.
A number is given as a decimal, a fraction or a mixed number and will be non-negative. If a number is positive, its decimal value is between 10
-9
and 10
9
, numerator and denominator are also non-negative and not larger than 10
9
each, given decimals have at most 9 digits overall. These constraints also hold for all calculations, if done properly. The length of the fraction bar depends on the maximum length of the numerator or the denominator respectively. If lengths of numerator and denominator are different, the shorter one will be centered based on the fraction bar. If centering isn't possible, it is set one digit to the right.
Output
For each testcase print the result the calculator will display in its output-line: first fractional, then decimal, both representations separated by " [S-D] ". If a result is negative, the negative sign has to be printed directly (i.e. no space) in front of the integer part or the fraction bar.
The fractional representation has to be printed in lowest terms either as a proper fraction or mixed number. If the number has an integer representation, that has to be printed instead. Numerator and denominator have to be placed as described in the input section.
After " [S-D] " the exact(!) decimal represenation has to be printed. As the screenshot shows, the calculator is even able to display a repeating decimal in its decimal representation using a vinculum, so that's what the program has to do as well, using underscores in the line above. You can assume that no decimal expansion is longer than 100 digits (it's a calculator with XXL-display).
The number of lines for every output depends on the result. It may be three lines (if fractions appear) or a single line (if result is an integer). Print a blank line after every testcase except the last one. Be careful not to print any trailing spaces.
For more clarity of input and output format please look at the examples below.
Example
Input:
5
9 50
2-- + 0.26 x --
11 15
4 9
5.88 - -- : -
18 5
3 - 5.125
9 + 14
1
--- x 0.5
100
Output:
113 __
3--- [S-D] 3.684
165
1532 _________
5---- [S-D] 5.75654320987
2025
1
-2- [S-D] -2.125
8
23 [S-D] 23
1
--- [S-D] 0.005
200 | 32,311 |
Subset sum (MAIN72)
You are given an array of N integers. Now you want to find the sum of all those integers which can be expressed as the sum of at least one subset of the given array.
Input
First line contains T the number of test case. then T test cases follow, first line of each test case contains N (1 ≤ N ≤ 100) the number of integers, next line contains N integers, each of them is between 0 and 1000 (inclusive).
Output
For each test case print the answer in a new line.
Example
Input:
2
2
0 1
3
2 3 2
Output:
1
21 | 32,312 |
Manoj and Pankaj (MAIN73)
Manoj and Pankaj play the following game on a N×M grid, Each cell of which is either empty or contain a stone.
Each player in his his turn must take one of the two moves described below:-
He can shift an stone to its adjacent right cell, if that cell is empty.
He can remove a stone completely from the grid.
The first player who is unable to take a move looses the game. It is also given that both the players will play optimally and Manoj always take the first turn.
You have to find who will win the game.
Input
First line of each test case contains two integers N and M. (1 ≤ N, M ≤ 200) Each of next N lines contains an string, jth character on of ith string is '*' if there is an stone otherwise it is '.' (empty). Input ends when N, M = 0, 0. which is not to be processed.
Output
For each test case print 'Manoj' if Manoj wins, print 'Pankaj' otherwise.
Example
Input:
2 2
.*
.*
2 2
.*
*.
0 0
Output:
Pankaj
Manoj | 32,313 |
Euclids algorithm revisited (MAIN74)
Consider the famous Euclid algorithm to calculate the GCD of two integers (a, b):
int gcd(int a, int b) {
while (b != 0) {
int temp = a;
a = b;
b = temp % b;
}
return a;
}
for input (7, 3) the 'while' loop will run 2 times as follows: (7, 3) → (3, 1) → (1, 0)
Now given an integer N you have to find the smallest possible sum of two non-negative integers a, b (a ≥ b) such that the while loop in the above mentioned function for (a, b) will run exactly N times.
Input
First line of input contains T (1 ≤ T ≤ 50) the number of test cases. Each of the following T lines contains an integer N (0 ≤ N ≤ 10
18
).
Output
For each test case print the required answer modulo 1000000007 in a separate line.
Example
Input:
1
1
Output:
2
Explanation: (1, 1) is the required pair. | 32,314 |
BST again (MAIN75)
N nodes are labelled with integers from 1 to N. Now these N nodes are inserted in a empty binary search tree. But the constraint is that we have to build this tree such that height of tree is exactly equal to H. Your task is to find how many distinct binary search trees exists of these nodes such that their height is exactly equal to H?
Two BSTs are considered to be different if there exist a node whose parent is different in both trees.
Input
Input First line contains 1 ≤ T ≤ 10 the number of test cases. Following T lines contains 2 integers each. N and H. 1 ≤ N ≤ 500, 0 ≤ H ≤ 500.
Output
For each test case print the required answer modulo 1000000007.
Example
Input:
1
2 1
Output:
2 | 32,315 |
Longest Square Factor (LSQF)
Given a string x, the string obtained by concatenating x to itself is sometimes called the square of x.
Given a string s, output the longest string x such that its square is a substring of s. If you find more than one solution, output the lexicographically smallest.
Input
The first and only line of input contains a string s (consisting only of lowercase letters of the English alphabet). The length of s is less than or equal to 10
5
.
Output
To the first line of output print the length of the string x. To the second line print the string x.
Such a string will always exist in the test data.
Example
Input:
abcabc
Output:
3
abc | 32,316 |
Colours A, B, C, D (ABCD)
Consider a table with 2 rows and 2N columns (a total of 4N cells). Each cell of the first row is coloured by one of the colours A, B, C, D such that there are no two adjacent cells of the same colour. You have to colour the second row using colours A, B, C, D such that:
There are exactly N cells of each colour (A, B, C and D) in the table.
There are no two adjacent cells of the same colour. (Adjacent cells share a vertical or a horizontal side.)
It is guaranteed that the solution, not necessarily unique, will always exist.
Input
[a natural number N ≤ 50000]
[a string of 2N letters from the set {A, B, C, D}, representing the first row of the table]
Output
[a string of 2N letters from the set {A, B, C, D}, representing the second row of the table]
Example
Input:
1
CB
Output:
AD
Input:
2
ABAD
Output:
BCDC | 32,317 |
Linear Equation Solver (LINQSOLV)
Given a system of linear equations, print the solution of that system.
Input
Input starts with a positive integer t < 100 in a single line, then t test cases follow. Every test case represents a linear system and starts with one line containing a positive integer n < 21, the number of equations and also the number of variables of that system. Then n equations follow, each one in a single line.
An equation is written in schoolbook notation, i.e. variables noted by single small letters (English alphabet), no multiplication sign, factor 1 left out, no spaces in between. A variable or a value may occur zero or more times in an equation. All coefficients are integers with an absolute value less than 100, a single line won't be longer than 100 characters and will always contain a valid linear equation.
The following equations are considered to be
valid
:
a+b-c+b-2c-a=1 -x+5-9=-4x+y-8 c-c+t+1=0 y=z
The following equations are considered to be
invalid
:
4*a+b=6 6+-2x=99 c-c+t-t=0 4+9 = h
Output
For each test case print all variables of the linear system in alphabetical order together with the associated value as an integer or a fraction in lowest terms respectively. Print a blank line between test cases. For exact notation see example below. All (interim) results will fit into 64-bit, if algorithm is implemented properly. You can assume that all linear systems have an unique solution.
Example
Input:
2
2
a+b=5
b-a=1
3
5u-5z+4=0
8k-3z=-2
9k-u=u
Output:
a=2
b=3
k=-4/55
u=-18/55
z=26/55 | 32,318 |
Four in a row (FOUROW)
You probably know the popular two-players game "Four in a row". Each player gets 21 chips of the same color at the beginning. Then the two players take turns in putting a chip into one of seven slots (each one six cells in height), trying to get at least four of their chips "in a row", i.e. horizontally, vertically or diagonally.
Given a series of moves, your task is to first check, if this is a valid game. A game is
invalid
, if one or more moves are made after a player has already won the game or if more than six chips are put into a single slot. If a game is valid, check if the game is over. A game is over, if one of the players got at least four chips "in a row" with his last move (i.e. he is the winner of the game) or if all slots are filled. If a game is over, check if there is a winner and if so, who it is. If there is a winner, then print the final state of the game.
The picture shows the final state of a game, won by the first player (yellow chips).
Input
Input starts with a positive integer t < 100 in a single line, then t test cases follow. Every test case starts with "Game #n: ", where n is the number of the game, numbered from 1 to t. Then the description of a game follows, given as a series of digits 1 to 7 indicating the number of the slot (as noted in the picture), in which the player puts his chip. The players are taking turns and the number of moves (i.e. the number of chips put into the slots) will be at most 42.
Output
For each test case print exactly one of the following five lines, where n has to be replaced by the game's number:
Game #n is invalid.
Game #n is over. There is no winner.
Game #n is over. The first player won.
Game #n is over. The second player won.
Game #n is not over, yet.
If there is a winner, you also have to print a snapshot of the game's final state. A game's state consists of at most six lines representing the (horizontal) rows of the game's grid plus a leading and a trailing line containing seven hyphens. Every line has a length of exactly seven characters. Use "x" for the chips of the first player, "o" for those of the second player, whitespaces for all cells without a chip. If a (horizontal) row contains only whitespaces, it must not be printed.
To make it easier to find the winning row in the grid,
all
chips that belong to the winning row(s) have to be marked either by "X" (instead of "x", if the first player has won) or by "O" (instead of "o", if the second player has won). Be aware that there can be more than four chips in a winning row and more than one winning row!
Example
Input:
2
Game #1: 2143563445575
Game #2: 123456
Output:
Game #1 is over. The first player won.
-------
X
Xx
Xoo
oXoxxoo
-------
Game #2 is not over, yet. | 32,319 |
Reverse the Sequence (REVSEQ)
This is a very ad-hoc problem. Consider a sequence (N, N-1, ..., 2, 1). You have to reverse it, that is, make it become (1, 2, ..., N-1, N). And how do you do this? By making operations of the following kind.
Writing three natural numbers A, B, C such that 1 ≤ A ≤ B < C ≤ N means that you are swapping the block (block = consecutive subsequence) of elements occupying positions A...B with the block of elements occupying positions B+1..C. Of course, the order of elements in a particular block does not change.
This means that you can pick any two adjacent blocks (each of an arbitrary length) and swap them. The problem can easily be solved in N-1 operations, but to make it more difficult, you must think of a faster way.
Input
A natural number 1 < N < 100.
Output
Output at most 50 operations, one per line. Each operation is represented by three numbers as described above.
Example
Input:
5
Output:
2 3 5
1 2 4
2 3 5
Explanation of the sample
(5 4 3 2 1) → (5 2 1 4 3) → (1 4 5 2 3) → (1 2 3 4 5) | 32,320 |
Garden (NPOWM)
Vasya has a very beautiful country garden, which is a rectangular field n × m in size, divided into n · m square cells. One day, Vasya remembered that he needed to pave pathd between k cells with important buildings - for that he can fill some of the cells in his garden with concrete.
For each cell of the garden, the number a
ij
is known, which means the number of flowers growing in the cell with coordinates (i, j). When pouring concrete all the flowers that grow in the cell die.
Vasya wants to fill some cells with concrete so that the conditions:
all k important cells must be filled with concrete.
from each important cell to any other important cell, there was a path through the cells filled with concrete, provided that cells with a common side are considered neighboring.
the total number of dead plants should be minimal.
Since Vasya has a rather large garden, he asks you to help him.
Input
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 100, n·m ≤ 200, 1 ≤ k ≤ min(n·m, 7) — the size of the garden and the number of important cells. The following n lines with m numbers each contain numbers a
ij
(1 ≤ a
ij
≤ 1000) — the number of flowers in the cells. Next k lines contain the coordinates of important cells in the format "x y" (without quotes) (1 ≤ x ≤ n, 1 ≤ y ≤ m). Numbers on the same line are separated by spaces. It is guaranteed that all k important cells have different coordinates.
Output
In the first line print a single integer — the minimum number of plants killed during the construction. Then output n lines of m characters each — the plan of the garden, where the character "X" (capital Latin letter X) denotes a cell filled with concrete, and the character "." (dot) - not filled. If there are several solutions, print any
Sample
Input
3 3 2
1 2 3
1 2 3
1 2 3
1 2
3 3
Output
9
.X.
.X.
.XX
Input
4 5 4
1 4 5 1 2
2 2 2 2 7
2 4 1 4 5
3 2 1 7 1
1 1
1 5
4 1
4 4
Output
26
X..XX
XXXX.
X.X..
X.XX. | 32,321 |
Factorial factorisation (PRIME)
Factorial
n!
of an integer number
n ≥ 0
is defined recursively as follows:
0! = 1
n! = n * (n - 1)!
While playing with factorials ChEEtah noticed that some of them can be represented as a product of other factorials, e.g.
6! = 3! * 5! = 720
. Such factorisation helps ChEEtah to simplify a certain class of equations he is working on during his research.
So he needs a program that finds a compact factorisation of a given factorial or determines that it is impossible if that is the case. If there are more than one factorisation the program has to find such that contains the minimum number of terms. For example,
10!
can be factorised in two different ways:
10! = 6! * 7! = 3! * 5! * 7!
. The first factorisation contains only two terms and should be preferred to the second one. If there are several factorisations with the same minimum number of terms then any optimal solution is acceptable.
Input
Input contains the only integer
2 ≤ n ≤ 1000
which factorial
n!
should be factorised.
Output
Output should contain the optimal factorisation in the format shown in the samples. The factorisation terms should go in non-decreasing order. If no factorisation can be found print
No solution
.
Example
Input:
9
Output:
9! = 2! * 3! * 3! * 7! | 32,322 |
Prime Permutations (PRIMPERM)
Given two positive integers n and m, we call m a prime permutation of n, if m is prime and can be obtained by zero or more permutations of the digits of n. Permutations with leading zeros are invalid.
Input
Input starts with a positive integer t<10
4
in a single line, then t lines follow.
Each of the t lines contains one positive integer n<10
7
.
Output
For every n print the number of distinct prime permutations of n in a single line.
Example
Input:
2
13
110
Output:
2
1
Hint
:If your solution times out, you may try the
tutorial version
with a longer time limit. | 32,323 |
Covering the Corral (CORRAL)
The cows are so modest they want Farmer John to install covers around the circular corral where they occasionally gather. The corral has circumference C (1 ≤ C ≤ 1,000,000,000), and FJ can choose from a set of M (1 ≤ M ≤ 100,000) covers that have fixed starting points and sizes. At least one set of covers can surround the entire corral.
Cover i can be installed at integer location x
i
(distance from starting point around corral) (0 ≤ x
i
< C) and has integer length l
i
(1 ≤ l
i
≤ C).
FJ wants to minimize the number of segments he must install. What is the minimum number of segments required to cover the entire circumference of the corral?
Consider a corral of circumference 5, shown below as a pair of connected line segments where both '0's are the same point on the corral (as are both 1's, 2's, and 3's).
Three potential covering segments are available for installation:
Start Length
i x
i
l
i
1 0 1
2 1 2
3 3 3
0 1 2 3 4 0 1 2 3 ...
corral: +---+---+---+---+--:+---+---+---+- ...
1111 1111
22222222 22222222
333333333333
|..................|
As shown, installing segments 2 and 3 cover an extent of (at least) five units around the circumference. FJ has no trouble with the overlap, so don't worry about that.
Input:
Line 1: Two space-separated integers: C and M.
Lines 2..M+1: Line i+1 contains two space-separated integers: x
i
and l
i
Output:
Line 1: A single integer that is the minimum number of segments required to cover all segments of the circumference of the corral.
Sample
Input
5 3
0 1
1 2
3 3
Output
2 | 32,324 |
Tails all the way (TAILS)
John and James planned to play a game with coins. John has 20 coins and he places it on the table in a random manner (i.e. either with heads(1) or tails(0) facing up). John asked James to convert all heads into tails in minimum number of flips with the condition that if a coin is flipped the coins present immediately to the right and left of the chosen coin should also be flipped.
Input
A single line with 20 space-separated integers
Output
The minimum number of coin flips necessary to convert all heads into tails (i.e. to 0). For the inputs given, it will always be possible to find some combination of flips that will manipulate the coins to 20 tails.
Example
Input:
0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0
Output:
3
Explanation of the Sample
Flip coins 4, 9, and 11 to make them all tails:
0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 [initial state]
0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 [after flipping coin 4]
0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 [after flipping coin 9]
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [after flipping coin 11] | 32,325 |
Wood, Axe and Grass (WAGE)
Danny has created a new civilization on a 2D grid. At the outset each grid location may be occupied by one of three life forms: Woods, Axe, or Grass. Each day, differing life forms occupying horizontally or vertically adjacent grid locations wage war. In each war, Woods always defeat Axe, Axe always defeat Grass, and Grass always defeat Woods. At the end of the day, the winner expands its territory to include the loser's grid position. The loser vacates the position. Determine the territory occupied by each life form after n days.
Input
The first line of input contains t, the number of test cases. Each test case begins with three integers not greater than 100: r and c, the number of rows and columns in the grid, and n. The grid is represented by the r lines that follow, each with c characters. Each character in the grid is W, A, or G, indicating that it is occupied by Woods, Axe, or Grass respectively.
Output
For each test case, print the grid as it appears at the end of the nth day.
Example
Input:
2
3 3 1
WWW
WAW
WWW
3 4 2
WAGW
AGWA
GWAG
Output:
WWW
WWW
WWW
WWWA
WWAG
WAGW | 32,326 |
Traverse through the board (TRAVERSE)
An n × n game board is filled with integers, one positive integer per square. The objective is to travel along any legitimate path from the upper left corner to the lower right corner of the board.
Rules:
The number in any one square describes how far a step away from that location must be.
If the step size moves out of the game board, then that step is not allowed.
All steps must be either to the right or towards the bottom.
Note that a 0 is a dead end which prevents any further progress.
Consider the 4 × 4 board shown in Figure 1, where the solid circle identifies the start position and the dashed circle identifies the target.
Input
The first line contains the value of n followed by a n × n matrix depicting the board configuration.
Output
The output consists of a single integer, which is the number of paths from the upper left corner to the lower right corner.
Example
Input:
4
2331
1213
1231
3110
Output:
3
Input:
4
3332
1213
1232
2120
Output:
0
Input:
5
11101
01111
11111
11101
11101
Output:
7 | 32,327 |
Non-Decreasing Digits (NY10E)
A number is said to be made up of non-decreasing digits if all the digits to the left of any digit is less than or equal to that digit.For example, the four-digit number
1234
is composed of digits that are non-decreasing. Some other four-digit numbers that are composed of non-decreasing digits are
0011
,
1111
,
1112
,
1122
,
2223
. As it turns out, there are exactly 715 four-digit numbers composed of non-decreasing digits.
Notice that leading zeroes are required: 0000, 0001, 0002 are all valid four-digit numbers with non-decreasing digits.
For this problem, you will write a program that determines how many such numbers there are with a specified number of digits.
Input
The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set is a single line that contains the data set number, followed by a space, followed by a decimal integer giving the number of digits N, (1 ≤ N ≤ 64).
Output
For each data set there is one line of output. It contains the data set number followed by a single space, followed by the number of N digit values that are composed entirely of non-decreasing digits.
Example
Input:
3
1 2
2 3
3 4
Output:
1 55
2 220
3 715 | 32,328 |
Penney Game (NY10A)
Penney’s game is a simple game typically played by two players. One version of the game calls for each player to choose a unique three-coin sequence such as
HEADS TAILS HEADS (HTH)
. A fair coin is tossed sequentially some number of times until one of the two sequences appears. The player who chose the first sequence to appear wins the game.
For this problem, you will write a program that implements a variation on the Penney Game. You willread a sequence of 40 coin tosses and determine how many times each three-coin sequence appears. Obviously there are eight such three-coin sequences:
TTT
,
TTH
,
THT
,
THH
,
HTT
,
HTH
,
HHT
and
HHH
. Sequences may overlap. For example, if all 40 coin tosses are heads, then the sequence HHH appears 38 times.
Input
The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set consists of 2 lines. The first line contains the data set number N. The second line contains the sequence of 40 coin tosses. Each toss is represented as an upper case H or an upper case T, for heads or tails, respectively. There will be no spaces on any input line.
Output
For each data set there is one line of output. It contains the data set number followed by a single space, followed by the number of occurrences of each three-coin sequence, in the order shown above, with a space between each one. There should be a total of 9 space separated decimal integers on each output line.
Example
Input:
4
1
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
2
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
3
HHTTTHHTTTHTHHTHHTTHTTTHHHTHTTHTTHTTTHTH
4
HTHTHHHTHHHTHTHHHHTTTHTTTTTHHTTTTHTHHHHT
Output:
1 0 0 0 0 0 0 0 38
2 38 0 0 0 0 0 0 0
3 4 7 6 4 7 4 5 1
4 6 3 4 5 3 6 5 6 | 32,329 |
Nim-B Sum (NY10B)
Note: This problem has nothing to do with siting sewage plants, power lines or wind farms. NIM is an ambigram.
The game of NIM is played with any number of piles of objects with any number of objects in each pile. At each turn, a player takes one or more (up to all) objects from one pile. In the normal form of the game, the player who takes the last object is the winner. There is a well-known strategy for this game based on the nim-2 sum.
The Nim-B sum (nim sum base
B
) of two non-negative integers
X
and
Y
(written
NimSum
(
B
,
X
,
Y
)) is computed as follows:
Write each of
X
and
Y
in base
B
.
Each digit in base
B
of the Nim-B sum is the sum modulo
B
of the corresponding digits in the base
B
representation of
X
and
Y
.
For example:
NimSum
(2, 123, 456) = 1111011 ¤ 111001000 = 110110011 = 435
NimSum
(3, 123, 456) = 11120 ¤ 121220 = 102010 = 300
NimSum
(4, 123, 456) = 1323 ¤ 13020 = 10303 = 307
The strategy for normal form Nim is to compute the Nim-2 sum
T
of the sizes of all piles. If at any time, you end your turn with
T
= 0, you are guaranteed a WIN. Any opponent move must leave
T
not 0 and there is always a move to get
T
back to 0. This is done by computing
NimSum
(2,
T
,
PS
) for each pile; if this is less than the pile size (
PS
), compute the difference between the
PS
and the Nim-2 sum and remove it from that pile as your next move.
Write a program to compute
NimSum
(
B
,
X
,
Y
).
Input
The first line of input contains a single integer
P
, (1 <=
P
<= 1000), which is the number of data sets that follow. Each data set is a single line that contains the data set number, followed by a space, followed by three space separated decimal integers,
B
,
X
and
Y
. 2 <=
B
<= 2000000, 0 <=
X
<= 2000000, 0 <=
Y
<= 2000000.
Output
For each data set there is one line of output. It contains the data set number followed by a single space, followed by
N
, the decimal representation of the Nim sum in base
B
of
X
and
Y
.
Sample
Input:
4
1 2 123 456
2 3 123 456
3 4 123 456
4 5 123 456
Output:
1 435
2 300
3 307
4 429 | 32,330 |
Just The Simple Fax (NY10C)
Fax machines use a form of compression based on run-length encoding. Run-length encoding (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. This is most useful on data that contains many such runs: for example, relatively simple graphic images such as icons, text, and line drawings. It is not useful with files that don't have many runs as it could potentially double the file size (photograph, for example).
For this problem, you will write a program that encodes a block of data using a very simple RLE algorithm. A run is encoded using a two byte sequence. The first byte of the sequence contains the count, and the second contains the value to repeat. The count is encoded using an 8 bit value with the high order bit set to 1. The remaining 7 bits represent the count-3. This gives a maximum run count of 130 per 2 byte sequence. (This implies that the minimum run count is 3). Bytes that are not part of a run are encoded as-is with a prefix byte indicating the count of bytes in the non-run minus 1, 0 through 127, representing a range of 1 - 128 (the high order bit will always be 0 in the case of non-run data).
If a run contains more than 130 bytes, then it must be encoded using multiple sequences, the first of which will always be a run of 130. All runs of 3 or more must be encoded as a run. If a non-run contains more than 128 bytes, then multiple non-run sequences must be used. For example, a run of 262 would be encoded as two runs of 130 followed by a non-run of 2.
Input
The first line of input contains a single integer
P
, (1 ≤
P
≤ 1000), which is the number of data sets that follow. Each data set consists of multiple lines. The first line contains two (2) decimal integer values: the problem number, followed by a space, followed by the number of bytes
B
, (1 ≤
B
≤ 5000), to encode. The remaining line(s) contain(s) the data to be encoded. Each line of data to encode will contain 80 hexadecimal digits (except the last line, which may contain less). 2 hexadecimal digits are used to represent each byte. Hexadecimal digits are:
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
A
,
B
,
C
,
D
,
E
,
F
.
Output
For each data set, there are multiple lines of output. The first line contains a decimal integer giving the data set number followed by a single space, followed by a decimal integer giving the total number of encoded bytes. The remaining lines contain the encoded data each with 80 hexadecimal digits, except the last, which may contain less.
Example
Input:
4
1 1
07
2 5
F4A5A5A5A5
3 44
0000000000000000FFFFFF66665A5A5A5A5A71727374758008011011135555555555555501020399
777777CC
4 40
68686868686868686868686868686868686868686868686868686868686868686868686868686868
Output:
1 2
0007
2 4
00F481A5
3 32
850080FF016666825A0A717273747580080110111384550301020399807700CC
4 2
A568 | 32,331 |
Show Me The Fax (NY10D)
Fax machines use a form of compression based on run-length encoding. Run-length encoding (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. This is most useful on data that contains many such runs: for example, relatively simple graphic images such as icons, text, and line drawings. It is not useful with files that don't have many runs as it could potentially double the file size (photograph, for example).
For this problem, you will write a program that decodes a block of data using a very simple RLE algorithm. A run is encoded using a two byte sequence. The first byte of the sequence contains the count, and the second contains the value to repeat. The count is encoded using an 8 bit value with the high order bit set to 1. The remaining 7 bits represent the count-3. This gives a maximum run count of 130 per 2 byte sequence. (This implies that the minimum run count is 3). Bytes that are not part of a run are encoded as-is with a prefix byte indicating the count of bytes in the non-run minus 1, 0 through 127, representing a range of 1 - 128 (the high order bit will always be 0 in the case of non-run data).
Input
The first line of input contains a single integer
P
, (1 <=
P
<= 1000), which is the number of data sets that follow. Each data set consists of multiple lines. The first line contains two (2) decimal integer values: the problem number, followed by a space, followed by the number of bytes
B
, (1 <=
B
<= 5000), to decode. The remaining line(s) contain(s) the data to be decoded. Each line of data to decode contains 80 hexadecimal digits (except the last line, which may contain less). 2 hexadecimal digits are used to represent each byte. Hexadecimal digits are:
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
A
,
B
,
C
,
D
,
E
,
F
.
Output
For each data set, there are multiple lines of output. The first line contains a decimal integer giving the data set number followed by a single space, followed by a decimal integer giving the total number of decoded bytes. The remaining lines contain the decoded data, 80 hexadecimal digits per line, except the last line which may contain less.
Example
Input:
4
1 2
0007
2 4
00F481A5
3 32
850080FF016666825A0A717273747580080110111384550301020399807700CC
4 2
A568
Output:
1 1
07
2 5
F4A5A5A5A5
3 44
0000000000000000FFFFFF66665A5A5A5A5A71727374758008011011135555555555555501020399
777777CC
4 40
68686868686868686868686868686868686868686868686868686868686868686868686868686868 | 32,332 |
I2C (NY10F)
I
2
C (Inter-Integrated Circuit) is a serial communication protocol that is used to attach low-speed peripherals (100 kbit/sec) to a motherboard, embedded system or cell phone. A single I
2
C data bus may have several devices attached, each with a different 7-bit address. One of the nice things about I
2
C is that it only requires two signal lines, SCL (clock) and SDA (data). One bit of data is presented on the I2C data bus (SDA line) per clock (SCL). Typically, one device on the bus is designated as the master, and the other devices are slaves. The master will initiate communication to a specific device on the bus by specifying its address in a transaction.
If there is no activity on the I
2
C bus, both the SCL and SDA signals are in a high state (1). The master initiates a transaction on the bus by pulling the SDA signal to a low state (0), while the SCL signal is high (1): this is called a START bit. At this point, all slaves on the bus must start paying attention to the signalling to see if the transaction is directed at them. The master will then send the 7bit slave address (most significant bit first), one bit at-a-time. This is done by bringing the SCL signal low (0), presenting the next bit value on the SDA line, then releasing the SCL signal so it goes high (1). The slaves will read the SDA signal as soon as the clock goes high (1). This operation is repeated 7 times, one for each bit of the desired slave address. Another data bit is presented on the bus in the same manner. This last bit is an indicator as to whether the master wants to read from (1) or write to (0) the addressed slave device. When a slave recognizes its address on the bus, it must acknowledge (ACK) that it is available and ready by pulling the SDA line low. The master will see this the next time it brings the clock high, at which point, the data transfer can begin. If no ACK is seen this means that the slave specified by the address does not exist. Note: If no device pulls a signal low, it will go high by default; a device simply releases a signal, and it will go high.
Data is always transferred as 8 bit bytes, 1 bit at-a-time, most significant bit first. After each byte, the slave must ACK the master by pulling the SDA line low. If the slave is not ready to transmit (or receive) the next byte of data, it may pull the SCL line low. This will cause the master to go into a wait mode until the slave is ready. The slave indicates it is ready by bringing SDA low, and releasing the SCL line so it goes high. The next byte of data can then be transferred. The sequence repeats until the master decides all the data has been transferred, at which point it will send a STOP bit. This is done when the master lets the SDA line go high while the SCL line is high.
For this problem, you will write a program that sniffs the
I
2
C
bus signals and displays the details of transactions.
Input
The first line of input contains a single integer
P
, (1 ≤
P
≤ 1000), which is the number of data sets that follow. Each data set consists of multiple lines which represents a single
I
2
C
transaction. The first line contains two (2) decimal integer values: the problem number, followed by a space, followed by the number of signal samples
S
, (1 ≤
S
≤ 1161), for the transaction. The remaining line(s) contain(s) the signal samples. Each line of samples contains 40 samples (except the last which may contain less). Each sample consists of 2 binary digits characters representing SCL and SDA in that order.
Output
For each data set, display a single line containing a decimal integer giving the data set number followed by a single space, followed by a description of the transaction. There will only be six different descriptions (two non-error cases, and four error cases):
Non-error cases:
WRITE OF
n
BYTES TO SLAVE
xx
READ OF
n
BYTES FROM SLAVE
xx
Error cases:
ERROR NO START BIT
ERROR NO STOP BIT
ERROR NO ACK FROM SLAVE
xx
ERROR NO ACK FOR DATA
n
is a decimal integer (1 - 128) representing the number of data bytes.
xx
is a 2 digit hexadecimal value (00-7F) representing the slave address.
The
ERROR NO ACK FROM SLAVE
xx
case occurs when there is no ACK for the supplied address
The
ERROR NO ACK FOR DATA
case occurs when there is no ACK after a data byte
For the error cases, only the first error detected should be displayed.
Example
Input:
4
1 97
01111001110010001000100111011101110111001000100010011100100010001000100010001000
10001001110010001000100010011100100010001001110010001000100111001000100010001001
1100100010001001110111001000101111
2 169
01111000100010011100100010001001110010001000100010011100100010001000100010001000
10001001110010001000100010011100100010001001110010001000100111001000100010001001
11001000100010011101110010001000100111001000100111001000100010001000100111001000
10011100100111001000100010011100100010011101110010001000100010011100100010011101
110111001000101111
3 60
01111000100010001001110010011101110010001000100010011100100010001000100010001000
1000100111001000100010001001110010001111
4 40
01111000100010011101110010011100100111001111111111111111111111111111111111111111
Output:
1 READ OF 4 BYTES FROM SLAVE 47
2 WRITE OF 8 BYTES TO SLAVE 11
3 ERROR NO STOP BIT
4 ERROR NO ACK FROM SLAVE 0B | 32,333 |
Selling Land (NWERC10G)
As you may know, the country of Absurdistan is full of abnormalities. For example, the whole country can be divided into unit squares that are either grass or swamp. Also, the country is famous for its incapable bureaucrats. If you want to buy a piece of land (called a parcel), you can only buy a rectangular area, because they cannot handle other shapes. The price of the parcel is determined by them and is proportional to the perimeter of the parcel, since the bureaucrats are unable to multiply integers and thus cannot calculate the area of the parcel.
Per owns a parcel in Absurdistan surrounded by swamp and he wants to sell it, possibly in parts, to some buyers. When he sells a rectangular part of his land, he is obliged to announce this to the local bureaucrats. They will first tell him the price he is supposed to sell it for. Then they will write down the name of the new owner and the coordinates of the south-east corner of the parcel being sold. If somebody else already owns a parcel with a south-east corner at the same spot, the bureaucrats will deny the change of ownership.
Per realizes that he can easily trick the system. He can sell overlapping areas, because bureaucrats only check whether the south-east corners are identical. However, nobody wants to buy a parcel containing swamp.
Now Per would like to know how many parcels of each perimeter he needs to sell in order to maximize his profit. Can you help him? You may assume that he can always find a buyer for each piece of land, as long as it doesn't contain any swamps. Also, Per is sure that no square within his parcel is owned by somebody else.
Input
On the first line a positive integer: the number of test cases, at most 100. After that per test case:
One line with two integers n and m (1 ≤ n, m ≤ 1 000): the dimensions of Per's parcel.
n lines, each with m characters. Each character is either `
#
' or `
.
'. The j-th character on the i-th line is a `
#
' if position (i, j) is a swamp, and `
.
' if it is grass. The north-west corner of Per's parcel has coordinates (1, 1), and the south-east corner has coordinates (n,m).
Output
Per test case:
Zero or more lines containing a complete list of how many parcels of each perimeter Per needs to sell in order to maximize his profit. More specifically, if Per should sell p
Example
Input:
1
6 5
..#.#
.#...
#..##
...#.
#....
#..#.
Output:
6 x 4
5 x 6
5 x 8
3 x 10
1 x 12 | 32,334 |
Stock Prices (NWERC10H)
In this problem we deal with the calculation of stock prices. You need to know the following things about stock prices:
The
ask price
is the lowest price at which someone is willing to sell a share of a stock.
The
bid price
is the highest price at which someone is willing to buy a share of a stock.
The
stock price
is the price at which the last deal was established.
Whenever the bid price is greater than or equal to the ask price, a deal is established. A buy order offering the bid price is matched with a sell order demanding the ask price, and shares are exchanged at the rate of the ask price until either the sell order or the buy order (or both) is fulfilled (i.e., the buyer wants no more stocks, or the seller wants to sell no more stocks). You will be given a list of orders (either buy or sell) and you have to calculate, after each order, the current ask price, bid price and stock price.
Input
On the first line a positive integer: the number of test cases, at most 100. After that per test case:
One line with an integer n (1 ≤ n ≤ 1 000): the number of orders.
n lines of the form "
order_type x shares at y
", where
order_type
is either "buy" or "sell", x (1 ≤ x ≤ 1 000) is the number of shares of a stock someone wishes to buy or to sell, and y (1 ≤ y ≤ 1 000) is the desired price.
Output
Per test case:
n lines, each of the form "ai bi si", where ai, bi and si are the current ask, bid and stock prices, respectively, after the i-th order has been processed and all possible deals have taken place. Whenever a price is not defined, output "-" instead of the price.
Example
Input:
2
6
buy 10 shares at 100
sell 1 shares at 120
sell 20 shares at 110
buy 30 shares at 110
sell 10 shares at 99
buy 1 shares at 120
6
sell 10 shares at 100
buy 1 shares at 80
buy 20 shares at 90
sell 30 shares at 90
buy 10 shares at 101
sell 1 shares at 80
Output:
- 100 -
120 100 -
110 100 -
120 110 110
120 100 99
- 100 120
100 - -
100 80 -
100 90 -
90 80 90
100 80 90
100 - 80 | 32,335 |
Alien arithmetic (ALIENS1)
Little Johnny of Byteland has been kidnapped by aliens from the Andromeda galaxy! Johnny is currently locked in a small room inside an UFO, which has been parked in his backyard. Johnny is desperately trying to open the door of the room. He finds that the door asks a series of arithmetic questions: addition, subtraction, multiplication or exponentiation (the aliens don't know how to divide) of two given numbers. Johnny laughs aloud and thinks that it will be very easy to answer these questions and escape. But when he sees the questions, he realises that the aliens use base 42! Now Johnny has panicked and asks you to help him out.
Input
The first line of the input has a number T (<= 500), denoting the number of tests cases. T lines follows, each of the form A op B, where A and B are numbers in base 42 having up to 10000 digits without unnecessary zeros and op is either +, -, * or ^ denoting the operation to be performed. Base 42 numbers are denoted by:
'0' to '9' denotes 0 to 9
'A' to 'Z' denotes 10 to 35
'a' to 'f' denotes 36 to 41
Output
For each test case, output one line: the result of the required operation in base 42 modulo LIFE
42
, without any unnecessary zeros.
Example
Input:
11
a + a
e - A
91 * 89
AEIOU + abcd
A - B
b ^ 2
5 ^ 0
123 - 45
ABC * 10
6 - 6
0 ^ 0
Output:
1U
U
1W59
L6ZR
LIFD
WP
1
de
ABC0
0
1
Warning: large Input / Output data, be careful with certain languages. | 32,336 |
The Bovine Accordion and Banjo Orchestra (BAABO)
The 2×N (3 ≤ N ≤ 1,000) cows have assembled the Bovine Accordion and Banjo Orchestra! They possess various levels of skill on their respective instruments: accordionist i has an associated talent level A
i
(0 ≤ A
i
≤ 1,000); banjoist j has an associated talent level B
j
(0 ≤ B
j
≤ 1,000).
The combined "awesomeness" of a pairing between cows with talents A
i
and B
j
is directly proportional to the talents of each cow in the pair so a concert with those two cows will earn FJ precisely A
i
× B
j
dollars in "charitable donations". FJ wishes to maximize the sum of all revenue obtained by his cows by pairing them up in the most profitable way.
Unfortunately, FJ's accordionists are a bit stuck up and stubborn. If accordionist i is paired with banjoist j, then accordionists i+1..N refuse to be paired with banjoists 1..j-1. This creates restrictions on which pairs FJ can form. FJ thus realizes that in order to maximize his profits, he may have to leave some cows unpaired.
To make matters worse, when one or more of the musicians is skipped, they will be greatly upset at their wasted talent and will engage in massive binge drinking to wash away their sorrows.
After all pairings are made, a list is constructed of the groups of each of the consecutive skipped musicians (of either instrument). Every group of one or more consecutive skipped cows will gather together to consume kegs of ice cold orange soda in an amount proportional to the square of the sum of their wasted talent.
Specifically, FJ has calculated that if the x-th to y-th accordionists are skipped, they will consume precisely (A
x
+ A
x+1
+ A
x+2
+ ... + A
y
)
2
dollars worth of orange soda in the process of drinking themselves into oblivion. An identical relationship holds for the banjoists. FJ realizes that he'll end up getting stuck with the bill for his cows' drinking, and thus takes this into account when choosing which pairings to make.
Find the maximum amount of total profit that FJ can earn after the contributions are collected and the orange soda is paid for.
Input
Line 1: A single integer: N
Lines 2..N+1: Line i+1 contains the single integer: A
i
Lines N+2..2×N+1: Line i+N+1 contains the single integer: B
i
Output
Line 1: A single integer that represents the maximum amount of cash that FJ can earn.
Example
Input:
3
1
1
5
5
1
1
Output:
17
Explanation
There are 6 cows: 3 accordionists and 3 banjoists. The accordionists have talent levels (1, 1, 5), and the banjoists have talent levels (5, 1, 1).
FJ pairs accordionist 3 with banjoist 1 to get earn A
3
× B
1
= 5 × 5 = 25 in profit. He loses a total of (1 + 1)
2
+ (1 + 1)
2
= 8 dollars due to the cost of soda for his remaining cows. Thus his final (net) profit is 25 - 8 = 17. | 32,337 |
Bogosort (CHEFFEB)
Recently Johnny have learned bogosort sorting algorithm. He thought that it is too ineffective. So he decided to improve it. As you may know this algorithm shuffles the sequence randomly until it is sorted. Johnny decided that we don't need to shuffle the whole sequence every time. If after the last shuffle several first elements end up in the right places we will fix them and don't shuffle those elements furthermore. We will do the same for the last elements if they are in the right places. For example, if the initial sequence is (3, 5, 1, 6, 4, 2) and after one shuffle Johnny gets (1, 2, 5, 4, 3, 6) he will fix 1, 2 and 6 and proceed with sorting (5, 4, 3) using the same algorithm. Johnny hopes that this optimization will significantly improve the algorithm. Help him calculate the expected amount of shuffles for the improved algorithm to sort the sequence of the first n natural numbers given that no elements are in the right places initially.
Input
The first line of input file is number t - the number of test cases. Each of the following t lines hold single number n - the number of elements in the sequence.
Constraints
1 ≤ t ≤ 175
2 ≤ n ≤ 175
Output
For each test case output the expected amount of shuffles needed for the improved algorithm to sort the sequence of first n natural numbers in the form of irreducible fractions.
Example
Input:
3
2
6
10
Output:
2
1826/189
877318/35343 | 32,338 |
Squares Game (CHEFMAR)
Fat Tony and Fit Tony are playing the square painting game. There are n squares drawn on a plane. The sides of the squares are parallel to the axes. Squares don't intersect, but some of them can be inside others. In his turn a player can choose any square and paint its internal area black. All squares inside the painted one are also painted black. The player can't paint the squares that were already painted. The loser is the player who can't make a turn. Determine the winner of the game if both players play optimally and Fat Tony's turn is the first. Also if Fat Tony can win the game determine which square he has to paint on his first turn in order to win. If there are many squares which guarantee victory to Fat Tony choose the one with the smallest number.
Input
The first line of input contains t - the number of test cases. Each test case starts with n - the number of squares. Next n lines consist of three integers each x, y, a - the coordinates of the lowest left corner of the square and the length of its sides. The squares in the input are numbered from 1 to n in the order they are listed.
Constraints
1 ≤ t ≤ 10
1 ≤ n ≤ 50000
The total number of squares over all test cases in one file won't exceed 250000.
x, y won't exceed 10
8
in absolute value.
a will be positive and less than 10
8
.
Output
For each test case print "Fat x", where x - is the number of square which needs to be painted on the first turn in order to win (if there are many such square chose the one with the smallest number), if Fat Tony wins or "Fit" if Fit Tony wins.
Example
Input:
2
5
0 0 10
15 15 1
1 1 3
5 5 1
14 14 3
2
1 1 1
3 3 1
Output:
Fat 2
Fit | 32,339 |
Maximum - Profit -- Version II (ITRIX_C)
Everyone enjoyed
BYTECODE11
. So the “Maximum Profit” problem is:
Chakra is a young and dynamic entrepreneur, who is developing rapidly as a successful hotelier. He owns the Quickbyte chain of restaurants, 'M' of which are fully functional now. He divides each day into 'M' time slots. For each time slot 'j', in every restaurant 'i', there are Aij waiters and Bij customers. Being a quality conscious person, he wants each waiter to handle at most one customer in a given time slot. Since he is really busy, in a day each restaurant is open only during one of the time slots. Since the hunger and demand for food varies during the day, the price which the customer is willing to pay varies, and is given by Cij for a restaurant 'i' during a time slot 'j'.Given the values of Aij, Bij and Cij, find the maximum profit which Chakra can make in a day.
Let’s add a constraint “
Only one restaurant can be opened in a time slot
”. Also the number of restaurants and number of time slots will be equal (‘
M
’).
Input
The first line of input contains an integer 't', denoting the number of test cases.
For each test case, the first line contains an integer 'M'.
Each of the next 'M' lines contains 'M’ integers. The jth integer on the ith line denotes the value of Aij.
Each of the next 'M' lines contains 'M' integers. The jth integer on the ith line denotes the value of Bij.
Each of the next 'M' lines contains 'M' integers. The jth integer on the ith line denotes the value of Cij.
Output
For each test case output one value, denoting the maximum profit which Chakra can make in a day.
Example
Input:
2
2
1 2
3 2
3 2
1 2
4 5
3 1
3
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1000 33 10
75 1000 1000
100 50 39
Output:
13
2050
Constraints
t ≤ 50
1 ≤ M ≤ 15
1 ≤ Aij, Bij ≤ 5000
0 ≤ Cij ≤ 10
9 | 32,340 |
Board-Queries (ITRIX_D)
RishiKumar
spends most of his time in solving querying problems. When solving a 2D querying problem he got exhausted and he needs the help of someone. Yes he got!! ..
Karthi
is in search of his girl and asked Rishi whether he saw his girl on his way. Rishi replied he knew where she has gone but he will disclose the truth if Karthi solve this bloody querying problem. Help Karthi to solve this!!!!
Given two 2D arrays X and Y. Maximum size of X and Y is 500. (500 × 500)
There are 3 operations (Three types of queries)
0
x1 y1 x2 y2 - Swaps the contents of the rectangle given by the points (x1, y1) and (x2, y2) of X and Y.
1
x1 y1 x2 y2 - Print the sum of all elements in rectangle given by points (x1, y1) and (x2, y2) of the array X.
2
x1 y1 x2 y2 - Print the sum of all elements in rectangle given by points (x1, y1) and (x2, y2) of the array Y.
(Points (x1, y1) and (x2, y2) inclusive.)
(x1, y1) - Top left point of the rectangle and (x2, y2) – Bottom right point of the rectangle.
Input
The first line of the input file contains N – Dimension of the array (It is clear that array is square array i.e. length = breadth). The next N lines contains N integers per line separated by space which are the elements of array X. The next N lines contains N integers per line separated by space which are the elements of the array Y. The next line contains the integer Q – the number of queries. Then each of the following Q lines contains the queries as per the above operations.
Constraints
N ≤ 500
0 ≤ X
ij
Y
ij
≤ 10
6
Q ≤ 10
5
Array indexing start from
[1, 1]
to
[N, N]
.
Output
Print the result of each query of type 1 and type 2 line by line.
Example
Input:
5
1 2 3 4 5
6 7 8 9 0
1 2 3 4 5
6 7 8 9 0
9 1 2 3 4
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
4
1 1 1 4 4
0 1 1 4 4
1 1 1 4 4
2 1 1 4 4
Output:
80
16
80
Warning: Huge I/O, make your I/O fast. | 32,341 |
THE BLACK AND WHITE QUEENS (ITRIX_E)
Subru and Shanmu are playing Chess. Shanmu wonder about
queens
. So he asked Subru the following question
“
How many ways are there to place a black and a white Queen on an M × N chessboard such that they do not attack each other? The queen can be moved any number of unoccupied squares in a straight line vertically, horizontally, or diagonally.
”
Subru gave the answer in seconds for a given chess board of size M × N (M ≤ N). Can you repeat the same with your code?
Input
The first line contains the integer “t” which indicates the number of test cases. Each of the following
t
lines contains two integers M and N separated by spaces (M ≤ N).
Output
Output for each case consists of one line: The number of ways of placing a black and a white queen on a M × N chess board
such that they do not attack each other
.
Constraints
T ≤ 10000, 2 ≤ M ≤ 10
10
, 2 ≤ N ≤ 10
10
. and M ≤ N.
Input:
3
5 5
3 4
2 2
Output:
280
40
0 | 32,342 |
THE MAX LINES (MAXLN)
In this problem you will be given a half-circle. The half-circle’s radius is
r
.
You can take any point A on the half-circle and draw 2 lines from the point to the two sides of the diameter(AB and AC). Let the sum of square of one line’s length and the other line’s length is
s
Like in the figure
s
=
AB
2
+
AC
. And
BC
= 2
r
.
Now given
r
you have to find the maximum value of
s
. That is you have to find point A such that
AB
2
+
AC
is maximum.
Input
First line of the test case will be the number of test case T (1 ≤ T ≤ 1000). Then T lines follows. On each line you will find a integer number
r
(1 ≤
r
≤ 1000000); each representing the radius of the half-circle.
Output
For each input line, print a line containing
"Case I: "
, where I is the test case number and the maximum value of
s
. Print 2 digit after decimal (Errors should be less then .01).
Example
Sample Input:
1
1
Sample Output:
Case 1: 4.25 | 32,343 |
Looks like Nim - but it is not (GAME2)
Goran and Stjepan play an interesting game. On the table between them, there is a sequence of N skyscrapers made of Lego bricks. All of them are made of equal bricks and each of them has a height, which equals the number of bricks in it.
Goran plays first; then Stjepan, then Goran, then Stjepan and so on. In each move, a player has to find the
highest
skyscraper in the sequence (if there's more than one, he chooses any of them) and reduces its height - that is, takes away an arbitrary (positive) number of bricks from it.
The winner of the game is the one who takes away the last brick. Equivalently, the loser of the game is the one who is not able to make a move.
Help Goran and tell him in how many ways he can play his first move, so that he can certainly win (no matter how Stjepan played). If Goran doesn't have a winning strategy at all, the number of ways is zero.
Input
In the first line of input, there is an integer T ≤ 3, the number of test cases.
Then follow T blocks, each of them in two lines:
N ≤ 300 000, the number of skyscrapers in the sequence.
a sequence of N integers in the range [0, 10
6
].
Output
For each of the T games, print the required number of ways.
Example
Input:
3
5
0 1 0 1 0
3
0 7 0
5
1 0 1 0 1
Output:
0
1
3 | 32,344 |
Closest Point Pair (CLOPPAIR)
You are given N points on a plane and your task is to find a pair of points with the smallest Euclidean distance between them.
All points will be unique and there is only one pair with the smallest distance.
Input
First line of input will contain N (2<=N<=50000) and then N lines follow each line contains two integers giving the X and Y coordinate of the point. Absolute value of X,Y will be at most 10^6.
Output
Output 3 numbers a b c, where a, b (a<b) are the indexes (0 based) of the point pair in the input and c is the distance between them. Round c to 6 decimal digits.
See samples for more clarification.
Input:
5
0 0
0 1
100 45
2 3
9 9
Output:
0 1 1.000000
Input:
5
0 0
-4 1
-7 -2
4 5
1 1
Output:
0 4 1.414214 | 32,345 |
Hierarchy (MAKETREE)
A group of graduated students decided to establish a company; however, they don't agree on who is going to be whose boss.
Generally, one of the students will be the
main
boss, and each of the other students will have exactly one boss (and that boss, if he is not the main boss, will have a boss of his own too). Every boss will have a strictly greater salary than all of his subordinates - therefore, there are no cycles. Therefore, the hierarchy of the company can be represented as a rooted
tree
.
In order to agree on who is going to be who's boss, they've chosen K most successful students, and each of them has given a statement: I want to be the superior of him, him, and him (they could be successful or unsuccessful). And what does it mean to be a superior? It means to be the boss, or to be one of the boss' superiors (therefore, a superior of a student is not necessary his direct boss).
Help this immature company and create a hierarchy that will satisfy all of the successful students' wishes. A solution, not necessary unique, will exist in all of the test data.
Input
In the first line of input, read positive integers N (N ≤ 100 000), total number of students, and K (K < N), the number of successful students. All students are numbered 1..N, while the successful ones are numbered 1..K.
Then follow K lines. In A
th
of these lines, first read an integer W (the number of wishes of the student A, 1 ≤ W ≤ 10), and then W integers from the range [1, N] which denote students which student A wants to be superior to.
Output
Output N integers. The A
th
of these integers should be 0 if student A is the main boss, and else it should represent the boss of the student A.
Example
Input:
4 2
1 3
2 3 4
Output:
2
0
1
2
Input:
7 4
2 2 3
1 6
1 7
2 1 2
Output:
4
1
1
0
4
2
3 | 32,346 |
Best Fit (BFIT)
You are given a sequence of N random values (s1, s2, s3, s4, ... sN) You have to find a function f(t) = a*t+b such that the Euclidean Distance between the given sequence and the function values where t varies from 1 to N is minimum.
In effect, you have to minimize
Output the values a and b for each test case, rounded up to 4 decimal places.
Input
Line 1: T /* Number of test cases T <= 1000 */
Line 2: N /* Number of values in first test case N <= 10000 */
Line 3: s1 s2 s3 s4 … sN /* all values are less than 10000 and integers */
.
.
.
Output
a b /* Output the values a and b rounded to 4 decimal places for each test case */
Example
Input:
3
3
1 1 1
3
1 2 3
3
1 3 1
Output:
0.0000 1.0000
1.0000 0.0000
0.0000 1.6667 | 32,347 |
Charlie and the Chocolate Factory (CHARLIE)
Charlie works in a magical chocolate factory. Packets of its marzipan are made on conveyor belts. To make marzipan perfect, M conveyor belts are used, and the process is as follows.
Each of the M belts has N cells. Charlie first makes a few initial packets and puts them on the cells of the first belt (there may be zero or more packets in a particular cell).
Then the first belt generates a second belt such that each cell of the second belt, at the same time, counts the packets in some five cells of the first belt and creates that number of packets in itself.
Fox example, the first cell of the second belt sums the packets in the cells 1, 2, 3, 5, 9 of the first belt, the second cell of the second belt sums the packets in the cells 2, 3, 4, 5, 6 of the first belt and so on.
Then, from the second belt, a third belt is generated in the same manner, then the fourth from the third and so on until the M
th
. Since the number of packets on the belts usually increases, the number of packets in each cell is observed only modulo 10007.
You, as the winner of the golden ticket to the factory, are able to see how the M
th
belt looks like - that is, how many packets of marzipan there is in each cell. Charlie has also explained to you the production process and now you are wondering how first belt looked like.
Input
The first line of input contains positive integers N (N ≤ 100) and M (M < 2
31
).
The next N lines describe the process of generating each new belt. In the A
th
of these lines there are five distinct integers from the interval [1, N], denoting the cells of a previous belt from which the packets are added to the A
th
cell of a new belt.
The next line contains N integers describing the state of the M
th
belt (modulo 10007).
Output
Print N integers describing the state of the first belt (modulo 10007). A
unique
solution will exist in all of the test data.
Example
Input:
6 3
1 2 3 4 5
1 2 3 4 6
1 2 3 5 6
1 2 4 5 6
1 3 4 5 6
2 3 4 5 6
13 12 12 12 14 12
Output:
1 0 0 0 2 0
Explanation of the sample case:
The process goes like this: (1 0 0 0 2 0) - (3 1 3 3 3 2) - (13 12 12 12 14 12) | 32,348 |
Suffix Of Cube (CUBEND)
Given any string of decimal digits, ending in 1, 3, 7 or 9, there is always a decimal number, which when cubed has a decimal expansion ending in the original given digit string. The number need never have more digits than the given digit string.
Write a program, which takes as input a string of decimal digits ending in 1, 3, 7 or 9 and finds a number of at most the same number of digits, which when cubed, ends in the given digit string.
Input
The input begins with a line containing only the count of problem instances, nProb, as a decimal integer, 1 <= nProb <= 100. This is followed by nProb lines, each of which contains a string of between 1 and 10 decimal digits ending in 1, 3, 7 or 9.
Output
For each problem instance, there should be one line of output consisting of the number, which when cubed, ends in the given digit string. The number should be output as a decimal integer with no leading spaces and no leading zeroes.
If there are many answers, the minimum should be chosen.
Example
Input:
4
123
1234567
435621
9876543213
Output:
947
2835223
786941
2916344917 | 32,349 |
Substrings II (NSUBSTR2)
You are given a string T which consists of 40000 lowercase latin letters at most. You are also given some integers A, B and Q. You have to answer Q queries. For i-th query you are given a string S
i
and you need to output how many times S
i
appears in T. Immediately after answering the current query you need to add ((A*ans+B) modulo 26+1)-th lowercase symbol of the English alphabet to the end of T where ans is the answer to this query.
Input
The first line of input contains a string T. The next line consists of three integers Q (1<=Q<=40000), A (0<=A<=27) and B (0<=B<=26). The following Q lines contain Q query strings, S
i-2
on i-th line. Input will not exceed 600 kb.
Output
Output Q lines. Output the answer to the i-th query on the i-th line output.
Example
Input:
aaaaa
2 0 0
a
aa
Output:
5
5 | 32,350 |
Wordplay (WORD)
Ivana made up a long word of N letters. Then she wrote down all K-letter-substrings of that word. For example, if the original word is BANANA and K=3, Ivana writes down the words BAN, ANA, NAN, ANA. The number of these words is, obviously, N-K+1.
Ivana sorted these words in lexicographic order (in the given example, that would be ANA, ANA, BAN, NAN).
But the sad thing happened: Ivana forgot the original word! Your task is to reconstruct it. A unique solution will exist in all of the test data.
Constraints: 3 ≤ N ≤ 100 000, 2 ≤ K ≤ 15, K < N.
Input
[integers N, K]
[N-K+1 words in lexicographic order, each consisting of capital English letters]
Output
[the required word]
Example
Input:
6 3
ANA
ANA
BAN
NAN
Output:
BANANA | 32,351 |
Shake Shake Shaky (MAIN8_C)
Shaky has N (1<=N<=50000) candy boxes each of them contains a non-zero number of candies (between 1 and 1000000000). Shakey want to distibute these candies
among his K (1<=K<=1000000000) IIIT-Delhi students. He want to distibute them in a way such that:
Shaky has N (1<=N<=50000) candy boxes each of them contains a non-zero number of candies (between 1 and 1000000000). Shakey want to distibute these candies among his K (1<=K<=1000000000) IIIT-Delhi students. He want to distibute them in a way such that:
1. All students get equal number of candies.
2. All the candies which a student get must be from a single box only.
As he want to make all of them happy so he want to give as many candies as possible. Help Shaky in finding out what is the maximum number of candies which a student can get.
Input
First line contains 1<=T<=20 the number of test cases. Then T test cases follow. First line of each test case contains N and K. Next line contains N integers, ith of which is the number of candies in ith box.
Output
For each test case print the required answer in a seperate line.
Example
Input:
2
3 2
3 1 4
4 1
3 2 3 9
Output:
3
9 | 32,352 |
Coing tossing (MAIN8_D)
One day Rohil was getting very bored so he was tossing an unbiased coin randomly. He observed that certain patterns (a sequence of Head and Tail) appear very frequently while some other are very rare. Being a programmer he decided to code a solution which takes a pattern string as input and tells what is the expected number of times he will have to toss his coin to see that pattern. He wrote this program very quickly. Can you?
Input
First line contains (1 <= T <= 25) the number of test cases. Each of following T lines contains a pattern string of 'H' and 'T' only. H is for Head and T is for Tail.
|S| <= 40
Output
For each test case print the output in a new line (it is guaranteed that answer will always be an integer and fits in 64 bit type).
Example
Input:
3
H
HTHT
TTHTHTHTHTHHTHTHTHTTTTTTHTHHHHHTT
Output:
2
20
8589934598 | 32,353 |
Cover the string (MAIN8_E)
Given two strings A and B. You have to find the length of the smallest substring of A, such that B is the subsequence of this substring.
Formally speaking you have to find the length of smallest possible string S such that:
S is the substring of A.
B is the subsequence S.
Note: Subsequence of an string S is obtained by deleting some (possibly none) of the characters from it. for example "ah" is the subsequence of "aohol".
Input
First line contains T, the number of test cases. Then T test cases follow, 2 lines for each test case, 1st contains A and 2nd contain B.
|A| ≤ 20000, |B| ≤ 100
Output
For each test case print the answer in a new line. if no such substring exists print -1 instead.
Example
Input:
2
aaddddcckhssdd
acs
ghkkhllhjkhthkjjht
hh
Output:
10
3 | 32,354 |
Alpine Skiing (SKIING)
Believe it or not, the devices measuring time in alpine ski racing are not perfect. Instead of measuring the exact time, they measure an interval in which the ski racer finished the race (for example 53.42 sec - 53.45 sec).
The probability is distributed evenly on this interval. (More precisely, if we choose any two sub-intervals of equal length, the probability that the ski racer finished the race in each of these sub-intervals is equal. One can also say that each moment in the given interval has equal probability assigned to it, but this in fact says nothing since the probability for each moment is equal to zero (since there are infinitely many moments in the interval) no matter how we distribute the probability.)
And what if there are N ski racers? Then we have N intervals. Find the probability that the first ski racer on the list won the race (that is, finished the race with the minimal time).
Input
In the first line, there is an integer N (1 ≤ N ≤ 300).
In the next N lines, read the intervals assigned to the ski racers: two real numbers A
i
and B
i
in each line, representing the interval [Ai, Bi] of the i-th ski racer. (0 < A
i
< B
i
< 1000)
Output
Print the required probability. The absolute difference between yours and official solution may be at most 10
-6
.
Example
input
2
1.000 5.000
2.500 3.000
output
0.437500
input
4
3.500 17.300
12.700 21.200
2.900 15.000
1.000 20.000
output
0.263541 | 32,355 |
Cut the Silver Bar (SILVER)
A creditor wants a daily payment during n days from a poor miner in debt. Since the miner can not pay his daily obligation, he has negotiated with the creditor an alternative way, convenient for both parties, to pay his debt: the miner will give an equivalent of a 1µ (= 0.001mm) long piece of a silver bar as a guarantee towards the debt. The silver bar owned by the poor miner is initially nµ units long.
By the end of n days the miner would not have any more silver to give and the creditor would have received an amount of silver equivalent to that of the silver bar initially owned by the miner. By then, the miner expected to have enough money to pay the debt at the next day so that he would have back all his silver.
With this negotiation in mind, the miner has realized that it was not necessary to cut exactly 1µ silver piece from the bar everyday. For instance, at the third day he could give the creditor a 3µ silver piece, taking back the equivalent of a 2µ silver piece which the creditor should already have.
Since cutting the bar was rather laborious and time consuming, the miner wanted to mini-mize the number of cuts he needed to perform on his silver bar in order to make the daily silver deposits during the n days. Could you help him?
Input
Input consists of several cases, each one defined by a line containing a positive integer number n (representing the length in micras of the silver bar and the number of days of the amortization period). You may assume that 0 < n < 20000. The end of the input is recognized by a line with 0.
Output
For each given case, output one line with a single number: the minimum number of cuts in which to cut a silver bar of length nµ to guarantee the debt during n days.
Example
Input:
1
5
3
0
Output:
0
2
1 | 32,356 |
The Longest Chain of Domino Tiles (DOMINO1)
You are given N domino tiles. Each tile is made of some number of squares (not necessarily two), and each square is coloured either white or black (we use the Croatian letters: B for white and C for black).
Find the longest chain that can be made of these tiles. Each tile can be used at most once and cannot be rotated (for example, BC cannot become CB). The chain is made by a common rule: in adjacent tiles, touching squares must be of the same colour.
Input
[N ≤ 100, the number of dominoes]
in the next N lines:
[a string of size between 1 and 100, representing the domino]
Output
The length of the longest chain.
Example
Input:
4
CB
BCC
BBCC
BCBBC
Output:
11 | 32,357 |
Dynamic LCA (DYNALCA)
A forest of rooted trees initially consists of N (1 ≤ N ≤ 100,000) single-vertex trees. The vertices are numbered from 1 to N.
You must process the following queries, where (1 ≤ A, B ≤ N) :
link
A B : add an edge from vertex A to B, making A a child of B, where initially A is a root vertex, A and B are in different trees.
cut
A : remove edge from A to its parent, where initially A is a non-root vertex.
lca
A B : print the lowest common ancestor of A and B, where A and B are in the same tree.
Input
The first line of input contains the number of initial single-vertex trees N and the number of queries M (1 ≤ M ≤ 100,000). The following M lines contain queries.
Output
For each
lca
query output the lowest common ancestor (vertex number between 1 and N).
Example
Input:
5 9
lca 1 1
link 1 2
link 3 2
link 4 3
lca 1 4
lca 3 4
cut 4
link 5 3
lca 1 5
Output:
1
2
3
2 | 32,358 |
Separate Points (SPOINTS)
Numbers of black and white points are placed on a plane. Let’s imagine that a straight line of infinite length is drawn on the plane. When the line does not meet any of the points, the line divides these points into two groups. If the division by such a line results in one group consisting only of black points and the other consisting only of white points, we say that the line “separates black and white points”.
Let’s see examples in the figure below. In the leftmost example, you can easily find that the black and white points can be perfectly separated by the dashed line according to their colors. In the remaining three examples, there exists no such straight line that gives such a separation.
In this problem, given a set of points with their colors and positions, you are requested to decide whether there exists a straight line that separates black and white points.
Input
The input is a sequence of datasets, each of which is formatted as follows.
n m
x
1
y
1
.
.
.
x
n
y
n
x
n+1
y
n+1
.
.
.
x
n+m
y
n+m
The first line contains two positive integers separated by a single space;
n
is the number of black points, and
m
is the number of white points. They are less than or equal to 100. Then
n
+
m
lines representing the coordinates of points follow. Each line contains two integers x
i
and y
i
separated by a space, where (x
i
, y
i
) represents the x-coordinate and the y-coordinate of the i-th point. The color of the i-th point is black for
1 ≤ i ≤ n
, and is white for
n + 1 ≤ i ≤ n + m
. All the points have integral x- and y-coordinate values between 0 and 10000 inclusive. You can also assume that no two points have the same position.
The end of the input is indicated by a line containing two zeros separated by a space.
Output
For each dataset, output “YES” if there exists a line satisfying the condition. If not, output “NO”. In either case, print it in one line for each input dataset.
Example
Input:
3 3
100 700
200 200
600 600
500 100
500 300
800 500
3 3
100 300
400 600
400 100
600 400
500 900
300 300
3 4
300 300
500 300
400 600
100 100
200 900
500 900
800 100
1 2
300 300
100 100
500 500
1 1
100 100
200 100
2 2
0 0
500 700
1000 1400
1500 2100
2 2
0 0
1000 1000
1000 0
0 1000
3 3
0 100
4999 102
10000 103
5001 102
10000 102
0 101
3 3
100 100
200 100
100 200
0 0
400 0
0 400
3 3
2813 1640
2583 2892
2967 1916
541 3562
9298 3686
7443 7921
0 0
Output:
YES
NO
NO
NO
YES
YES
NO
NO
NO
YES | 32,359 |
Swimming Jam (SWJAM)
Despite urging requests of the townspeople, the municipal office cannot afford to improve many of the apparently deficient city amenities under this recession. The city swimming pool is one of the typical examples. It has only two swimming lanes. The Municipal Fitness Agency, under this circumstances, settled usage rules so that the limited facilities can be utilized fully.
Two lanes are to be used for one-way swimming of different directions. Swimmers are requested to start swimming in one of the lanes, from its one end to the other, and then change the lane to swim his/her way back. When he or she reaches the original starting end, he/she should return to his/her initial lane and starts swimming again.
Each swimmer has his/her own natural constant pace. Swimmers, however, are not permitted to pass other swimmers except at the ends of the pool; as the lanes are not wide enough, that might cause accidents. If a swimmer is blocked by a slower swimmer, he/she has to follow the slower swimmer at the slower pace until the end of the lane is reached. Note that the blocking swimmer’s natural pace may be faster than the blocked swimmer; the blocking swimmer might also be blocked by another swimmer ahead, whose natural pace is slower than the blocked swimmer. Blocking would have taken place whether or not a faster swimmer was between them.
Swimmers can change their order if they reach the end of the lane simultaneously. They change their order so that ones with faster natural pace swim in front. When a group of two or more swimmers formed by a congestion reaches the end of the lane, they are considered to reach there simultaneously, and thus change their order there. The number of swimmers, their natural paces in times to swim from one end to the other, and the numbers of laps they plan to swim are given. Note that here one “lap” means swimming from one end to the other and then swimming back to the original end. Your task is to calculate the time required for all the swimmers to finish their plans. All the swimmers start from the same end of the pool at the same time, the faster swimmers in front. In solving this problem, you can ignore the sizes of swimmers’ bodies, and also ignore the time required to change the lanes and the order in a group of swimmers at an end of the lanes.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
n
t
1
c
1
. . .
t
n
c
n
n
is an integer (1 ≤
n
≤ 50) that represents the number of swimmers.
t
i
and
c
i
are integers (1 ≤
t
i
≤ 300, 1 ≤
c
i
≤ 250) that represent the natural pace in times to swim from one end to the other and the number of planned laps for the i-th swimmer, respectively.
t
i
and
c
i
are separated by a space.
The end of the input is indicated by a line containing one zero.
Output
For each dataset, output the time required for all the swimmers to finish their plans in a line.
No extra characters should occur in the output.
Example
Input:
2
10 30
15 20
2
10 240
15 160
3
2 6
7 2
8 2
4
2 4
7 2
8 2
18 1
0
Output:
600
4800
36
40 | 32,360 |
Twenty Questions (TWENTYQ)
Consider a closed world and a set of features that are defined for all the objects in the world. Each feature can be answered with “yes” or “no”. Using those features, we can identify any object from the rest of the objects in the world. In other words, each object can be represented as a fixed-length sequence of booleans. Any object is different from other objects by at least one feature.
You would like to identify an object from others. For this purpose, you can ask a series of questions to someone who knows what the object is. Every question you can ask is about one of the features. He/she immediately answers each question with “yes” or “no” correctly. You can choose the next question after you get the answer to the previous question.
You kindly pay the answerer 100 yen as a tip for each question. Because you don’t have surplus money, it is necessary to minimize the number of questions in the worst case. You don’t know what is the correct answer, but fortunately know all the objects in the world. Therefore, you can plan an optimal strategy before you start questioning.
The problem you have to solve is: given a set of boolean-encoded objects, minimize the maximum number of questions by which every object in the set is identifiable.
Input
The input is a sequence of multiple datasets. Each dataset begins with a line which consists of two integers,
m
and
n
: the number of features, and the number of objects, respectively. You can assume 0 <
m
≤ 11 and 0 <
n
≤ 128. It is followed by n lines, each of which corresponds to an object. Each line includes a binary string of length m which represent the value (“yes” or “no”) of features. There are no two identical objects.
The end of the input is indicated by a line containing two zeros.
Output
For each dataset, minimize the maximum number of questions by which every object is identifiable and output the result.
Example
Input:
8 1
11010101
11 4
00111001100
01001101011
01010000011
01100110001
11 16
01000101111
01011000000
01011111001
01101101001
01110010111
01110100111
10000001010
10010001000
10010110100
10100010100
10101010110
10110100010
11001010011
11011001001
11111000111
11111011101
11 12
10000000000
01000000000
00100000000
00010000000
00001000000
00000100000
00000010000
00000001000
00000000100
00000000010
00000000001
00000000000
9 32
001000000
000100000
000010000
000001000
000000100
000000010
000000001
000000000
011000000
010100000
010010000
010001000
010000100
010000010
010000001
010000000
101000000
100100000
100010000
100001000
100000100
100000010
100000001
100000000
111000000
110100000
110010000
110001000
110000100
110000010
110000001
110000000
0 0
Output:
0
2
4
11
9 | 32,361 |
Cubist Artwork (CUBARTWK)
International Center for Picassonian Cubism
is a Spanish national museum of cubist artworks, dedicated to Pablo Picasso. The center held a competition for an artwork that will be displayed at the facade of the museum building.
The artwork is a collection of cubes that are piled up on the ground and is intended to amuse visitors, who will be curious how the shape of the collection of cubes changes when it is seen from the front and the sides. The artwork is a collection of cubes with edges of 1 foot long and is built on a flat ground that is divided into a grid of unit squares, measuring 1 foot long on each side. Due to some technical reasons, cubes of the artwork must be either put on the ground, fitting into a unit square in the grid, or put on another cube in the way that the bottom face of the upper cube exactly meets the top face of the lower cube. No other way of putting cubes is possible.
You are a member of the judging committee responsible for selecting one out of a plenty of artwork proposals submitted to the competition. The decision is made primarily based on artistic quality but the cost for installing the artwork is another important factor. Your task is to investigate the installation cost for each proposal. The cost is proportional to the number of cubes, so you have to figure out the minimum number of cubes needed for installation.
Each design proposal of an artwork consists of the front view and the side view (the view seen from the right-hand side), as shown in Figure 1.
The front view (resp., the side view) indicates the maximum heights of piles of cubes for each column line (resp., row line) of the grid.
There are several ways to install this proposal of artwork, such as follows.
In these figures, the dotted lines on the ground indicate the grid lines. The left figure makes use of 16 cubes, which is not optimal. That is, the artwork can be installed with a fewer number of cubes. Actually, the right one is optimal and only uses 13 cubes.
Notice that swapping columns of cubes does not change the side view. Similarly, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks.
For example, consider the artwork proposal given in Figure 2.
An optimal installation of this proposal of artwork can be achieved with 13 cubes, as shown in the following figure, which can be obtained by exchanging the rightmost two columns of the optimal installation of the artwork of Figure 1.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing two
zeros separated by a space. Each dataset is formatted as follows.
w d
h
1
h
2
··· h
w
h′
1
h′
2
··· h′
d
The integers
w
and
d
separated by a space are the numbers of columns and rows of the grid, respectively. You may assume 1 ≤
w
≤ 10 and 1≤
d
≤ 10. The integers separated by a space in the second and third lines specify the shape of the artwork. The integers
h
i
(1≤
hi
≤ 20, 1≤
i
≤
w
) in the second line give the front view, i.e., the maximum heights of cubes per each column line, ordered from left to right (seen from the front); The integers
h′
i
(1≤
h′
i
≤ 20, 1≤
i
≤
d
) in the third line give the side view, i.e., the maximum heights of cubes per each row line, ordered from left to right (seen from the right-hand side).
Output
For each dataset, output a line containing the minimum number of cubes. The output should not contain any other extra characters.
You can assume that for each dataset there is at least one way to install the artwork.
Example
Input:
5 5
1 2 3 4 5
1 2 3 4 5
5 5
2 5 4 1 3
4 1 5 3 2
5 5
1 2 3 4 5
3 3 3 4 5
3 3
7 7 7
7 7 7
3 3
4 4 4
4 3 4
4 3
4 2 2 4
4 2 1
4 4
2 8 8 8
2 3 8 3
10 10
9 9 9 9 9 9 9 9 9 9
9 9 9 9 9 9 9 9 9 9
10 9
20 1 20 20 20 20 20 18 20 20
20 20 20 20 7 20 20 20 20
0 0
Output:
15
15
21
21
15
13
32
90
186 | 32,362 |
Mravograd (MRAVOGRA)
The hard working ants have built a town called Ant Town. They modeled their town after Manhattan, with H horizontal and V vertical streets which cross in V×O intersections. As ants don't like water, with the first raindrops comes chaos in Ant Town. Town authorities have placed umbrellas under which any number of ants can hide, but only on N intersections.
When the rain starts, each ant on an intersection starts running,
using streets
, to the nearest intersection with an umbrella. But, if an ant can choose from more than one such intersection, it panics and, not knowing where to go,
stays on its starting intersection
and gets wet. Town authorities use the name "wet intersections" for such starting intersections.
For example, if Ant Town has 10 horizontal and 10 vertical streets, and if there are 4 intersections with umbrellas, then the question marks in the figure represent "wet intersections":
Picture represents first example. We count streets from left to right from 1 to V and from down upwards from 1 to H.
Write a program which, given the locations of intersections with umbrellas, determines the
number of "wet intersections
" in Ant Town.
Input
The first line contains two integers H and V (1 ≤ H, V ≤ 30 000), the numbers of horizontal and vertical streets in Ant Town.
Horizontal streets are numbered 1 to H, vertical streets 1 to V.
The second line contains an integer N (1 ≤ N ≤ 10), the number of intersections with umbrellas.
Each of the following N lines contains two integer h and v, meaning that there is an umbrella on the crossing of horizontal street h and vertical street v. The locations of all umbrellas will be distinct.
Output
Output the number of "wet intersections" in Ant Town.
Example
Input:
10 10
4
4 4
4 6
6 4
9 9
Output:
19
Input:
9 9
3
2 2
5 5
8 8
Output:
36
Input:
100 100
2
50 50
50 51
Output:
0 | 32,363 |
Okret (OKRET)
There is a text consisting of N characters. At each step Mirko chooses two numbers A and B and then reverses the subsequence consisting of characters between indices A and B, inclusive. Indices are 1-based.
Write a program that prints the final text after all operations are made.
Input
The first line of input contains the initial text of length N (1 ≤ N ≤ 2500000). It consists only of lowercase letters of the English alphabet.
The second line contains integer M (
1
≤ M ≤ 2500), the number of steps.
Each of the following M lines contain two integer A and B (1 ≤ A ≤ B ≤ N).
Output
In the first and only line output the final text.
Example
Input:
lukakuka
3
1 4
5 8
1 8
Output:
kukaluka
Input:
kukulelebodumepcele
5
3 7
10 12
2 10
5 18
5 15
Output:
kubeeludomepcelluke | 32,364 |
Yet Another Sequence Problem (SEQ7)
We have an infinite non-decreasing sequence A which is created as follows:
A[1] = 1 and A[2] = 2.
A number i occurs A[i] times in the sequence.
First few terms in the sequence are: { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7... }. Note that 3 occurs 2 times in the sequence, (because A[3] = 2).
Your task is to find the term A[n] for any given n, where 0 < n <= 1e13.
Input
First line contains t, the number of test cases. Each of the next t lines contains a number n.
Output
For every case, print the nth term of the sequence.
Example
Input:
2
5
12
Output:
3
6 | 32,365 |
Longest Common Difference Subsequence (LCDS)
GIven two sequences of integers, your task is to find the longest common subsequence where every two adjacent values differ the same.
For example, if the sequences are A = {1, 5, 8, 3} and B = {3, 10, 5}, then the common subsequence with adjacent values same are A
L
= {1, 8, 3} and B
L
= {3, 10, 5} since the differences in A
L
are 7 and -5 which is also the same in B
L
.
Input
First line of the input contains N
A
and N
B
, the sizes of the sequences A and B. Then follow two lines, the sequences A and B. (1 ≤ N
A
, N
B
≤ 1000 and all values in the sequence will lie between -1e9 and 1e9).
Output
Print one line, the length of the LCDS as described above.
Examples
Input:
4 3
1 5 8 3
3 10 5
Output:
3
Input:
1 2
5
6 8
Output:
1 | 32,366 |
Avaricious Maryanna (AVARY)
After Maryanna found the treasure buried by 27 pilots in a secret cave, she wanted to leave there immediately. Unfortunately, finding the door closed because of the overweight treasure she carried, she had to find out the password of the lock. She remembered someone had told her the password is an
N
-digit natural decimal integer (without extra leading zeroes), and the
N
least significant digits of any positive integral power of that integer is same as itself. She, being a smart girl, came up with all the possible answers within 1 minute. After a few times of tries, she escaped from that cave successfully. To show your intelligence you may solve the same task with your computer within only 10 seconds!
Input
The first line contains
T
(
T
<= 1000), the number of test cases.
T
lines follow, each contains a single positive integer
N
(
N
<= 500).
Output
For each test case, output a single line, which should begin with the case number counting from 1, followed by all the possible passwords sorted in increasing order. If no such passwords exist, output
Impossible
instead. See the sample for more format details.
Example
Input:
2
2
1
Output:
Case #1: 25 76
Case #2: 0 1 5 6 | 32,367 |
Boring Homework (BWORK)
Professor Z. always gives his students lots of boring homework. Last week, after explaining binary search trees (BSTs), he asked his students to draw a picture of BST according to the list of numbers inserted into the tree sequentially. Maryanna spent so much time playing the game "Starcraft II" that she can't finish her homework in time. She needs your help.
A binary search tree, which may sometimes also be called ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
--from Wikipedia
To draw a picture of BST, you may follow the rules listed below:
The picture of a 1-node BST, whose size is 1*1, is a single 'o' (15th small Latin letter).
If a BST has a non-empty subtree, draw a single '|' just above the subtree's root, and a single '+' just above previous drawn '|'. Finally, in the row of '+', use the least number (including 0) of '-'s to connect '+' (denoting the left subtree and right subtree) and 'o' (denoting the parent node of the subtree)
The left subtree (if exists) must be drawn on the left side of its parent. Similarly, the right subtree (if exists) must be drawn on the right side of its parent.
The column of the BST's root must not contain any character from left subtree or right subtree.
Any column containing any characters from BST's left subtree must not contain any characters from BST's right subtree, and vice versa. That is, for a node of the BST, the picture of its left subtree and the picture of its right subtree do not share common columns in the picture of the whole tree.
The sample output may give a clear clarification about the format of the picture.
Input
The first line contains
T
(
T
<= 2500), the number of test cases. T lines follow. Each line contains a positive integer
N
(
N
< 80), followed by
N
integers - a permutation of 1 to
N
. The permutation indicates the insert order for the BST.
Output
For each test case:
Output the case number counting from 1 in the first line. The next lines should be the image described above without any trailing spaces. See the sample for more format details.
Notice that no trailing whitespaces after the last visible characters of each line are allowed.
Example
Input:
3
3 3 1 2
6 4 5 6 1 3 2
5 3 4 5 2 1
Output:
Case #1:
+-o
|
o+
|
o
Case #2:
+--o+
| |
o-+ o+
| |
+o o
|
o
Case #3:
+o+
| |
+o o+
| |
o o | 32,368 |
Complete the Set (COMPLETE)
Archaeologists have made a discovery on the Temple of Topology. The temple was once used as a place for ritual ceremony thousands of years ago. Among the relics that were unearthed, a scroll of parchment raised the interest of scientists. The parchment contained many numbers written in ancient symbols.
By decrypting the words carved on a stone, scientists know that these numbers form an interesting set of integers satisfying the following two properties:
Bitwise AND any number of integers from the set result in an integer in that set again.
Bitwise OR any number of integers from the set result in an integer in that set again.
As the parchment is extremely old, some part of it were broken and the numbers were lost. Now you job is to complete the original set from the remaining integers such that the size of the set is as small as possible.
Input
The input contains several test cases. The total number of test cases is less than 1100. Each test case begins with a line containing an integer
n
(
n
> 1). The following line contains
n
integers
a
i
(0 ≤
a
i
< 2
16
), the remaining integers on the parchment. The integers are distinct.
Output
For each test case, output one line containing a single integer, the minimal number of additional integers to make the set complete. If these numbers are already a complete set, print 0.
Example
Input:
4
5
0 1 3 5 7
2
2 4
3
3 7 11
3
1 2 4
Output:
Case #1: 0
Case #2: 2
Case #3: 1
Case #4: 5 | 32,369 |
Detection of Extraterrestrial (DETECT)
E.T. Inc. employs Maryanna as alien signal researcher. To identify possible alien signals and background noise, she develops a method to evaluate the signals she has already received. The signal sent by E.T is more likely regularly alternative.
Received signals can be presented by a string of small latin letters 'a' to 'z' whose length is
N
. For each
X
between 1 and
N
inclusive, she wants you to find out the maximum length of the substring which can be written as a concatenation of
X
same strings. For clarification, a substring is a consecutive part of the original string.
Input
The first line contains
T
, the number of test cases (
T
<= 200). Most of the test cases are relatively small.
T
lines follow, each contains a string of only small latin letters 'a' - 'z', whose length
N
is less than 1000, without any leading or trailing whitespaces.
Output
For each test case, output a single line, which should begin with the case number counting from 1, followed by
N
integers. The
X
-th (1-based) of them should be the maximum length of the substring which can be written as a concatenation of
X
same strings. If that substring doesn't exist, output 0 instead. See the sample for more format details.
Example
Input:
2
arisetocrat
noonnoonnoon
Output:
Case #1: 11 0 0 0 0 0 0 0 0 0 0
Case #2: 12 8 12 0 0 0 0 0 0 0 0 0
Hint
For the second sample, the longest substring which can be written as a concatenation of 2 same strings is "noonnoon", "oonnoonn", "onnoonno", "nnoonnoo", any of those has length 8; the longest substring which can be written as a concatenation of 3 same strings is the string itself. As a result, the second integer in the answer is 8 and the third integer in the answer is 12. | 32,370 |
Entertainment (TENNIS)
Maryanna and Lucyanna play tennis every Sunday afternoon since 10 years ago.
A tennis match is determined through 5 sets. Typically the first player to win 3 sets wins the match. A set consists of games, and games, in turn, consist of points.
A game consists of a sequence of points played with the same player serving. A game is won by the first player to have won at least four points in total and at least two points more than the opponent. The running score of each game is described in a manner peculiar to tennis: scores from zero to three points are described as "love", "fifteen", "thirty", and "forty" respectively. If at least three points have been scored by each player, and the scores are equal, the score is "deuce". If at least three points have been scored by each side and a player has one more point than his opponent, the score of the game is "advantage" for the player in the lead. During informal games, "advantage" can also be called "ad in" or "ad out", depending on whether the serving player or receiving player is ahead, respectively.
A set consists of a sequence of games played with service alternating between games, ending when the count of games won meets certain criteria. Typically, a player wins a set by winning at least six games and at least two games more than the opponent.
The first servers of two consecutive sets are different.
Maryanna has found out when she is the server, her winning probability of this point is
M
%; otherwise,
Y
%. She wants to know her winning probability of the whole match if she serves first.
Input
The first line contains
T
(
T
≤ 10000), the number of test cases.
T
lines follow. Each line contains two space-separated positive integers
M
,
Y
(0 <
M
,
Y
< 100).
Output
For each test case, output a single line, which should begin with the case number counting from 1, followed by Maryanna's winning percentage accurate to 4 decimal places. See the sample for more format details.
Example
Input:
2
50 50
51 51
Output:
Case #1: 50.0000%
Case #2: 63.5654% | 32,371 |
Fudan Extracurricular Lives (MAHJONG)
Background
Students in Fudan University have various extracurricular lives. It seems to be widely known that many students in the Zhangjiang Campus prefer Tractor(a game of poker with four players, also named as “80-points” or “Upgrading”), but it is true that a considerable mass of students (especially in Department of Computer S&T) love another four player game, Mahjong, very much. Mahjong is one of the most historied multiplayer games in China. People in several provinces prefer this game most with various modified rules respectively.
To begin this problem, firstly, we shall introduce some basic concepts about the game:
Game Going
The game of Mahjong is played with a special set of “Mahjong Tiles”, which made by piece of wood or stones, each tile have a corresponding image on one face, which denotes particular signification. Initially, all tiles should be randomly shuffled and put into a pile with their (tiles') faces down, thus all their contents are hidden. After that, the participating players each get 13 tiles as there Holding Tiles (will be definitely explained and discussed later). Consequently, players come to the "Dealing Section" that everyone alternatively gets one tile from the hidden pile and includes it into this player's Holding Tiles, then chooses one tile from the current Holding Tiles to discard. This procedure will continue until there's no tile in the hidden pile or any player meet the Win condition (Practically, there are further modified rules such as "Bloody Battle", which pronounced as "Shyue-Chan" in Chinese, will break this traditional rule, but we do not take them into account in this problem).
Holding Tiles
In the process of game, players should manage their own set of tiles; these tiles are considered as Holding Tiles of each player respectively. Holding Tiles of one player have two particular types: Declared and Hidden. Declared Tiles are shown into public while Hidden Tiles are kept private, thus one can know all the four players’ Declared Tiles but only his or her own Hidden Tiles. The event causing Hidden Tiles into Declared will be discussed later.
Win
Before introducing the concept of how to Win a game, we have to firstly give out two essential sub-concepts, please remember that they are quite important for solving this problem:
(a) Architecture
A player's Holding Tiles are just a set of tiles, they can be separated and assembled into special Components, and all these Components compose the Architecture of Holding Tiles.
(b) Analysis
The procedure and method to determine the Architecture of one's Holding Tiles is called Analysis (please ignore the changing part of speech). Analyzing one's Holding Tiles should be based on a system of related rules and might be somewhat complex and tricky, discussed later.
In the rules of Mahjong, the Target Architecture will be defined. As the name implies, if a player's Holding Tiles can be Analyzed into a particular Architecture coinciding the Target Architecture, then this player can Win the game.
Score
one player Win a game, the score of this Win should be judged under a scoring rules system. The score is used for determining the worth of this Win -- It is widely known that Mahjong is originally invited for gambling.
Description
Now in China, people in Sichuan Province prefer the game of Mahjong much more than people in other area; causally, most of students in Fudan University who prefer Mahjong come from Sichuan. To this reason, we would like to use the rule of Sichuan Mahjong to go on this problem. With related to the traditional Mahjong rule, regulation of this game in Sichuan Province have been changed most obviously in the following two ways:
Tiles simplification
In the original rule of Chinese Mahjong, the game is based on a large set of tiles. All these tiles can be classified into several Categories -- including Simple Category, Honor Category, and Bonus Category -- with different functions when the game playing. The last two kinds of Categories are used in rules of some other area of China. (In other words, has nothing to do with this problem) Sichuan Mahjong only uses Simple Category in the game:
There are three different Suits in Simple Category and each Suit is numbered 1 to 9. They are Dots, Bamboo and Myriads.
There are four matching tiles for each value (e.g. there are four Dots tiles with the number 2). Generally, there are two essential aspects of information for determining the Kind of a tile: the Suit and number, thus we can uniquely name a tile with its order of number and Suit, for example: name
as “Third Bamboo” and name
as “First Dots”. Uniquely, players always call
(First Bamboo) as “Yao-Jhee”. It is easy to calculate that there in total 108 tiles used in the game of Sichuan Mahjong, that is, there are nine kinds in each suit and four tiles of each Kind.
Two Suits Limitation
This limitation constrains that at most two suits are permitted in one's Holding Tiles, that is, one with all the three suits in the Holding Tiles can never Win a game (Actually, would cause some penalty).
After clarifying these modifications, we can go on the description of Mahjong game.
During the process that every player gets new tiles alternatively, there are some situations which would cause case of Interruption. In detail, the rule of Mahjong allows players to meld (“meld” is a conventional glossary in Mahjong game, it is better to understand it as “adopt”) tiles discarded by others and, after that, sometimes discard a Holding Tiles for exchange. In order to explain the concept of Interruption and the way to Win the game, we shall now define some concepts of components (we’ve mentioned before but never defined) of Holding Tiles. Please review the concept of Target Architecture, a Target Architecture is composed by a set of Components, and there are two kinds of Components:
Sentence
There are two kinds of sentences:
(a) Sequence A Sequence is a triple of tiles with sequential number, for example:
There must be no skipping of numbers, nor does 9 loop around to 1. The sequence must be in the same Suit.
(b) Chunk
A Chunk is a triple of tiles with identical number, for example:
There Chunk must be in the same suit.
Pair
Similar to Chunk, A Pair is a couple of (two) tiles with identical number and same suit, see the following example:
With the definition of Component, there are three ways of melding others’ discarded tiles, and each time if a player calls for a melding, then an Interruption was made. However, only two ways of Interruption are used in rule of Sichuan Mahjong:
Refine (pronounced as “Pong” in Chinese) If someone discards a tile while you have a Pair of the same tile in your Hidden Tiles, you may (but not must) Refine the discarded tiles with the pair in your hand, after that these three identical tiles should become Declared. As we have mentioned before, each time you Refine a tile, you should discard another Hidden Tile for exchange.
Upgrade (pronounced as “Kong” in Chinese) If you have got a sentence of Chunk in Hidden Tiles while another player discards the identical (in fact, the only one) tile -- or you get this only identical tile by yourself -- you may (but not must) Upgrade the Chunk into a Component with four same tiles (a “Kong”) by melding the discarded tile. The same with Refining, after Upgrading these four identical tiles should become Declared. Specially, when making an Upgrade, you should never discard another Hidden Tiles. It seems that after an Upgrade, an extra tile is merged into one’s Holding Tiles (Accurately, into Declared Tiles), in fact these four same tiles should also be considered as a Chunk, the extra tile is only for “honor”, which means being used for calculate the score but never used when Analyzing the Architecture.
According to the descriptions of Refine & Upgrade, we can consequently conclude that:
Declared Tiles of a player always come from one or more melding Interruptions.
Once a tile becomes Declared, it will never be back to Hidden and never be discarded any more.
Another type of Interruption is Win – Which has been defined above -- that is, once another player discards a particular tile, or you get such a tile by yourself, if you can merge such a tile into your Holding Tiles and then Analyze all the Holding Tiles (14 tiles now) as a Target Architecture, then you can Win this game. Now, we should give the detailed explanation of Target Architecture under the rule of Sichuan Mahjong. The Target Architecture of Holding Tiles can be considered as that:
Following the Two Suits Limitation.
Components in the Architecture fits one of the following two structural styles:
(a) Consist of FOUR Sentences and ONE Pair, here we name the unique Pair as “Jong”. We name this style as Regular Target.
(b) Consist of SEVEN Pairs.
Remember that the Declared Tiles is a group of Sentences (an Upgraded Chunk can be considered as an ordinary Chunk with “honor” for scoring, discussed later). When Analyzing the Holding Tiles, the Declared Tiles and Hidden Tiles must be considered separately and can never be mixed; furthermore, Declared Tiles can only be Analyzed as several Chunks (ordinary Chunk or Upgraded Chunk) but never Sequences. To finish a Target Architecture, we need 14 tiles, (ignored extra tile from Upgrading), however, each one has only 13 Holding Tiles. Therefore, players always need another extra tile to complete the Architecture; this situation gives the concept of Expected Tile: If a player's Holding Tiles can fit the Target Architecture by adding a particular and existing tile, then such a tile is considered as one of the player's Expecting Tiles. Pay attention on the word “existing” please: that is, if you have held all such existing (four) tiles, then this kind of tile cannot be considered as Expected Tile.
Now we come to specify the rule of Scoring: once a player meets the Target Architecture (has got Win), he or she will have the basic score of ONE, that is, the lowest score of a Win is ONE. In addition, there are lots of specific conditions for awarding further extra scores. See the following items for description:
Dragon (pronounced as “Kong” and “Gher” in Chinese, especially in Chengdu dialect) If a player has collected all the four tiles of same kind of tiles in his or her Holding Tiles, then we say this kind become a Dragon. Each Dragon gives the owner ONE additional score. Apparently, once a player making an Interruption of Upgrade, a Declared Dragon is created, but there’s another situation: sometimes player shows a Declared Chunk in Declared Tiles but hides the rest one of that kind of tiles in Hidden Tiles, or even hides all the four same tiles in Hidden Tiles, these two cases will also be acknowledged as Dragon.
Seven Couples (pronounced as "Chee Dwee" in Chinese) If the Architecture meets the second style of Target Architecture – in other words: consists by seven pairs – then such an Architecture can be identified as Seven Couples, this special style gives the owner TWO additional score.
Purely (pronounced as "Ching Yi-Seh" in Chinese) If one players all Holding Tiles (Attention, not only the Hidden or Declared Tiles) have the same Suit, then Purely can be identified, TWO additional score awarded.
Chunkious (pronounced as "Dwee-Tsi Hoo" in Chinese) Chunkious is a special style of Regular Target, the condition is that all sentences of Holding Tiles are Chunks, Sequence never appears. Chunkious is worth ONE additional score.
Sky-ground Related (pronounced as "Tai Yao-Jhew" in Chinese) This is a very unique and confusing rule in Sichuan Mahjong, even not all players in Sichuan admit this condition, but in this problem we take it into account for generalization. No matter what style of Target Architectures, the condition of Sky-ground Related asks each components in the Architecture have at least one tile has numbers of 1 or 9. For instance, the following components are acceptable (This special style gives the owner TWO additional scores.):
Royal Chunkious (pronounced as "Jong Dwee" in Chinese) As the name implies, the Royal Chunkious is a special style of Chunkious, thus if an Architecture does not meet the condition of Chunkious, it can never be judged as Royal. This style means in an Architecture of Chunkious, only tiles with numbers 2, 5 and 8 appear. As examples, the following components are valid:
Royal Chunkious worth TWO more scores than normal Chunkious.
There are some other items relating to Scoring such as Seizing (“Chiang Kong”), Lucky Flower (“Kong Hsiang-Hwa”), but are not considered in this problem.
In order to solve this problem, the concept of CONSISTENCE might be somewhat a critical logic. We’ve just listed all the special situation causing extra scores for the Winning player, you may come up with the idea that some of them can occur simultaneously, for example, the following Holding Tiles (has Won):
Hidden Tiles are:
, and Declared Tiles are:
and
set of Holding Tiles can be obviously Analyzed as an Architecture which meeting the condition of Chunkious, Purely and double Dragons (just Analyze as how they are displayed in the example), and worth 1(basic) + 1(Chunkious) + 2(Purely) + 1(Dragon)*2 = 6 scores.
However, when we consider another example: Hidden Tiles are (there is no Declared Tiles in this example):
At first glance, we can Analyze them as an Architecture fitting rule of Seven Couples, which is trivial; yet we can also Analyze them in another way (fitting the rule of Sky-ground Related):
This way, can we judge the score as 1(basic) + 2(Seven Couples) + 2(Sky-ground Related) = 5? The answer is negative. For explaining this paradox, please remind yourself to notice the definition of Win: a player gets Win means he or she can Analyze the Holding Tiles into a Target Architecture, when we calculate the score, we are in fact aiming at such an resulting Architecture, scilicet, scoring is based on a particular Architecture but not based on the set of Holding Tiles, that is, if a set of Holding Tiles can be Analyzed as more than one Target Architectures, they are independent when scoring and cannot merge. Now we can give the correct answer of the last example: if Analyze in first way, then 1(basic) + 2(Seven Couples) = 3; otherwise, if use the second way, then 1(basic) + 2(Sky-ground Related) = 3, therefore the final score should be considered as 3. The last remaining confusion of scoring is that: if two or more Analyzed Architecture has different scores, which should be the delegate? The policy for dealing with this question is totally determined by real players, in this problem we choose the higher one – we choose the highest possible score among all Analyzed Target Architecture.
Your task in this problem is: given a player’s Holding Tiles, please determine all this player’s Expected Tiles (if exists) and their corresponding scores.
Input
The first line of input file is a integer T (T <= 100) indicating number of test cases, then T lines are following. Each line describes a case of Holding Tiles: two separated strings, the first string giving the Hidden Tiles and the second one giving the Declared Tiles. If there are no Declared ones, the second string would be “NONE” (quotes for clarity). Each tile contains two characters, the first one is a digit character which indicates this tile’s number and the second is a capital letter within ‘D’,’B’ and ’M’, that ‘D’ for Dots and ‘B’ for Bamboo and ‘M’ for Myriads, indicating tile’s Suit. For example, “7M” means Seventh Myriad and “1B” means First Bamboo (also known as “Yao-Jhee”). You may assume that all the input cases are valid in the rule of Sichuan Mahjong.
Output
For each case, firstly output a single line containing the case number counting from 1. Then, if there’s no Expected Tiles, output a single lines containing string of “NONE” (quotes for clarity); otherwise, output all the player’s Expected Tiles (with the same format of input) and then output their corresponding scores after each Expected Tiles, separated with a colon (“:”) and a space. All the Expected Tiles are printed in separated lines. Any extra blanks (spaces or empty lines) will cause “Wrong Answer”. The outputted Expected Tiles should be sorted in this way: first sorted by Suits, ‘D’ at first and then ‘B’ and ‘M’ in the last; second sorted by their numbers, smaller number has higher priority.
Sample Input
7
8D8D8D5D2D2D2D 6D6D6D7D7D7D
8D8D8D5D2D2D2D6D6D6D7D7D7D NONE
1D1D1D1D 3D3D3D4D4D4D5D5D5D
2D2D2D5D5D5D2M2M2M5M5M8M8M NONE
1D1D1D1D2D2D2D2D3D3D3D3D9M NONE
1D1D1D1D9D9D9D9D1M1M1M1M9M NONE 2D2D3D3D4D5D5D6D6D7D7D8D8D NONE
Sample Output
Case #1:
5D: 4
Case #2:
4D: 3
5D: 4
6D: 4
7D: 4
8D: 4
Case #3:
NONE
Case #4:
5M: 4
8M: 4
Case #5:
9M: 6
Case #6:
9M: 8
Case #7:
1D: 3
4D: 5 | 32,372 |
Herbicide (HERBICID)
Professor Z. has a courtyard beside his house. In the past, he loved to clean it and prune the flowers in his yard. However, with the JavaFF class taught by Professor Z. being offered, he indulged in assigning boring homework to the students and had no time for caring his yard.
Consequently, weeds begin to grow up and then his yard becomes overgrown. In the last weekend, after Professor Z. assigned a mass of boring homework again, he suddenly brought his yard to mind. And after he saw the weedy ground, he decided to remove the weeds. But he did not have much time to deal with the garden’s problem because of the uncompleted plans of further boring homework in the next JavaFF class.
He sprayed herbicide on the ground optionally and, strangely, herbicide was sprayed as several simple polygons on the ground. In order to determine whether he should continue his work or not, Professor Z. needed to know how many weeds were covered by the herbicide.
Notice that we assume that the weeds were not killed by the herbicide applied before. In the other words, a single weed can be counted several times in different polygon of herbicide. It seems that counting this number is quite a tough job. Then he asked Maryanna, one of his students in JavaFF class, for help. But Maryanna has no time because her boring homework had never been finished. Please help her!
Input
The very first line of input contains an integer
T
(
T
<= 100) indicating the number of test cases. The first line of each test case is an integer
N
(
N
<= 1000), which is the number of weeds in Professor Z's yard. In the following
N
lines, each line has a pair of integers (Xi, Yi) denoting the coordinate of a weed (-10000 <= Xi, Yi <= 10000). You can assume all the coordinates are unique. The next line is an integer
M
(
M
<= 1000) which denotes the number of polygons covered by herbicide, all these polygon's vertices are located on one of the
N
weeds, then
M
polygons descriptions are following. Each polygon Pi has two lines, the first line of
i
th polygon has an integer Si (3 <= Si <= N) denoting the number of vertices in this polygon. The following line contains Si integers, describing the vertices of this polygon in clockwise or counter-clockwise order. In detail, each integer in this line is an index of the coordinates of the N weeds listed before. Notice that the indexes start from 1. See the sample input for further details.
Output
For each test case, output
M
lines, each line has a single integer indicating the number of weeds covered by the corresponding polygon. If a weed lies on the edge of a polygon, then we consider such a weed as being covered.
Example
Input:
1
6
1 1
3 2
2 3
1 -1
-1 -2
-1 1
3
3 5 4 3
3 1 5 6
5 5 4 2 3 6
Output:
Case #1:
4
3
6 | 32,373 |
Imitation (IMITATE)
Iris is a student of ethology studying the animal behavior. She is interested by the imitation behavior of animals. Imitation is an advanced behavior whereby an individual observes and replicates another’s.
Iris is such a good researcher that she builds a mathematical model to describe the body figure of animals. She describes the body as a number of joints. And the figure or the status of animal body can be denoted as a set of ordered pairs of two different joints. To study the imitation of the animals, Iris defines the correlation of joints. She defines the correlation as the transitive closure of the ordered pairs of body status with its reflexive pairs eliminated. That is to say, the correlation is an anti-reflexive relation. In this case, we could say that one body status is imitating the other one when the correlations of both body statuses are the same.
For example, for the joint set {J1, J2, J3}. The first body status contains the ordered pair (J1, J2), (J2, J3). And the second body status contains the ordered pair (J1, J2), (J2, J3), (J1, J3). We could say that the first body status is imitating the other one because both of the correlation sets are (J1, J2), (J2, J3), (J1, J3) since the definition of the correlation is the transitive closure of body status.
For a given body status, that is, a given set of ordered pairs of joints, Iris want to get another body status, which is imitating the given one. At the same time, the desired body status must contain the minimum number of ordered pairs or the maximum number of ordered pairs. Your task is to calculate the minimum number and the maximum number.
Input
There are several test cases. The first line of the input contains a single integer denoting the number of test cases. There are about 100 test cases, but 90% of them are relatively small.
For each test case, the first line contains two integers
N
and
M
where
N
is the number of joints of both the given body status and the desired body status,
M
is the number of ordered pairs of the given body status. (1 <=
N
<= 1000, 0 <=
M
<= 10000)
Next
M
lines, each line denoting an ordered pair (
X
i
,
Y
i
). The
X
i
and
Y
i
are integers between 1 and N. Note that we consider the joints as the number between 1 and N.
Output
For each test case, output two integers denoting the minimum and maximum number of ordered pairs of the desired set. Two integers are separated by a single space.
Example
Input:
3
3 3
1 2
2 3
1 3
3 3
1 2
2 3
3 1
9 9
1 2
2 3
3 1
4 5
5 6
6 4
7 8
8 9
9 7
Output:
Case #1: 2 3
Case #2: 3 6
Case #3: 9 18
Hint
In mathematics, the transitive closure of a binary relation R on a set X is the transitive relation R+ on set X such that R+ contains R and R+ is minimal. If the binary relation itself is transitive, then the transitive closure will be that same binary relation; otherwise, the transitive closure will be a different relation.
A relation R on a set X is transitive if, for all x, y, z in X, whenever x R y and y R z then x R z. Examples of transitive relations include the equality relation on any set, the "less than or equal" relation on any linearly ordered set, and the relation "x was born before y" on the set of all people. Symbolically, this can be denoted as: if x < y and y < z then x < z.
(From Wikipedia::transitive closure) | 32,374 |
Juice Extractor (JUICE)
Jerry loses himself in the interesting game: Fruit Ninja. Fruit Ninja is a game of iPhone and iPad in which the players cut the fruits coming from the bottom of the screen and gain the bonus from cutting more than two fruits with a single slice. Once a fruit is cut, it breaks into small pieces and cannot be cut any more.
After months of training, he becomes pro of this game. Actually, he can cut all the fruits on the screen at any time. Jerry also has a bad habit that he has no willing to leave some fruits for the future cutting. In the other words, after Jerry cuts the fruits, all the fruits on the screen breaks and no one left. That is why all his friends call him
Juice Extractor
.
Now he only consider about the bonus, when he cuts more than two fruits, he can gain some bonus scores as same as the number of fruits he slice at that time. For example, if Jerry cuts 4 fruits with a single slice, he can get 4 scores from this slice.
After Jerry gets the fruit schedule, he knows the appearing time and the disappearing time for every single fruit. He can only cut a fruit into pieces between its appearing time and disappearing time inclusive. He wants to know the maximum possible bonus scores he can receive.
Input
There are several test cases; the first line of the input contains a single integer
T
, denoting the number of the test cases. (
T
≤ 200)
For each test case, the first line contains an integer
N
, denoting the total number of fruits. (1 ≤
N
≤ 1000)
The next
N
lines, each line describe a fruit. For each line, there are two integers
X
i
and
Y
i
, where
X
i
is the appearing time of the fruit and
Y
i
is the disappearing time of this fruit. (0 ≤
X
i
≤
Y
i
≤ 1000000000)
Output
For each test case, output a single integer denoting the maximum scores that Jerry could possibly gain. See the sample for further details.
Example
Input:
1
10
1 10
2 11
3 12
4 13
13 14
14 15
13 19
20 22
21 23
22 24
Output:
Case #1: 10 | 32,375 |
Roti Prata (PRATA)
IEEE is having its AGM next week and the president wants to serve cheese prata after the meeting. The subcommittee members are asked to go to food connection and get P (P ≤ 1000) pratas packed for the function. The stall has L cooks (L ≤ 50) and each cook has a rank R (1 ≤ R ≤ 8). A cook with a rank R can cook 1 prata in the first R minutes 1 more prata in the next 2R minutes, 1 more prata in 3R minutes and so on (he can only cook a complete prata) (For example if a cook is ranked 2, he will cook one prata in 2 minutes one more prata in the next 4 mins an one more in the next 6 minutes hence in total 12 minutes he cooks 3 pratas in 13 minutes also he can cook only 3 pratas as he does not have enough time for the 4th prata). The webmaster wants to know the minimum time to get the order done. Please write a program to help him out.
Input
The first line tells the number of test cases. Each test case consist of 2 lines. In the first line of the test case we have P the number of prata ordered. In the next line the first integer denotes the number of cooks L and L integers follow in the same line each denoting the rank of a cook.
Output
Print an integer which tells the number of minutes needed to get the order done.
Example
Input:
3
10
4 1 2 3 4
8
1 1
8
8 1 1 1 1 1 1 1 1
Output:
12
36
1 | 32,376 |
Guess number! (GNUM)
There was an application "Guess number!" in one of the popular social network recently. On each of the levels of this offered game it is necessary to define the secret number with some information provided.
In particular, one of the most difficult levels consists in guessing the rational number
x
(0 <
x
< 1). It is known, that the result of multiplication of this number by natural number
k
is exactly one alteration: the
i
-th and
j
-th digits after a decimal point are exchanged by each other.
As the number in front of decimal point isn't changed, the inequality
0 <
kx
< 1 is executed. Initially the numbers after a decimal point can be infinite.
Your problem consists in writing the program which will define value
x
on numbers
i
,
j
,
k
.
Input
The first input line contains in one integer
t
(about 1000). Each of the following
t
lines contains three numbers:
i
,
j
,
k
(1 ≤
i
<
j
≤ 1000; 2 ≤
k
≤ 10
9
).
Output
If the required number exists, output consists in two integers — numerator and denominator of a non-reducible fraction setting required number. Otherwise output is "NO SOLUTION".
Example
Input:
1
1 4 13
Output:
2997 40000 | 32,377 |
Double Time (DOUTI)
In 45 BC a standard calendar was adopted by Julius Caesar - each year would have 365 days, and every fourth year have an extra day - the 29th of February. However this calendar was not quite accurate enough to track the true solar year, and it became noticeable that the onset of the seasons was shifting steadily through the year. In 1582 Pope Gregory XIII ruled that a new style calendar should take effect. From then on, century years would only be leap years if they were divisible by 400. Furthermore the current year needed an adjustment to realign the calendar with the seasons. This new calendar, and the correction required, were adopted immediately by Roman Catholic countries, where the day following Thursday 4 October 1582 was Friday 15 October 1582. The British and Americans (among others) did not follow suit until 1752, when Wednesday 2 September was followed by Thursday 14 September. (Russia did not change until 1918, and Greece waited until 1923.) Thus there was a long period of time when history was recorded in two different styles.
Write a program that will read in a date, determine which style it is in, and then convert it to the other style.
Input
Input will consist of a series of lines, each line containing a day and date (such as Friday 25 December 1992). Dates will be in the range 1 January 1600 to 31 December 2099, although converted dates may lie outside this range. Note that all names of days and months will be in the style shown, that is the first letter will be capitalised with the rest lower case. The file will be terminated by a line containing a single '#'.
Output
Output will consist of a series of lines, one for each line of the input. Each line will consist of a date in the other style. Use the format and spacing shown in the example and described above. Note that there must be exactly one space between each pair of fields. To distinguish between the styles, dates in the old style must have an asterisk ('*') immediately after the day of the month (with no intervening space). Note that this will not apply to the input.
Example
Input:
Saturday 29 August 1992
Saturday 16 August 1992
Wednesday 19 December 1991
Monday 1 January 1900
#
Output:
Saturday 16* August 1992
Saturday 29 August 1992
Wednesday 1 January 1992
Monday 20* December 1899 | 32,378 |
Power Crisis (POCRI)
During the power crisis in New Zealand this winter (caused by a shortage of rain and hence low levels in the hydro dams), a contingency scheme was developed to turn off the power to areas of the country in a systematic, totally fair, manner. The country was divided up into N regions (Auckland was region number 1, and Wellington number 13). A number, m, would be picked 'at random', and the power would first be turned off in region 1 (clearly the fairest starting point) and then in every m'th region after that, wrapping around to 1 after N, and ignoring regions already turned off. For example, if N = 17 and m = 5, power would be turned off to the regions in the order:1, 6, 11, 16, 5, 12, 2, 9, 17, 10, 4, 15, 14, 3, 8, 13, 7.
The problem is that it is clearly fairest to turn off Wellington last (after all, that is where the Electricity headquarters are), so for a given N, the 'random' number m needs to be carefully chosen so that region 13 is the last region selected.
Write a program that will read in the number of regions and then determine the smallest number m that will ensure that Wellington (region 13) can function while the rest of the country is blacked out.
Input
Input will consist of a series of lines, each line containing the number of regions (N) with 13 <= N < 100. The file will be terminated by a line consisting of a single 0.
Output
Output will consist of a series of lines, one for each line of the input. Each line will consist of the number m according to the above scheme.
Example
Input:
17
0
Output:
7 | 32,379 |
Pattern Matching (PATT)
A regular expression is a string which contains some normal characters and some meta characters.
The meta characters include:
.
means any character
[c1 - c2]
means any character between c1 and c2 (c1 and c2 are two characters).
[ˆc1 - c2]
means any character not between c1 and c2 (c1 and c2 are two characters).
*
means the character before it can occur any times.
+
means the character before it can occur any times but at least one times.
\
means any character follow should be treated as normal character.
You are to write a program to find the leftmost substring of a given string, so that the substring can match a given regular expression. If there are many substrings of the given string can match the regular expression, and the left positions of these substrings are same, we prefer the longest one.
Input
Every two lines of the input is a pattern-matching problem. The first line is a regular expression, and the second line is the string to be matched. Any line will be no more than 80 character. A line with only an end will terminate the input.
Output
For each matching problem, you should give an answer in one line. This line contains the string to be matched, but the leftmost substring that can match the regular expression should be bracketed. If no substring matches the regular expression, print the input string.
Example
Input:
.*
asdf
f.*d.
sefdfsde
[0-9]+
asd345dsf
[^\*-\*]
**asdf**fasd
b[a-z]*r[s-u]*
abcdefghijklmnopqrstuvwxyz
[T-F]
dfkgjf
end
Output:
(asdf)
se(fdfsde)
asd(345)dsf
**(a)sdf**fasd
a(bcdefghijklmnopqrstu)vwxyz
dfkgjf | 32,380 |
Probablistic OR (PROBOR)
Everyone knows OR operation. Let us define new operation which we will call Probabilistic OR. We will denote this operation as #. For given real number p (0 ≤ p ≤ 1) and two bits a and b:
if a = 1 and b = 1, then #(a, b) = 1;
if a = 0 and b = 0, then #(a, b) = 0;
else #(a, b) = 0 with probability p, #(a, b) = 1 with probability 1-p.
Now for two given non-negative integers x and y we can define bitwise Probabilistic OR operation. The result of this operation is a number received by performing # operation for each pair of bits of x and y in same positions. For example, for p= 0.5, x = 2, and y = 4, we will get 0, 2, 4 or 6 each with probability 0.25.
You will be given a list of non-negative integers. You have to implement a program which will calculate the expected value of the result of performing bitwise probabilistic OR operation on all these numbers given some p. The numbers will be taken from left to right.
Input
Input file starts with real number p (0 ≤ p ≤ 1) with exactly two digits after the decimal point. Integer n follows (1 ≤ n ≤ 100). Next line contains n numbers ai in the order they are taking pert in the operation (0 ≤ ai ≤ 10
9
).
Output
Output the expected value of performing Probabilistic OR operation on the given numbers for given p. Print the result with two digits after the decimal point.
Example
Input:
0.25 4
1 2 3 4
Output:
5.11 | 32,381 |
Villages by the River (VILLAGES)
In a far away country there is a wide river, N villages on the left and N villages on the right side of this river (denoted by 1..N on each side). There are also M small ships, each of them connecting one village from the left and one village from the right side (in both ways).
You are to organize a film festival in four of these villages: two from the left and two from the right side. Each two of these four villages must be connected by a ship (directly) if they belong to opposite sides of the river.
Help yourself to choose these four villages and first find out; in how many ways can you choose them?
Input
In the first line there are integers N ≤ 1000 and M ≤ N
2
.
In the next M lines there are two integers from the interval [1, N] representing the village from the left and the village from the right side connected by this ship.
Output
Print the required number of ways to choose villages for the festival.
Example
Input:
3 5
1 1
1 2
1 3
2 2
2 3
Output:
1
(the only possibility is to choose the villages 1, 2 from the left and 2, 3 from the right side) | 32,382 |
How Many Plusses (PLUSEVI)
Mirko is a strange boy so he has written down a square matrix full of ones and zeroes. Now he is interested in how many plusses there are in his matrix.
A plus is a square such that its side has an odd length greater than 1 and all of its cells are zero, except for the middle row and the middle column: they must be full of ones. For example, in the matrix below there are two plusses, one inside the other:
00100
00100
11111
00100
00100
Input
In the first line there is an integer N ≤ 2000, dimension of the square matrix.
The next N lines are the rows of the matrix.
Output
Print the number of plusses appearing in the matrix.
Example
Input:
8
00010000
00010000
00010000
11111111
00010000
00010010
00010111
00010010
Output:
3 | 32,383 |
Party! (PAAAARTY)
Kate is preparing a party. She have bought a very strange garland for it. The garland is a closed chain of bulb. Each bulb can be in one of the following states: N - don't glow, R - glow red, G - glow green, B - glow blue. Each second the state of each bulb changes according to the following table:
N
R
G
B
N
N
R
G
B
R
R
N
B
G
G
G
B
N
R
B
B
G
R
N
where row is chosen by the current state of the bulb and column is chosen by the state of the bulb on the right. The value at the intersection of the chosen row and column gives the new state of the bulb. For example, if the bulb glows red (R) and the bulb on its right glows green (G) then in the next second the bulb will glow blue (B). And if the bulb and its right neighbour both glow blue then the bulb won't glow at all in the next second. Also all the bulbs change their states simultaneously. Such behaviour should (theoretically) lead to constant twinkling of the garland. Unfortunately it turns out that sometimes eventually the garland goes into such a state that all bulb don't glow. So the garland stops twinkling. Kate is rather worried that this can spoil the party. She is going to set the initial states of each bulb as she like. Help her determine for how long the garland will twinkle starting from this initial state.
Input
The input file consists of a single string containing characters 'N', 'R', 'G' and 'B', which describes the initial state of the garland. Each character defines the initial state of some bulb. The bulbs are listed from left to right. There is the first bulb on the right of the last one. The length of the string will be no more than 1234567 characters.
Output
Print the number of seconds during which the garland will twinkle. If the garland won't stop twinkling (at least until the power is turned off) print "Party!" (quotes for clarity).
Example
Input:
RGBG
Output:
4
Explanation
The garland will change the state in such a way:
RGBG
BRRB
GNGN
GGGG
NNNN | 32,384 |
Grid points (speed variation) (GRIDPNTS)
There's a Cartesian lattice with 0 <= x, y <= n. Given one point (x1, y1>0) in this lattice rotating clockwise as little as possible around the origin find the next point (x2, y2). The given and searched points mustn't have another point between the origin (0, 0) and this point itself.
x1, y1, x2, y2 are non-negative integers.
Input
In the first line the number T (T<10000) of test cases.
Then T lines with the space-separated n (1<=n<=1000000), x1 and y1.
Output
For each test case the space-separated x2 and y2.
Example
Input:
3
1 1 1
5 3 2
100 97 98
Output:
1 0
5 3
98 99 | 32,385 |
brownie (XIXO)
Bessie has baked a rectangular brownie that can be thought of as
an R×C grid (1 <= R <= 500; 1 <= C <= 500) of little brownie squares.
The square at row i, column j contains N_ij (0 <= N_ij <= 4,000)
chocolate chips.
Bessie wants to partition the brownie up into A*B chunks (1 <= A
<= R; 1 <= B <= C): one for each of the A*B cows. The brownie is
cut by first making A-1 horizontal cuts (always along integer
coordinates) to divide the brownie into A strips. Then cut each
strip *independently* with B-1 vertical cuts, also on integer
boundaries. The other A*B-1 cows then each choose a brownie piece,
leaving the last chunk for Bessie. Being greedy, they leave Bessie
the brownie that has the least number of chocolate chips on it.
Determine the maximum number of chocolate chips Bessie can receive,
assuming she cuts the brownies optimally.
As an example, consider a 5 row × 4 column brownie with chips
distributed like this:
1 2 2 1
3 1 1 1
2 0 1 3
1 1 1 1
1 1 1 1
Bessie must partition the brownie into 4 horizontal strips, each
with two pieces. Bessie can cut the brownie like this:
1 2 | 2 1
---------
3 | 1 1 1
---------
2 0 1 | 3
---------
1 1 | 1 1
1 1 | 1 1
Thus, when the other greedy cows take their brownie piece, Bessie
still gets 3 chocolate chips.
Input
Line 1: Four space-separated integers: R, C, A, and B.
Lines 2 to R+1: Line i+1 contains C space-separated integers: N
i,1
... N
i,c
.
Output
A single integer giving the required answer.
Example
Input:
5 4 4 2
1 2 2 1
3 1 1 1
2 0 1 3
1 1 1 1
1 1 1 1
Output:
3
Problem was added from USACO. | 32,386 |
Catapult that ball (THRBL)
Bob has unusual problem. In Byteland we can find a lot of hills and cities. King of Byteland ordered Bob to deliver magic balls from one city to another. Unfortunately, Bob has to deliver many magic balls, so walking with them would take too much time for him. Bob came up with great idea - catapulting them.
Byteland is divided into intervals. Each interval contains city and hill.
Bob can catapult magic ball accurately from city A to city B, if between them there isn't higher hill than A's hill.
Input
Every test case contains N and M (N ≤ 50000, M ≤ 50000), number of intervals and number of balls.
In next line there's N numbers H (H ≤ 10
9
) separated by one space.
In next M lines numbers A and B (1 ≤ A, B ≤ N), number of city from which we want to catapult the ball and number of city to which we want to catapult the ball.
Output
Write one number - number of magic balls that Bob can catapult successfully.
Example
Input:
7 3
2 3 5 4 2 1 6
3 5
2 5
4 6
Output:
2
Explanation
Bob can catapult balls numbered 1 and 3. | 32,387 |
LQDNUMBERS (LQDNUMS)
During a meeting with professors in the Asian Confederation of Mathematics, a Russian professor came up with a problem:
He choose a number N (1 ≤ N ≤ 10
18
), then write all the numbers from 1 to N to form a continuous string of digits. Next he replaced substrings of identical digits with a single digit. For example string fragment "14445556677666" would be changed to "145676". Then he asked his fellow professors: given a length of string S determine the number N which results in that kind of string S. Can you help the professors?
Your task: write a program to help your country's mathematicians.
Input
A single number M, length of the string S (1 ≤ M ≤ 10
18
.)
Output
A single number N, the number which Russian professor selected.
Example
Input:
13
Output:
12
Explanation:
With N = 12, we get the string: 123456789101112.
Because there are three consecutive number ones, we delete the first two numbers, then we have: 1234567891012. The length of this string is 13 | 32,388 |
Cost (KOICOST)
You are given an undirected graph with N vertices and M edges, where the weights are unique.
There is a function Cost(u, v), which is defined as follows:
While there is a path between vertex u and v, delete the edge with the smallest weight. Cost(u,v) is the sum of the weights of the edges that were deleted in this process.
For example, from the graph above (same as the sample input), Cost(2,6) is 2+3+4+5+6 = 20.
Given an undirected graph, your task is to calculate the sum of Cost(u,v) for all vertices u and v, where u < v. Since the answer can get large, output the answer modulo 10^9.
Input
The first line of the input consists of two integers, N and M. (1 <= N <= 100,000, 0 <= M <= 100,000)
The next M lines consists of three integers, u, v, and w. This means that there is an edge between vertex u and v with weight w. (1 <= u, v <= N, 1 <= w <= 100,000)
Output
Output the sum specified in the problem statement.
Example
Input:
6 7
1 2 10
2 3 2
4 3 5
6 3 15
3 5 4
4 5 3
2 6 6
Output:
256 | 32,389 |
Representatives (KOIREP)
There are N classes in a school, each with M students. There is going to be a race of 100m dash, and a representative from each class will be chosen to participate in this race. You were assigned a task to choose these representatives. Since you did not want the race to be one sided, you wanted to choose the representatives such that the difference between the ability of the best representative and the worst representative is minimal.
For example, if N = 3 and M = 4, and each class has students with following abilities:
Class 1: {12, 16, 67, 43}
Class 2: {7, 17, 68, 48}
Class 3: {14, 15, 77, 54}
it is best to choose the student with ability 16 from Class 1, 17 from Class 2, and 15 from Class 3. Thus, the difference in this case would be 17-15 = 2.
Your task is to calculate the minimal possible difference you can achieve by choosing a representative from each class.
Input
The first line of the input consists of two integers, N and M. (1<=N<=1000, 1<=M<=1000).
The next N lines will have M integers. The jth element of ith line is the ability of the jth student in ith class. The number is between 0 and 10^9, inclusive.
Output
Output the minimal difference one can achieve by choosing the representative from each class.
Example
Input:
3 4
12 16 67 43
7 17 68 48
14 15 77 54
Output:
2
Input:
4 3
10 20 30
40 50 60
70 80 90
100 110 120
Output:
70 | 32,390 |
Line up (KOILINE)
N people are lined up in a straight line to enter a concert. Each person in this line knows how many people in front have shorter or same heights. Let's call the sequence representing these numbers S. So in other words, S[i] means that there are S[i] people in front of the ith person who have shorter or same heights than that of person i.
Given the heights of N people and a sequence S, determine the correct order of people lined up. (left is front)
Input
The first line of the input is an integer N. (1 ≤ N ≤ 100,000)
The next N lines each consists of one integer H. (1 ≤ H ≤ 2×10
9
) These N integers are the heights of people lined up.
Then, sequence S is given in a single line, separated by a space.
Output
Determine the correct ordering of people lined up. Total of N lines should be output. The integer on the ith line represents the height of the ith person in the line.
Example
Input:
12
120
167
163
172
145
134
182
155
167
120
119
156
0 1 0 0 3 2 6 7 4 6 9 4
Output:
134
167
120
119
156
120
167
182
155
163
172
145 | 32,391 |
Funny programming contest (FUPRCO)
Bob is trying to solve many problems.
Today he's trying to do his best at "Funny programming contest". In this contest there is N rounds.
Each round is starting in moment Ai and ends in moment Bi. Rounds can overlap on each other. For each round there is one problem to solve. He can't solve more than one problem at once.
Bob knows that problems are very difficult, so he assumed that he will do each round for more than half of time the round lasts.
He knows start and end time for each round.
Help him figuring out if he can spend as much time as he want for each round.
Input
First line contains number N (1 ≤ N ≤ 2×10
5
). In the next N lines there are three numbers, ai, bi, ci (0 ≤ ai < bi ≤ 10
9
, (bi-ai)/2 < ci ≤ bi-ai), time when round i starts, time when round i ends, and time which Bob wants to spend for round i.
Output
Print "YES" if Bob can spend as much time as he wants for each round, otherwise print "NO"
Example
Input:
2
1 5 3
1 2 1
Output:
YES
Input:
2
1 5 3
2 3 1
Output:
NO | 32,392 |
Number Guessing Game 2 (GUESSLNK)
I really enjoy setting problem
GUESSING
. After three years, I decided to set another "kind of interactive" problem based on it.
Given a link for GUESSING problem, find the server's response
Specification
The script runs on server works like this, the URL contains 12 digits, first 6 digits represents
SEED
generated by random number generator, and it won't change during a guessing session. The last 6 digits represents
GUESS
, which is the number user just typed.
The unknown part (for you, of course) is an integer function
f
which is a bijection from [0,999999] to [0,999999].
The server first generate
TARGET
=
f
(
SEED
), then it compares
TARGET
and
GUESS
and give response back to user.
for more details on
f
, it's in format (expr(x) % 1000000), and expr (x) is a expression contains
only
operation add, subtract, multiply, division, modulo, each
exactly once
, and every constants are in [0,999999], every variable is x(of course), brackets are allowed.
for example, expr(x) could be "x/12-34%(x+1)*56", but it's invalid since
f
is not a bijection.
the modulo/division operations here works well if left side is a negative number, for example, -2 % 5 = 3, -2 / 5 = -1. but it's undefined if the number on the right side is not positive.
Input
each line contains a link in format
"
http://www.spoj.com/problems/GUESSING/XXXXXXYYYYYY/
", where
XXXXXXYYYYYY
contains exactly 12 digit.
Output
The server's response, in format "
XAYB
".
Example
Input:
http://www.spoj.com/problems/GUESSING/123456123456/
http://www.spoj.com/problems/GUESSING/000000000000/
Output:
1A3B
1A5B | 32,393 |
A los saltos (SALTOS)
(The English version is following the Spanish version at each section, and is in green text.)
Una secuencia de
k
números enteros positivos
, (k > 1),
es
saltarina
, si los valores absolutos de las diferencias entre elementos sucesivos toman todos los valores posibles desde 1 hasta
k-1.
Por ejemplo: la secuencia 51423, es una secuencia saltarina de longitud 5, porque las diferencias entre los elementos sucesivos de la secuencia son: 4,3,2,1
Se desea conocer cuántas secuencias saltarinas hay de longitud L.
En este problema consideramos que las secuencias están formadas únicamente por valores en 1..k.
A sequence of
k > 1
integers is called a
jolly jumper
if the absolute values of the difference between successive elements take on all the values 1 through
k-1
.
For example, the sequence 51423 is a jolly jumper of length 5, because the differences between consecutive elements are 4,3,2,1
You must to find out how many jolly jumpers are with length = L.
(in this problem we only consider the jolly jumpers built with values only in the 1..k range).
Input
Cada línea de la entrada consta de un entero k, (> 1). Cada línea es un caso diferente para informar. La entrada termina con una línea conteniendo el valor 0, el cual no se procesa.
Each line of the input have an integer k, (> 1). Each line is a different case to process. The input ends with a line that contains the value 0 (this value is the end of data signal and won't be processed).
Output
Por cada línea de la entrada, se debe generar una línea de salida que informa la cantidad de secuencias saltarinas de longitud igual a k.
Your program must to generate one output line for each input line. At each output line you must inform the quantity of jolly jumpers with length equal to k.
Sample
Input
2
3
4
0
Output
2
4
4 | 32,394 |
CANDY (LQDCANDY)
John had a chocolate bar with the size of 2
i
. At his birthday party, he shared this chocolate bar to his friend. But his friend just wanted to taste a piece of this chocolate bar which had the length of N (1 ≤ N ≤ 10
18
) so that John had to break this chocolate bar into pieces to get the piece for his friend. Unfortunately, this chocolate bar was so breakable that John just can break it into half each time.
Help him find the smallest length of the chocolate bar that he needs and the minimum times of breaking the chocolate bar to get the piece for his friend.
Input
T - the number of test cases. In each of the next T lines, there is one numbers N.
Output
For every test case, print one line the length of the chocolate bar and the minimum number of times to break the bar.
Example
Input:
3
8
5
7
Output:
8 0
8 3
8 3 | 32,395 |
Bob and his new kite factory (KITEPRBL)
Bob, owner of kite factory decided to make some good money.
He has bought new machine to produce kites, but this machine doesn't have any software in it! He was very sad, oh, so very sad. Every kite is produced from big square sheet of paper.
He didn't want to spend next big sum of money hiring programmers, so he decided to ask you for help.
He wants his machine to:
Cut exactly as much color paper as needed to cover kite and then cover it immediately.
Make N very little small holes in the kite (through which he can put colorful bows and other shiny things.)
At the end he wants his machine to sort convex shape kites and non-convex shapes kites (he thinks that convex shape kites should be transported to "Biedronka" - shop for poor people, so he doesn't want to mix them with really expensive ones.)
Input
In first line there is number T, number of test cases.
In first line of each test case there is number X (X < 200), number of vertices of the each kite.
Then X pairs of number, xi and yi, coordinates of each vertex.
Left-bottom corner of paper have (0, 0) coordinates.
In next line number N (N < 20000), number of holes to make in the kite.
Then N number, xi and yi, coordinates of each hole to make in the kite.
Obviously, hole cannot be made on the perimeter of a kite.
We can assume that no three points are colinear, also there is no point duplicate. Bob always would give you vertices of kite in clockwise order.
Output
For each test case print area (10^-3 precision) of paper which was used to produce each kite, holes which were made successfully, and digit 1 if kite is convex shape, otherwise digit 0. Separate each test case with new line
Example
Input:
1
6
0 0
5 0
4 2
5 4
0 4
1 2
3
1 1
1 2
5 2
Output:
32.000 1 0
Explanation:
32.000 area of paper to cover the kite. Only 1st hole can be made successfully (2nd is on perimeter, 3rd is outside the kite.) Kite has non-convex shape | 32,396 |
Maximum Self-Matching (MAXMATCH)
You're given a string
s
consisting of letters 'a', 'b' and 'c'.
The matching function m
s
( i ) is defined as the number of matching characters of
s
and its i-shift. In other words, m
s
( i ) is the number of characters that are matched when you align the 0-th character of
s
with the i-th character of its copy.
You are asked to compute the maximum of m
s
( i ) for all i ( 1 <= i <= |
s
| ). To make it a bit harder, you should also output all the optimal i's in increasing order.
Input
The first and only line of input contains the string
s
. 2 <= |
s
| <= 10
5
.
Output
The first line of output contains the maximal m
s
( i ) over all i.
The second line of output contains all the i's for which m
s
( i ) reaches maximum.
Example
Input:
caccacaa
Output:
4
3
Explanation:
cac
cac
a
a
cac
c
a
caa
The underlined characters indicate the ones that match when shift = 3. | 32,397 |
Bob and his towers (KVALTWR)
Bytie has got a set of wooden blocks for his birthday. The blocks are indistinguishable from one another, as they are all cubes of the same size. Bytie forms piles by putting one block atop another. Soon he had a whole rank of such piles, one next to another in a straight line. Of course, the piles can have different heights.
Bytie's father, Byteasar, gave his son a puzzle. He gave him a number k and asked to rearrange the blocks in such a way that the number of successive piles of height at least k is maximised. However, Bytie is only ever allowed to pick the top block from a pile strictly higher than k and place it atop one of the piles next to it. Further, Bytie is not allowed to form new piles, he can only move blocks between those already existing.
Input
In the first line of the standard input there are two integers separated by a single space: n (1 ≤ n ≤ 1,000,000), denoting the number of piles, and m (1 ≤ m ≤ 50), denoting the number of Byteasar's requests. The piles are numbered from 1 to n. In the second line there are n integers x
1
,x
2
,…,x
n
separated by single spaces (1 ≤ x
i
≤ 1,000,000,000). The number xi denotes the height of the i-th pile. The third line holds m integers k
1
,k
2
,…,k
m
separated by single spaces (1 ≤ k
i
≤ 1,000,000,000). These are the subsequent values of the parameter k for which the puzzle is to be solved. That is, the largest number of successive piles of height at least k that can be obtained by allowed moves is to be determined for each given value of the parameter k.
Output
Your program should print out m integers, separated by single spaces, to the standard output - the i-th of which should be the answer to the puzzle for the given initial piles set-up and the parameter k
i
.
Example
For the input data:
5 6
1 2 1 1 5
1 2 3 4 5 6
the correct result is:
5 5 2 1 1 0 | 32,398 |
Cube Free Numbers (CUBEFR)
A cube free number is a number who’s none of the divisor is a cube number (A cube number is a cube of a integer like 8 (2 * 2 * 2) , 27 (3 * 3 * 3) ). So cube free numbers are 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18 etc (we will consider 1 as cube free). 8, 16, 24, 27, 32 etc are not cube free number. So the position of 1 among the cube free numbers is 1, position of 2 is 2, 3 is 3 and position of 10 is 9. Given a positive number you have to say if its a cube free number and if yes then tell its position among cube free numbers.
Input
First line of the test case will be the number of test case T (1 <= T <= 100000) . Then T lines follows. On each line you will find a integer number n (1 <= n <= 1000000).
Output
For each input line, print a line containing
“Case I: ”
, where I is the test case number. Then if it is not a cube free number then print
“Not Cube Free”
. Otherwise print its position among the cube free numbers.
Example
Sample Input:
10
1
2
3
4
5
6
7
8
9
10
Sample Output:
Case 1: 1
Case 2: 2
Case 3: 3
Case 4: 4
Case 5: 5
Case 6: 6
Case 7: 7
Case 8: Not Cube Free
Case 9: 8
Case 10: 9 | 32,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.