1 - Problem Archive Scoreboard

Time

2015/04/30 22:00:25 2015/04/30 22:00:25

Clarification

# Problem Asker Description Reply Replier Reply Time For all team

# Problem Pass Rate (passed user / total user)
1000 The A+B Problem
1001 Simple Relation
1002 String Reverse
1003 OTAKU
1004 Toy
1005 How Many Trees?
1006 The Disks
1007 Convex hull
1008 Tester
1009 Dropping Balls
1010 The Stern-Brocot Number System
1011 Number Sequence
1012 ICPC Team Strategy
1013 Message
1014 A+B
1015 May the Right Force with you
1016 Sum of Different Primes
1017 Wavio Sequence
1018 Wedding Shopping
1019 Cutting Sticks
1020 Membership Management
1021 Balloon Collecting
1022 Towns along a Highway
1023 Awkward Lights
1024 The Two Men of the Japanese Alps
1025 Find the Multiples
1026 Test Case Tweaking
1027 Where's Wally
1028 Intersection of Two Prisms
1029 Matrix Calculator
1030 Maximum Sum (II)
1031 sqrt log sin
1032 Lotto
1033 What goes up?
1034 Products
1035 Daily Meals
1036 Vigenère cipher
1037 Gray Code
1038 The Price of Houses I
1039 Robot Lab
1040 Tetris Battle
1041 Fibonacci Numbers
1042 Painter Jobz
1043 IMMVP
1044 Doraemon Hon’s Chessboard
1045 The Price of Houses II
1046 BnB
1047 Ordering
1048 The Sultan's Successors
1049 Virtual Friends
1050 Cashier Employment
1051 Twin Primes
1052 Longest Paths
1053 Dominos II
1054 Optimal Binary Search Tree
1055 Highways
1056 Fire Drill
1057 OmniGravity
1058 Visible Lattice
1059 Chest of Drawers
1060 Consecutive Sums
1061 Zones
1062 Trust groups
1063 Bar Codes
1064 Software Allocation
1065 The Skyline Problem
1066 Shortest Path (I)
1069 Directed-graph (I)
1072 Topological Sort (I)
1099 POJ A + B
1100 Easy Problem from Rujia Liu?
1104 DNA Sorting
1108 Product
1112 Simply Emirp
1116 Power Crisis
1120 You want what filled?
1124 Morning Walk
1128 Airport Express
1132 The Party, Part I
1136 Audiophobia
1140 The Sultan's Successors
1144 Colour Hash
1196 Uninstall
1197 Stepmania
1199 Guess
1200 Circuits
1201 Segments
1202 Enigma
1203 The L-VALUE
1204 Stepmania (III)
1205 Stepmania (II)
1206 PA - Ice Arena
1207 PB - The Balloon Kingdom
1208 PC - Ant
1209 PD - Keys
1210 PE - Biased Grade
1211 PF - Crimiville
1301 Parity
1302 Sorting
1303 Time is Money!
1304 More Profit!
1305 Treasures of the Sea
1306 Energy Saver
1307 Gift Wrapping Algorithm for Convex Hull
1400 PT - Tedious Job
1402 PV - Veteran Engineer
1403 PW - World War V
1404 PX - Xanadu Protector
1405 PY - Yoyo Movie Theater
1406 PZ - Zombiefest!
1407 Bracket Matching
1410 Modified Josephus
1413 Queue with delete middle
1416 BST Problem 1 (I)
1419 BST Problem 2 (I)
1422 BST Problem 3 (I)
1425 Problem A - Minimum Scalar Product
1426 PB - Bribe the Prisoners
1427 AVL Tree Sample
1428 AVL Tree Sample (Insert)
1429 AVL Tree Sample (Insert with big data)
1430 AVL Insert(Small)
1434 BST Insert
1500 What's Cryptanalysis? [01]
1504 Cantor Fractions[01]
1508 Goldbach's Conjecture[01]
1512 How many Fibs?[01]
1516 Mouse Clicks[01]
1520 Rank the Languages[01]
1524 Play on Words[01]
1528 The Gossipy Gossipers Gossip Gossips[01]
1532 A Node Too Far [01]
1536 Commandos [01]
1540 Turn the Lights Off [01]
1544 23 Out of 5 [01]
1548 Numerically Speaking [1]
1552 Twin Primes [1]
1556 Closest Sums [1]
1560 Foreign Exchange [1]
1564 Not That Kind of Graph [01]
1568 Critical Links [01]
1572 Play on Words [01]
1576 Domino Effect [01]
1580 The Net [01]
1584 Page Hopping [01]
1588 Fans and Gems [01]
1599 Accumulated Error
1600 PA - Loyal Army
1601 PB - Weather Report
1602 PC - Suffix Marking
1603 PD - David's Golden Chain
1604 PE - Prime Grid
1605 PF - Conveyor Belt
1606 PG - Monkey Hunter
1607 PH - Take Short-cuts!
1608 PI - HEX Network
1609 ZOJ A + B
1701 Art of Search Engine - Gogomei
1702 Build a Program
1703 Castle Defend
1704 Double Pieces
1705 Earthquake
1706 Fun Game
1707 Game Bug
1708 The Integer All-time Champ
1709 Problem TEST. TESTaceology
1710 Problem A. Ambrosia
1711 Problem B. Black Dark Witch
1712 Problem C. Cavern
1713 Problem D. Doom
1714 Problem E. Energy Gun
1715 Problem F. Friendly Fire
1716 Problem G. Gate
1717 Problem H. Hyper Portal
1718 Problem I. Information
1719 Problem J. Journey’s End
1720 PA - My Legend
1721 PB - Working at the Park
1722 PC - Mirrored Double Maze
1723 PD - Simple Number
1724 PE - H-Game Finder
1725 PF - Les Misérables
1726 PG - My Kingdom
1727 PH - Catalan Number
1728 PI - Walking on the Grid
1729 PJ - Robot's Walk
2000 The Sky is the Limit
2001 Painter
2002 Fence Repair
2101 The Traveling Judges Problem
2102 Bit Compressor
2103 Ferries
2104 Network
2105 Clues
2106 Consanguine Calculations
2107 Containers
2108 Grand Prix
2109 Anti Brute Force Lock
2110 Jollybee Tournament
2111 Degrees of Separation
2112 Air Conditioning Machinery
2113 The Sky is the Limit
2114 Interstar Transport
2115 Huffman Codes
2116 Balloons in a Box
2117 Island Hopping
2118 AGTC
2119 Wordfish
2120 Simplified GSM Network
2121 Assemble
2122 Find Terrorists
2123 Clicking Checkboxes
2124 Postmaster's Wish
2125 Triangle Hazard
2126 Picnic Planning
2127 Sharing Chocolate
2128 Schedule Pairs of Jobs
2129 Lots of Sunlight
2130 March of the Penguins
2131 Text Formatting
2132 Self-divisible Numbers
2133 Challenging "Butts"
2134 A Fitting Advertisement!
2135 The Zits Code
2136 DNA Chopper
2137 Automatic Marking
2138 MODEX
2139 JONES
2140 ACORN
2141 TUSK
2142 SKYLINE
2143 USHER
2144 RACING
2145 Molar mass
2146 Editor
2147 Network
2148 PHONE
2149 Tile Code
2150 Meteor
2151 Signals
2152 Puzzle
2153 Turtle Graphics
2154 Number
3001 Fence Repair
3002 The Blocks Problem
3003 (*) Tic Tac Toe
3004 Fire!
3005 Nice Prefixes
3006 Convex Hull
3007 Slalom
3008 Another lottery
3009 Ballot evaluation
3010 Dark roads
3011 Elias gamma coding
3012 Food portion sizes
3013 Generate random numbers
3014 Hotel booking
4000 Airplane Parking
4001 In­circles Again
4002 Rating Hazard
4003 Your Ways
4004 Hexagonal Sticks
4005 Buy Your House
4006 Synnerg Lifeform
4007 Nowhere Money
4008 Highway Patrol
4009 A Spy in the Metro
4010 Low Cost Air Travel
4011 Covering Whole Holes
4012 Remember the A La Mode!
4013 Lattice Squares
4014 Trip Compulsion
4015 Visible Lattice
4016 XOR Sum
4017 Find The Number
4018 Love for Pizza
4019 Succession
4020 Assembling Services
4021 Box Relations
4022 Exclusive-OR
4023 Help Bubu
4024 Jiajia's Robot
4025 String LD
4026 Painting
4027 Another Brick in the Wall
4028 Blast the Enemy!
4029 deltree
4030 Solar Eclipse
4031 Grey Area
4032 Expected Allowance
4033 Stopped Watches
4034 Digits on the Floor
4035 Spherical Mirrors
4036 Traveling Cube
4037 Mystic Craft
4038 Top 10
4039 Random Simple Polygon
4040 Alien
4041 A+B
4042 1:1000000000000...
4043 The Unique MST
4044 Network of Schools
4045 Toll! Revisited
4046 Bonus Adjustment
4047 Morning Walk
4048 Channel Allocation
4049 Halloween Costumes
4050 Yahtzee
4051 Dangerous Tunnels
4052 Trip Planning
4053 Flea circus
4054 Lining Up
4055 Trainsorting
4056 GATTACA
4057 Menu
4058 Count the people
4059 Count the people Extreme!!!!!
4060 Walking on a Grid
4061 My T-shirt suits me
4062 Right triangle pool
4063 Mister George visit
4064 Attractive game
4065 Points in Figures: Rectangle
4066 Fortune Card Game
4067 Trip Planning
4068 Squares
4069 The Swallowing Ground
4070 Mapmaker
4071 Cantor Fractions
4072 Hotel booking
5000 Pi
5001 Play with Floor and Ceil
5002 Minesweeper
5003 Knight Moves
5004 Odd Sum
5005 You can say 11
5006 All in All
5007 Ternary
5008 Triangle Wave
5009 The jackpot
5010 Hashmat the brave warrior
5011 Zeros and Ones
5012 Maximum Sum
5013 Grade List
5014 Month Bill
5015 Average
5016 Poker
5017 ``Accordian'' Patience
5018 Prime Number Testing
5019 How many primes?
5020 Prime Words
5021 Prime Distance
5022 Prime Factors
6001 Send a Table
6002 Deer-Proof Fence
6003 War
6004 Polygons on the Grid
6005 Sunny Mountains
6006 Lowest Pyramid
6007 9 Puzzle
6008 Census
6009 String Cutting
6010 Fun Game
6011 Color a Tree
6012 Glass Beads
6013 Babel
6014 Determine the Shape
6015 Crossing Streets
6016 Destroying the bus stations
6017 The Closest Pair Problem
6018 Intersecting line segments
6019 Enjoyable Commutation
6020 Trip Routing
6021 Painter
6022 Subway Timing
6023 ACM Puzzles
6024 Undetectable Tour
6025 Sightseeing
6026 Magnetic Train Tracks
6027 Nested Squares
6028 Traveling Cube
6029 Puzzle
6030 Difficult Melody
6031 Paper Presentation
6032 The Sky is the Limit
6033 Key Task
6034 The Separator in Grid
6035 Best Coalitions
6036 Take the Land
6037 Stopped Watches
6038 Underwater Snipers
6039 Twenty Questions
6040 Jogging Trails
6041 Gomoku
6046 Test Case Tweaking
6047 The Islands
6048 The Two Men of the Japanese Alps
6049 Jumping monkey
6050 Rendezvous
6051 The Tree Root
6052 Plants vs. Zombies HD Super Pro
6053 And Then, How Many Are There?
6054 Taxi Cab Scheme
6056 Network
6058 Proving Equivalences
6059 Movie collection
6500 Colorful World and Monochromatic World
8001 Problem B
8002 Problem C
8003 Problem D
8004 Problem E
8005 Problem F
9001 Add Big Numbers
9002 Factorials
9003 Power
9004 A+B in radix N
9005 AxB
9006 Carry In
9007 Fibonacci number
9008 Encryption
9009 Partial Sum
9010 Polynomial Addition
9011 Minesweeper
9012 Word Frequency
9013 Longest Common Substring
9014 Find the Longest Palindrome
9015 Palindrome
9016 String Reverse
9017 Alphabetically order
9018 Tree
9019 Territory Expansion
9020 Is it a forest?
9021 Lowest common ancestor
9022 Tree distance
9023 Count the Leaves
9024 The Sum of a Tree Path
9025 Tree Recovery
9026 Level-Order Traversal
9027 K Characters
9028 Fill
9029 All combinations
9030 Blocks
9031 Subset sum
9032 Swamp maze
9033 Colorful map

1000 - The A+B Problem   

Description

Given a,b, output a+b.

Input

a,b<=100000000.

Output

a+b

Sample Input  Download

Sample Output  Download

Tags

4 5 ddd 3 a #include <stdio.h> p klrscpp ? CCY rain orange



Discuss




1001 - Simple Relation   

Description

Given two integer sequences A, B. Add them in some specific order O.
O is described via a representation of the location relationship from input.

For example, O = 100101 means A[i] + B[i+2] write to result C[i+1];
O = 111 means A[i] + B[i] write to C[i].

Note that if index is out of the length of B or C, imagine that B,C are circular.

Input

N
L
A
B
O

N is the number of total test data.
L is the number of element in A,B.

A,B sequences have the same number of elements, each element e:
0< e < 1000000
1<= num. of A,B <= 1000

O is the description of the order
3 <= length of O < 1000
there are exactly three ones in O, and the leading one is always happen!

Output

Output your result by the same format of input sequence.

Sample Input  Download

Sample Output  Download

Tags

klrscpp



Discuss




1002 - String Reverse   

Description

Given a string S, output the reverse of S.

Input

The input consists of many lines. Each line is a string S with length <= 1000000.
The string S does not contain any spaces.

Output

Output the the reverse of S. One in each line.

Sample Input  Download

Sample Output  Download

Tags

klrscpp sss



Discuss




1003 - OTAKU   

Description

"Otaku" is a Japanese term used to refer to people with obsessive interests, particularly anime,
manga, and video games. Otaku usually has much features such that you can recognize someone as
a otaku with those features.


Dr.Davidsu now want to do a research about Otaku. First he wants a program to help him.
The program should read the list of characteristics of many people and to determine how possible
they are Otaku.

Although Dr.Davidsu is a great programmer, but since he realizes so much knowledge about Otaku
with his research, now he also becomes a OTAKU!! So he only plays games day and night and could
not write program anymore. Please help the great Ota.. uh.. great Dr. Davidsu!!

Input

There are two positive integer N, M in the first line of input following N lines of the features of Otaku.
Each line has a distinct string describes the feature. And then there are M people's describing below.
In each people's data, first line there is a positive integer K which is the number of the people's characteristics
and K lines below are the K features of the people. 

Limits

1 <= N <= 10000
1 <= M <= 1000
1 <= K <= 1000

the string describes the feature of otaku or people is consecutive characters only contains uppercase

letter or underline char "_"  and no more than 16 characters.

Output

For each people, if more than half of its characteristics is a feature of OTAKU, then output 'Y'.
Otherwise output 'N' on each line.

Sample Input  Download

Sample Output  Download

Tags

Otaku



Discuss




1004 - Toy   

Description

Jasio is a little boy - he is only three years old and enjoys playing with toy cars very much. Jasio has n different cars. They are kept on a shelf so high, that Jasio cannot reach it by himself. As there is little space in his room, at no moment may there be more than k toy cars on the floor.

Jasio plays with one of the cars on the floor. Jasio's mother remains in the room with her son all the time. When Jasio wants to play with another car that is on the floor, he reaches it by himself. But when the toy is on the shelf, his mummy has to hand it to him. When she gives Jasio one car, she can at the same time pick any car from the floor and put it back on the shelf (so that there remains sufficient space on the floor).

The mother knows her child very well and therefore can predict perfectly which cars Jasio will want to play with. Having this knowledge, she wants to minimize the number of times she has to hand Jasio a toy from the shelf. Keeping that in mind, she has to put the toys off on the shelf extremely thoughtfully.

Write a programme that:

  • reads from the standard input the sequence of toy cars in order in which Jasio will want to play with them,
  • calculates the minimal number of times the mother has to pick cars from the shelf,
  • writes the result to the standard output.

Input

In the first line of the standard input there are three integers: n, k, p (1 <= k <= n <= 100,000, 1 <= p <= 500,000), separated by single spaces. These denote respectively: the total number of cars, the number of cars that can remain on the floor at once and the length of the sequence of cars which Jasio will want to play with. Each of the following p lines contains one integer. These integers are the numbers of cars Jasio will want to play with (the cars are numbered from 1 to n ). 

Output

In the first line of the standard output one integer should be written - the minimal number of times his mother has to pick a car from the shelf.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1005 - How Many Trees?   

Description

A binary search tree is a binary tree with root k such that any node v in the left subtree of k has label (v) <label (k) and any node w in the right subtree of k has label (w) > label (k).

When using binary search trees, one can easily look for a node with a given label x: After we compare x to the label of the root, either we found the node we seek or we know which subtree it is in. For most binary search trees the average time to find one of its n nodes in this way is O(log n).

Given a number n, can you tell how many different binary search trees may be constructed with a set of numbers of size n such that each element of the set will be associated to the label of exactly one node in a binary search tree?

Input

The input will contain a number 1 <= i <= 1000 per line representing the number of elements of the set.

Output

You have to print a line in the output for each entry with the answer mod 32767 to the previous question.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1006 - The Disks   

Description

For his birthday present little Johnny has recieved from his parents a new plaything which consists of a tube and a set of disks. The aforementioned tube is of unusual shape. Namely, it is made of a certain number of cylinders (of equal height) with apertures of different diameters carved coaxially through them. The tube is closed at the bottom, open at the top. An exemplary tube consisting of cylinders whose apertures have the diameters: 5cm, 6cm, 4cm, 3cm, 6cm, 2cm and 3cm is presented in the image bellow.

includegraphics{kra1}% WIDTH=277 HEIGHT=162

The disks in Johnny's plaything are cylinders of different diameters and height equal to those forming the tube.

Johnny has invented a following game: having a certain set of disks at his disposal, he seeks to find what depth the last of them would stop at, assuming that they are being thrown into the centre of the tube. If, for instance, we were to throw disks of consecutive diamaters: 3cm, 2cm and 5cm, we would obtain the following situation:

includegraphics{kra2}% WIDTH=277 HEIGHT=162

As you can see, upon being thrown in, every disk falls until it gets stuck (which means that it lies atop a cylinder, aperture of which has a diameter smaller than the diameter of the disk) or it is stopped by an obstacle: the bottom of the tube or another disk, which has already stopped.

The game being difficult, Johnny constantly asks his parents for help. As Johnny's parents do not like such intelectual games, they have asked you - an acquaintance of theirs and a programmer - to write a programme which will provide them with answers to Johnny's questions.

Write a programme which:

  • reads the description of the tube and the disks which Johnny will throw into it from the standard input,
  • computes the depth which the last disk thrown by Johnny stops at,
  • writes the outcome to the standard output.

Input

The first line of the standard input contains two integers n and m ( 1$ le$% WIDTH=16 HEIGHT=30 n, m$ le$% WIDTH=16 HEIGHT=30 300 000) separated by a single space and denoting the height of Johnny's tube (the number of cylinders it comprises) and the number of disks Johnny intends to throw into it, respectively. The second line of the standard input contains n integers r1, r2,...,rn ( 1$ le$% WIDTH=16 HEIGHT=30 ri$ le$% WIDTH=16 HEIGHT=30 1 000 000 000 for 1$ le$% WIDTH=16 HEIGHT=30 i $ le$% WIDTH=16 HEIGHT=30 n) separated by single spaces and denoting the diameters of the apertures carved through the consecutive cylinders (in top-down order), which the tube consists of. The third line contains m integers k1, k2,..., km ( 1$ le$% WIDTH=16 HEIGHT=30 kj$ le$% WIDTH=16 HEIGHT=30 1 000 000 000 for 1$ le$% WIDTH=16 HEIGHT=30 j $ le$% WIDTH=16 HEIGHT=30 m) separated by single spaces and denoting the diameters of consecutive disks which Johnny intends to throw into the tube.

Output

The first and only line of the standard output should contain a single integer denoting the depth which the last disk stops at. Should the disk not fall into the tube at all, the answer should be 0.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1007 - Convex hull   

Description

Given N points, find the convex hull

 

 

 

 

 

 

 

 

 

.

Input

Each testcase starts with 3<= N <= 10^6, which represents the number of points. Following N lines describe N points x, y-coordinate, where |x|, |y| <= 1000, and x, y are intergers. Input file ends up with a single 0.

There are no such cases that one line can pass through every point.

Output

Each testcase contains two lines.

Frist line prints Case #: , where # is the number of testcases.

Second line output the index of the points in counterclockwise order(index is the order of input, and the first point has index "1"). Start from the leftmost point, or the lowest one in case of a tie.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1008 - Tester   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1009 - Dropping Balls   

Description

A number of K balls are dropped one by one from the root of a fully binary tree structure FBT. Each time the ball being dropped first visits a non-terminal node. It then keeps moving down, either follows the path of the left subtree, or follows the path of the right subtree, until it stops at one of the leaf nodes of FBT. To determine a ball's moving direction a flag is set up in every non-terminal node with two values, either false or true. Initially, all of the flags are false. When visiting a non-terminal node if the flag's current value at this node is false, then the ball will first switch this flag's value, i.e., from the false to the true, and then follow the left subtree of this node to keep moving down. Otherwise, it will also switch this flag's value, i.e., from the true to the false, but will follow the right subtree of this node to keep moving down. Furthermore, all nodes of FBT are sequentially numbered, starting at 1 with nodes on depth 1, and then those on depth 2, and so on. Nodes on any depth are numbered from left to right.



For example, Fig. 1 represents a fully binary tree of maximum depth 4 with the node numbers 1, 2, 3, ..., 15. Since all of the flags are initially set to be false, the first ball being dropped will switch flag's values at node 1, node 2, and node 4 before it finally stops at position 8. The second ball being dropped will switch flag's values at node 1, node 3, and node 6, and stop at position 12. Obviously, the third ball being dropped will switch flag's values at node 1, node 2, and node 5 before it stops at position 10.



Fig. 1: An example of FBT with the maximum depth 4 and sequential node numbers.


Now consider a number of test cases where two values will be given for each test. The first value is D, the maximum depth of FBT, and the second one is I, the Ith ball being dropped. You may assume the value of I will not exceed the total number of leaf nodes for the given FBT.

Please write a program to determine the stop position P for each test case.


For each test cases the range of two parameters D and I is as below:

Input

Contains l+2 lines.

Line 1 I the number of test cases
Line 2 D1 I1
test case #1, two decimal numbers that are separatedby one blank
...
Line k+1 Dk Ik
test case #k
Line l+1 Dl Il
test case #l
Line l+2 -1 a constant -1 representing the end of the input file

Output

Contains l lines.

Line 1 the stop position P for the test case #1
...
Line k the stop position P for the test case #k
...
Line l the stop position P for the test case #l

Sample Input  Download

Sample Output  Download

Tags




Discuss




1010 - The Stern-Brocot Number System   

Description


Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1011 - Number Sequence   

Description

A single positive integer i is given. Write a program to find the digit located in the position i in the sequence of number groups S1S2…Sk. Each group Sk consists of a sequence of positive integer numbers ranging from 1 to k, written one after another. For example, the first 80 digits of the sequence are as follows:
11212312341234512345612345671234567812345678912345678910123456789101112345678910

Input

The first line of the input file contains a single integer t (1 <=t <=25), the number of test cases, followed by one line for each test case. The line for a test case contains the single integer i (1 <=i <=2147483647)

Output

There should be one output line per test case containing the digit located in the position i.

Sample Input  Download

Sample Output  Download

Tags

test



Discuss




1012 - ICPC Team Strategy   

Description

ICPC (International Collegiate Programming Contest), as you might know, is a team programming contest for college students. Each team consists of exactly three students and they will work on a number of programming problems.

Andi, Budi and Chandra plan to participate in this year ICPC as a team. As for their team strategy, they come up with a simple one:

In the first 20 minutes of 5 hours contest, they will read through all problems. Then each of them will assign a number to each problem. This number indicates how many minute(s) it will take for him to get the problem accepted (correct solution). Then they will start to code, meaning that they only have 280 minutes to really work on the problems. You may assume that they always get accepted on time whenever they work on a problem.
There's only one computer for each team, so it's not possible for them to code two different problems simultaneously.
To avoid any brain fatigue and adrenaline rush (because they attend competitions so frequently), they decided to switch role after each problem, such that none of them will work at the computer for more than one problem consecutively.
They want to solve as many problems as they can. The order of problem to be solved does not matter.

Input

The first line of input contains an integer T , number of test cases to follow. Each case begins with an integer N (1N12) in one line, denoting the number of problems. The second line contains N integers, A1..N (1Ai300) , denoting the total time (in minutes) needed by Andi to solve ith problem. The third and fourth line will correspond to the total time needed by Budi and Chandra respectively and will have the same input format as the second line.

Output


For each case, print in a single line containing the maximum total number of problem that can be solved by that team.


Explanation for 1st sample case:

Actually Andi could solve all the three problems alone, but the team has decided that none of them should work at the computer for more than one problem consecutively.


Explanation for 2nd sample case:

The team can solve all the problems. Here is one solution:

Let Budi work on Problem-2 (100 minutes).
Switch to Andi and let him work on Problem-1 (50 minutes).
Switch to Budi again and let him work on Problem-3 (30 minutes).
Finally, switch to Chandra and let him work on Problem-4 which (100 minutes).
Overall, they need 100 + 50 + 30 + 100 = 280 minutes.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1013 - Message   

Description

Astronomers have been looking for living beings in the outer planets. Recently the Hobble telescope has picked up binary (black and white) images from the Zkrets planet (1 light-years away). Each image contains exactly one symbol. Together the sequence of symbols (images) represents a message for aliens from other planets. A team of deciphering experts has found some decoding scheme that assigns an English alphabet to each symbol. The decoding process would be easy if each received image were in perfect condition. Unfortunately, due to long distance transmission, the images received usually contain some noise, meaning that some white pixels are turned into black pixels and vise versa. Furthermore, due to self-rotation of the Hobble telescope, the images, when captured, might be rotated 0, 90, 180 or 270 degrees. To expedite the message decoding process, please write a program to decode the received sequence of images automatically.


Technical Specification

The number of images received is n, where 1n100 . The size of the image is always scaled to 10×10 . Within the image, `1' represents a black pixel (part of the symbol) and `0' represents a white pixel (not part of the symbol).
Each received image may contain at most 20% noise. This means that at most 20 pixels may have their gray levels changed (from black to white or from white to black) during transmission. Each image is rotated 0, 90, 180 or 270 degrees in clockwise direction.
The number of matching symbols and English Alphabets is m , where 1m52 . The matching English Alphabets can be either upper-case or lower-case letters.

Input

There are two parts of input, one follows the other. For the first part, it contains the matching English alphabets and image symbols. Thus, the first line contains an integer m , the number of matching alphabets and symbols. The next 11m lines define the m sets of matching alphabets and symbols. The first line of each set contains a single unique English letter. The next 10 lines give the matching symbol in a perfect (no noise, no rotation) 10×10 image of 0's and 1's. For the second part, it contains a sequence of received images. The first line contains an integer n , the number of 10×10 images received. The next 10n lines present the n images received. Every 10 lines define one image. Each line contains exactly 10 consecutive 0's and 1's.

Output

Please print out the corresponding English letters of the received input images in sequence, all on one line. If more than one match is possible for a given input image, output the matching one with the least number of noise pixels. If there is still a tie, output the one that appears first in the input sequence of English alphabets.

Explanations for the Sample:

There are 2 deciphered matching codes.
The first is coded as letter a. The corresponding image is giving in 10 rows of consecutive 0's and 1's.

The second image is coded as letter X. The corresponding image is giving in 10 rows of consecutive 0's and 1's.

There are 3 received images waiting to be decoded.
The first received image has 10 rows of consecutive 0's and 1's. It matches with the corresponding image of the coded symbol 'X' perfectly without any noise. The image is either not rotated or perhaps rotated by 180 degrees.

The second image has also 10 rows of consecutive 0's and 1's. It also matches with the corresponding image of the coded symbol 'X' perfectly without any noise. However, the image is either rotated by 90 or 270 degrees.

The third image has also 10 rows of consecutive 0's and 1's. It contains 12 noise pixels. The image is also rotated by 90 degrees. It matches with the corresponding image of the coded symbol 'a'.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1014 - A+B   

Description

Given two integers A and B that are not necessarily in base-10, find the smallest possible A + B in base-10.

For example,

A = 213, possibly base-4 (39 in base-10)
B = 4721, possibly base-8 (2513 in base-10)
A + B = 39 + 2513 = 2552

Input

First line of the input contains a positive integer T (1 <= T <= 100), the number of cases. Each case contains two positive integers A and B. A and B will contain at most 5 digits, each digit will be between 0 and 9, inclusive, and no leading zeroes.

Output

For each case, output an integer in base-10 denoting the smallest possible A + B.

Sample Input  Download

Sample Output  Download

Tags

error



Discuss




1015 - May the Right Force with you   

Description

In a sensational scene in the 8-th installment of the Voldemort book series, the robot Weighd was attacked and its rotating top and wings were severely damaged. Weighd cannot rotate its famous top and can only fly forward or make a right-turn. However, the brave Weighd must still navigate a magically created series of mazes to deliver its precious message to Ttoper.

Weighd enters each maze at the top-left square of the maze, takes one unit of time to travel between adjacent squares in the magic maze (forward or right), and cannot stay in one square to rotate itself, and thus change direction, for fear of evil jinx. Your task is to write a program to calculate the smallest number of squares that Weighd must travel to reach a certain square in each maze. Do not you worry about how? Weighd will feel its correct way through the force. Examples are:



Weighd can reach the location marked ``X" of the top maze in ``19" steps, but it cannot reach the marked location in the bottom maze at all.

Input

Input consists of multiple mazes. Each maze description starts with two integers, on a separate line, that represent its dimensions. The first integer N (1<=1000) represents the number of rows and the second M (1<=1000) represents the number of columns. The last maze is followed by a line containing two zeros that indicate the end of the input data and should not be processed as a valid situation.

The second line contains two integers, C (1<=N) and R (1<=M), that represent the column number and the row number of the square where Weighd must reach in the maze. Consecutive integers are separated by a blank space.

Each of the following N lines contains a sequence of 0s and 1s. The sequence is M characters long. The sequence does not contains blank spaces. A value one (1) represents a wall in the maze (that is, a square into which Weighd cannot fly).

Output

Output consists of one line for each maze. It will be in one of the following two formats:

1. an integer that represents the number of steps to be taken, inside the maze, by Weighd to reach its destination.
2. The string ``NOOO!", if no path can be found.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1016 - Sum of Different Primes   

Description

A positive integer may be expressed as a sum of different prime numbers (primes), in one way or another. Given two positive integers n and k, you should count the number of ways to express n as a sum of k different primes. Here, two ways are considered to be the same if they sum up the same set of the primes. For example, 8 can be expressed as 3 + 5 and 5 + 3 but they are not distinguished.

When n and k are 24 and 3 respectively, the answer is two because there are two sets {2, 3, 19} and {2, 5, 17} whose sums are equal to 24. There are no other sets of three primes that sum up to 24. For n = 24 and k = 2, the answer is three, because there are three sets {5, 19}, {7, 17} and {11, 13}. For n = 2 and k = 1, the answer is one, because there is only one set {2} whose sum is 2. For n = 1 and k = 1, the answer is zero. As 1 is not a prime, you shouldn't count {1}. For n = 4 and k = 2, the answer is zero, because there are no sets of two different primes whose sums are 4.

Your job is to write a program that reports the number of such ways for the given n and k.

Input

The input is a sequence of datasets followed by a line containing two zeros separated by a space. A dataset is a line containing two positive integers n and k separated by a space. You may assume that n<=1120 and k<=14.

Output

The output should be composed of lines, each corresponding to an input dataset. An output line should contain one non-negative integer indicating the number of ways for n and k specified in the corresponding dataset. You may assume that it is less than 231.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1017 - Wavio Sequence   

Description

Wavio is a sequence of integers. It has some interesting properties.
· Wavio is of odd length i.e. L = 2*n + 1.
· The first (n+1) integers of Wavio sequence makes a strictly increasing sequence.
· The last (n+1) integers of Wavio sequence makes a strictly decreasing sequence.
· No two adjacent integers are same in a Wavio sequence.
For example 1, 2, 3, 4, 5, 4, 3, 2, 0 is an Wavio sequence of length 9. But 1, 2, 3, 4, 5, 4, 3, 2, 2 is not a valid wavio sequence. In this problem, you will be given a sequence of integers. You have to find out the length of the longest Wavio sequence which is a subsequence of the given sequence. Consider, the given sequence as :

1 2 3 2 1 2 3 4 3 2 1 5 4 1 2 3 2 2 1.

Here the longest Wavio sequence is : 1 2 3 4 5 4 3 2 1. So, the output will be 9.

Input

The input file contains less than 75 test cases. The description of each test case is given below: Input is terminated by end of file.

Each set starts with a postive integer, N(1<=N<=10000). In next few lines there will be N integers.

Output

For each set of input print the length of longest wavio sequence in a line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1018 - Wedding Shopping   

Description

One of our best friends is getting married and we all are nervous because he is the first of us who is doing something similar. In fact, we have never assisted to a wedding, so we have no clothes or accessories, and to solve the problem we are going to a famous department store of our city to buy all we need: a shirt, a belt, some shoes, a tie, etcetera.

We are offered different models for each class of garment (for example, three shirts, two belts, four shoes, ..). We have to buy one model of each class of garment, and just one.

As our budget is limited, we cannot spend more money than it, but we want to spend the maximum possible. It's possible that we cannot buy one model of each class of garment due to the short amount of money we have.

Input

The first line of the input contains an integer, N, indicating the number of test cases. For each test case, some lines appear, the first one contains two integers, M and C, separated by blanks (1<=M<=200, and 1<=C<=20), where M is the available amount of money and C is the number of garments you have to buy. Following this line, there are C lines, each one with some integers separated by blanks; in each of these lines the first integer, K (1<=K<=20), indicates the number of different models for each garment and it is followed by K integers indicating the price of each model of that garment.

Output

For each test case, the output should consist of one integer indicating the maximum amount of money necessary to buy one element of each garment without exceeding the initial amount of money. If there is no solution, you must print "no solution".

Sample Input  Download

Sample Output  Download

Tags




Discuss




1019 - Cutting Sticks   

Description

You have to cut a wood stick into pieces. The most affordable company, The Analog Cutting Machinery, Inc. (ACM), charges money according to the length of the stick being cut. Their procedure of work requires that they only make one cut at a time.
It is easy to notice that different selections in the order of cutting can led to different prices. For example, consider a stick of length 10 meters that has to be cut at 2, 4 and 7 meters from one end. There are several choices. One can be cutting first at 2, then at 4, then at 7. This leads to a price of 10 + 8 + 6 = 24 because the first stick was of 10 meters, the resulting of 8 and the last one of 6. Another choice could be cutting at 4, then at 2, then at 7. This would lead to a price of 10 + 4 + 6 = 20, which is a better price.

Your boss trusts your computer abilities to find out the minimum cost for cutting a given stick.

Input

The input will consist of several input cases. The first line of each test case will contain a positive number l that represents the length of the stick to be cut. You can assume l < 1000. The next line will contain the number n (n < 50) of cuts to be made.
The next line consists of n positive numbers ci ( 0 < ci < l) representing the places where the cuts have to be done, given in strictly increasing order.

An input case with l = 0 will represent the end of the input.

Output

You have to print the cost of the optimal solution of the cutting problem, that is the minimum cost of cutting the given stick. Format the output as shown below.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1020 - Membership Management   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1021 - Balloon Collecting   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1022 - Towns along a Highway   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1023 - Awkward Lights   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1024 - The Two Men of the Japanese Alps   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1025 - Find the Multiples   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1026 - Test Case Tweaking   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1027 - Where's Wally   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1028 - Intersection of Two Prisms   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1029 - Matrix Calculator   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1030 - Maximum Sum (II)   

Description

In a given a sequence of non-negative integers you will have to find such a sub-sequence in it whose summation is maximum.


Input

The input file contains several input sets. The description of each set is given below:
Each set starts with an integer N (N<1000) that indicates how many numbers are in that set. Each of the next N lines contains a single non-negative integer. All these numbers are less than 10000.
Input is terminated by a set where N=0. This set should not be processed.


Output

For each set of input produce one line of output. This line contains one or more integers which is are taken from the input sequence and whose summation is maximum. If there is more than one such sub-sequence print the one that has minimum length. If there is more than one sub-sequence of minimum length, output the one that occurs first in the given sequence of numbers. A valid sub-sequence must have a single number in it. Two consecutive numbers in the output are separated by a single space.


Sample Input  Download

Sample Output  Download

Tags




Discuss




1031 - sqrt log sin   

Description

An evil professor has just assigned you the following problem.
A sequence is defined by the following recurrence:


Determine x1000000.


Input

Input consists of a number of lines, each containing one integer, a value of i, no less than zero and no greater than one million. Input is followed by a single line containing the integer -1. This last line is not a value of i and should not be processed.

Output

For each value of i in the input (but not the final -1), output the corresponding value of xi modulo 1000000.

Sample Input  Download

Sample Output  Download

Tags

1 121515



Discuss




1032 - Lotto   

Description

In the German Lotto you have to select 6 numbers from the set {1,2,...,49}.
A popular strategy to play Lotto - although it doesn't increase your chance of winning - is to select a subset S containing k (k>6) of these 49 numbers, and then play several games with choosing numbers only from S.
For example, for k=8 and S = 1,2,3,5,8,13,21,34 there are 28 possible games: [1,2,3,5,8,13], [1,2,3,5,8,21], [1,2,3,5,8,34], [1,2,3,5,13,21], ..., [3,5,8,13,21,34].
Your job is to write a program that reads in the number k and the set S and then prints all possible games choosing numbers only from S.


Input

The input file will contain one or more test cases.
Each test case consists of one line containing several integers separated from each other by spaces. The first integer on the line will be the number k (6 < k < 13). Then k integers, specifying the set S, will follow in ascending order.
Input will be terminated by a value of zero (0) for k.


Output

For each test case, print all possible games, each game on one line.
The numbers of each game have to be sorted in ascending order and separated from each other by exactly one space. The games themselves have to be sorted lexicographically, that means sorted by the lowest number first, then by the second lowest and so on, as demonstrated in the sample output below.
The test cases have to be separated from each other by exactly one blank line. Do not put a blank line after the last test case.


Sample Input  Download

Sample Output  Download

Tags




Discuss




1033 - What goes up?   

Description

Write a program that will select the longest strictly increasing subsequence from a sequence of integers.


Input

The input file will contain a sequence of integers (positive, negative, and/or zero). Each line of the input file will contain one integer.


Output

The output for this program will be a line indicating the length of the longest subsequence, a newline, a dash character ('-'), a newline, and then the subsequence itself printed with one integer per line. If the input contains more than one longest subsequence, the output file should print the one that occurs last in the input file.
Notice that the second 8 was not included -- the subsequence must be strictly increasing.


Sample Input  Download

Sample Output  Download

Tags




Discuss




1034 - Products   

Description

The problem is to multiply two integers X, Y. (0<=X,Y<10250)


Input

The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.


Output

For each input pair of lines the output line should consist one integer the product.


Sample Input  Download

Sample Output  Download

Tags




Discuss




1035 - Daily Meals   

Description

  Farmer Jiang has n (1 n ≤ 200) cows. He loves the cows so much that for every single cow he prepares a huge “food court” – actually it’s an area fulfilled with foods and drinks. There are exactly n food courts, with distinct themes.

Everyday Farmer Jiang takes his cows to the food courts and put exactly one cow in one food court. He knows that some cows is favoring with some specific food court. He does not want to see cows feeling sad, so he decided only taking the cows into one of their favored food courts.

In how many ways that Farmer Jiang can let his cows pick favored food court and each food court is having at most one cow? Farmer Jiang knows that there are always less than 200,000 possible configurations in total.


Input

 The file begins with an integer T (T ≤ 25) indicating the number of test cases follows. For each test case, first line contains two integers n, m (1 ≤ n ≤ 200, 1 ≤ mn^2). Each of the next m lines contains 2 integers u, v (1 ≤ u, v ≤ n) means that u-th cow loves v-th food court. You may assume each (u, v) pair in a single test case never occurs more than once. There may be white spaces and empty lines everywhere in the input file.

 

Output

For each test case, please output “Case #x:” with x being the case number starting from 1 and output the number of total ways.

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1036 - Vigenère cipher   

Description

  There was an ancient encryption method called ‘Vigenère cipher’. The one who wants to read a message encrypted need a secret word, the key to the plaintext. The encryption method is shown below. Your task is to write a program that can decode a set of characters into a valid string. Of course, keys are given.


Let   A=0, B=1, C=2 … Z=25, add operation of two character is to convert each of them into numbers. The sum of two characters is the sum of two numbers modulo 26 and converts it back to character.


Ex: T=19   S=18

T+S = 19+18(mod 26) = 11 = L


Vigenère cipher involves adding the plaintext to a letter of duplicated key. For Example,


Plaintext:   this is a test message

Key:  sesame

Input

There are several test cases.

 

The first line of each case is a string, key. All keys are in capital alphabet set ‘A’ – ‘Z’.

 

The second line to the end of each test case is cipher-text you should decode.

Each test case is separated by a single ‘#’ symbol in a line.

You have to do nothing to the words without capital alphabet set ‘A’ – ‘Z’, in another words, ignore those symbol not in the set.


Output

For each test, output several lines of plaintext. Each case is separated by a blank line.

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1037 - Gray Code   

Description

  Gray Code is a binary numeral system where two successive values differ in only one bit. The n-bit-width gray code is the sequence consisting of numbers between 0 and 2^n-1. 


For example, 2-bit-width gray code is the sequence of {00, 01, 11, 10}. 3-bit-width gray code is the sequence of {000, 001, 011, 010, 110, 111, 101, 100}.


Now, we want you to construct the n-bit-width gray code by using the following algorithm.


  1. If n = 1, Return {0,1}
  2. Let S1 be the sequence of Gray(n-1).
  3. Let S2 be the reverse of S1.
  4. Add “0” to the head of every element in S1.
  5. Add “1” to the head of every element in S2.
  6. Return S1 + S2

Input

The input includes multiple test cases. 

 

In each test case, the first line contains one integer n

1 ≤ n ≤ 11

Output

The multiply lines contains 2^n integers, which indicate the n-bit-width gray code.

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1038 - The Price of Houses I   

Description

  The king of the Sky-Dragon Kingdom likes the trading of houses. If there are some houses on sell, he buys the houses and sells them at high price. If there are no houses on sell, he will buy some land to build houses and then sell all them.

One day, the king wants to do something interesting. Since he loves the business transaction between houses so much, he decides to hold a big business that all people in the kingdom to trade their houses between each other.

There are N people in the kingdom, all they have his own house. There are K types of house, and the type of the each N houses is one of them.

In order to make sure that the big trading business is going on well, the kings make the price of each type of house. All the price of the N houses should comply with the rule of the king. After making the prices, the king will first buy all the N houses and sell them to the N people with the same price.

To avoid people unhappy, the N people give their preference list of the types of house. And the king wants to make prices of each type of house such that all N people each can buy a house and all houses are sold. And for each people, the type of the house he buys is in his preference list and it's the favorite type in the types whose price is no more than his originally own house. That is, after obtaining the money by selling his house, he buys the house of favorite type in all the types he can pay with the money.

Please write a program to help the king that gives the type of house each N people own, and their preference list, tell the king if it's possible to make a price of each type of house?

Input

The first line of the input file contains an integer T (T 20) indicating the number of

test cases. For each test case, the first line contains two integers N and K (1N,K30000), the number of people and number of types. The types are numbered from 1 to K. In the i-th line of following N lines, the first integer is the type of his own house of i-th people, the second integer mi (1mi  50) is the length of his preference list and following mi integer are the types of his list start from the favorite one in order.


Output

For each test case, output 'Y' if it's possible to make a price for each type in a

single line. Otherwise output 'N'.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1039 - Robot Lab   

Description

Robot Lab is a lab filled with a lot of NPCs. In the lab, there is more devices needed power. Therefore, there is two power supply lines x=0 and y=0.

You need to buy some horizontal or vertical cables to connect these devices to one of the power supply lines. But you can't connect two cables. It means you should connect the devices to the power supply line "directly" with the cable. What is the minimum length of the total cables you buy? To simplify the problem, we guarantee every two devices must be at different x-coordinate and different y-coordinate.


Input

The input includes multiple test cases. 

In each test case, the first line contains one integer n

In the next n lines, every line contains two integers xi, yi.

1 ≤ n ≤ 100

-10000 ≤ xi, yi ≤ 10000


Output

The one line contains one integer, which indicates the minimum value of the sum.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1040 - Tetris Battle   

Description

 

Tetris Battle is a hot and funny game on the pastedGraphic.pdf that you can train your skill and challenge your friend. 

At the last of the story, you will receive the name that “God of Tetris” and everybody’s respecting. But this problem is not about Tetris Battle. 

We will talk the other funny game, “Step Mania”!

pastedGraphic_1.pdf

Step Mania” is an engine of the music game.

For each meter, there is four floating up arrows, and we can use keyboard to “hit” it on fixed positions. And there is a system for rewarding, we called “Combo” if you hit arrows in continued meter and get extra score.

NOW there is a new “Step Mania EX” had at most 10 arrows you should hit for each meter.(It’s OK because the keyboard has 108 keys and you have ten fingers.)

You are an extreme player of the “Step Mania” and you can hit every arrow in every meter!

But your keyboard is so bad that is unlike your skill, it cannot detect the continued hits on same key.

Now there is a score for a song in “Step Mania EX”, what score you will have?


PS1. You have gotten one point if you hit an arrow and (#theNumberOfCombo-1) for bonus.

PS2. If the computer does not detect any arrow in a meter, the number of combo will be reset.

PS3. Though you will get higher score if you do not hit some arrow, you still hit EVERY arrow  because the spirit of “Step Mania” tell you not to do it!

PS4. At fact, it not yet sells.

PS5. You can buy the keyboard called “RealForce” and you can win the game easily though it’s  very expensive.


HINT: Each arrow hiting will have its bonus score.

For sample data,

you will get score as following:

1 0 0 1

0 2 2 0

0 X 0 1

1 X 1 0

 

HINT2:

If there a meter contains no arrow, you will not hit any key and the number of combos will be same such that it can be higher when you have a nice hiting in next meter.

 

Input

 There is multiple dataset, for each data:

The first line contains two integers n, m , which mean the number of meters and the number of the arrow type. (0 < n ≤ 105, 0 < m ≤ 10)

The line 2 to the line n+1, each line has m numbers split by space means the arrows if the number is 1.


Output

Print out a line contains the number of the score for each dataset.


 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1041 - Fibonacci Numbers   

Description

Don’t worry. It’s just a very simple problem. See the recursive function below.


pastedGraphic.pdf


The only thing you should do is to showpastedGraphic_1.pdfand nothing else. Easy, right?

 

Input

 

There are several test cases. Each line contains one integer, n

pastedGraphic.pdf

Output

 For each test, output a line containing a single,pastedGraphic.pdf (modulo 100000007).


Sample Input  Download

Sample Output  Download

Tags




Discuss




1042 - Painter Jobz   

Description

Jobz is a special kid. He likes painting. One day, he paints a lot of segments in 1-D line with many color pens. In every round, he will choose one color c and one integer interval [xi, yi]. Then he draws the interval with the color. Now, we know what he did in every round. And we want to know the final result what 1-D line looks like. Please write a program to solve the problem.


Input

The input contains multiple test cases. The first line contains one integer n. In the next n lines, every line contains three integers ci, xi and yi. It represents he draw the interval [xi, yi] with the color ci in the i-th round.

n ≤ 100000

0 ≤ xi < yi ≤ 200000

ci is a 32-bit signed integer.

Output

Output every maximum-length intervals with the same color.

Sort them by the increasing order of the xi value.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1043 - IMMVP   

Description

  The Evil Terran, Dreamoon Zero, is going to attack our planet!

As a smart cerebrate, you have dispatched the scouts for discover the status of the enemies. You discovered that the force of enemies are all small vanguards composed by “marine”, so the best way to bear them up is using the “baneling landmine”!

“Baneling” can see as a remote-controlled bomb, it can kill the enemies who are in the range of two blocks from the boom.

You propose to kill all Dreamoon’s vanguards by “baneling”, then Dreamoon probably cannot dispatch new troop to attack such that you can discuss the plan to defeat Dreamoon with other cerebrates.

Of course, you hope use the least “baneling” to ***** the goal.


Input

There are multiple test data, for each test data:

The first line contains two integer, H and W. (1 ≤ H, W ≤ 50 )

The following H lines, each line contains W characters, are meaning that the lineup of the enemies, “m” means “Marine” and “.” means nothing.

The next line contains a integer H’ (1 ≤ H’ ≤ 50) that you can have H’ x W sized place to put “Baneling”.

And the following H’ lines, each line contains W characters, are meaning that your place, ‘X’ means that the soil is too hard to put “Baneling” and “.” means you can put “Baneling” completely.

The enemies will move forward(v) by the speed of 1 block/second, you can control the time of the explosion of each baneling freely.

A block can put more than 1 “Baneling” and the explosion will not effect on other “Baneling”.

By the way, there are at most twenty marines.


Output

For each test case, output a line contains a integer that the minimum number of “Baneling” to kill all the enemies. If we cannot do it, please output “impossible”(Do need output the symbol of the double quote.)

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1044 - Doraemon Hon’s Chessboard   

Description

  Some day, Doraemon Hon sends you a new problem as homework. He designs an n*n chessboard and every grid is one of three states. States are “empty”, “star”, and “broken”. You can put the balls on the grids, whose state is “empty” or “star”. The problem is to find the maximum value of the balls you can put on the chessboard. You are easy to solve the problem. 

 

So, Doraemon Hon adds two constraints. One is that the number of the balls on the row i should be equal to the number of the balls on the column i. Another one is that you must put the ball on the “star” grid.

 

 

To get the higher grade, you should solve the problem quickly.

 

 

If he designs an chessboard with no solutions, please output “impossible”.

 


Input

The input includes multiple test cases. In each test case, the first line contains one integer n. In the following n lines, every line contains n characters.

1 ≤ n ≤ 40

‘C’ means the “star” grid

‘/’ means the “broken” grid

‘.’ means the “empty” grid 


Output

The one line contains one integer, which indicates the maximum value.

 If he designs an chessboard with no solutions, please output “impossible”.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1045 - The Price of Houses II   

Description

  The king of the Sky-Dragon Kingdom likes the trading of houses. If there are some houses on sell, he buys the houses and sells them with high price. If there are no houses on sell, he will buy some land to build houses and then sell them.

One day, the king buys some houses and wants to sell some of them as a house set together. And he wants the price of this set as high as possible.

Each house has its profit pi and cost ci that if we add a house into our house set, the price of the set will increase pi and decrease ci. Moreover, for some pair of house i and j, if we pick one of them, but not another, that is, we sell them separately, the price of the set will decrease Si,j.
And for some personal interest of the king, some houses must be included in the set to sell. Please write a program to help the king that gives pi, ci, 1 ≤ iN of his N houses, and the costs S
i,j between some pair of houses. Please compute the highest price of a set of houses.

Input

  The first line of the input file contains an integer T (T ≤ 5) indicating the number of testcases. For each test case, the first line contains three integers N (1 ≤ N ≤ 200) and M, K (0 ≤ KN) represents the number of house, the number of pair that they have separation cost and the number of houses must be included in the set. Following N lines each has two positive integer

pi and ci (0 ≤ pi, ci ≤ 10000) . And next M lines each contains three integer i, j, Si,j (1 ≤ i, j ≤ N, 1 ≤ Si,j ≤ 10000) represent that there is a separation cost Si,j between house i and house j. Then there is one integer in each next K lines represent the number of houses must be included in the set.


Output

For each test case, output the highest price of a set of house. Output 0 if there are no set with positive price


Sample Input  Download

Sample Output  Download

Tags




Discuss




1046 - BnB   

Description

Here is a well-known game, ‘ 彈水阿給’(=瘋狂阿給=爆爆王). This is very similar to Bomber Man. The range of explosion of each water-ball is a cross shape on the map, and it will trigger any water-ball on the path of that cross.

 

Illustrated by following pictures:

 

pastedGraphic.pdf, pastedGraphic_1.pdf

 

Now you are in this intense “Rising Green Pepper Contest”, trying to play this exciting game. We redefined the rule as following:

0. You are playing on an N * M map. There’s no obstacles on that map, only several  placed water-balls.

1. Assume that every water-ball have infinite explosion range, that is to say, it would explode until the bound of the map.

2. The horizontal explosion of the water-ball will trigger water-balls on the same row, while doing no damage.

3. The vertical explosion of the water-ball will NOT trigger water-ball on the same column, while bringing damage.

 

Now things you are trying to do is:

0. Choose several water-balls to make them explode, and the number of choosing water-balls should be a minimum.

1. The total DAMAGE range should cover the whole map.

2. We want to be eco-friendly, so the DAMAGE range cannot be overlapped, or we would waste water.

 

Input

There are several testcases.

The first line of each testcases indicates N, M, which represents an N * M map.

Following will be N lines, each consists of M number(0 or 1), representing the state of the map. 0 means null, while 1 means water-ball.

1 <= N,M <= 100

Output

Print a positive integer, the minimum number of your choose.

If the goal cannot be achieved, print -1.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1047 - Ordering   

Description

Ordering

Background

Order is an important concept in mathematics and in computer science. For example, Zorns Lemma states: a partially ordered set in which every chain has an upper bound contains a maximal element. Order is also important in reasoning about the fix-point semantics of programs.
This problem involves neither Zorns Lemma nor fix-point semantics, but does involve order.

Problem

Given a list of variable constraints of the form A < B, you are to write a program that prints all orderings of the variables that are consistent with the constraints. For example, given the contraints A < B and A < C there are two orderings of the variables A, B and C that are consistent with these constraints: ABC and ACB.

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

The input consists of two lines: a list of variables on one line, followed by a list of constraints of the form A < B on the next line. Variables and contraints are separated by single spaces.
All variables are single character, upper-case letters. There will be at least two variables, and no more than 20 variables. There will be at least one constraint, and no more than 50 constraints. There will be no more than 300 orderings consistent with the contraints in a specification.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.

All orderings consistent with the constraints should be printed. Orderings are printed in alphabetical order, one per line. Characters on a line are separated by a space. If no ordering is possible, the output is a single line with the word NO.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1048 - The Sultan's Successors   

Description

The Sultan of Nubia has no children, so she has decided that the country will be split into up to k separate parts on her death and each part will be inherited by whoever performs best at some test. It is possible for any individual to inherit more than one or indeed all of the portions. To ensure that only highly intelligent people eventually become her successors, the Sultan has devised an ingenious test. In a large hall filled with the splash of fountains and the delicate scent of incense have been placed k chessboards. Each chessboard has numbers in the range 1 to 99 written on each square and is supplied with 8 jewelled chess queens. The task facing each potential successor is to place the 8 queens on the chess board in such a way that no queen threatens another one, and so that the numbers on the squares thus selected sum to a number at least as high as one already chosen by the Sultan. (For those unfamiliar with the rules of chess, this implies that each row and column of the board contains exactly one queen, and each diagonal contains no more than one.)

Write a program that will read in the number and details of the chessboards and determine the highest scores possible for each board under these conditions. (You know that the Sultan is both a good chess player and a good mathematician and you suspect that her score is the best attainable.)

Input

Input will consist of k (the number of boards), on a line by itself, followed by k sets of 64 numbers, each set consisting of eight lines of eight numbers. Each number will be a positive integer less than 100. There will never be more than 20 boards.

Output

Output will consist of k numbers consisting of your k scores, each score on a line by itself and right justified in a field 5 characters wide.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1049 - Virtual Friends   

Description

These days, you can do all sorts of things online. For example, you can use various websites to make virtual friends. For some people, growing their social network (their friends, their friends' friends, their friends' friends' friends, and so on), has become an addictive hobby. Just as some people collect stamps, other people collect virtual friends.

Your task is to observe the interactions on such a website and keep track of the size of each person's network.

Assume that every friendship is mutual. If Fred is Barney's friend, then Barney is also Fred's friend.

Input

The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing an integer F, the number of friendships formed, which is no more than 100 000. Each of the following F lines contains the names of two people who have just become friends, separated by a space. A name is a string of 1 to 20 letters (uppercase or lowercase).

Output

Whenever a friendship is formed, print a line containing one integer, the number of people in the social network of the two people who have just become friends.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1050 - Cashier Employment   

Description

A supermarket in Tehran is open 24 hours a day every day and needs a number of cashiers to fit its need. The supermarket manager has hired you to help him, solve his problem. The problem is that the supermarket needs different number of cashiers at different times of each day (for example, a few cashiers after midnight, and many in the afternoon) to provide good service to its customers, and he wants to hire the least number of cashiers for this job.

The manager has provided you with the least number of cashiers needed for every one-hour slot of the day. This data is given as R(0), R(1), ..., R(23): R(0) represents the least number of cashiers needed from midnight to 1:00 A.M., R(1) shows this number for duration of 1:00 A.M. to 2:00 A.M., and so on. Note that these numbers are the same every day. There are N qualified applicants for this job. Each applicant i works non-stop once each 24 hours in a shift of exactly 8 hours starting from a specified hour, say ti (0 <= ti <= 23), exactly from the start of the hour mentioned. That is, if the ith applicant is hired, he/she will work starting from ti o'clock sharp for 8 hours. Cashiers do not replace one another and work exactly as scheduled, and there are enough cash registers and counters for those who are hired.

You are to write a program to read the R(i) 's for i=0..23 and ti 's for i=1..N that are all, non-negative integer numbers and compute the least number of cashiers needed to be employed to meet the mentioned constraints. Note that there can be more cashiers than the least number needed for a specific slot.

Input

The first line of input is the number of test cases for this problem (at most 20). Each test case starts with 24 integer numbers representing the R(0), R(1), ..., R(23) in one line (R(i) can be at most 1000). Then there is N, number of applicants in another line (0 <= N <= 1000), after which come N lines each containing one ti (0 <= ti <= 23). There are no blank lines between test cases.

Output

For each test case, the output should be written in one line, which is the least number of cashiers needed.
If there is no solution for the test case, you should write No Solution for that case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1051 - Twin Primes   

Description

Twin primes are pairs of primes of the form (p, p+2). The term "twin prime" was coined by Paul Stäckel (1892-1919). The first few twin primes are (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43). In this problem you are asked to find out the S-th twin prime pair where S is an integer that will be given in the input.

Input

The input will contain less than 10001 lines of input. Each line contains an integers S (1<=S<=100000), which is the serial number of a twin prime pair. Input file is terminated by end of file.

Output

For each line of input you will have to produce one line of output which contains the S-th twin prime pair. The pair is printed in the form (p1,p2). Here means the space character (ASCII 32). You can safely assume that the primes in the 100000-th twin prime pair are less than 20000000.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1052 - Longest Paths   

Description

It is a well known fact that some people do not have their social abilities completely enabled. One example is the lack of talent for calculating distances and intervals of time. This causes some people to always choose the longest way to go from one place to another, with the consequence that they are late to whatever appointments they have, including weddings and programming contests. This can be highly annoying for their friends.

César has this kind of problem. When he has to go from one point to another he realizes that he has to visit many people, and thus always chooses the longest path. One of César's friends, Felipe, has understood the nature of the problem. Felipe thinks that with the help of a computer he might be able to calculate the time that César is going to need to arrive to his destination. That way he could spend his time in something more enjoyable than waiting for César.


Your goal is to help Felipe developing a program that computes the length of the longest path that can be constructed in a given graph from a given starting point (César's residence). You can assume that the graph has no cycles (there is no path from any node to itself), so César will reach his destination in a finite time. In the same line of reasoning, nodes are not considered directly connected to themselves.

Input

The input consists of a number of cases. The first line on each case contains a positive number n (1<=n<=100) that specifies the number of points that César might visit (i.e., the number of nodes in the graph).
A value of n = 0 indicates the end of the input.


After this, a second number s is provided, indicating the starting point in César's journey (1<=s<=n). Then, you are given a list of pairs of places p and q, one pair per line, with the places on each line separated by white-space. The pair ``p q" indicates that César can visit q after p.

A pair of zeros (``0 0") indicates the end of the case.


As mentioned before, you can assume that the graphs provided will not be cyclic.

Output

For each test case you have to find the length of the longest path that begins at the starting place. You also have to print the number of the final place of such longest path. If there are several paths of maximum length, print the final place with smallest number.

Print a new line after each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1053 - Dominos II   

Description

Dominos are lots of fun. Children like to stand the tiles on their side in long lines. When one domino falls, it knocks down the next one, which knocks down the one after that, all the way down the line. However, sometimes a domino fails to knock the next one down. In that case, we have to knock it down by hand to get the dominos falling again.
Given a set of dominos that are knocked down by hand, your task is to determine the total number of dominos that fall.

Input

The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing three integers n, m, l no larger than 10 000, followed by m+l additional lines. The first integer n is the number of domino tiles. The domino tiles are numbered from 1 to n. Each of the m lines after the first line contains two integers x and y indicating that if domino number x falls, it will cause domino number y to fall as well. Each of the following l lines contains a single integer z indicating that the domino numbered z is knocked over by hand.

Output

For each test case, output a line containing one integer, the total number of dominos that fall over.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1054 - Optimal Binary Search Tree   

Description

Given a set S = (e1, e2, ..., en) of n distinct elements such that e1 < e2 < ... < en and considering a binary search tree (see the previous problem) of the elements of S, it is desired that higher the query frequency of an element, closer will it be to the root.

The cost of accessing an element ei of S in a tree (cost(ei)) is equal to the number of edges in the path that connects the root with the node that contains the element. Given the query frequencies of the elements of S, (f(e1), f(e2, ..., f(en)), we say that the total cost of a tree is the following summation:

f(e1)*cost(e1) + f(e2)*cost(e2) + ... + f(en)*cost(en)

In this manner, the tree with the lowest total cost is the one with the best representation for searching elements of S. Because of this, it is called the Optimal Binary Search Tree.

Input

The input will contain several instances, one per line.

Each line will start with a number 1 <= n <= 250, indicating the size of S. Following n, in the same line, there will be n non-negative integers representing the query frequencies of the elements of S: f(e1), f(e2), ..., f(en). 0 <= f(ei) <= 100. Input is terminated by end of file.

Output

For each instance of the input, you must print a line in the output with the total cost of the Optimal Binary Search Tree.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1055 - Highways   

Description

The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has a very poor system of public highways. The Flatopian government is aware of this problem and has already constructed a number of highways connecting some of the most important towns. However, there are still some towns that you can't reach via a highway. It is necessary to build more highways so that it will be possible to drive between any pair of towns without leaving the highway system.

Flatopian towns are numbered from 1 to N and town i has a position given by the Cartesian coordinates (xi, yi). Each highway connects exaclty two towns. All highways (both the original ones and the ones that are to be built) follow straight lines, and thus their length is equal to Cartesian distance between towns. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways.

The Flatopian government wants to minimize the cost of building new highways. However, they want to guarantee that every town is highway-reachable from every other town. Since Flatopia is so flat, the cost of a highway is always proportional to its length. Thus, the least expensive highway system will be the one that minimizes the total highways length.

Input

The first line of the input consists of an integer indicating the number of test cases in the input. Then there's a blank line and the datasets separated by a blank line.

Each test case consists of two parts. The first part describes all towns in the country, and the second part describes all of the highways that have already been built.

The first line of the test case contains a single integer N (1 ≤ N ≤ 750), representing the number of towns. The next N lines each contain two integers, xi and yi separated by a space. These values give the coordinates of ith town (for i from 1 to N). Coordinates will have an absolute value no greater than 10000. Every town has a unique location.

The next line contains a single integer M (0 ≤ M ≤ 1000), representing the number of existing highways. The next M lines each contain a pair of integers separated by a space. These two integers give a pair of town numbers which are already connected by a highway. Each pair of towns is connected by at most one highway.

Output

Write to the output file a single line for each new highway that should be built in order to connect all towns with minimal possible total length of new highways. Each highway should be presented by printing town numbers that this highway connects, separated by a space.

If no new highways need to be built (all towns are already connected), then the output file should contain a line with the sentence "No new highways need".

Print a blank line between test cases.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1056 - Fire Drill   

Description

Joko is taking part in a fire drill which is held by the Jakarta Fire Department to recruit new firemen. The drill is about rescuing volunteers (who act as unconscious people) trapped in a building in a limited time. The building has several floors, and the volunteers are scattered throughout the building. Each volunteer has points assigned to her. The fireman candidate should rescue volunteers through carrying them to the exit. The candidate will earn the assigned points for each volunteer he rescued.

Each floor of a building can be seen as a grid of cells. Each cell can be an obstacle, an empty space, a stair or an entry/exit point.

A candidate starts at the entry point which exists only at one single cell of the first floor of the building. The candidate can move to any adjacent non-obstacle cells (north, south, west or east) or climb up or down a stair in 1 second. The movement slows down to 2 seconds when the candidate carries a volunteer. When a candidate finds a volunteer, he may decide to rescue her or not, but if he decides to rescue her, he has to carry her back to the exit without stopping. He can only carry at most one volunteer at a time.

Joko has the floor plan of the test building. Help him plan his moves, so he can get the highest possible score.

Input

The first line of input contains an integer T (T<=100) denoting the number of case. Each case has five integers L (1<=L<=10), H (1<=H<=100), W (1<=W<=100), N (1<=N<=100) and S (1<=S<=10, 000) denoting the number of floors, height and weight of each floor, the number of unconscious people, and the given time respectively.

The next L blocks describe the map of each floor from the 1st floor to the L-th floor respectively. Each floor consists of H lines each contains W characters. Characters that may appear in each floor are:

``S" : The starting point, also serves as the exit point. There will be only one starting/exit point and it will appear in the first floor.
``X" : Obstacle, cell that cannot be visited (wall, fire, etc.).
``U" : Stair that connect to the upper floor. There will be a ``D" character at the same place in the upper level. This character will not appear in the highest level of the building.
``D" : Stair that connect to the lower floor. There will be a ``U" character at the same place in the lower level. This character will not appear in the lowest level of the building.
``." : Empty space, cell that can be visited.

The next N lines each contains four integers fi (1<=fi<=L), ri (1<=ri<=H), ci (1<=ci<=W), pi (1<=pi<=1, 000) denoting the location of each volunteer (floor, row, column) and the point assigned to this volunteer respectively. You can assume that each volunteer will be located in empty space and no two volunteer occupy the same location.

Output

For each case, output in a line a single integer the highest point that he can earn by rescuing unconscious people within the given time.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1057 - OmniGravity   

Description

In this problem, we will play with four 2 x 2 squared pieces, an 8 x 8 board, few obstacles and gravity(!!!).


Initially the board contains few obstacles and the 4 colored pieces randomly placed. An example of an initial configuration is shown in the above diagram. The black squares represent the obstacles and the 4 colored pieces are shown with labels A, B, C and D - (in order to help the colorblind people). Initially there is no gravity and thus the pieces remain at a steady position. We can enable `gravity' in any of the four directions to move the pieces. The pieces move in the direction of gravity. A piece continues to move until it hits an edge of the board, an obstacle or any other piece. The obstacles aren't affected by gravity and so remains in their initial position at all times. We can enable at most one `gravity' at a time. The gravitational direction can only be changed when all the pieces are static.

 

The diagram above shows the positions of the pieces after the `gravity' from the right is enabled.

How many different static states can be reached by enabling at least one `gravity'? Two states are different if there is at least once cell that has a different color. A static state is one in which all the pieces are steady!

Input

The first line of input is an integer T (T<=100) that indicates the number of test cases. Each case consists of 8 lines with 8 characters in each line. Every character will be from the set {A, B, C, D, ., #}. Dots(.) represent empty spaces, hashes(#) represent obstacles and the alphabets represents the pieces. The frequencies of each letter (A,B,C,D) will be exactly 4 and each letter will occupy positions so that they form squares of size 2 x 2. There is a blank line before every case.

Output

For each case, output the case number followed by the number of different static states that can be reached from the original position by enabling at least one ``gravity".

Sample Input  Download

Sample Output  Download

Tags




Discuss




1058 - Visible Lattice   

Description

Consider a N * N * N lattice. One corner is at (0,0,0) and the opposite one is at (N, N, N). How many lattice points are visible from corner at (0,0,0)? A point X is visible from point Y iff no other lattice point lies on the segment joining X and Y.

Input

The first line contains the number of test cases T. The next T lines contain an interger N.


Constraints:
T<=100 1<=N<=100

Output

Output T lines, one corresponding to each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1059 - Chest of Drawers   

Description

A chest of drawers means a wardrobe which has many drawers aligned vertically as shown in the figure on the left. Although this is useful furniture, some problems arise when all the drawers need have provisions of locking - that is sometimes a drawer is not secured even if it is locked. For example assume that the third drawer from the top is locked but the drawer immediately above it is not locked. Then the drawer that is locked is also not secured because one can access it by pulling out the drawer immediately above it.

 

In a chest of n drawers, there are a number of ways to ensure that exactly s drawers are secure. For example for the chest of drawers shown on the left, exactly four drawers can be secured in six ways. These six ways are shown in Figure 2.

 

Given the value of n and s, your job is to find out in how many ways they can be secured.

 

 

 

 

 

 

 

Figure 2: In this figure L means that the drawer is locked and U means that the corresponding drawer is unlocked. And here all six locking combinations are shown which ensures that exactly four drawers are secured. Letters corresponding the secured drawers are boldfaced.


Input

The input file contains at most 5000 lines of inputs.

Each line contains two integers n and s (1 ≤ n ≤ 65 and 0 ≤ s ≤ 65). Here n is the total number of drawers and s is the number of drawers that needs to be secured.

Input is terminated by a line containing two negative numbers. This input should not be processed.

 

Output

For each line of input produce one line of output. This line contains an integer which denotes in how many, s drawers out of the n drawers can be secured.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1060 - Consecutive Sums   

Description

The sum of p (p>0) consecutive integers can often be equal to the sum of next q consecutive positive integers. For example:

9+10+11+12 = 13+14+15, Here p = 4 and q = 3

4+5+6+7+8 = 9+10+11, Here p = 5 and q = 3.

Given the value of q, how many possible values of p are there?

Input

The input file contains at most 1500 lines of inputs. Each line contains a positive integer less than 1014, which denotes the value of q. Input is terminated by a line containing a single zero. This line should not be processed.

Output

For each line of input produce one line of output. This line contains an integer, which denotes the total number of possible values of p.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1061 - Zones   

Description

Telephone poles are part of an outdated technology. Cell phones nowadays allow us to call whoever we want, wherever we want, independent of any wire. There is one problem - without a service tower nearby a cell phone is useless.


In the absence of hills and mountains, a service tower will provide coverage for a circular area. Instead of planning where to place the wires, a wireless telephone company has to plan where to build its service towers. Building the towers too far apart causes holes in the coverage and increases complaints. Building the towers too close to each other results in large areas covered by more than one service tower, which is redundant and inefficient.


International Cell Phone Company is developing a network strategy to determine the optimal placement of service towers. Since most customers have replaced their old wired home phones by cell phones, the strategy for planning service towers is therefore to cover as many homes of customers as possible.


The figure below shows the service areas for the five towers ICPC's strategic department planned to build this year. Tower 5 will serve 24 customers, 6 of which are also served by tower 4. Towers 1, 2 and 3 have a common service area containing 3 customers.



Shortly after the plans for these five towers had been published, higher management issued a stop on all tower building. Protesting customers forced them to weaken this decree, and allow the building of three towers out of the five planned. These three towers should serve as many customers as possible, of course. Finding the best possible choice for the towers to build is not trivial (the best choice in this case is towers 2, 4 and 5, serving 68 customers).


You must write a program to help ICPC choose which towers to build in cases like these. If several choices of towers serve the same number of customers, choices including tower 1 are preferable. If this rule still leaves room for more than one solution, solutions including tower 2 are preferable, and so on.

Input

The input file contains several test cases. The first line of each test case contains two positive integers: the number n (n<=20) of towers planned, and the number of towers to be actually built. The next line contains n numbers, each giving the number of customers served by a planned tower. (The first number refers to the first tower, and so on.) No tower serves more than a million people. The next line contains the number m (m<=10) of common service areas. Each of the next m lines contains the description of a common service area. Such a line starts with the number t (t > 1) of towers for which this is a common service area, followed by the t numbers of the towers. The last number on the line is the number of customers in the common service area. The last line of the input file consists of the two integers `0 0'.

Output

For each test case, display the number of customers served and the best choice for the location of the towers. Follow the format of the sample output. All numbers are left-justified and there are no blank spaces at the end of any line. Print a blank line after each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1062 - Trust groups   

Description

The personnel department of Association of Cookie Monsters (ACM) has noticed that the productivity of various work groups in the company is not as good as it could be. They have interviewed the employees in the affected groups and they have detected the root of the problem: trust (or, rather, the lack thereof). Some employees do not trust the rest of the group, and this is decreasing their motivation and happiness. The personnel department wants to solve this problem, and has decided to reorganize the groups so that they are stable, i.e., they are formed by people who trust each other. They have asked the employees, and they know the people each employee trusts directly. Moreover, if employee A trusts employee B and employee B trusts employee C, then employee A will trust employee C. And obviously, each employee trusts himself. They want to create as few groups as possible to reduce administration overhead (they also do not want to work too hard).

With this information they have contacted you, and asked you to write a program that finds the minimum number of stable groups that can be created.

Input

The input consists of several test cases. Each test case begins with a line containing two positive integers P and T ( 1<=P<=1000, 0<=T<=999000) separated by a single space. P lines come next, each containing the name of one person. The names will have the following format: surname, a comma, a space and first name (for example McBride, John or Smith, Peter). Both the surname and the first name will be strings of uppercase or lowercase characters (with no blanks or punctuation marks), with a maximum length of 10 characters. There will not be repetitions in the complete names of the people. After the names there will appear T blocks of 2 lines representing the trust relations between people. Each line of the block will contain the name of a person in the same format as before, and the block will mean that the person in the first line trusts the person in the second line. All people appearing in the confidence relations will have appeared in the previous list of P people.
The input will end with the ``phantom'' test case `0 0', which must not be processed.

Output

For each test case, the output will be a line containing a positive integer representing the minimum number of stable groups of people that can be formed.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1063 - Bar Codes   

Description

 A bar-code symbol consists of alternating dark and light bars, starting with a dark bar on the left. Each bar is a number of units wide. Figure 1 shows a bar-code symbol consisting of 4 bars that extend over 1+2+3+1=7 units.


Figure 1: Bar-code over 7 units with 4 bars

In general, the bar code BC(n,k,m) is the set of all symbols with k bars that together extend over exactly n units, each bar being at most m units wide. For instance, the symbol in Figure 1 belongs to BC(7,4,3) but not to BC(7,4,2). Figure 2 shows all 16 symbols in BC(7,4,3). Each `1' represents a dark unit, each `0' a light unit.

0: 1000100 | 4: 1001110 | 8:  1100100 | 12: 1101110
1: 1000110 | 5: 1011000 | 9:  1100110 | 13: 1110010
2: 1001000 | 6: 1011100 | 10: 1101000 | 14: 1110100
3: 1001100 | 7: 1100010 | 11: 1101100 | 15: 1110110

Figure 2: All symbols of BC(7,4,3)

 

Input

Each input will contain three positive integers nk, and m (1 ≤ nkm ≤ 50).

Output

 For each input print the total number of symbols in BC(n,k,m). Output will fit in 64-bit signed integer.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1064 - Software Allocation   

Description

A computing center has ten different computers (numbered 0 to 9) on which applications can run. The computers are not multi-tasking, so each machine can run only one application at any time. There are 26 applications, named A to Z. Whether an application can run on a particular computer can be found in a job description (see below).

Every morning, the users bring in their applications for that day. It is possible that two users bring in the same application; in that case two different, independent computers will be allocated for that application.

A clerk collects the applications, and for each different application he makes a list of computers on which the application could run. Then, he assigns each application to a computer. Remember: the computers are not multi-tasking, so each computer must handle at most one application in total. (An application takes a day to complete, so that sequencing i.e. one application after another on the same machine is not possible.)

A job description consists of

one upper case letter A...Z, indicating the application.
one digit 1...9, indicating the number of users who brought in the application.
a blank (space character.)
one or more different digits 0...9, indicating the computers on which the application can run.
a terminating semicolon `;'.
an end-of-line.

Input

The input for your program is a textfile. For each day it contains one or more job descriptions, separated by a line containing only the end-of-line marker. The input file ends with the standard end-of-file marker. For each day your program determines whether an allocation of applications to computers can be done, and if so, generates a possible allocation.

Output

The output is also a textfile. For each day it consists of one of the following:

ten characters from the set {`A'...`Z' , `_'}, indicating the applications allocated to computers 0 to 9 respectively if an allocation was possible. An underscore `_' means that no application is allocated to the corresponding computer.
a single character `!', if no allocation was possible.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1065 - The Skyline Problem   

Description

 With the advent of high speed graphics workstations, CAD (computer-aided design) and other areas (CAM, VLSI design) have made increasingly effective use of computers. One of the problems with drawing images is the elimination of hidden lines -- lines obscured by other parts of a drawing.

 

You are to design a program to assist an architect in drawing the skyline of a city given the locations of the buildings in the city. To make the problem tractable, all buildings are rectangular in shape and they share a common bottom (the city they are built in is very flat). The city is also viewed as two-dimensional. A building is specified by an ordered triple tex2html_wrap_inline149 where tex2html_wrap_inline151 and tex2html_wrap_inline153 are left and right coordinates, respectively, of building i and tex2html_wrap_inline157 is the height of the building. In the diagram below buildings are shown on the left with triples (1,11,5), (2,6,7), (3,13,9), (12,7,16), (14,3,25), (19,18,22), (23,13,29), (24,4,28)

the skyline, shown on the right, is represented by the sequence: (1, 11, 3, 13, 9, 0, 12, 7, 16, 3, 19, 18, 22, 3, 23, 13, 29, 0)

 

figure26

 

 

Input

 The input is a sequence of building triples. All coordinates of buildings are positive integers less than 10,000 and there will be at least one and at most 5,000 buildings in the input file. Each building triple is on a line by itself in the input file. All integers in a triple are separated by one or more spaces. The triples will be sorted by tex2html_wrap_inline151 , the left x-coordinate of the building, so the building with the smallest left x-coordinate is first in the input file.

Output

 The output should consist of the vector that describes the skyline as shown in the example above. In the skyline vector tex2html_wrap_inline183 , the tex2html_wrap_inline185 such that i is an even number represent a horizontal line (height). The tex2html_wrap_inline185such that i is an odd number represent a vertical line (x-coordinate). The skyline vector should represent the ``path'' taken, for example, by a bug starting at the minimum x-coordinate and traveling horizontally and vertically over all the lines that define the skyline. Thus the last entry in the skyline vector will be a 0. The coordinates must be separated by a blank space.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1066 - Shortest Path (I)   

Description

Given an undirected graph and a source vertex s, compute the minimum distance of each node from s. We may assume the label of s is always 0, and then the other nodes in the graph are labeled respectively by 1, 2, ..., n.

Input

The input format:

n, m := number of nodes, number of edges
x1 y1
x2 y2
...
xm ym := the m edges

For each case, the first line contains two integers n and m. Then m lines follow. Each line contains two integers x and y, denoting there is an edge between x and y.
 There is at most one edge between two nodes.
There are many cases in the input. Cases are separated by a blank line.
 Input will be terminated by EOF (End-Of-File).

Problem size :
1066: 1 <= n <= 15
1067: 1 <= n <= 200
1068: 1 <= n <= 1000
0 <= m <= n*(n-1)/2


Note that there are exactly n+1 nodes, including the source node 0.
For this problem, any algorithm with time complexity O(n2) is accepted.

 

 

You can download the testdata and test your program, we do not use the same data to test your program.

140.114.86.238/DS/prob1.zip

 

Output

The output format:

5 4 1 - 3 2 1 2 1 4 ... #

where the ith number is the min distance between node i with s (node 0) and "-" indicates such a node is unreachable from s, and "#" indicates end of each case.

 

For this case, the output is:
1 2 - 1 2 #

Sample Input  Download

Sample Output  Download

Tags




Discuss




1069 - Directed-graph (I)   

Description

Please write a program to find out that whether a directed graph has cycles.

Input

There are many cases in input.

The first line in the input contains three integers: n, m, representing the number of nodes in the graph and the number of edges in the graph.
The next m lines, each line contains 2 integers, u and v (1<= u, v <= n). That means there is an edge from u to v(v to u has no edge).
Input will be terminated by EOF (End-Of-File).

There has no node connected to itself!!

Problem size 
1069: 1 <= n <= 10

1070: 1 <= n <= 100 

1071: 1 <= n <= 1000

0 <= m <= n*(n-1)

 

Input 1: O(n!) can pass this
Input 2: O(n3) can pass this
Input 3: O(n2) can pass this 

 

You can download the testdata and test your program, we do not use the same data to test your program.

140.114.86.238/DS/prob2.zip

Output

For each case, print YES if there has at least one cycle in the graph, otherwise, print NO.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1072 - Topological Sort (I)   

Description

This problem is special judge.
To accerlelate judging, we will use offline judge.

You should test your program with this zip file(like lab):

140.114.86.238/DS/prob3.zip (windows)

prob3_Mac.zip

If you have confidence with your code, please sumbit your C or C++ code to this link:
140.114.86.238/DS/topo.php


Please write a program to implement topological sort.

Input

There are many cases in input.
The first line in the input contains three integers: n and m, representing the number of nodes in the graph, the number of edges in the graph.
The next m lines, each line contains 2 integers, u and v (1<= u, v <= n). That means there is an edge between u and v. There is at most one edge between two nodes.
Input will be terminated by EOF (End-Of-File).

1 <= n <= 100000
0 <= m <=500000

Input 1: O(n!) can pass this
Input 2: O(n2) can pass this
Input 3: O(n+m) can pass this

Output

For each case, output one line with the traversal order of DFS from the source.

We will test your program by special judge. So you can pass the testing data if you give valid topological order.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1099 - POJ A + B   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1100 - Easy Problem from Rujia Liu?   

Description

Category: Binary search

Though Rujia Liu usually sets hard problems for contests (for example, regional contests like Xi'an 2006, Beijing 2007 and Wuhan 2009, or UVa OJ contests like Rujia Liu's Presents 1 and 2), he occasionally sets easy problem (for example, 'the Coco-Cola Store' in UVa OJ), to encourage more people to solve his problems :D

Given an array, your task is to find the k-th occurrence (from left to right) of an integer v. To make the problem more difficult (and interesting!), you'll have to answer m such queries.

Input

There are several test cases. The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 100,000), the number of elements in the array, and the number of queries. The next line contains n positive integers not larger than 1,000,000. Each of the following m lines contains two integer k and v (1 ≤ kn, 1 ≤ v ≤ 1,000,000). The input is terminated by end-of-file (EOF). The size of input file does not exceed 5MB.

Output

For each query, print the 1-based location of the occurrence. If there is no such element, output 0 instead.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1104 - DNA Sorting   

Description

One measure of ``unsortedness'' in a sequence is the number of pairs of entries that are out of order with respect to each other. For instance, in the letter sequence ``DAABEC'', this measure is 5, since D is greater than four letters to its right and E is greater than one letter to its right. This measure is called the number of inversions in the sequence. The sequence ``AACEDGG'' has only one inversion (E and D)--it is nearly sorted--while the sequence ``ZWQM'' has 6 inversions (it is as unsorted as can be--exactly the reverse of sorted).

You are responsible for cataloguing a sequence of DNA strings (sequences containing only the four letters A, C, G, and T). However, you want to catalog them, not in alphabetical order, but rather in order of ``sortedness'', from ``most sorted'' to ``least sorted''. All the strings are of the same length.

Input

The first line of the input is an integer M, then a blank line followed by M datasets. There is a blank line between datasets.

The first line of each dataset contains two integers: a positive integer n (0 < n ≤ 50) giving the length of the strings; and a positive integer m (0 < m ≤ 100) giving the number of strings. These are followed by m lines, each containing a string of length n.

Output

For each dataset, output the list of input strings, arranged from ``most sorted'' to ``least sorted''. If two or more strings are equally sorted, list them in the same order they are in the input file.

Print a blank line between consecutive test cases.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1108 - Product   

Description

The problem is to multiply two integers X, Y. (0 ≤ X, Y < 10250)

Input

The input will consist of a set of pairs of lines. Each line in pair contains one multiplier.

Output

For each input pair of lines, the output line should consist of one integer the product.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1112 - Simply Emirp   

Description

An integer greater than 1 is called a prime number if its only positive divisors (factors) are 1 and itself. Prime numbers have been studied over the years by a lot of mathematicians. Applications of prime numbers arise in Cryptography and Coding Theory among others.

Have you tried reversing a prime? For most primes, you get a composite (43 becomes 34). An Emirp (Prime spelt backwards) is a Prime that gives you a different Prime when its digits are reversed. For example, 17 is Emirp because 17 as well as 71 are Prime. Notice that 131 is Prime but not Emirp because reverse of 131 is still 131. In this problem, you have to decide whether a number N is Non-prime or Prime or Emirp. Assume that 1 < N < 1000000.

Interestingly, Emirps are not new to NTU students. We have been boarding 199 and 179 buses for quite a long time!

Input

Input consists of several lines specifying values for N.

Output

For each N given in the input, output should contain one of the following:

 

  1. "N is not prime.", if N is not a Prime number.
  2. "N is prime.", if N is Prime and N is not Emirp.
  3. "N is emirp.", if N is Emirp.

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1116 - Power Crisis   

Description

[[Category: Simulation]]

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, which 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 T (T ≤50000) 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.

You may assume that m is less than 1000 for any N < 100.

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.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1120 - You want what filled?   

Description

[[Category: Graphs and DFS]]

Now that Ryan and Larry infuriated the bear, they're now forced to do menial tasks for food; one such task is filling in potholes on this deserted island. But of course, it's never quite that easy, as the bear forces them to fill in the biggest hole first. Since Ryan and Larry are still lazy (very little has changed, you see), can you tell them the order to fill in the holes?

Input

There are at most 100 test cases. The first line will contain two numbers x and y, followed by x lines of y characters each. (x and y are less than 50). The holes will be represented by the uppercase characters A to Z, and regular land will be represented by ".". There will be no other characters in the map. Two characters in the map are considered in the same hole if and only if they are adjacent in either vertical or horizontal direction. The size of a hole is measured by the number of characters in the hole. Input will be terminated by having 0 0 as input.

Output

For each map, output the problem number (as shown below), then output the hole represented by the character, and the number of space the hole takes up, sorted by the size of the hole, break ties by sorting the characters in alphabetical order, as shown in the sample output on a separate line as shown below.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1124 - Morning Walk   

Description

[[Category: Eulerian Circuit]]

Kamal is a Motashota guy. He has got a new job in Chittagong. So, he has moved to Chittagong from Dinajpur. He was getting fatter in Dinajpur as he had no work in his hand there. So, moving to Chittagong has turned to be a blessing for him. Every morning he takes a walk through the hilly roads of charming city Chittagong. He is enjoying this city very much. There are so many roads in Chittagong and every morning he takes different paths for his walking. But while choosing a path he makes sure he does not visit a road twice not even in his way back home. An intersection point of a road is not considered as the part of the road. In a sunny morning, he was thinking about how it would be if he could visit all the roads of the city in a single walk. Your task is to help Kamal in determining whether it is possible for him or not.

Input

Input will consist of at most 100 test cases. Each test case will start with a line containing two numbers. The first number indicates the number of road intersections and is denoted by N (2 ≤ N ≤ 200). The road intersections are assumed to be numbered from 0 to N - 1. The second number R denotes the number of roads (0 ≤ R ≤ 10000). Then there will be R lines each containing two numbers c1 and c2 indicating the intersections connecting a road.

Output

Print a single line containing the text “Possible” without quotes if it is possible for Kamal to visit all the roads exactly once in a single walk otherwise print “Not Possible”.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1128 - Airport Express   

Description

[[Category: Single Source Shortest Path]]

In a small city called Iokh, a train service, Airport-Express, takes residents to the airport more quickly than other transports. There are two types of trains in Airport-Express, the Economy-Xpress and the Commercial-Xpress. They travel at different speeds, take different routes and have different costs.

Jason is going to the airport to meet his friend. He wants to take the Commercial-Xpress which is supposed to be faster, but he doesn't have enough money. Luckily he has a ticket for the Commercial-Xpress which can take him one station forward. If he used the ticket wisely, he might end up saving a lot of time. However, choosing the best time to use the ticket is not easy for him.

Jason now seeks your help. The routes of the two types of trains are given. Please write a program to find the best route to the destination. The program should also tell when the ticket should be used.

Input

The input consists of at most 20 test cases. Consecutive cases are separated by a blank line.

The first line of each case contains 3 integers, namely N, S and E (2 ≤ N ≤ 500, 1 ≤ S, EN), which represent the number of stations, the starting point and where the airport is located respectively.

There is an integer M (1 ≤ M ≤ 1000) representing the number of connections between the stations of the Economy-Xpress. The next M lines give the information of the routes of the Economy-Xpress. Each consists of three integers X, Y and Z (X, YN, 1 ≤ Z ≤ 100). This means X and Y are connected and it takes Z minutes to travel between these two stations.

The next line is another integer K (1 ≤ K ≤ 20) representing the number of connections between the stations of the Commercial-Xpress. The next K lines contain the information of the Commercial-Xpress in the same format as that of the Economy-Xpress.

All connections are bi-directional. You may assume that there is exactly one optimal route to the airport. There might be cases where you MUST use your ticket in order to reach the airport.

Output

For each case, you should first list the number of stations which Jason would visit in order. On the next line, output "Ticket Not Used" if you decided NOT to use the ticket; otherwise, state the station where Jason should get on the train of Commercial-Xpress. Finally, print the total time for the journey on the last line. Consecutive sets of output must be separated by a blank line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1132 - The Party, Part I   

Description

[[Category: BFS]]

Don Giovanni likes to dance--especially with girls! And everyone else in the party enjoyed the dance, too. Getting a chance to dance with the host (that is Don Giovanni) is the greatest honour; failing that, dancing with someone who has danced with the host or will dance with the host is the second greatest honour. This can go further. Define the Giovanni number of a person as follows, at the time after the party is over and therefore who has danced with whom is completely known and fixed:

  1. No one has a negative Giovanni number.
  2. The Giovanni number of Don Giovanni is 0.
  3. If a person p is not Don Giovanni himself, and has danced with someone with Giovanni number n, and has not danced with anyone with a Giovanni number smaller than n, then p has Giovanni number n + 1.
  4. If a person's Giovanni number cannot be determined from the above rules (he/she has not danced with anyone with a finite Giovanni number), his/her Giovanni number is ∞.

Your job is to write a program to compute Giovanni numbers.

Input

The input begins with a single positive integer k ≤ 100 on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

The first line has two numbers P and D; this means there are P persons in the party (including Don Giovanni) and D dancing couples (2 ≤ P ≤ 105 and 0 ≤ D ≤ 106) Then D lines follow, each containing two distinct persons, meaning the two persons has danced. Persons are represented by numbers between 0 and P-1; Don Giovanni is represented by 0.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line. Output P-1 lines. Line i is the Giovanni number of person i, for 1 ≤ iP-1. If the Giovanni number is ∞, print ``INF". Note that it is P-1 because we skip Don Giovanni in the output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1136 - Audiophobia   

Description

[[Category: All-Pairs Shortest Path]]

(Hint: Transitive Closure)

Consider yourself lucky! Consider yourself lucky to be still breathing and having fun participating in this contest. But we apprehend that many of your descendants may not have this luxury. For, as you know, we are the dwellers of one of the most polluted cities on earth. Pollution is everywhere, both in the environment and in society and our lack of consciousness is simply aggravating the situation.

However, for the time being, we will consider only one type of pollution ­- the sound pollution. The loudness or intensity level of sound is usually measured in decibels and sound having intensity level 130 decibels or higher is considered painful. The intensity level of normal conversation is 60-­65 decibels and that of heavy traffic is 70-­80 decibels.

Consider the following city map where the edges refer to streets and the nodes refer to crossings. The integer on each edge is the average intensity level of sound (in decibels) in the corresponding street.

To get from crossing A to crossing G you may follow the following path: A-­C-­F-­G. In that case you must be capable of tolerating sound intensity as high as 140 decibels. For the paths A­-B-­E-­G, A-­B-­D-­G and A-­C-­F-­D-­G you must tolerate respectively 90, 120 and 80 decibels of sound intensity. There are other paths, too. However, it is clear that A-­C-­F-­D-­G is the most comfortable path since it does not demand you to tolerate more than 80 decibels.

In this problem, given a city map you are required to determine the minimum sound intensity level you must be able to tolerate in order to get from a given crossing to another.

Input

The input may contains at most 100 test cases.

The first line of each test case contains three integers C(2 ≤ C ≤ 100), S(0 ≤ S ≤ 104) and Q(1 ≤ Q ≤ 104) where C indicates the number of crossings (crossings are numbered using distinct integers ranging from 1 to C), S represents the number of streets and Q is the number of queries.

Each of the next S lines contains three integers: c1, c2 and d(0 ≤ d ≤ 108) indicating that the average sound intensity level on the street connecting the crossings c1 and c2 (c1c2) is d decibels. The streets are bidirectional and you can assume that there is no two lines describing the same street in these S lines.

Each of the next Q lines contains two integers c1 and c2 (c1c2) asking for the minimum sound intensity level you must be able to tolerate in order to get from crossing c1 to crossing c2.

The input will terminate with three zeros form C, S and Q.

Output

For each test case in the input first output the test case number (starting from 1) as shown in the sample output. Then for each query in the input print a line giving the minimum sound intensity level (in decibels) you must be able to tolerate in order to get from the first to the second crossing in the query. If there exists no path between them just print the line ``no path".

Print a blank line between two consecutive test cases.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1140 - The Sultan's Successors   

Description

[[Category: Branch and Bound]]

The Sultan of Nubia has no children, so she has decided that the country will be split into up to k separate parts on her death and each part will be inherited by whoever performs best at some test. It is possible for any individual to inherit more than one or indeed all of the portions. To ensure that only highly intelligent people eventually become her successors, the Sultan has devised an ingenious test. In a large hall filled with the splash of fountains and the delicate scent of incense have been placed k chessboards. (A chessboard has eight rows and eight columns.) Each chessboard has numbers in the range 1 to 99 written on each square and is supplied with 8 jewelled chess queens. The task facing each potential successor is to place the 8 queens on the chessboard in such a way that no queen threatens another one, and so that the numbers on the squares thus selected sum to a number at least as high as one already chosen by the Sultan. (For those unfamiliar with the rules of chess, this implies that each row and column of the board contains exactly one queen, and each diagonal contains no more than one. It is known that the number of valid placements of the 8 queens on the chessboard is less than 100.)

Write a program that will read in the number and details of the chessboards and determine the highest scores possible for each board under these conditions. (You know that the Sultan is both a good chess player and a good mathematician and you suspect that her score is the best attainable.)

Input

Input will consist of k (the number of boards), on a line by itself, followed by k sets of 64 numbers, each set consisting of eight lines of eight numbers. Each number will be a positive integer less than 100. There will never be more than 105 boards .

Output

Output will consist of k numbers consisting of your k scores, each score on a line by itself and right justified in a field 5 characters wide.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1144 - Colour Hash   

Description

[[Category: 2-Way BFS]]

This puzzle consists of two wheels. Both wheels can rotate both clock and counter-clockwise. They contain 21 coloured pieces, 10 of which are rounded triangles and 11 of which are separators. Figure 1 shows the final position of each one of the pieces. Note that to perform a one step rotation you must turn the wheel until you have advanced a triangle and a separator.

Figure 1. Final puzzle configuration

Your job is to write a program that reads the puzzle configuration and prints the minimum sequence of movements required to reach the final position. We will use the following integer values to encode each type of piece:

 

  • 0    grey separator
  • 1    yellow triangle
  • 2    yellow separator
  • 3    cyan triangle
  • 4    cyan separator
  • 5    violet triangle
  • 6    violet separator
  • 7    green triangle
  • 8    green separator
  • 9    red triangle
  • 10    red separator

 

A puzzle configuration will be described using 24 integers, the first 12 to describe the left wheel configuration and the last 12 for the right wheel. The first integer represents the bottom right separator of the left wheel and the next eleven integers describe the left wheel clockwise. The thirteenth integer represents the bottom left separator of right wheel and the next eleven integers describe the right wheel counter-clockwise.

The final position is therefore encoded like:

0 3 4 3 0 5 6 5 0 1 2 1 0 7 8 7 0 9 10 9 0 1 2 1

If for instance we rotate the left wheel clockwise one position from the final configuration (as shown in Figure 2) the puzzle configuration would be encoded like:

2 1 0 3 4 3 0 5 6 5 0 1 0 7 8 7 0 9 10 9 0 5 0 1

Figure 2. The puzzle after rotating the left wheel on step clockwise from the final configuration.

Input

Input for your program consists of at most 50 puzzles. The first line of the input will contain an integer n specifying the number of puzzles. There will then be n lines each containing 24 integers separated with one white space, describing the initial puzzle configuration as explained above.

Output

For each configuration your program should output one line with just one number representing the solution. Each movement is encoded using one digit from 1 to 4 in the following way:

 

  • 1    Left Wheel Clockwise rotation
  • 2    Right Wheel Clockwise rotation
  • 3    Left Wheel Counter-Clockwise rotation
  • 4    Right Wheel Counter-Clockwise rotation

 

No space should be printed between each digit. Since multiple solutions could be found, you should print the solution that is encoded as the smallest number. The solution will never require more than 16 movements.

If no solution is found you should print ``NO SOLUTION WAS FOUND IN 16 STEPS". If you are given the final position you should print ``PUZZLE ALREADY SOLVED".

Sample Input  Download

Sample Output  Download

Tags




Discuss




1196 - Uninstall   

Description

Recently, Mr. ATH's hard disk is almost full so his computer crashes often. He decided to clean up his hard disk by
uninstalling some programs. Currently his computer is running under an operation system called SOD, which is an
operation system that has similar commands to DOS.

To remove a program, he needs to change his working directory to the directory of the program.
After typing "uninstall" in the directory, then the program will be automatically uninstalled.

However, unlike DOS, this operation system's command of changing directory is fairly limited.
The command "cd" has the following usage:

  1. cd [directory_name]
    This command would allow user to swap his directory exactly one level down in the hierarchy.
    For example, if the current directory is "/tmp", the command "cd aaaa" would change the directory to "/tmp/aaaa"
    However, "cd aaaa/bbbb" does not work.
     
  2. cd ..
    This command would allow user to move his directory one level up in the hierarchy.
    For example, if the current directory is "/tmp/aaaaa", the command "cd .." would change the directory to "/tmp"

Note that in the SOD operation system, the root directory is "/" and he started at root directory initially.

Now Mr. ATH has listed the directories of the programs that he wanted to delete IN ORDER,
because violation of the order would cause his computer to crash.

Since the function of executing a batch file is not even implemented in SOD operation system (what a bad OS),
Mr. ATH would have to type these commands by hand.
Besides, because Mr. ATH is lazy, he wanted to type as few lines of commands as possible.

You going to write a program that will generate minimum lines of commands that Mr. ATH could use to
delete all program he listed.

Input

The input may contain many cases (Mr. ATH need to clean his hard disk very often).
The first line of each case contain exactly one integer n (1<=n<=50) indicating the number of program that Mr. ATH wanted to delete.
Then the following n lines consist of strings without any spaces that describe the directories of the programs.
The names of adjacent directories are separated by a slash "/", and there is no slash succeeding the last directory name.
There will be no same strings appear in the same case. Besides, he will not uninstall his root directory "/".

The name for each directory has length at least 1 and at most 32 and consist of
only letters (a-z, A-Z), digits (0-9) and underscores "_".
Moreover, the SOD operation system can only allow the depth of hierarchy to at most 10 levels.
That is, "/1/2/3/4/5/6/7/8/9/10" is valid, while "/1/2/3/4/5/6/7/8/9/10/11" is not a valid directory.
You should also note that the names are case sensitive, that is, "/Aaaa" is a directory different from "/aaaa".

Output

For each case, output "Case x:" in the first line, where x is the number of case, starting from 1.
Then output the commands, each in a line, which can be "cd ..", "cd [directory_name]", or "uninstall".
Note that he always starts at root directory "/" in every case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1197 - Stepmania   

Description


Stepmania is a widely played game among otakus. Mr. SuBaRaSi has always wanted to become an otaku.
So he wanted to be a maestro in Stepmania. However, it would take a lot of time to practice.

For each song, some parts are difficult while other parts are easy. For example, the chorus at the middle part of the song
might be hard that he need to practice 25 times in order to get familiar. On the other hand, the intro part might be easy that he
only need to practice 5 times.

He found it is NOT efficient to always practice from the start all the way to the end of the song. As in the previous example,
he can start at the chorus part till the end for 20 times, and from intro to the end 5 times, which might be more efficient.
However, since is not good for him to interrupt at too many different parts, he can ONLY start or stop at the breakpoints settled.

Given a song that contain n parts that numbered from 1 to n, and the difficulty of every part (number of times 
needed to practice). Now he has inserted k breakpoints on k different points between two adjacent parts of the song.
Then for each practice, he can start at the beginning or any of the breakpoints, and stop at the end
or any of the breakpoints. The time needed for each practice is exactly the number of parts practiced.
For example, if he started at part 3 and ended at part 7, then the time needed is (7-3+1) = 5.

You are to write a program that help SuBaRaSi to arrange his practice so that the total sum of his
practice time is minimum. In this way, he will thank you because he can then achieve his otaku's dream
more quickly.
 

Input

The input may contain many cases. In each case, the first line contain 
two integers n, k (0<=k<n<=500) representing the number of parts in the song
and the number of breakpoints SuBaRaSi has set. In the following n lines, the i'th line
contain exactly one integer di (0<=di<=1000) denoting the difficulty of part i.
Then, in each of the following k lines contains an integer pi (1<=pi<n) representing the breakpoint
has been inserted between part pand part pi+1. Note that these k integers are all distinct.

Output

For each case, print exactly one integer on a line representing the minimum time needed for SuBaRaSi to
become proficient in this song.

In the first case of the sample input, he can practice from beginning to the end once.
Then he practices part 2 to part 5 twice. Finally, he practices from part 2 to part 3 twice.
Therefore, the total time used is 18.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1199 - Guess   

Description

One day, Mary told you that she really liked someone in your class.
However, Mary is so shy that she won't tell who it is.
But curiosity has driven you to try pumping more information from Mary.
For example, you might write to Mary the following:

  • You questioned: 
  • "Is he rich?"
  • "Is he handsome?"
  • "Is he humor?"
  • "Is he an otaku?"
     
  • Mary replied:
  • "No."
  • "No."
  • "No."
  • "Yes."

Then you suddenly realized who it is.

But, the above is an ideal scenario. Because Mary is shy, she is so reluctant that she will not answer too many questions.
Since you know the characteristics of everyone in the class, you are going to ask as few questions as possible from Mary.
No matter who is the person Mary likes, you have to ensure that you will know the answer after asking these questions.
Note that you will write all the questions you are going to ask to Mary before getting any replies from her.
You are going to write a program that determines what the minimum number of question needed is.
 

Input

The input may contain many cases. In each case, there are 2 numbers, n and m (1<=n<=10000, 0<=m<=12) that
describe the number of students in your class and the number of possible characteristics.
Then the following are n lines, where in each line there is a string denote the name of the student.
Then the following describe the characteristics of people.  For each characteristic, there is a string describing
the characteristic followed by an integer ki (1<=ki<=n) denoting the number of people who has this characteristic.
The next line contains exactly ki strings separated by a space which represent the people who have this characteristic.

 All the strings in the input only contain "_", digits or upper-case letters and have length at most 24.

Output

For each case, you should output exactly one non-negative integer in a line representing the minimum number of
questions needed to get the answer regardless of who it is. If there is a possibility that you will never know
who it is then output -1.

In the sample input, you can choose to ask "Is he smart?", "Is he handsome?", and "Is he an unicorn?".
Then no matter who is it, you can recognize him from the answers responded by Mary.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1200 - Circuits   

Description

Given a grid which represents a circuit, the current passing each grid point has its direction which can either 
be north, east, south, or west. According to the right hand rule, if the current formed a closed loop then
a magnetic field is generated inside the loop. A closed loop is defined as follow:

If you started at some point and keep follow the arrow and finally go back to the point, the path you traversed
is a closed loop. In addition, the loop must consists of at least four arrows. Therefore, a right followed by a left
does not account for a closed loop. Note that it is not guranteed that every point lies on a closed loop.

The direction of the magnetic field depends on whether the current loop is clockwise or counter-clockwise.
If the loop is clockwise, then magnitude of -1 is generated. If it is counter-clockwise, +1 is generated.
In addition, the magnitudes are cumalaitve. For example, if there is a clockwise loop A and a counter-clockwise
loop B. If B is inside A, then the magnetic field inside B has magnitude of 0.

In this problem, you have to find the greatest absolute value of the magnetic field magnitude in the circuit.

Input

The input may consist of many cases. In each case, the first line are two integers n, m (1<=n, m<=1000) indicating
the size of the grid circuit. The followings are n lines describing the circuit, and in each line there are m integers.
The integers can be 0, 1, 2, 3 representing north, east, south, west respectively.

Output

In each case, you should output exactly one integer in one line which indicates the greatest absolute value
of magnitude induced by the circuit.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1201 - Segments   

Description

Dr. SiRaBaSu always has trouble memorizing large numbers. To remember a number x, he will need | x | units of energy.
As a programmer and a notorious problemsetter who enjoy setting very hard problems, he often needs to memorize a
lot of number sequences. Fortunately, he invented a mnemonic to help himself memorize better.

When a sequence of numbers is given, instead of memorizing each number in the sequence, now he memorizes
several consecutive segments and their sum instead. For example, in the sequence <ai> = <1, -3, 2, 4>, he would memorize
the following:
a1 = 1
a2a3 = -1
a2 + a3 + a4 = 3
a3 = 2

Then, he is able to reconstruct the original sequence from the information he just memorized.
For example, he can retrieve a4 by using the third equality to minus the second equality.
As mentioned, the total energy needed for him is | 1 | + | -1 | + | 3 | + | 2 |  = 7, which is less than
10 units of that in the straightforward way.
(Note that this strategy is not the best in this case. The minimum energy he needed can be 6 here. )

You are going to write a program that helps Dr. SiRaBaSu to determine the best strategy to memorize
the sequence using minimum energy, so he can set more hard problems.
 

Input

The input may contain no more than 50 cases. In each case, there is an integer n (1<=n<=500) denoting the length of the sequence.
The following n lines describe the sequence, where the i'th line contains an integer representing ai (-10000 <= ai <= 10000).

Output

For each case, please output exactly one integer in a line representing the minimum energy SiRaBaSu
can use to memorize the sequence.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1202 - Enigma   

Description

Tom's girlfriend, Enigma, is a very mysterious person. When answering a question, she sometimes tell the truth
but sometimes don't. For example, "yes" might actually means "no", and "no" might actually means "yes". It could be very
dangerous to Tom if he didn't get the actual meaning.
Tonight, Tom want to ask his girlfriend whether she want to watch a movie or not.
Tom: "Enigma, would you like to watch a movie tonight?"
Enigma: "No."
Tom: "Was your last answer correct?"
Enigma: "Yes."
Tom: "Was your last answer correct?"
Enigma: "No."
....
Enigma always answered "no" to the first question which is actually meaningless.
Then Tom will ask n more "Was your last answer correct?" before he gets tired or... fired.
Fortunately, there is a way for Tom to get the true meaning of Enigma. He knows that although Enigma is
very strange, however, she still has a principle: At any moment, the number of times she lied will not be greater than
the number of times she said the truth plus k. Therefore, the number of strategy that Enigma can use is limited.
Note that the number of times she told a truth or a lie includes the answer of the first question.

Besides, Tom is very smart, Enigma is so afraid that he will understand her true meaning.
So Enigma turned to you, a nice man programmer, and begged for your help. She wanted to know how
many different strategies she can use to answer these n questions so that (1)Tom will be still confused whether
she want to see the movie or not. (2)Her principle is not violated.
 
The following example illustrate a strategy that would fail when n = 2 and k = 1

  watch a movie? Was your last answer correct? Was your last answer correct?
Enigma's answer no yes no
Possibility 1 lie lie truth
Possibility 2 truth truth lie

Since in Possibility 1, at the moment when the first "Was your last answer correct?" is answered, Enigma has told 2 lies 
while 0 truth is told. Therefore, Tom knows that Possibility 2 is the only possibility that Enigma really
don't want go to the movie. So, the strategy "yes, no" does not work for Engima.
However, as you can verify, "no, yes" works well in this case.

Input

The input consists of many cases. In each case, two integers n, k (1<=n, k<=1000) are given
in a line, separated by a space. The number n indicates how many "Was your last answer correct?" will Tom ask
after he ask "Enigma, would you like to watch a movie tonight?". The number k is the maximum number of lies could be
more than truths told by Enigma at any moment.

Output

For each case, output x % 100000007, where x is the number of strategies that Enigma
can use that (1)confuse Tom, (2)does not violate her principle.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1203 - The L-VALUE   

Description

Davidku and Otasu are brothers who love ACG(Anime, Comic and Game) very much.  Due to their professional skills and
knowledge on ACG, everybody called them  "Super OTAKU brothers".

One day, an new video game, "Tales of KoKuHaKu in the end of century" is published.   The game is a typical love simulation
game that you have to interactive with each girls in the games and make decisions in the conversation.
For the relationships between you and each girls, there are numerical values representing how good it is and how the girl likes
you, called L-value.    Some events would arise depending on your conversation decisions and therefore it matter the L-values of
girls and the ending of story.   So if you like some girls, you may try raising the L-values with them.

 To live up to their reputation, the name of  "Super OTAKU brothers", this time they  also want to write the playing guide
of  the game to other video game players on internet.  
Now they want to make a section in the guide talking about "What events must arise to maximize the L-values of the girls?".

After disassembling the game and tracing the code, they know the rules about the changing of L-values.
For every event E, there is a corresponding set S(E) consisting of elements indicating how it affects the L-values of girls.
Every element is a pair of value (N, V) repsenting the name of girl and the variation of L-value.
For example, let S(E) = {(Raou, 5), (Kenshirou, -2)}. Then if you arise the event E, Raou's L-value would increase by 5 and Kenshirou's L-value would decrease by 2. 
In addition, when you arise two events E and F, for this two events, if the number of girls who participates in exactly
one of the two events is a prime number more than 2(excluded), these girls would be resentful and their L-values would decrease 
by the square of the prime number (what a geek design).   
For example, suppose there are two events E and F, and S(E) = {(Raou, 10), (Kenshirou, -10), (Toki, -5)},   S(F) = {(Kenshirou, 20), (Yuria, 5)}.   
Then if you arise both the events, The variation of L-values is the following result.

Kenshirou: -10 + 20 = +10
Raou: +10 - 3 * 3 = +1
Toki: -5 - 3 * 3 = -14
Yuria: 5 - 3 * 3 = -4 

Now they want someone to help them. You are to write a program that they can import the event data and indicate
which girls they want to maximize the L-value. Then the program would find out what events should arise to maximize the sum of L-values of the indicated girls .

 

Input

The input consists of many cases.  The first line of input contains a integer T (1 <= T <= 30) indicates the number of testcase.
For each case there is first a non-negative integers N (N <= 100) which is the number of events.  We conveniently number the
events as 1 to N.   Then following N lines describe the S(i) for each event i.  Each line is preceded an integer M-i  indicates the
number of elements in the event i and then there are M-i pairs consisiting of a alphabet string which is the name of girls and an
integer indicates the variation of L-value separated by spaces.
And there is a single line following contains a integer G and G names of girls they want to maximize the L-value.  
 
The absolute value of the  variation are less than 1000.  And there are at most 60 girls whose name are all  alphabet strings
no longer than 15 characters.
 

Output

For each case,  output a single line containing the maximum L-value they can achieve.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1204 - Stepmania (III)   

Description


Stepmania is a widely played game among Otakus. Mr. SuBaRaSi has always wanted to become an Otaku.
So he wanted to be a maestro in Stepmania. However, it would take a lot of time to practice.

For each song, some parts are difficult while other parts are easy. For example, the chorus at the middle part of the song
might be hard that he need to practice 25 times in order to get familiar. On the other hand, the intro part might be easy that he
only need to practice 5 times.

He found it is NOT efficient to always practice from the start all the way to the end of the song. As in the previous example,
he can start at the chorus part till the end for 20 times, and from intro to the end 5 times, which might be more efficient.
However, since is not good for him to interrupt at too many different parts, he can ONLY start or stop at the breakpoints settled.

Given a song that contain n parts that numbered from 1 to n, and the difficulty of every part (number of times 
needed to practice). Now he is limited to set at most k breakpoints between two adjacent parts of the song.
Then for each practice, he can start at the beginning or any of the breakpoints, and stop at the end
or any of the breakpoints. The time needed for each practice is exactly the number of parts practiced.
For example, if he started at part 3 and ended at part 7, then the time needed is (7-3+1) = 4.

You are to write a program that help SuBaRaSi to set up the breakpoints and arrange his practice so that
the total sum of his practice time is minimum. In this way, he will thank you because he can then achieve
his Otaku's dream more quickly.
 

Input

The input may contain many cases. In each case, the first line contain 
two integers n, k (1<=n<=500, 1<=k<=123) representing the number of parts in the song
and the maximum number of breakpoints SuBaRaSi can set. In the following n lines, the i'th line
contain exactly one integer di (0<=di<=1000) denoting the difficulty of that part.

Output

For each case, print exactly one integer on a line representing the minimum time needed for SuBaRaSi to
become proficient in this song.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1205 - Stepmania (II)   

Description


After many years of discipline and persistent practices, SuBaRaSi has almost become an otaku that
play Stepmania really well. However, to play even better, he needs to analyze the songs.

Many of rhythms have specifics patterns that SuBaRaSi can perform much easier because he is familiar with those patterns.
Note that he played Stepmania using his computer keyboard with both hands because it looks more like an otaku.
Since SuBaRaSi has learned the "technique of alternating left-right hands" from the "old-stubborn child", Zhou Buotong,
now he can play the songs using two hands independently without interfering other hand.

Patterns are described by strings consist of 0, 1, and 2. A zero means no taps, a one means a single tap on any 
of the arrows, and a two means two taps simultaneously on any of two distinct arrows. For each pattern, either of his
hand could recognize it independently and apply it for playing more easily. Depending on the cost of the patterns, you
are going to help SuBaRaSi to develop an analysis such that he can use as small cost as possible to play the
song without any single miss or any extra taps.

Note that, the pattern with a single "0", "1" or "2" and their costs will be given in the input so that it is guaranteed that he can 
perfectly play the song. The following is an example:

P1 = "0", cost 0
P2 = "1", cost 1
P3 = "2", cost 2
P4 = "121212", cost 2
P5 = "1012", cost 1

After the analysis:


Therefore, the cost for right hand is  2 + 1 + 0 + 2 = 5, and the cost for left hand is 1 + 0 + 1 + 1 + 0 = 3.
He needs totally 8 cost to play this song in this analysis.
 

Input

The input may consist of many cases. For each case, there are two integers p, l (3<=p<=20, 1<=l<=200) denoting
the number of patterns SuBaRaSi could recognize and the length of the song. In the each of following p lines, there
are a string Pi and an integer ci representing the patterns and cost of the patterns. Each Pi is consisted of digits 0, 1 or 2
and has length at most 10. The values of ci are all non-negative and less than 1000.

The following four lines describe the left, down, up, right arrows of the song. Each line is a string with length l and consisted
of 0 and 1. A 0 means the arrow does not appear, a 1 means the arrow is there.
 

Output

For each case, output exactly one number denoting the minimum cost SuBaRaSi can perform the song under any analysis.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1206 - PA - Ice Arena   

Description

Citizens of the ice kingdom plan to build an ice arena, which is a rectangular area of N x M ice grids. However, they find that the original heights of the ice cubes on the grids are not equal, and given the time constraints it is difficult for them to modify the original height too much. Thus, only one of the three possible actions can be taken on the ice cube for each grid: digging it (decreasing its height by 1), filling it (increasing its height by 1), or doing nothing.
After taking one and only one action for each grid, the citizens choose grids with the same modified height for ice skating to prevent getting hurt on an uneven surface, and place barriers on the grids that are not chosen.
To form a safe area for ice skating , the citizens hope to use the chosen grids that are connected through vertical or horizontal walks. Please find the maximum possible safe area, that is, the maximum number of chosen grids that are connected.

Input

The first line of input data contains an integer T(1 <= T <= 1000) specifying the number of the cases.
The first line of each test case contains two integers N and M (1<=N, M<=100) indicating the dimensions of the ice arena. Each of the next N lines contains M integers H (1<=H<=10000) denoting the original height of each gird.

Output

For each test case, display a single line containing the maximum number of chosen grids (after taking the actions) that are connected.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1207 - PB - The Balloon Kingdom   

Description


Input


Output


Sample Input  Download

Sample Output  Download

Tags




Discuss




1208 - PC - Ant   

Description


Input


Output


Sample Input  Download

Sample Output  Download

Tags




Discuss




1209 - PD - Keys   

Description


Input


Output


Sample Input  Download

Sample Output  Download

Tags




Discuss




1210 - PE - Biased Grade   

Description


Input

 

Output

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1211 - PF - Crimiville   

Description

 

Input

 

Output

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1301 - Parity   

Description

Given a non-negative interger with n <= 100, please find a number has the same parity with it.

Input

Each line contain a non-negative integer n <= 100.

Output

For each line, please print a non-negative integer <= 100 that has the same parity with n.
Note that the solutions are not unique.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1302 - Sorting   

Description

Given some integers, please list them in increasing order.

Input

First line is an integer T (T <= 20) followed by T test cases. For each test case, start with an integer n (n <= 106) and follow by n integers V1, V2, ..., Vn. ( V< 231 for 1 <= i <= n )

Output

For each test case, list numbers from the smallest one to the largest one in one line. Two adjacent numbers in one line should be separated by a whitespace.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1303 - Time is Money!   

Description

Peter is an employee of certain company. Since the policy of company, his salary is related to the type of works and the corresponding time. For example, if Peter spent 2 hours in updating server, and company paid him $600 per hour, then he earned $1200.

Now you have the list of Peter's works, please compute Peter's salary.

Input

The first line is an integer T(<=100) meaning the number of test cases in the input file. In each test case, it begins with N, the number of works(N<=103), come up with N works' details, P TS TF. P(03) is the payment of work per hour, TS means start time, and TF means finish time. All three numbers are integer, you can see sample input for more details.

For simplicity, we assume that all works are done in one day, no durations cross two or more days. Moreover, the durations of any two works doesn't overlap each other and the time in one day is from 00:00 to 23:59. Besides, if the duration is less than one hour, we take this duration as if he works for an hour. For instance, a duration 1 hour and 23 minutes is counted as 2 hours.

Output

For each test case, output test case number and the salary in a line. There should be an empty line between two adjacent test cases.

See sample output for more details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1304 - More Profit!   

Description

In some online games, property of character is important. One of the famous way to increase your money is commerce. More precisely, we can buy something in lower price and then sell it by higher price. Because of the difference between two prices, player can make money easily. 

In Amusement Commerce Game, player can buy some items from a commerce port and sell it in a big city. There are many items that is sold by supplier and the amount of each item is limited. Moreover, player can put at most M items on character. Give the profit of each item, what is the maximum profit can achieve in a single journey from port to city?

Input

There is an integer T representing the number of test cases, which is followed by T test cases. Each test case begins with two integers N, M, and then the next N lines are N items' information. Each line has two numbers, n_i and p_i, representing the amount and the price per quantity for i_th item. You can assume that there are at most 1,000 cases and at most 10,000 items for each case. Also n_i and p_i are both non-negative integers.

Output

For each test case, output the maximum profit can be made. The maximum profit would not exceed 2,147,483,647.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1305 - Treasures of the Sea   

Description

Your friend, John, is a pirate. One day, he found a map marking the treasures of the sea, which described as following:
    1. Like most maps in the world, the east is on the right-hand side of map.
    2. The map splits the sea into grids, separated by vertical and horizontal lines.
    3. For each grid, there is a non-negative number presenting how many treasures are there on the islands in the grid.
    4. Any regions out of the map contain no treasure.
In this season, the wind blows from the north to the south. With the help of wind, John will drive his boat from the north of sea to the south. The boat can sail to east or west, but there are some limitations.
John will start his journey from any grids in the north side of the sea in map (any grid on the top of map). After gathering the treasures in the grid, there are 3 directions he can choose:
    1. South. He will go down on the map.
    2. Southeast. He will reach the grid on the right of choice 1.
    3. Southwest. He will reach the grid on the left of choice 1.
As described above, there is no way to sail east, west, or north. After John sail out of the south grids on the grid, his journey will end.
Since John promised you to share half of the treasures he gets in the journey, you are to find out how may treasures you and John can get most if he chooses the path carefully.
 

Input

There will be multiple cases in the input.
The first line contains a positive integer T, T≦10, which denotes the number of cases.
The next line contains 2 positive integers, R and C (≦100), denoting the size of map for rows and columns. There are R lines following, denoting the rows from north to south, and each row contains C integers, which are the value of treasures in that grid(≦10000).
Values will be separated with spaces.

Output

For each case, output a line containing one integer denoting the maximum value of treasures John and you may get.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1306 - Energy Saver   

Description

Welcome to NTHU Online Judge! You must notice the avenue planted with many streetlamps. Since energy issue is serious, NTHU decided to turn off some streetlamps. However, there are so many activities held in NTHU, sometimes we need more lights for safety, so a fixed setting is not flexible. 

As a computer science student, Scott designed a system to control the setting of streetlamps. At first, he gave every streeplamps a number from 1, 2, 3, ..., and so on. There is a control panel with two lines of buttons, and the buttons each line are indexed from 1 to n provided that the total number of streeplamps is n. When Scott pushed a button on first line, e.g: i_th one, the status of i_th streetlamp changes. Changing status means that if a streetlamp is turn off, then it would be turned on, and vice versa. This kind of action is called "normal" push.

Another line of buttons is more powerful, called "toggle" push. If we toggle pushed the i_th button, then the status of streetlamps from the i_th streetlamp to the last(n_th) one would be changed. For example, if we toggle pushed 5th button, then the status of streetlamps with index 5, 6, ..., n will be changed.

Now we want to know how to minimize the total number of normal push and toggle push on buttons. Please write a program to help Scott. We assume that originally all streetlamps are turned off.

Input

The first line is the number of test cases. Each test case starts with an integer n and the next line are n integers v_1, v_2, ..., v_n. n(<=10^6) is the number of streeplamps, and v_i is i_th streeplamp status for final setting. v_i is either 0 or 1, 0 is turned off and 1 is turned on.

Output

For each test case, output the test case number and the minimum number of push. See sample for more details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1307 - Gift Wrapping Algorithm for Convex Hull   

Description

On a 2D plane, there are N non-overlapping points. Consider a string which forms a large cycle and surrounds all of the N points. As we shorten the string, the cycle will become smaller and smaller. Since we have to surround all points, when the string can not be any shorter, the string will form a polygon, which is called the convex hull.
There is a simple way to find a convex hull of N points, which is the so call “gift wrapping algorithm.” We will show the steps as follows.
    1. Consider the coordinates, and select the point with the smallest X. If there are multiple choices, select the one with the smallest Y. Let a point P denotes this point.
    2. Set a vector D=(0,1), denote the “direction”.
    3. For all the other points, find the point, Q, which forms the smallest angle, Θ, between direction D and direction PQ. Use a dot product D*PQ = |D||PQ|cosΘ, we can use the value of cosΘ to compare the angles of Θ for different Q. If there are more than one Qs form the same Θ, choose the one with the largest |PQ|.
    4. Do step 3 continuously until the convex hull is closed (we reach the first point).

Hint: to get the square root, use the function:

double sqrt(double x)

in math.h

Input

There will be multiple cases in the input.
The first line contains a positive integer T, T≦100, which denotes the number of cases.
For each case, the first line contains an integers N ,2≦N≦1000, which is the number of points on the plane. There are N lines following, and each line contains 2 integers X and Y, which are the coordinates of that point. All coordinates are between -10000 and 10000.
Values will be separated with spaces.

Output

For each case, output a line containing one integer denoting the minimum number of points needed to form a convex hull to cover all points.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1400 - PT - Tedious Job   

Description

PT - Tedious Job

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1402 - PV - Veteran Engineer   

Description

PV - Veteran Engineer

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1403 - PW - World War V   

Description

PW - World War V

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1404 - PX - Xanadu Protector   

Description

PX - Xanadu Protector

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1405 - PY - Yoyo Movie Theater   

Description

PY - Yoyo Movie Theater

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1406 - PZ - Zombiefest!   

Description

PZ - Zombiefest!

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1407 - Bracket Matching   

Description

Given a sequence of well-formed parentheses that consists only of '(' and
')', our target is to output, for each of the closing parentheses that we
scan from left to right, the location of the corresponding open parenthesis.

Remark: We will include some very long sequences of parentheses as our
test cases. If your program cannot pass all the test cases, the most
common reasons are either it contains bugs, or it does not run in linear
time.

Input

There are many cases in the input.
For each case, it is one line with legal brackets.
Input will end with EOF.

1407: length <= 30
1408: length <= 2000
1409: length <= 40000

Output

For each case, output the closing parentheses that we scan from left to right, the location of the corresponding open parenthesis.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1410 - Modified Josephus   

Description

Given n persons, labeled by 1, 2, 3, ..., n in a circle, each surviving
person takes turn to kill some person, until only one person survives. The
rule is similar to the Josephus problem, where player 1 starts the
killing. The difference is that in the i-th turn, a player kills the i-th
person in front of him/her in the circle (where such a person could be
himself/herself). Also, after each killing, the one immediately after the
person being killed starts the killing in the next round. Our target is,
given the input n, output the label of the survivor.

 

Example:

Suppose n = 5. Beginning: 1 2 3 4 5 (in the circle)
Round 1: 1 3 4 5 (1 kills 2)
Round 2: 1 3 4 (3 kills 5)
Round 3: 3 4 (1 kills 1)
Round 4: 4 (3 kills 3)
==> Output 4 as the survivor.

Suppose n = 6. Beginning: 1 2 3 4 5 6 (in the circle)
Round 1: 1 3 4 5 6 (1 kills 2)
Round 2: 1 3 4 6 (3 kills 5)
Round 3: 1 3 6 (6 kills 4)
Round 4: 3 6 (6 kills 1)
Round 5: 3 (3 kills 6)
==> Output 3 as the survivor.

Input

There are many cases in the input.
For each case, it is one line with n.
Input will end with EOF.

1410: n <= 30
1411: n <= 1000
1412: n <= 4000

 

Output

For each case , output the label of the survivor.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1413 - Queue with delete middle   

Description

Implement a queue of numbers that supports the following operations:

1. print: print the content of the queue, from beginning to end
(use # to specify the end of queue)
2. enqueue: add a number at the end of the queue
3. dequeue: remove a number from the front of the queue
4. delete-mid: remove the item in the middle of the queue, if the
queue has odd number of items. Otherwise, remove the
two items in the middle of the queue if the queue has
even number of items.
(Do nothing when the queue is empty)

Assuming we start with an empty queue, our target is to perform a sequence
of operations specified by the input


Case 1: operations <= 50
Case 2: operations <= 1500
Case 3: operations <= 10000

Input

Each line contains one operation. The input is terminated by end of file. (EOF)

Example Input 1: 

enqueue 1
enqueue 2
print

 

Example Input 2: 

enqueue 1
enqueue 2
enqueue 5
enqueue 4
enqueue 3
delete-mid
print


Example Input 3: 

enqueue 1
enqueue 2
enqueue 5
enqueue 4
enqueue 3
dequeue
delete-mid
print


Example Input 4: 

enqueue 1
enqueue 2
enqueue 5
enqueue 4
enqueue 3
dequeue
dequeue
dequeue
delete-mid
print

Output

For each print operation, print the content of the queue, from beginning to end. Use # to specify the end of queue. Each number and # should be separated by a blank. Note that there is no blank after #. See the Sample Output below.

Example Output 1:

1 2 #


Example Output 2:

1 2 4 3 #


Example Output 3:

2 3 #


Example Output 4:

#

Sample Input  Download

Sample Output  Download

Tags




Discuss




1416 - BST Problem 1 (I)   

Description

In this problem, please implement a binary search tree (BST).
You have to implement the following methods:


(1) Insert x:
      Insert an integer x into the BST if x hasn’t in the BST yet.
(2) Size x:
      Find the node x in the BST and print the number of nodes in this subtree.
      If x isn't in the BST, print -1.

Input

 For each subproblem:

(1) 1416: N <= 200
(2) 1417: N <= 10000
(3) 1418
: N <= 60000

N is the number of nodes in the tree.

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1419 - BST Problem 2 (I)   

Description

 

In this problem, please implement a binary search tree (BST).
You have to implement the following methods:


(1) Insert x:
      Insert an integer x into the BST if x hasn’t in the BST yet.
(2) Depth x:
      Find the node x in the BST and print the depth of x.
      The depth of root is 0. If x isn't in the BST, print -1.

 

Input

For each subproblem:

(1) 1419: N <= 2000
(2) 1420: N <= 20000
(3) 1421: N <= 50000

N is the number of nodes in the tree.

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1422 - BST Problem 3 (I)   

Description

In this problem, please implement a binary search tree (BST).
You have to implement the following methods:

(1) Insert x:
      Insert an integer x into the BST if x hasn’t in the BST yet.
(2) Height x:
      Find the node x in the BST and print the height of the node in this subtree.
      If x isn't in the BST, print -1. The height of leaf is 0.

Input

For each subproblem:

(1) 1422: N <= 2000
(2) 1423: N <= 20000
(3) 1424: N <= 50000
N is the number of nodes in the tree.

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1425 - Problem A - Minimum Scalar Product   

Description

You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.
Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.

Input

The first line of the input file contains integer number T - the number of test cases. For each test case, the first line contains integer number n. The next two lines contain n integers each, giving the coordinates of v1 and v2 respectively.

 
T = 10
100 ≤ n ≤ 800
-100000 ≤ xi, yi ≤ 100000

 

Output

For each test case, output a line

Case #X: Y

where X is the test case number, starting from 1, and Y is the minimum scalar product of all permutations of the two given vectors.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1426 - PB - Bribe the Prisoners   

Description


In a kingdom there are prison cells (numbered 1 to P) built to form a straight line segment. Cells number i and i+1 are adjacent, and prisoners in adjacent cells are called "neighbours." A wall with a window separates adjacent cells, and neighbours can communicate through that window.

All prisoners live in peace until a prisoner is released. When that happens, the released prisoner's neighbours find out, and each communicates this to his other neighbour. That prisoner passes it on to his other neighbour, and so on until they reach a prisoner with no other neighbour (because he is in cell 1, or in cell P, or the other adjacent cell is empty). A prisoner who discovers that another prisoner has been released will angrily break everything in his cell, unless he is bribed with a gold coin. So, after releasing a prisoner in cell A, all prisoners housed on either side of cell A - until cell 1, cell P or an empty cell - need to be bribed.

Assume that each prison cell is initially occupied by exactly one prisoner, and that only one prisoner can be released per day. Given the list of Q prisoners to be released in Q days, find the minimum total number of gold coins needed as bribes if the prisoners may be released in any order.

Note that each bribe only has an effect for one day. If a prisoner who was bribed yesterday hears about another released prisoner today, then he needs to be bribed again.

Input

The first line of input gives the number of cases, N. N test cases follow. Each case consists of 2 lines. The first line is formatted as
P Q
where P is the number of prison cells and Q is the number of prisoners to be released.
This will be followed by a line with Q distinct cell numbers (of the prisoners to be released), space separated, sorted in ascending order.

1 ≤ N ≤ 100
Q ≤ P
Each cell number is between 1 and P, inclusive.

1 ≤ P ≤ 10000

1 ≤ Q ≤ 100 

Output

For each test case, output one line in the format

Case #X: C
where X is the case number, starting from 1, and C is the minimum number of gold coins needed as bribes.  

Sample Input  Download

Sample Output  Download

Tags




Discuss




1427 - AVL Tree Sample   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1428 - AVL Tree Sample (Insert)   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1429 - AVL Tree Sample (Insert with big data)   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1430 - AVL Insert(Small)   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1434 - BST Insert   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1500 - What's Cryptanalysis? [01]   

Description

Cryptanalysis is the process of breaking someone else's cryptographic writing. This sometimes involves some kind of statistical analysis of a passage of (encrypted) text. Your task is to write a program which performs a simple analysis of a given text.

Input

The first line of input contains a single positive decimal integer n. This is the number of lines which follow in the input. The next n lines will contain zero or more characters (possibly including whitespace). This is the text which must be analyzed.

Output

 Each line of output contains a single uppercase letter, followed by a single space, then followed by a positive decimal integer. The integer indicates how many times the corresponding letter appears in the input text. Upper and lower case letters in the input are to be considered the same. No other characters must be counted. The output must be sorted in descending count order; that is, the most frequent letter is on the first output line, and the last line of output indicates the least frequent letter. If two letters have the same frequency, then the letter which comes first in the alphabet must appear first in the output. If a letter does not appear in the text, then that letter must not appear in the output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1504 - Cantor Fractions[01]   

Description

Background

In the late XIXth century the German mathematician George Cantor argued that the set of positive fractions Q+ is equipotent to the set of positive integers N, meaning that they are both infinite, but of the same class. To justify this, he exhibited a mapping from N to Q+ that is onto. This mapping is just traversal of the N x N plane that covers all the pairs:

The first fractions in the Cantor mapping are:

Problem

Write a program that finds the i-th Cantor fraction following the mapping outlined above.

Input

The inputs consists of several lines with a positive integer number i each one.

Output

The output consists of a line per input case, that contains the i-th fraction, with numerator and denominator separed by a slash (/). The fraction should not be in the most simple form.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1508 - Goldbach's Conjecture[01]   

Description

 

In 1742, Christian Goldbach, a German amateur mathematician, sent a letter to Leonhard Euler in which he made the following conjecture:

Every number greater than 2 can be written as the sum of three prime numbers.

Goldbach cwas considering 1 as a primer number, a convention that is no longer followed. Later on, Euler re-expressed the conjecture as:

Every even number greater than or equal to 4 can be expressed as the sum of two prime numbers.

 


For example:

 

  • 8 = 3 + 5. Both 3 and 5 are odd prime numbers.
  • 20 = 3 + 17 = 7 + 13.
  • 42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23.

Today it is still unproven whether the conjecture is right. (Oh wait, I have the proof of course, but it is too long to write it on the margin of this page.)

 


Anyway, your task is now to verify Goldbach's conjecture as expressed by Euler for all even numbers less than a million.

 

Input

The input file will contain one or more test cases.

Each test case consists of one even integer n with $6 le n < 1000000$.

Input will be terminated by a value of 0 for n.

 

Output

For each test case, print one line of the form n = a + b, where a and b are odd primes. Numbers and operators should be separated by exactly one blank like in the sample output below. If there is more than one pair of odd primes adding up to n, choose the pair where the difference b - a is maximized.

If there is no such pair, print a line saying ``Goldbach's conjecture is wrong."

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1512 - How many Fibs?[01]   

Description

 Recall the definition of the Fibonacci numbers:

f1 := 1 
f2 := 2 
fn := fn-1 + fn-2     (n>=3)

Given two numbers a and b, calculate how many Fibonacci numbers are in the range [a,b].

 

Input

The input contains several test cases. Each test case consists of two non-negative integer numbers a and b. Input is terminated by a=b=0. Otherwise, a<=b<=10100. The numbers a and b are given with no superfluous leading zeros. 

Output

For each test case output on a single line the number of Fibonacci numbers fi with a<=fi<=b

Sample Input  Download

Sample Output  Download

Tags




Discuss




1516 - Mouse Clicks[01]   

Description

A typical windowing system on a computer will provide a number of icons on the screen as well as some defined regions. When the mouse button is clicked, the system has to determine where the cursor is and what is being selected. For this problem we assume that a mouse click in (or on the border of) a region selects that region, otherwise it selects the closest visible icon (or icons in the case of a tie).

Consider the following screen:

A mouse click at `a' will select region A. A mouse click at `b' will select icon 1. A mouse click at `c' will select icons 6 and 7. A mouse click at `d' is ambiguous. The ambiguity is resolved by assuming that one region is in front of another. In the data files, later regions can be assumed to be in front of earlier regions. Since regions are labelled in order of appearance (see later) `d' will select C. Note that regions always overlap icons so that obscured icons need not be considered and that the origin (0,0) is at the top left corner.

Write a program that will read in a series of region and icon definitions followed by a series of mouse clicks and return the selected items. Coordinates will be given as pairs of integers in the range 0..499 and you can assume that all icons and regions lie wholly within the screen. Your program must number all icons (even invisible ones) in the order of arrival starting from 1 and label regions alphabetically in the order of arrival starting from `A'.

Input

Input will consist of a series of lines. Each line will identify the type of data: I for icon, R for region and M for mouse click. There will be no separation between the specification part and the event part, however no icon or region specifications will follow the first mouse click. An I will be followed by the coordinates of the centre of the icon, R will be followed by the coordinates of the top left and bottom right corners respectively and M will be followed by the coordinates of the cursor at the time of the click. There will always be at least one visible icon and never more than 25 regions and 50 icons. The entire file will be terminated by a line consisting of a single #.

Output

Output will consist of one line for each mouse click, containing the selection(s) for that click. Regions will be identified by their single character identifier, icon numbers will be written out right justified in a field of width 3, and where there is more than one icon number they will appear in increasing numerical order.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1520 - Rank the Languages[01]   

Description

You might have noticed that English and Spanish are spoken in many areas all over the world. Now it would be nice to rank all languages according to the number of states where they are spoken.

You're given a map which shows the states and the languages where they are spoken. Look at the following map:

ttuuttdd
ttuuttdd
uuttuudd
uuttuudd

The map is read like this: Every letter stands for a language and states are defined as connected areas with the same letter. Two letters are "connected" if one is at left, at right, above or below the other one. So in the above map, there are three states where the language "t" is spoken, three where "u" is spoken and one state where people speak "d".

Your job is to determine the number of states for each language and print the results in a certain order.

 

Input

The first line contains the number of test cases N. Each test case consists of a line with two numbers H and W, which are the height and the width of the map. Then follow H lines with a string of W letters. Those letters will only be lowercase letters from "a" to "z". 

Output

For each test case print "World #n", where n is the number of the test case. After that print a line for each language that appears in the test case, which contains the language, a colon, a space and the number of states, where that language is spoken. These lines have to be ordered decreasingly by the number of states. If two languages are spoken in the same number of states, they have to appear alphabetically, which means language "i" comes before language "q", for example. 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1524 - Play on Words[01]   

Description

Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve it to open that doors. Because there is no other way to open the doors, the puzzle is very important for us.

There is a large number of magnetic plates on every door. Every plate has one word written on it. The plates must be arranged into a sequence in such a way that every word begins with the same letter as the previous word ends. For example, the word ``acm'' can be followed by the word ``motorola''. Your task is to write a computer program that will read the list of words and determine whether it is possible to arrange all of the plates in a sequence (according to the given rule) and consequently to open the door. 

Input

The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing a single integer number Nthat indicates the number of plates (1 <= N <= 100000). Then exactly Nlines follow, each containing a single word. Each word contains at least two and at most 1000 lowercase characters, that means only letters 'a' through 'z' will appear in the word. The same word may appear several times in the list. 

Output

Your program has to determine whether it is possible to arrange all the plates in a sequence such that the first letter of each word is equal to the last letter of the previous word. All the plates from the list must be used, each exactly once. The words mentioned several times must be used that number of times.

If there exists such an ordering of plates, your program should print the sentence "Ordering is possible.". Otherwise, output the sentence "The door cannot be opened.". 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1528 - The Gossipy Gossipers Gossip Gossips[01]   

Description

"Gossipy gossiper, what did you get of so much gossiping?
You set your soul into hell. Behold your great achievement!"

M.A. Hevia. Mermuradora.

Gossiping mechanism is quite simple, but effective. Everything starts with a master gossiper (most probably a she), who hears, witnesses, or makes up some extraordinary news. Whenever she meets another person, she tells him the news. As soon as these people meet others, they tell them the news. Soon, everybody is informed of the news, and the process finishes.

Gossipers meet each other daily at the same hours. We have information on when every pair of gossipers meet. For simplicity, days are divided into 100 instants. The first day goes from 0 to 99, the second from 100 to 199, and so on.

Suppose the gossiping process starts at time 0. When will it finish? That is, when will all the people be informed of the news? 

Input

The first line of the input contains an integer N, indicating the number of test cases.

For each test case, the first line contains two integers M and KM indicates the number of people in this case (numbered from 1 to M). The master gossiper is always number 1. K indicates the number of pairs of people who meet.

Next, we have 2K lines (two lines for each pair of people who meet). The first line of each pair contains three integers, G1G2 and V. This line means that gossipers G1 and G2 meet V times a day. The second line contains V numbers from 1 to 99, that indicate the instants when G1 and G2 meet daily.

For example, the pair:

3 7 2
28 88
means: person 3 and person 7 meet twice a day, at instants 28 and 88 everyday (that is, at 28, 88, 128, 188, 228, 288, ...).

You can assume that M ≤ 20, K ≤ M*M, and V ≤ 12 . 

Output

For each test case, the output should consist of a single integer F in one line, indicating the instant when the process finishes. If the process does not finish (for example, there is some isolated person who will never be informed), the result should be -1. 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1532 - A Node Too Far [01]   

Description

To avoid the potential problem of network messages (packets) looping around forever inside a network, each message includes a Time To Live (TTL) field. This field contains the number of nodes (stations, computers, etc.) that can retransmit the message, forwarding it along toward its destination, before the message is unceremoniously dropped. Each time a station receives a message it decrements the TTL field by 1. If the destination of the message is the current station, then the TTL field's value is ignored. However, if the message must be forwarded, and the decremented TTL field contains zero, then the message is not forwarded.

 

In this problem you are given the description of a number of networks, and for each network you are asked to determine the number of nodes that are not reachable given an initial node and TTL field value. Consider the following example network:

 

If a message with a TTL field of 2 was sent from node 35 it could reach nodes 15, 10, 55, 50, 40, 20 and 60. It could not reach nodes 30, 47, 25, 45 or 65, since the TTL field would have been set to zero on arrival of the message at nodes 10, 20, 50 and 60. If we increase the TTL field's initial value to 3, starting from node 35 a message could reach all except node 45.

Input

There will be multiple network configurations provided in the input. Each network description starts with an integer NC specifying the number of connections between network nodes. An NC value of zero marks the end of the input data. Following NC there will be NC pairs of positive integers. These pairs identify the nodes that are connected by a communication line. There will be no more than one (direct) communication line between any pair of nodes, and no network will contain more than 30 nodes. Following each network configuration there will be multiple queries as to how many nodes are not reachable given an initial node and TTL field setting. These queries are given as a pair of integers, the first identifying the starting node and the second giving the initial TTL field setting. The queries are terminated by a pair of zeroes.

Output


For each query display a single line showing the test case number (numbered sequentially from one), the number of nodes not reachable, the starting node number, and the initial TTL field setting. The sample input and output shown below illustrate the input and output format.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1536 - Commandos [01]   

Description

A group of commandos were assigned a critical task. They are to destroy an enemy head quarter. The enemy head quarter consists of several buildings and the buildings are connected by roads. The commandos must visit each building and place a bomb at the base of each building. They start their mission at the base of a particular building and from there they disseminate to reach each building. The commandos must use the available roads to travel between buildings. Any of them can visit one building after another, but they must all gather at a common place when their task in done.  In this problem, you will be given the description of different enemy headquarters. Your job is to determine the minimum time needed to complete the mission. Each commando takes exactly one unit of time to move between buildings. You may assume that the time required to place a bomb is negligible. Each commando can carry unlimited number of bombs and there is an unlimited supply of commando troops for the mission.

Input

The first line of input contains a number T<50, where T denotes the number of test cases. Each case describes one head quarter scenario. The first line of each case starts with a positive integer N≤100, where N denotes the number of buildings in the head quarter. The next line contains a positive integer R, where R is the number of roads connecting two buildings. Each of the next R lines contain two distinct numbers,  0≤u,v, this means there is a road connecting building u to building v. The buildings are numbered from 0 to N-1. The last line of each case contains two integers  0≤s,d. Where s denotes the building from where the mission starts and d denotes the building where they must meet.

You may assume that two buildings will be directly connected by at most one road. The input will be such that, it will be possible to go from any building to another by using one or more roads.

Output

For each case of input, there will be one line of output. It will contain the case number followed by the minimum time required to complete the mission. Look at the sample output for exact formatting.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1540 - Turn the Lights Off [01]   

Description

Since we all rely on mother earth, it's our duty to save her. Therefore, you're now asked to save energy by switching lights off.

A friend of yours has the following problem in his job. There's a grid of size 10x10, where each square has a light bulb and a light switch attached to it. Unfortunately, these lights don't work as they are supposed to. Whenever a switch is pressed, not only its own bulb is switched, but also the ones left, right, above and under it. Of course if a bulb is on the edge of the grid, there are fewer bulbs switched.

When a light switches it means it's now on if it was off before and it's now off if it was on before. Look at the following examples, which show only a small part of the whole grid. They show what happens if the middle switch is pressed. "O" stands for a light that's on, "#" stands for a light that's off.

###      #O#
###  ->  OOO
###      #O#
 
###      #O#
OOO  ->  ###
###      #O#

Your friend loves to save energy and asks you to write a program that finds out if it is possible to turn all the lights off and if possible then how many times he has to press switches in order to turn all the lights off.

Input

There are several test cases in the input. Each test case is preceded by a single word that gives a name for the test case. After that name there follow 10 lines, each of which contains a 10-letter string consisting of "#" and "O". The end of the input is reached when the name string is "end".

Output

For every test case, print one line that consists of the test case name, a single space character and the minimum number of times your friend has to press a switch. If it is not possible to switch off all the lights or requires more than 100 presses then the case name should be followed by space and then a -1.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1544 - 23 Out of 5 [01]   

Description

Your task is to write a program that can decide whether you can find an arithmetic expression consisting of five given numbers ai (1 ≤ i ≤ 5) that will yield the value 23.

For this problem we will only consider arithmetic expressions of the following from:

where :{1,2,3,4,5} -> {1,2,3,4,5} is a bijective function and {+,-,*} (1 ≤ i ≤ 4)

Input

The Input consists of 5-Tupels of positive Integers, each between 1 and 50.

Input is terminated by a line containing five zero's. This line should not be processed.

Output

For each 5-Tupel print "Possible" (without quotes) if their exists an arithmetic expression (as described above) that yields 23. Otherwise print "Impossible".

Sample Input  Download

Sample Output  Download

Tags




Discuss




1548 - Numerically Speaking [1]   

Description

A developer of crossword puzzles (and other similar word games) has decided to develop a mapping between every possible word with from one to twenty characters and unique integers. The mapping is very simple, with the ordering being done first by the length of the word, and then alphabetically. Part of the list is shown below.

a 1
b 2
...
z 26
aa 27
ab 28
...
snowfall 157,118,051,752
...
 

Your job in this problem is to develop a program which can translate, bidirectionally, between the unique word numbers and the corresponding words.

Input

Input to the program is a list of words and numbers, one per line starting in column one, followed by a line containing a single asterisk in column one. A number will consist only of decimal digits (0 through 9) followed immediately by the end of line (that is, there will be no commas in input numbers). A word will consist of between one and twenty lowercase alphabetic characters (a through z).

Output

The output is to contain a single line for each word or number in the input data. This line is to contain the word starting in column one, followed by an appropriate number of blanks, and the corresponding word number starting in column 23. Word numbers that have more than three digits must be separated by commas at thousands, millions, and so forth.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1552 - Twin Primes [1]   

Description

Twin primes are pairs of primes of the form (p, p+2). The term "twin prime" was coined by Paul Stäckel (1892-1919). The first few twin primes are (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43). In this problem you are asked to find out the S-th twin prime pair where S is an integer that will be given in the input.

Input

The input will contain less than 10001 lines of input. Each line contains an integers S (1 ≤ ≤ 100000), which is the serial number of a twin prime pair. Input file is terminated by end of file. 

Output

For each line of input you will have to produce one line of output which contains the S-th twin prime pair. The pair is printed in the form (p1,p2). Here means the space character (ASCII 32). You can safely assume that the primes in the 100000-th twin prime pair are less than 20000000.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1556 - Closest Sums [1]   

Description

Given is a set of integers and then a sequence of queries. A query gives you a number and asks to find a sum of two distinct numbers from the set, which is closest to the query number.

Input

Input contains multiple cases.

Each case starts with an integer n (1 < ≤ 1000), which indicates, how many numbers are in the set of integer. Next n lines contain n numbers. Of course there is only one number in a single line. The next line contains a positive integer m giving the number of queries, 0 < m < 25. The next m lines contain an integer of the query, one per line.

Input is terminated by a case whose = 0. Surely, this case needs no processing.

 

Output

Output should be organized as in the sample below. For each query output one line giving the query value and the closest sum in the format as in the sample. Inputs will be such that no ties will occur.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1560 - Foreign Exchange [1]   

Description

Your non-profit organization (iCORE - international Confederation of Revolver Enthusiasts) coordinates a very successful foreign student exchange program. Over the last few years, demand has sky-rocketed and now you need assistance with your task.

The program your organization runs works as follows: All candidates are asked for their original location and the location they would like to go to. The program works out only if every student has a suitable exchange partner. In other words, if a student wants to go from A to B, there must be another student who wants to go from B to A. This was an easy task when there were only about 50 candidates, however now there are up to 500000 candidates!

Input

The input file contains multiple cases. Each test case will consist of a line containing n - the number of candidates (1 ≤ n ≤ 500000), followed by n lines representing the exchange information for each candidate. Each of these lines will contain 2 integers, separated by a single space, representing the candidate's original location and the candidate's target location respectively. Locations will be represented by nonnegative integer numbers. You may assume that no candidate will have his or her original location being the same as his or her target location as this would fall into the domestic exchange program. The input is terminated by a case where n = 0; this case should not be processed.

Output

For each test case, print "YES" on a single line if there is a way for the exchange program to work out, otherwise print "NO".

Sample Input  Download

Sample Output  Download

Tags




Discuss




1564 - Not That Kind of Graph [01]   

Description

(Simulation)

Your task is to graph the price of a stock over time. In one unit of time, the stock can either Rise, Fall or stay Constant. The stock's price will be given to you as a string of R's, F's and C's. You need to graph it using the characters '/' (slash), '' (backslash) and '_' (underscore).

Input

The first line of input gives the number of cases, N (N ≦ 30). N test cases follow. Each one contains a string of at least 1 and at most 50 upper case characters (R, F or C).

Output

For each test case, output the line "Case #x:", where x is the number of the test case. Then print the graph, as shown in the sample output, including the x- and y-axes. The x-axis should be one character longer than the graph, and there should be one space between the y-axis and the start of the graph. There should be no trailing spaces on any line. Do not print unnecessary lines. The x-axis should always appear directly below the graph. Finally, print an empty line after each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1568 - Critical Links [01]   

Description

(Graphs and DFS)

In a computer network a link L, which interconnects two servers, is considered critical if there are at least two servers A and B such that all network interconnection paths between A and B pass through L. Removing a critical link generates two disjoint sub-networks such that any two servers of a sub-network are interconnected. For example, the network shown in figure 1 has three critical links that are marked bold: 0 - 1, 3 - 4 and 6 - 7.

Figure 1: Critical links

It is known that:

  1. the connection links are bi-directional;
  2. a server is not directly connected to itself;
  3. two servers are interconnected if they are directly connected or if they are interconnected with the same server;
  4. the network can have stand-alone sub-networks.

Write a program that finds all critical links of a given computer network.

 

Input

The program reads sets of data from a text file. Each data set specifies the structure of a network and has the format:

no_of_servers
server0 (no_of_direct_connections) connected_server ... connected_server
...
serverno_of_serveres - 1 (no_of_direct_connections) connected_server ... connected_server

The first line contains a positive integer no_of_servers (possibly 0) which is the number of network servers. The next no_of_servers lines, one for each server in the network, are randomly ordered and show the way servers are connected. The line corresponding to serverk, 0 ≦ kno_of_servers – 1, specifies the number of direct connections of serverk and the servers which are directly connected to serverk. Servers are represented by integers from 0 to no_of_servers – 1. Input data are correct. The first data set from sample input below corresponds to the network in figure 1, while the second data set specifies an empty network.

Input Specifications

  1. The number of test cases: T (T ≦ 20)
  2. The number of servers in the network: N (N ≦ 100)
  3. There is at most one link between any two servers.

     

 

Output

The result of the program is on standard output. For each data set the program prints the number of critical links and the critical links, one link per line, starting from the beginning of the line, as shown in the sample output below. The links are listed in ascending order according to their first element, break tie by the second element. The output for the data set is followed by an empty line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1572 - Play on Words [01]   

Description

(Eulerian circuit)

Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve it to open those doors. Because there is no other way to open the doors, the puzzle is very important for us.

There are a large number of magnetic plates on every door. Every plate has one word written on it. The plates must be arranged into a sequence in such a way that every word begins with the same letter as the previous word ends. For example, the word ``acm'' can be followed by the word ``motorola''. Your task is to write a computer program that will read the list of words and determine whether it is possible to arrange all of the plates in a sequence (according to the given rule) and consequently to open the door.

Input

The input consists of T test cases. The number of them (T ≦ 20) is given on the first line of the input file. Each test case begins with a line containing a single integer number N that indicates the number of plates (1 ≦ N ≦ 100000). Then exactly N lines follow, each containing a single word. Each word contains at least two and at most 1000 lowercase characters, that means only letters 'a' through 'z' will appear in the word. The same word may appear several times in the list.

Output

Your program has to determine whether it is possible to arrange all the plates in a sequence such that the first letter of each word is equal to the last letter of the previous word. All the plates from the list must be used, each exactly once. The words mentioned several times must be used that number of times.

If there exists such an ordering of plates, your program should print the sentence "Ordering is possible.". Otherwise, output the sentence "The door cannot be opened.".

Sample Input  Download

Sample Output  Download

Tags




Discuss




1576 - Domino Effect [01]   

Description

 

Did you know that you can use domino bones for other things besides playing Dominoes? Take a number of dominoes and build a row by standing them on end with only a small distance in between. If you do it right, you can tip the first domino and cause all others to fall down in succession (this is where the phrase ``domino effect'' comes from).

While this is somewhat pointless with only a few dominoes, some people went to the opposite extreme in the early Eighties. Using millions of dominoes of different colors and materials to fill whole halls with elaborate patterns of falling dominoes, they created (short-lived) pieces of art. In these constructions, usually not only one but several rows of dominoes were falling at the same time. As you can imagine, timing is an essential factor here.

It is now your task to write a program that, given such a system of rows formed by dominoes, computes when and where the last domino falls. The system consists of several ``key dominoes'' connected by rows of simple dominoes. When a key domino falls, all rows connected to the domino will also start falling (except for the ones that have already fallen). When the falling rows reach other key dominoes that have not fallen yet, these other key dominoes will fall as well and set off the rows connected to them. Domino rows may start collapsing at either end. It is even possible that a row is collapsing on both ends, in which case the last domino falling in that row is somewhere between its key dominoes. You can assume that rows fall at a uniform rate.

Input

The input file contains descriptions of T domino systems (T ≤ 30). The first line of each description contains two integers: the number n of key dominoes (1 ≦ n < 500) and the number m of rows between them. The key dominoes are numbered from 1 to n. There is at most one row between any pair of key dominoes and the domino graph is connected, i.e. there is at least one way to get from a domino to any other domino by following a series of domino rows.

The following m lines each contain three integers a, b, and l, stating that there is a row between key dominoes a and b that takes l seconds to fall down from end to end.

Each system is started by tipping over key domino number 1.

The file ends with an empty system (with n = m = 0), which should not be processed.

Output

For each case output a line stating the number of the case (`System #1', `System #2', etc.). Then output a line containing the time when the last domino falls, exact to one digit to the right of the decimal point, and the location of the last domino falling, which is either at a key domino or between two key dominoes. If the last domino is between key domino A and key domino B, you should output the smaller one first and then the larger one. For example, if A = 5, B = 3, and the falling time of last domino is 3.0, you should output "The last domino falls after 3.0 seconds, between key dominoes 3 and 5.". Adhere to the format shown in the output sample. It is guaranteed that only one such output exists. Output a blank line after each system.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1580 - The Net [01]   

Description

Taking into account the present interest in the Internet, a smart information routing becomes a must. This job is done by routers situated in the nodes of the network. Each router has its own list of routers which are visible for him (so called ``routing table"). It is obvious that the information should be directed in the way which minimizes number of routers it has to pass (so called ``hop count").

Your task is to find an optimal route (minimal hop count) for the given network form the source of the information to its destination.

Input

First line contains number of routers in the network (n). Next n lines contain description of the network. Each line contains router ID, followed by a hyphen and comma separated list of IDs of visible routers. The list is sorted in ascending order. Next line contains a number of routes (m) you should determine. The consecutive m lines contain starting and ending routers for the route separated by a single space.

Input data may contain descriptions of many networks.

Output

For each network you should output a line with 5 hyphens and then, for each route, a list of routers passed by information sent from starting to destination routers.

In case passing of information is impossible (no connection exists) you should output a string ``connection impossible". In case of multiple routes with the same `hop count' the one with lower IDs should be outputted (in case of route form router 1 to 2 as 1 3 2 and 1 4 2 the 1 3 2 should be outputted).

Assumptions: A number of routers is not greater than 300 and there are at least 2 routers in the network. Each routers ``sees" no more than 50 routers.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1584 - Page Hopping [01]   

Description

It was recently reported that, on the average, only 19 clicks are necessary to move from any page on the World Wide Web to any other page. That is, if the pages on the web are viewed as nodes in a graph, then the average path length between arbitrary pairs of nodes in the graph is 19.

Given a graph in which all nodes can be reached from any starting point, your job is to find the average shortest path length between arbitrary pairs of nodes. For example, consider the following graph. Note that links are shown as directed edges, since a link from page a to page b does not imply a link from page b to page a.

The length of the shortest path from node 1 to nodes 2, 3, and 4 is 1,1, and 2 respectively. From node 2 to nodes 1, 3 and 4, the shortest paths have lengths of 3, 2, and 1. From node 3 to nodes 1, 2, and 4, the shortest paths have lengths of 1, 2, and 3. Finally, from node 4 to nodes 1, 2, and 3 the shortest paths have lengths of 2, 3, and 1. The sum of these path lengths is 1 + 1 + 2 + 3 + 2 + 1 + 1 + 2 + 3 + 2 + 3 + 1 = 22. Since there are 12 possible pairs of nodes to consider, we obtain an average path length of 22/12, or 1.833 (accurate to three fractional digits).

Input

The input data will contain multiple test cases. Each test case will consist of an arbitrary number of pairs of integers, a and b, each representing a link from a page numbered a to a page numbered b. Page numbers will always be in the range 1 to 100. The input for each test case will be terminated with a pair of zeroes, which are not to be treated as page numbers. An additional pair of zeroes will follow the last test case, effectively representing a test case with no links, which is not to be processed. The graph will not include self-referential links (that is, there will be no direct link from a node to itself), and at least one path will exist from each node in the graph to every other node in the graph.

Output

For each test case, determine the average shortest path length between every pair of nodes, accurate to three fractional digits. Display this length and the test case identifier (they're numbered sequentially starting with 1) in a form similar to that shown in the sample output below.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1588 - Fans and Gems [01]   

Description

Tomy's fond of a game called 'Fans and Gems' (also known as Gravnic). In the game, he can use fans to collect gems, but he's satisfied with his play only if all the gems are collected with minimal number of steps. The game is played as following:

There are three kinds of gems, one colored red, one colored green and one colored blue. There are walls in the space, as you see. There are also virtual fans everywhere in the game, but you cannot see them. What you can do each time is to select a DIRECTION to which the fans should blow. There are only four directions possible: UP, DOWN, LEFT and RIGHT. Then, the fans will work, pushing all the gems to fly to the selected direction at the same speed, until they cannot move further(blocked by the wall, other gems or a flyer). Then, if there are some gems touching some same-colored gem(touching means adjacent in one of the four directions), they disappear simultaneously. Note that the fans are still working, so some gems may go on moving in that direction after some gems disappeared. The fans stop working when all the gems cannot move any more, and none of them should disappear. There may be some flyers that can be moved by the fans, but they can NEVER disappear.

You are to write a program that finds the minimal number of operations to make all the gems disappear.

Input

The input file begins with an integer T, indicating the number of test cases. (1 ≤ T ≤ 15) Each test case begins with two integers N, M, indicating the height and width of the map. (1 ≤ N ≤ 12, 1 ≤ M ≤ 20) In the following N lines, each line contains M characters describing the map. There is one line after each map, ignore them. Spaces denotes empty square, '#' denotes a wall, '1' denotes a red gem, '2' denotes a green gem, '3' denotes a blue gem, and '@' denotes a flyer. It's guaranteed that the four sides of the map are all walls. There is at least one gem in the map, and no two same-colored gems will touch each other at the beginning of the game.

Output

You should print a single line for each case. If there is a solution, write the shortest operation sequence in a string. The ith character must be from the set {'U','D','L','R'}, describing ith operation. The four characters represent UP, DOWM, LEFT, RIGHT respectively. If there are more than one solution, choose the lexicographical smallest one, if there are no solution, output -1 on the line. When a solution exists, you need only 18 or fewer steps to carry it out.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1599 - Accumulated Error   

Description

For the safety concern, an elevator must have a limitation of the total weight it carries.  Supposed there are N people wants to take the elevator in the same time, it is important to know whether their total weight is over-weighted.  Unfortunately, measurement always comes with error.  Now, we know the weight of every person, and the error of the weight, marked as W+-E, like 72.0+-1.5.  Supposed the error is able to be accumulated, you are to determine the total weight of these N people, and the overall error of the sum of weight.

Input

There will be many test cases in a single file.

The first line of file contains one positive integer T, T≤10, indicating the number of test cases.

The following are T test cases.  For each case, it will have 3 lines as the information.  There is only one positive real number N, N≤100 in the first line, indicating the number of people.  The next line contains N real number, indicating the weight Wi for each person.  The third line also contains N integers, indicating the error Ei for each person. All Wi and Ei ≤ 200.

Output

For each test case, output a line with 2 real numbers which are the total weight and total error. You must output each real number with one digit after the decimal point, and separate them with a space.

If you use the in C language, you can use something like scanf(“%f”, &value) to read value, and use printf(“%.1f”, value) to write value.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1600 - PA - Loyal Army   

Description

  Alexander was a strict king. He asked the army not only had to win but defeat the enemy in the way he wanted. Because of stern discipline, the force he had was fighting and winning repeatedly.

  One of training was marching on a grid map. The army was on the northwestern square at first, and he gave some orders to the army. They would move into the southeastern square in the end. Alexander only gave them two types of orders: go east or go south. Then they would move along the direction to the next adjacent square on the map. Since Alexander would boil over when they made any mistake and probably killed somebody, they moved as Alexander’s commands in order to survive.

  However, the map was not safe since an ancient wizard set magic traps in some squares. Once the army moved into the trap, all of them would be wiped out. As a wisdom king, Alexander knew which square was not safe so that the force could pass the map without any casualty. You, as a loyal retainer, were asked to count the number of ways to pass through the map.

Input

   The first line is an integer T followed by T test cases. Each case will start with two integers N and M represented the number of row and column in a map. The next line is an integer K followed by K positions (ri, ci) in next K lines contained traps on the map.

   T < 20 and 1 < N, M < 18

   Notice that the first sample input is corresponding to the example above.

Output

   For every case, output the case number and the number of way to pass through the map. See sample output for more details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1601 - PB - Weather Report   

Description

  Weather reporting is a tough job.  Most of time, it is too hard to predict whether it will rain 2 weeks later even with the most powerful computer system since the atmosphere is a typical chaos system.

  Modeling is a typical way to solve such a complex system.  In today’s case, we check whether it rains for the past 5 days and determine the probability that the 6th day rains.  You are given the rainfall probability of the 1st, 2nd, 3rd, 4th, and 5th day, and have to answer the rainfall probability of the Nth day.

  The predicted rainfall probability is a linear combination of the past 5 days. i.e., the rainfall probability of the Nth day:

P(N) = a1×P(N-5) + a2×P(N-4) + a3×P(N-3) + a4×P(N-2) + a5×P(N-1).

  Given the number N, please answer the corresponding rainfall probability P(N) of the Nth day. 

Input

The first line of input contains a positive integer T, ≤ 10, which is the number of cases.

For each case, there are 3 lines.

There are 5 non-negative real numbers in the first line, denote the rainfall probability of day 1, day 2, day 3, day 4, and day 5. All probabilities are between 0.0 and 1.0.

The second line also contains 5 non-negative real numbers, which are a1, a2, a3, a4, a5a1 + a2 + a3 + a4 + a5 = 1.0

There is only one integer N, 1 ≤ ≤ 100, denoting the Nth day.

Output

For each input case, output a real number with one digit after the decimal point as P(N).

Sample Input  Download

Sample Output  Download

Tags




Discuss




1602 - PC - Suffix Marking   

Description

  Dr. Hon is an extraordinary researcher in indexing. As the best programmers of his students, you are given a task to help his research. First, you should have some basic knowledge of what his reaching area.

  Given a string T with N characters, we define “suffixes” of T as the strings “start at every possible character, and ends until T ends”. For example, for T=”NTHU-ZZ”, all suffixes of S are:

    S1=”NTHU_ZZ”,
    S2=”THU_ZZ”,
    S3=”HU_ZZ”,
    S4=”U_ZZ”,
    S5=”_ZZ”,
    S6=”ZZ”,
    S7=”Z”,
    S8=””.

  We can compare every 2 suffixes in lexical order. For example, S3<S2 because ‘H’<’T’. If suffix Si ends earlier before Sj while comparing, Si is smaller. For example, S7<S6 and S8 is the smallest suffix.

  For a string T, we will transform it to another string T’, which composed of also N characters, either ‘S’ or ‘L’. If Si<Si+1, the ith character of T’ is ‘S’; if Si>Si+1, the ith character of T’ is ‘L’.

  Given a string T, your task is to answer what the corresponding T’ is.

Input

There are several cases. Each case contains one line of string, the string is composed of the character set {A~Z, a~z, 0~9, _ }, so there will be no any spaces in the input.

The end of input will be a line contains only 1 character ‘#’.

Each case will not exceed 100,000 characters, and there will be no more than 100 cases.

Output

For each case T, output the T’ in a line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1603 - PD - David's Golden Chain   

Description

The graduate season has coming. As a gift for his girlfriend, David Huffman wants to build a golden chain.  After hard trying to look for cheap chains, he has gathered several chains in the same style.  And now, he has to link these chains into one chain.

The store charges for every welding and only two chains can be linked together. Any time two chains are linked, the length of new chain is the sum of two chains. If David wants to link N chains, he must link N-1 times. You might be guessing how the store charges for linking 2 chains. As most of you are thinking, if the length of the first golden chain is L1 and the length of the second golden chain is L2, linking these 2 chains will take David (L1+L2) dollars.

Since David wants to save money, he wants to know what the cheapest way to link all chains into one is.

Then, what is the cheapest way to link all chains? Only follow an easy rule. Pick up the shortest 2 chains, and link them together until there is only one chain are left. Just like the Huffman tree and Huffman code.

Input

The first line in the input file is an integer T( ≤ 20) followed by T test cases. Each test case describes the chains David purchases. The description consists of two parts:

1. The first part is an integer N( 1 ≤ N ≤ 40,000) describing the number of chains he purchases in a line.
2. There are N integers L1, L2, ..., LN, describing the length of N chains in N lines for each of them.

Output

For each test case, output the cheapest cost that David need to spend in a single line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1604 - PE - Prime Grid   

Description

In this problem, you are to solve a game which is composed of numbers on cards and a board.

Given a board which contains 2×N grids and 2N cards which are written the numbers 1~2N.  These grids are named a1, b1, a2, b2, …, aN, bN.  The rules of the game are listed as following:

1. Put these 2N cards onto these 2N grids.
2. For each adjacency pair of grids, i.e. (aibi), (aiai+1) or (bibi+1), the sum of numbers on cards should be a prime number.
3. After you finishing put all cards on the board, your solution is presented by listing the cards on a1, a2, …, aN, b1, b2, …, bN. If there are more than 1 solution, the solution starting with smaller number is better.

Given the number N, please output the best solution.

In mathematics, a prime number is a nature number that can only be divided by 1 and itself.

Input

The first line contains one positive integer T, ≤ 10, denoting the number of cases.

There are T lines following, each line contains one positive integer denoting N for this case. ≤ 10.

Output

For each case, there are 2 lines for output. The first line contains N integers, which are a1, a2, …, and aN, separated by a space. The second line contains N integers, which are b1, b2, …, and bN, also separated by a space.

There are no spaces at the end of each line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1605 - PF - Conveyor Belt   

Description

  There are so many buildings constructing in our campus! Instead of constructing a complicated structure, a modern building is made up of square modules, and every room is in the same shape and with same size. Following figure show a 3×4 model.

a figure illustrated the display of room in a floor.

  Now we want to set up a conveyor belt to put some stuff onto it. In every floor, there are two special rooms that must be the beginning and terminal of conveyor belt. The start room is at the northern-west corner, and the end room is at the southern-west corner. Because of the reachability and reduce cost, the conveyor belt has to pass through each room once and only once.

  It’s important to know whether it is possible to have such configuration, so they ask you to answer it. Moreover, they also want to know how many ways to achieve such configuration. Following is an 3×3 example that has two ways.

two examples of certain pipe configuration.

Input

  There are no more than 5,000 test cases. Every test case contains two integers, n and m, representing a n × m model, where 2 ≤ n ≤ 4, 1 ≤ m ≤ 109.

Output

  Output the number of way to achieve such configuration. Since the number maybe very large, you should take modulo by 7,777,777.If there is no such configuration, output “Impossible”.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1606 - PG - Monkey Hunter   

Description

   Monkey Hunter is an interplanetarily renowned online game. It provides a platform for all kinds of player, and the role they controlled can be stronger and stronger by making their effort on it. Players can get virtual props by completing some missions or defeating monkeys. The harder mission you complete, the rarer props you get.

   They enjoy hunting in Monkey Hunter not only because of the game realistic senses, but the cooperation between players provides an almost real way to interact. Players have to talk to each other to make an efficient communication; otherwise they might have great difficulty to complete a team mission. A team can be divided into several small groups, and each group can contain any the number of roles.

   In recently update, Monkey Hunter designed a new challenge “Paoxiao monkey” to be one of the most difficult challenges. Jelly’s team has spent a lot of time to challenge but they all failed. One of the failed reasons is the total power of defense in whole team is not high enough. When the two roles in the same group, there will be a bonus, additional increase or decrease in power of defense, due to the difference between the equipments, classes, races, and talents of two roles. The power of defense for whole team is the sum of all the characters’ power of defense and the sum of extra bonus.

  Fortunately, Jelly has setup an additional plug-ins to compute the bonus between the two roles, but he still doesn’t know the possible maximum power of his team. You should find out the maximum power of defense in a certain grouping configuration.

Input

  The input consists of multiple test cases. The first line of each test case contains an integer N (0 < N  12), which is the number of characters. The next line contains N integers dps1, dps2, …, dpsN, where dpsi represents ith character’s power of defense. This line is followed by N lines, each of which contains N integers. The ith integer at jth line implies the bonus between ith role and jth role.

  The last test case is followed by a line containing a single zero. There should be no more than 30 test cases.

Output

  For each test case, print the case number (starting with 1) followed by the maximum power of defense for whole team. Follow the format of the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1607 - PH - Take Short-cuts!   

Description

  Walking around the campus has become a part of our life. We attend class in CS building, have a meal in restaurant, and go back to sleep in your dorm.

  Peter thinks that it takes too much time to move between two places. He always wants to reach a place as fast as possible. So he often cuts the corner between two places by passing lawn. However, it is harmful to walk on lawn. Since he doesn’t want to do more harm on lawn, Peter makes a trade-off. He hopes to reach destination without using more than a certain time, so he might not need to pass every short-cut. As a friend of Peter, you want to compute the minimum number of short-cut he has to take to encourage him.

Input

   There are no more than 50 test cases. The first line of each test case contains an integer n, indicating the number of places. (1 ≤ n ≤ 100) The parts are numbered from 1 to n. The second line contains an integer M, indicating the number of roads. Then M lines in the form "a b c", which mean there is a road between the ath place and the bth place and takes c minutes to walk along it. Then an integer S and S lines follow, describing the short-cuts with the same way as the roads. The next contains two integers indicating the places to which the start and the destination. The last line contains one integer T, the time limit to reach the destination. (0 ≤ T ≤ 1,000,000,000)

   The roads and the shortcuts are all bidirectional. There is at most one road between any two places. There is at most one shortcut between any two places. The time cost of each road or shortcut do not exceed 1,500,000 but at least 1.

Output

   Output the minimum number of short-cuts Peter has to take in one line. If it’s impossible to reach on time, print “Impossible” in a single line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1608 - PI - HEX Network   

Description

Wireless communication has become a more and more popular issue in the EECS studies, even though almost all commercial applications are based on a “wired” backbone infrastructure. As the best engineer of the company Hexagonal Electrical eXample (HEX corp.), you are to solve the wire routing problem for the new wireless service of the company.

The HEX corp. is building a new wireless service in a city. As what we told you, the HEX corp. has decided where to build the Access Point (AP) for wireless communication. The APs are distributed depending on the population, geography, and some other issues, and then use the cable to connect them together. In order to keep the maintenance more easily, HEX corp. wishes to route the cables by the streets in the city. Except two ends of cable, any other parts on the cable are insulated. Therefore, two cables on the same street would not affect each other and not be merged into one cable.

The layout of streets in city is very special. There are 3 types of street, which are called type 1, type 2, and type 3. Within each type, streets are parallel. The distances between every 2 parallel streets are the same, and there must be 3 streets cross each intersection.

Any APs are built on the intersections of streets. Assume the length of each street segment is 1; the total cost of the routing is the sum of lengths of cables used. Any APs can be connected indirectly, i.e. if there is a cable connecting AP1 and AP2, and another cable connects AP2 and AP3, then AP1 and AP3 are connected.

You are to determine what is the minimum cost required to connect all APs, by telling the HEX corp. what is the minimum sum of lengths of cables required.

 

Input

There are several cases in the input. There is an integer T, ≤ 100, in first line of input, which indicates the number of cases.

For each case following, the first line contains a number N, ≤ 1000, which indicates the number of APs.

There are N lines following. For the ith line of these lines, there are 3 integers, S(i,1), S(i,2), and S(i,3), which indicate the streets of type 1, type 2, and type 3 which cross the intersection. All these numbers are between 1 and 1000.

Output

For each case, output one line with one integer to indicate the minimum cost of network.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1609 - ZOJ A + B   

Description

Test 

Input

Test 

Output

Test 

Sample Input  Download

Sample Output  Download

Tags




Discuss




1701 - Art of Search Engine - Gogomei   

Description

The Internet is the most important communication media nowadays. There are many powerful search engines, such as Google, Bing, and Baidu.

Dragon Tom is the king of an unknown country, whose countrymen use Google heavily to search for beautiful pictures. However, the engine is not enough for their needs. So Dragon Tom would like to create a brand new search engine, which can search for 99.99% of the beautiful pictures that his people need, and he names the engine Gogomei.

To design Gogomei, the two most significant parts are to create the keywords in the database, and to design an efficient algorithm for searching the query words among the keywords in the database. Dragon Tom has already defined the keywords based on the many beautiful pictures he has collected for about twenty years. To be a coworker of this engine, your task is to write a program for checking whether the query words are in the database or not.

Input

        First line contains a integer t which is the number of test cases.

        For each case, the first line contains a positive integer n (n <= 50,000) indicating the number of keywords in the database of Gogomei. In the next n lines, each line contains one keyword which is composed only by English letters (upper case and lower case are different) and the length of each keyword is less or equal to 30.

        After the keywords, the next line will give you a positive integer m (m <= 50,000) which is the number of queries. In the next m line, each line contains a query word and the format is the same as the keywords in the database.

Output

        For each case, output the line with the text “Case i:” without the quotes, where i is the case number starting from 1. For each query word, if the keyword is in the database, output a line with message “Yes”. Otherwise, output a line with message “No”.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1702 - Build a Program   

Description

        Linear algebra is widely used in scientific computation. Dr. Lee wants to design a system for scientific computation research, and he needs your help. In particular, your task is to write a program to compute the determinant of a square matrix A (n-by-n matrix), which will be one of most frequently used operations in this system.

        However, the closed form of the determinant is too complex when n is greater than three. Dr. Lee suggests you to use the Laplace formula to calculate the determinant recursively. Laplace formula expresses the determinant of a matrix A in terms of its minors. The minor Mij is defined to be the determinant of the (n−1)-by-(n−1) matrix that results from A by removing the ith row and the jth column. The expression (-1)i+jMij is known as cofactor. The determinant of A, denoted by det(A), can be computed by …

        Please write a program to achieve this task.

Input

        The first line contains an integer t (1 <= t <= 20), which indicates the number of test cases in the input.

        Following that, each case starts with an integer n (2 <= n <= 8), which indicates the size of the square matrix A. Then in the next n lines, each line contains n integers, showing the entries of each row of the matrix A. The range of values in the entries is from -5 to 5.

Output

        For each case, output one line with the determinant of matrix A.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1703 - Castle Defend   

Description

        Element TD is a hot game in the world of otaku, and all otakus are crazy about it. According to a CNN report, some friends even quarrel and fight because of the game. It is so terrible! To understand why this game drives people crazy, you decide to play the game now!

        Firstly, there are several maps in the game. Each map has a hole that monsters will come out from it unlimitedly. Monsters will only walk along the roads. Each road may contain up to a certain number of monsters. When a monster reaches a road junction, it will choose the next road to walk randomly.

 

 

        You have a castle to defend from monsters’ attack. To do so, you can build some towers at the road junctions to monitor the road and kill the intruding monsters. Different types of towers have different powers of killing (number of monsters that can be killed in a unit of time) and different building costs. The attack ranges of all the towers are unlimited. For example, for a tower with (power, cost) = (5, 10), then we need to pay 10 dollars to build the tower and this tower can kill 5 monsters in a unit of time.

        To be a perfect gamer, you must find the smallest cost for creating enough towers in a given map, such that you can block attacks from the monsters at any time.

Input

        The first line contains an integer t (t <= 20) that indicates the number of test cases.

        For each test case, the first line contains two integers n (2 <= n <= 70) and m (1 <= m <= n*(n-1)/2), denoting the number of intersections and the number of roads in this map, respectively. The intersections will be labeled by {1, 2, 3, …, n}.

        The next m lines are the information of the roads. Each line consists of three integers ei, ej, and cp(i, j). The integers ei and ej indicates that the road is from intersection i to intersection j, and the value cp(i, j) indicates that the road can contain at most cp(i, j) monsters. Each road is directed so that monsters can walk in one direction.

        The hole where monsters come out is located at intersection 1, and your castle is located at intersection n. The total number of monsters, which you will kill in a unit of time, will be less than 30,000.

        After the road information, the next line will be an integer Q (1 <= Q <= 100), indicating how many types of towers you can choose. And the following Q lines describe the information of each tower. Each line contains two integers pi and gi (1 <= pi, gi <= 1,000), which are the power and the cost of tower i, respectively. 

Output

        For each case, output a line with the minimum cost for creating enough towers.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1704 - Double Pieces   

Description

Monkey D. Luffy is a young man who wants to become the King of the Pirates! Now he and his crew are deciding which sailing route they want to go, among the many islands in the Grand Line.

Luffy’s good friend, Nami, is the navigator of Luffy’s pirate boat Thousand Sunny. Nami wants to know all the possible sailing routes to traverse all the islands in the Grand Line. As an assistant, you need to help Nami to do this work.

Input

The first line contains a positive integer t (t <= 20), which indicates how many cases in the input. Each case starts with a positive integer n (n <= 10), which denotes the number of the islands in the Grand Line. In the next n lines, each line contains the name of an island. The length of name is at most 20, and the name is composed only by English letters.

Output

For each case, first line output the case number (See the Sample Output). Next, output all possible sailing routes in the Grand Line, and for each route, use “-” to separate two consecutive islands. Each line contains one route and the ordering of the routes can be arbitrary (See the Sample Output).

Sample Input  Download

Sample Output  Download

Tags




Discuss




1705 - Earthquake   

Description

             The Great East Japan Earthquake was a magnitude 9.0 undersea megathrust earthquake that occurred off the coast of Japan on Friday, March 11th 2011. Actually, earthquakes are frequently occurring in the world. To understand the distribution of earthquakes, the researchers in Big Research Universal Central of Earthquake (BRUCE) plan to analyze the frequency of the earthquakes in each region in the world.


            Data of the earthquakes are collected from different locations. For ease of understanding, each earthquake is represented by a blue rectangle, whose area indicates the affected range. See Figure 1 for an example.

            Each blue rectangle is represented by the coordinates in its lower-left and upper-right corners. The coordinate values are all integers. In the figure, there are three earthquakes, A, B, and C.  Earthquake A affects the region (0,1) to (4,5), earthquake B affects the region (1,2) to (6,8), and earthquake C affects the region (3,0) to (7,6). Note that the region (3, 3) to (4, 5) was affected by all the three earthquakes.

Given the data, people would like to consider different regions to live. To find the safest place, one idea is to get the maximum earthquake frequency in each of the considered region.  For instance, suppose that the considered region is (2,4) to (8,7), which is represented by the red rectangle in Figure 1. Then the sub-region (3,4) to (4,5) is affected by all three earthquakes, and achieved the maximum frequency of 3. 

Your task is to calculate the maximum frequency for any considered region R.

Input

            The input begins with t (1 <= t <= 10), the number of test cases. For each case, the first line contains two integers n (1 <= n <= 1,000), which is the number of earthquakes, and Q (1 <= Q <= 1,000), which is the number of considered regions. For the next n lines, each line contains four integers x1, y1, x2, y2 (x1 < x2, y1 < y2, 10-9 <= x1, y1, x2, y2 <= 109), which are the regions of the earthquakes. After that, the next Q lines denote the considered regions, whose format will be the same as the regions of the earthquakes.

Output

             For each considered regions, print a line with the maximum earthquake frequency in the region. Print a blank line after the output for each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1706 - Fun Game   

Description

        Not The Huge Users Community Society (NTHUCS) is designing a new online game where people open shops to serve other people in a virtual world. In this game, each user needs to select a virtual country where he/she belongs to. Also, there is a map where each user needs to find a place to open his/her own shop (such as a restaurant, a post office, a bank, etc) to serve other people. Some parts of the map are reserved for the landscapes and the features, such as bridges, rivers, forests, remains …, etc. The remaining parts are empty spots that can be used for the shops.  There are also roads in the map, each road joining two empty spots. To increase the interaction between people from different countries, we wish to restrict that the two owners of the shops on the same road cannot be from the same country.        

        Eventually, each spot in the map will be occupied by some person. Your task is to write a program to check if there is at least a way that users can select their belonging countries so that the restriction can be followed.

Input

The first line of input contains a positive integer t (t <= 20), which indicates how many maps to check. For each map, the first line contains three positive integers n, m, k (n <= 50, m <= n*(n-1)/2, k <= n), indicating that there are n spots for opening shops (a spot is numbered from 1 to n) in the map, m roads, and people can select from one of the k countries. In next m lines, each line contains two integers u and v, which indicate the two end spots of a road.

Output

        For each map, output a line with “Yes” if this map can be used for this online game. Otherwise, output a line with “No”.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1707 - Game Bug   

Description

      Tiyano Playstation Company (TPC) has released a popular game in Android-based cellphone. Each instance of the game has two inputs: (1) a sequence of color blocks and (2) a 2-dimensional table. See Figure 1 for an example.


Figure 1

      The target is to merge adjacent blocks in the sequence until it is left exactly one block, with such a block being a black block. The merging of two adjacent blocks will result in a new block in the same position, whose color is specified by the 2-dimensional table. For example, in Figure 1, there is a block sequence: {red, yellow, blue, red, red, …}, if we merge the first two blocks, by the merge rules in the table, we can get a green block, and the sequence will become {green, blue, red, red, …}. At each step, you can choose two adjacent color blocks to merge as long as there is a merge rule in the table.

      However, the game designer of TPC made a mistake that some instances that you will play in the game have no solution. Unfortunately, he does not know how to check for such instances, and your task is to write a program to determine if an instance is solvable.

Input

        The input begins with t (1 <= t <= 100), the number of test cases. Each test case contains three parts.

        For each test case, the first line contains two integers n (1 <= n <= 10), which is the number of colors, and m (1 <= m <= 100), which is the length of the color sequence. After that, it gives the description of the n x n 2-dimensional matrix, M, such that Mij is the resulting color from merging color i and color j.  Each row of M is printed on a separate line. Here, we use {0, 1, 2, …, n-1} to represent the different colors in the matrix (assume 0 is black color) and Mij = -1 indicates that color i and color j cannot be merged. After that, it contains a line with m integers, indicating the input sequence of colors.

        Take Figure 1 for example. We use {0, 1, 2, 3, 4} to represent the five colors {black, red, yellow, blue, green}, and the matrix will be:

 1 -1  4 -1 -1

 1 -1  4  0  2

-1  3 -1  3  4

 2  4  2 -1  0

-1  0  1  3  2

and the sequence of colors is: 1 2 3 1 1 2 3 0 3 1 2 1 4 4 4 0

Output

    For each test case, print the message of “Yes” or “No” without quotes to indicate if the instance is solvable or not.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1708 - The Integer All-time Champ   

Description

  As Alan Turing and his friend David Champernowne gave the name “The All-time Champ” number (as a joke with the David surname) to the trascendental constant 0.1234567891011... obtained by concatenating the positive integers and interpreting them as decimal digits to the right of a decimal point, let us nominate “All-time Champ Integers” to the numbers constructed by concatenating the digits of a set of consecutive integers.

Given two natural numbers 0<m<=n, there is a such integer, but there are other natural numbers that contain, as substrings, all the numbers between m and n, both included. For example for m=1 and n=13, possible solutions are 12345678910111213(the corresponding “Champ”), 1011213456789or 1101213456789. We can see that the last two numbers have only 13digits as against the 17 of the“Champ”.

Your task is to find out the shortest such integer.

Input

   The input file contains several lines of input. Each line contains two natural numbers m and n (0<m<=n<100). Input is terminated by end of file.

Output

   For each line of input produce one line of output. This line contain a number which is the length of the shortest integer that contains as substring all the numbers between m and n (both included).

Sample Input  Download

Sample Output  Download

Tags




Discuss




1709 - Problem TEST. TESTaceology   

Description

Little Graphy is fond of testaceology, which is a topic of collecting shells.
One day, Little Graphy found a magic shell which can solve A + B problem.
However, Little Graphy can’t even solve the A + B problem, she want to know whether the answer C is correct.
Now, she need your help. She give you B and C, and want you to calculating the original A, then she can check the answer C is correct or not.

Input

The first line is an integer T indicating that there’re T test cases.
For each test case, there’s only one line cotains two integers C;B.
• T  <=100
• C,B will always fit in a 32-bit signed integer.

Output

For each test case, print one line cotains an integer A.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1710 - Problem A. Ambrosia   

Description

enough, they find the intruders’ power overwhelming. As a result, Little Graphy retreats from the Gobi secretly with two alpacas. They escape successfully, but three days after they leave Gobi, Little Graphy finds herself with an empty stomach.
“Are there any prone grass?” asks the hungry hare.
“Don’t see anything in sight,” the pink alpaca, Pinky, replies immediately.
But then the blue alpaca, Blues, bouncing up and down, announces with great enthusiasm, “but I know a place where you can find the holy ambrosia!”
“The holy ambrosia?” Little Graphy asks slightly confused.
“Yes, and there’s a whole mountain of prone grass there!” Pinky yells excitedly.
“Asi que bueno, ellos seran!” Blues says in Spanish.
Little Graphy has a weird feeling about this, but she’s too hungry to think. The only thing she can think about is eating.
“Okay, how to get to the place?” “The Holy Candy Mountain!” answers Pinky.
“Umm... then how are we going to get to the Holy Candy Mountain?”
“It’s quite easy,” said Blues. “All you have to do is write a program to print the following magic
spell.”
But Little Graphy knows nothing about programming, since she is too hungry to even think.
Now it’s your show time. Please write a programming to print the magic spell.

Input

Chaka Chaka Chaka Chaka Chu Chu~
You don’t have to read anything from standard input in this problem

Output

You should output the exactly same characters in the following fifteen lines.
There are always one hundred characters per single line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1711 - Problem B. Black Dark Witch   

Description

After the magic spell is printed, they find that they’ve already reach the Holy Candy Mountain, which is so magnificent that Little Graphy can’t even breathe. While Little Graphy is still in shock, a huge banana drops down in front of them out of the blue.
“Hey! It’s Banana King!” Pinky shouts, “What is he doing here?”
“Hummm, I think he’s dead.” Blues bounces on the body of Banana King.
“Wowwwwww, dead banana! Maybe it is time to have some fruit!” Pinky says excitedly, peeling the banana.
“Stop it, Pinky. We had better move on,” Little Graphy says with its trembling sound, “the sky is getting dark.”
They quickly bypass the dead Banana King, going straightly up to the summit. As soon as they cross one of the forests on the hillside, a woman with a black cloak appears.
“I’m Black Dark Witch. What are you guys doing here?” the woman stares at them.
“We’re here for the prone grass, do you have some?” Pinky answers, “Little Graphy is starving.”
“I think Little Graphy is hungry enough to eat a mountain of prone grass,” laughs Blues.
“Prone grass? Oh…okay, follow me.” Black Dark Witch says softly, entering the cottage behind her.
“Bang!” the door is slammed and locked.
“What are you doing, Little Graphy?” Blues asks.
“What? I’ve just entered, didn’t even touch the door yet!” Little Graphy says, confused.
“Hahahaha,” laughs the Black Dark Witch, “Why are there so many silly guys wants to steal my prone grass away just like the stupid banana?”
“Bye, poor animals,” Black Dark Witch smiles evilly, leaving through the Scary Door.
“Wait!” Little Graphy yells, “Oh chaaaka~~ the door is locked! So scary!”
“I know the way to open the Scary Door,” says Blues.
“There’re some magic plates in the room, all of them have the same size and same pattern.”
“You should pile them in a 5*L rectangle in such a way that none of the marks on plates overlap, and L is smallest.”
“Notice that you should never flip or rotate any of them.”
However, as you know, Little Graphy can’t even solve the A+B problem. It’s your show time again!

Input

There’re several test cases, ended with EOF.
There are two integers n;m in the first line of each test case, which means there’re m plates, with a size of 5*n.
The 2nd to 6th line of each test case represents the pattern. ‘.’ means blank. ‘X’ means mark, which can’t overlap.
• There’re no more than fifteen test cases.
• 1<=m
<=20
• 5
<=200
• nm
<=107

Output

For each test case, print a line containing an integer indicating the smallest length.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1712 - Problem C. Cavern   

Description

http://dl.dropbox.com/u/15327055/codingThorne/problem.pdf

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1713 - Problem D. Doom   

Description

Stepping into the chamber E, Little Graphy and her friend find the Black Dark Witch packaging up some prone grass.

“Black Witch!” yells Pinky, “I’ m gonna burnnnn youuuu!”

“Impressing, really impressing. Many people have died in this cavern,” says the Black Dark Witch.

“However, can you escape again?” she smiles, and disappears into thin air.

“Wai…, ” a laser shoots through Pinky’s body before she finishes her word.

“Pinkyyyyyyyyyyyyyyyyyyy!” cries Blues, “No one will be willing to go scuba diving wi…wow!!” Not until Little Graphy pulls Blues down does he find that the laser gun has been aimed at him.

“Chuchu! I almost get killed!” Blues cries again, “We have to shut this thing down!”

“Well, I think I’ve find the way to turn off the laser gun,” says Little Graphy.

“There’re n red stones and m blue stones on the floor, and there’re some links between some pairs of red and blue stones.”

“Everytime the laser gun shoots, one of the link shines.”

“I think we should destroy some stones in such a way that at least one stone is destroyed in each pair.”

“However, we don’t have lots of time to destroy them, we should spend as less time as possible!”

Can you help Little Graphy figure out the fastest way of destroying stones?

Input

The first line is an integer T indicating that there’re T test cases.

There’re three integers n, m, k in the first line of each test case, which means there’re n red stones, m blue stones, k pairs of links. The second line contains n integers, the ith integer Ri means red stone i will take Ri seconds to destroy. The third line contains m integers, the ith integer Bi means blue stone i will take Bi seconds to destroy. Each of the next k line contains a pair (a, b) means that there is a link between red stone a and blue stone b.

  • T ≤ 15
  • 1 ≤ n, m ≤ 150
  • 0 ≤ Ri, Bi < 231
  • 0 ≤ minimum time Little Graphy needs < 230

Output

Output three lines for each test case. The first line should contains an integer indicating the minimum time Little Graphy needs. The second line contains an integer A and followed by A accending integer represending the number of red stones to be destroyed and which red stones should be destroyed. The third line contains an integer B and followed by B accending integer represending the number of blue stones to be destroyed and which blue stones should be destroyed.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1714 - Problem E. Energy Gun   

Description

“Hurray! We finally destroyed the red stone system!” Blues bounces up and down.

Then he sees Pinky’s body going stiff. “Pinky, I will live for you!” He yells, but all that answers him are his own echoes.

“Little Graphy, let’s go!” Blues stands up, wipes his tears, and walks toward the exit.

Little Graphy keeps up with Blues, and soon she finds a chest filled with some potions. “Oh, the splash potion of harming 2! It may be a great weapon!” she thinks.

Outside the cavern, they find a guy going against a lot of monsters.

He says, “My name is Big China Day. Can you please help me defeat the little pets from the Black Dark Witch?”

Little Graphy looks around, and finds that there are N monsters surrounding them. Monster i has a HP (Health point) Hi. If a monster’s HP goes down to 0, it will die.

Little Graphy has M splash potions of harming 2, and each potion can cause 1 HP of damage on one monster. Big China Day has a magic energy gun which can nerf monsters. That is to say, if the monster i is shot, his HP will become Ci (CiHi). Then it will be easily defeated. However, you can’t shoot at the same monster twice!

The magic energy gun can shoot at most K times, and Little Graphy wants to know how many monsters they can kill with the best strategy.

Input

The first line contains an integer T indicating the number of test cases.

Each test case begins with N, K, M.

The following N lines contain two integers Hi, Ci.

  • T ≤ 30
  • 1 ≤ N ≤ 50000, 0 ≤ KN and 1 ≤ M ≤ 1014
  • 1 ≤ CiHi < 231

Output

For each test case, print a single line containing a non-negative integer which means the maximum number of monsters they can kill.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1715 - Problem F. Friendly Fire   

Description

http://dl.dropbox.com/u/15327055/codingThorne/problem.pdf

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1716 - Problem G. Gate   

Description

Being satisfied with Little Graphy’s performance, Big China Day says, “You already have the ability to be a good warrior.”

“I don’t have anything more to teach you. All you need to defeat those evil river crabs is faith.”

“Good luck, hare, maybe we’ll meet again in the future,” Big China Day waves his hand and starts his next journey.

After ten minutes of study, Little Graphy learns all the things Big China Day knows.

“Wow, it’s time to get our kidney…our Gobi back! Let’s roooooock!” Blues cheers.

“Calm down,” Little Graphy pulls Blues, “we still need something to bribe the guard of the Gobi Gate.”

“Ummm, You’re right. I’ll find out where Gobi is…” says Blues, acting as if he were The Thinker.

“Surely, you’re not listening to me…. Well, I might as well find a present myself,” sighs Little Graphy.

Entering a shop, she finds two queues of rabbit dolls. “I can’t imaginate how cute it would be if I combine these dolls!” Little Graphy thinks while pulling Blues, who is still acting The Thinker.

“Those guards will be too shocked to move if they see such a cute thing!” she says, “It’s god-like!!”

As a result, Little Graphy decides to make a tower of rabbit dolls.

Little Graphy can choose one doll from the front of the two queues each time. She may decide to keep or not to keep the doll each time she takes one doll. The dolls she keeps will be stacked onto the rabbit tower by the order she takes. It means that if the doll is the kth doll she keeps, it’ll be the kth doll if you count from the bottom.

Every rabbit doll has two values V, D. Any rabbit doll i in the tower, which has x dolls on top of it, will contributes Vix × Di points to the cuteness. In order to bribe the guard, Little Graphy wants to maximize the cuteness of the tower. Can you help her calculate the maximum value of cuteness?

Input

The first line contains an integer T indicating the number of test case.

Each test case starts with two integers n, m. indicating the length of the two queues.

The following line contains n pairs of integers V, D representing the n rabbits in the first queue.

The next line contains m pairs of integers V, D representing the m rabbits in the second queue.

  • T ≤ 10
  • 1 ≤ n, m ≤ 200
  • 0 ≤ Vi, Di ≤ 106

Output

For each test case, print the maximum cuteness of the rabbit tower.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1717 - Problem H. Hyper Portal   

Description

http://dl.dropbox.com/u/15327055/codingThorne/problem.pdf

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1718 - Problem I. Information   

Description

Once you get the information, you get victory,” Big China Day says seriously.

After hundreds of battles against each other, neither Little Graphy nor the river crabs are able to defeat the other. One day, when Little Graphy is trying to figure out where the crabs are hidding just like usual, Blues rushes into her tent.

“Graphy! Graphy!” he yells. “How many times did I tell you not to be so rough?” Little Graphy scolds.

“Big China Day said that ‘information is the key to victory,’ right?” Blues says excitedly.

Little Graphy tries to answer, “I’m not sure if h…”

“Guess what? I found some encoded messages in the fortress we destroyed last week!” Blues keeps talking, “Look!”

“My intuition of graph tells me this must be a description of a tree.” Little Graphy says.

“Tree? This is just two sequence of integers and an big number,” he asks, “how can it be a tree?”

Little Graphy smiles to Blues and says, “Obviously, the first sequence is the preorder of the tree.”

“And, the second sequence should be its postorder.”

“The big number k means that the tree’s inorder is the kth possible inorder in lexicographical order.”

“Wow! How do we construct the tree?” Blues asks.

“Hummmmmmnmmmmm…In fact, we need to find out the inorder first…” Little Graphy answers.

Guess what? It’s your show time!

Input

There’re several test cases in the file, ended with EOF.
Every test case starts with two integers n, k.
The following line contains n integers, representing the preorder.
The third line also contains n integers, representing the postorder.

  • 1 ≤ n ≤ 200000
  • 1 ≤ knumber of possible inorder ≤ 260
  • 1 ≤ any element of the tree ≤ 109
  • We guarantee that each number in the tree is distinct.
  • There are no more than 5 test cases.
  • Take a look at Problem C if you don’t know what lexicographical order is.

Output

For each test case, print the inorder traversal of the tree.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1719 - Problem J. Journey’s End   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




1720 - PA - My Legend   

Description

My Legend is a facebook game developed by Happy Elements. It is a RPG game. You are the hero in that world, you will kill enemies and get items, money and experience points. You can level up and get higher ability points by accumulating of the experience points. You can also use the items dropped from the enemies to make better equipment. The money can buy items and upgrade the buildings. There is also a gem system. You can add the gems on your equipment to make them stronger.

This time a new update version is coming. You will get a sequence of items, and there will be some rules told you that if two kinds of the items are adjacent, they can become a new item. This new item could be the same with one of the original item. And each fusion will cost some money. Now given you the sequence of the items, you want to use the minimum cost to make the sequences of items in to only one item left. Please write a program to calculate the minimum cost.

For example, you get "ANT" "BEAR" "CAT" "CAT" this four items. And the following are the rules of fusion.

(a) ANT BEAR CAT 10
(b) CAT CAT CAT 15

The first rule means if "ANT" and "BEAR" are adjacent(no matter which one is on the left), they can become "CAT" using 10 dollars, and in this case, you want to make "CAT".

So a possible step will be

1. using rule (a) and pay 10 dollars to make the sequence become "CAT" "CAT" "CAT".
2. and using rule(b) two times with paying 15+15 dollars and you will get the goal.

The total cost of this case is 40.

Input

The first line of the input is an integer Z (1 ≤ Z ≤ 30), which means the number of test cases below.

The first line of each test case contains two integers N and M, where N is the length of the given sequence and M is the number of rules (1 ≤ N ≤ 50, 1 ≤ MK(K-1)/2).The following N lines describe the sequence. Each line contains a string represent the item's name. The length of the items' name are smaller than 10 and contains only capital English letters. And there are at most K kinds of items. (1 ≤ K ≤ 10) The following M lines describe the rules. Each line contains three strings and a integer V (1 ≤ V ≤ 105). It means if the first two kinds of item are adjacent, the can become the third item by using V dollars. The next line of the input is the kind of the item you want to get.

Output

For each test case, print an integer on a line which means the minimum number of dollars you need to pay to make the item you want. If there is no way to make the item you want, please print "IMPOSSIBLE" (without quote) on the line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1721 - PB - Working at the Park   

Description

Benson, the manager of the park, is trying to assign the jobs to his workers. There are N workers and N different kinds of jobs. Each of the workers is able to, with various length of time required, finish a few kinds of jobs, but each of them must concentrate on finishing a single job and should not help with other jobs even if her or his own job is done.

They all start their work right after the jobs are assigned, so the time to call it a day depends on the latest ones who finish their jobs. The manager, and of course all of the workers, wish to go home as early as possible, so please help him to figure out a way to assign the jobs, with the restriction that each job is done by exactly one person and each person works on exactly one job, such that the latest finished job can be done as early as possible.

Input

The first line of the input is an integer Z (Z ≤ 10), which means the number of test cases that follows.

For each test case, the first line contains an integer N (N ≤ 100), which is the number of workers and jobs. Each of the next N lines contains N integers, where the j-th integer on the i-th line is the number of units of time for the i-th worker to finish the j-th kind of job, or -1 if the i-th worker should never work on the j-th kind of job. It is guaranteed that there is at least one possible assignment for each test case in the input.

There will be a leading blank line for each test case in the input.

Output

For each test case, output a line containing the test case number (starting from 1) and an integer, which is the minimum number of units of time to call it a day. The detailed format is shown in the sample output, and note that there is a single space character before the sharp sign and after the colon.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1722 - PC - Mirrored Double Maze   

Description

Given a duplicated maps like the ones shown below, you have to try to move ‘A’ and ‘B’ from the initial cell to the goal cell ‘E’ simultaneously. In these maps, you may travel through those free cell ‘.’, and may not move to the blocked cell ‘#’.

####### #######
#.....# #.....#
#.....# #.....#
#..E..# #..E..#
#.A...# #.B...#
#.....# #.....#
####### #######

However, there is a restriction that, whenever you try to move ‘A’ or ‘B’ a step to one of the adjacent cells in four directions, right, left, up and down, the other one must passively move a step to the adjacent cell in the opposite direction if possible. For example, if you move ‘A’ one step left, then ‘B’ must move one step right if the right cell is not a blocked cell. The following maps are the results after you move ‘A’ two steps up from the original position in the maps above.

####### #######
#.....# #.....#
#.A...# #.....#
#..E..# #..E..#
#.....# #.....#
#.....# #.B...#
####### #######

Note that in the second step, the cell that ‘B’ forced to move in is a blocked cell, so ‘B’ remains in the same position after ‘A’ moves up.

You have to find out the minimum number of steps to move ‘A’ and ‘B’ to the goal cell simultaneously, which means that ‘A’ and ‘B’ stay in the goal cell after a sequence of move. Note that moving one of them a step and forced the other one to move a step in the opposite direction is considered as a single step, instead of two. The starting cell and the goal cell are always considered as a free cell.

Input

The first line of the input is an integer Z (Z ≤ 10), which means the number of test cases that follows.

For each test case, the first line contains two integers N and M (1 ≤ N, M ≤ 20), denoting the number of rows and columns of the maze. Each of the following N lines contains M characters representing the cells. The character ‘.’ means a free cell, ‘#’ means a blocked cell, ‘S’ means the starting cell of ‘A’ and ‘B’, and ‘E’ means the goal cell. There will be exactly one ‘S’ and ‘E’ in the maze, and you may safely assumed that the maze will be surrounded by the blocked cells.

There will be a leading blank line for each test case in the input.

Output

For each test case, output a line containing the test case number (starting from 1) and the minimum number of steps to move ‘A’ and ‘B’ to the goal cell simultaneously. Output an integer -1 if it is impossible to achieve the goal. The detailed format is shown in the sample output, and note that there is a single space character before the sharp sign and after the colon.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1723 - PD - Simple Number   

Description

One day, you are playing a game called “Simple Number” with CKL.

The rules of the game is following:

At first, the judge decides a positive integer R to be the range.
Then, CKL will start the game. The two players try to find a special integer N in turns.
The special integer N is a positive integer less than R.
N is co-prime with R. (that is, gcd⁡(N, R) = 1)
The player who cannot find the new N will lose the game.

For example, if the judge decides R is 8, then one of the game’s situations will be:

  • Turn 1: CKL chose 1.
  • Turn 2: You chose 7.
  • Turn 3: CKL chose 5.
  • Turn 4: You chose 3.
  • CKL loses!!!!!!

But you are a lazy person. You don’t want to play too many turns. Just want to know how many turns will be played under the range R. Please write a program to solve it.

Input

The first line of the input is an integer Z (Z ≤ 105), which means the number of test cases.
For each test case, one line contains one positive integer R (R ≤ 109).

Output

For each test case, output the test case number and the turns of the game under the range R.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1724 - PE - H-Game Finder   

Description

You are a H(Heuristic)-Game lover. One day, you find out that a new H-Game is selling now. But the limit edition of this game is only sold in a city. You will ride your bicycle to the city to get it, but unfortunately, your energy is also limited. You can't ride the bicycle more than K kilometers in one day. You should take a rest in some city and go out on the next day. You want to buy the H-Game as soon as possible. Please calculate that after at least how many days you can get to the city which the H-Game is sold.

Input

The first line of the input is an integer Z (1 ≤ Z ≤ 30), which means the number of datasets below. The first line of a dataset contains two integers N and M, where N is the number of the cities and M is the number of roads which connect the two cities. (1 ≤ N ≤ 100, 1 ≤ MN(N-1)/2) The cities are numbered from 1 to N. The following M lines describe the roads. There are three integers a, b and c on one line. Which means there exist a road from city a to city b and the length of it is c kilometers. The roads are bi-connected. The next line contains three integers S, E and K (1 ≤ K ≤ 109). S means the city you live, E means the city where you can get the H-Game and K means the maximum distance you can ride in one day.

Output

For each dataset, please print an integer which is number of the minimum day you can get the H-Game. If you can reach to the city, please print "IMPOSSIBLE"(without quote) on the line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1725 - PF - Les Misérables   

Description

People lost their jobs during the great depression. In that time, people didn’t care about anything except power and money. They also used both to control another one. If some one's power and money are both less than yours, then you can control him. We have some data of many people. For every one, please compute how many people he can control.

Input

The first line of the input is an integer Z (Z ≤ 10), which means the number of test cases.
For each test case, one line contains one positive integer N (N ≤ 105).
There are N lines following. For each line, there are two integers Pi, Mi (|Pi|, |Mi| ≤ 106).

Output

For each test case, output the test case number in the first line, and then N lines follows.

Every line contains one integer representing the number of the people the person can control. Output one blank line between every two test cases.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1726 - PG - My Kingdom   

Description

My Kingdom is a facebook game which is developed by Happy Elements. In this game, you help the king to develop the kingdom. You can grow crops, train the army, build shops and get money and etc. There are also some mini games, such as BrickBreaker. You can get money or items in the mini game.This time a new update version is coming. They add a mini game called "Mystery Shape". The shape pattern is like the picture below.

You need to put as much as you can on a given plate to earn more award. The pattern can be rotated and flipped. For example, given the 5 x 5 plate below and the place with X is the forbidden area. In this case you can put at most 3 pieces of this pattern.

Input

The first line of the input is an integer Z (1 ≤ Z ≤ 30), which means the number of test cases below. The first line of a test case contains two integers N and M, where N is the height of the plate and M is the width of the plate (3 ≤ N ≤ 7, 3 ≤ M ≤ 7). The following N lines describe the plate. Each line contains M characters. The character '.' means it is an empty area, you can put the shape on it. And the character 'X' means it is an forbidden area, you can't put the pattern on it.

Output

For each test case, print an integer on a line which means the maximum number of pieces of the pattern you can put on the plate.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1727 - PH - Catalan Number   

Description

In computational mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems.

In programming contests, we usually use one of the two following forms of Catalan Number:

1. Division Version:

2. Non-division Version:

It's useful in many problem. There are some examples:

● The number of containing n pairs of parentheses which correct matched:
For n = 3, C(3) = 5:
((()))
()(())
()()()
(())()
(()())

● The number of full binary trees with n + 1 leaves
For n = 3, C(3) = 5:

● The number of different ways a convex polygon with n+2 sides can be cut into triangles by connecting vertices with straight lines.
For n = 4, C(4) = 14:

Input

The first line of the input is an integer Z (Z ≤ 500), which means the number of test cases. For each test case, one line contains one non-negative integer N (N ≤ 500). It is guaranteed that the number of digits of the largest Catalan number in this problem is less than 300.

Output

For each test case, output the test case number and the N-th Catalan number.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1728 - PI - Walking on the Grid   

Description

Image a two dimensional grid. Starting from the origin (0, 0), you have to find out how many ways to move back to the origin after K steps. In each step, you may move to those adjacent points in four directions, right, left, up, down, and you may visit the points more than one times during a walk. Two walks are considered different if not all of the points they visit in each step are the same.

Input

The first line of the input is an integer Z (Z ≤ 10), denoting the number of test cases that follows.

Each test case contains only a single integer, which is the number K (K ≤ 20) defined in the problem description.

There will be a leading blank line for each test case in the input.

Output

For each test case, output a line containing the test case number (starting from 1) and number of possible walks. The detailed format is shown in the sample output, and note that there is a single space character before the sharp sign and after the colon.

Sample Input  Download

Sample Output  Download

Tags




Discuss




1729 - PJ - Robot's Walk   

Description

In an infinite binary tree:

  • In an infinite binary tree:
  • If a node is labeled with the integer X, then its left child is labeled 2X and its right child 2X+1.
  • The root of the tree is labeled 1.

A walk on the binary tree starts in the root. Each step in the walk is either a jump onto the left child, onto the right child, or pause for rest (stay in the same node). A walk is described with a string of letters 'L', 'R' and 'P':

  • 'L' represents a jump to the left child;
  • 'R' represents a jump to the right child;
  • 'P' represents a pause.

The value of the walk is the label of the node we end up on. For example, the value of the walk LR is 5, while the value of the walk RPP is 3.

A set of walks is described by a string of characters 'L', 'R', 'P' and '*'. Each '*' can be any of the three moves; the set of walks contains all walks matching the pattern.

For example, the set L*R contains the walks LLR, LRR and LPR. The set ** contains the walks LL, LR, LP, RL, RR, RP, PL, PR and PP.

Finally, the value of a set of walks is the sum of values of all walks in the set. Calculate the value of the given set of walks.

Input

The first line of the input is an integer Z (1 <= Z <= 15), which means the number of test cases. For each test case, one line containing a string describing the set. Only characters 'L', 'R', 'P' and '*' will appear and there will be at most 10000 of them.

Output

For each test case, output the test case number and the value of the set.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2000 - The Sky is the Limit   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




2001 - Painter   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




2002 - Fence Repair   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




2101 - The Traveling Judges Problem   

Description

 A group of judges must get together to judge a contest held in a particular city, and they need to figure out the cheapest way of renting cars in order to get everyone to the contest. They observed that it might be cheaper if several judges share a rental car during all or part of the trip, thus reducing the overall cost. Your task is to identify the routes the judges should take in order to minimize the total cost of their car rentals.

We will make the following assumptions:
  • The cost of a rental car is proportional to the distance it is driven. There are no charges for more than one occupant in the car, fuel, insurance, or leaving the car in a city other than that in which it was rented.
  • All rental cars are billed at the same rate per mile.
  • A rental car can accommodate any number of passengers.
  • At most one road directly connects any pair of cities. Each road is two-way and has an integer length greater than zero.
  • There is at least one route from every judge's starting city to the city in which the contest is held.
  • All judges whose routes to the contest take them from or through the same city travel from that city to the contest together. (A judge might arrive at a city in one car and leave that city in a different car.)

Input

 The input contains several test cases. Each test case includes a route map, the destination city where the contest is being held, and the cities where the judges are initially located.

Each case appears in the input as a list of integers separated by blanks and/or ends of lines. The order and interpretation of the integers in each case is as follows:
  • NC-the number of cities that appear in the route map; this will be no larger than 20.
  • DC-the number of the destination city, assuming the cities are numbered 1 to NC.
  • NR-the number of roads in the route map. Each road connects a distinct pair of cities.
  • For each of the NR roads, three integers C1, C2, and DIST. C1 and C2 identify two cities connected by a road, and DIST gives the distance between these cities along that road.
  • NJ-the number of judges. This number will be no larger than 10.
  • NJ-integers, one for each judge each of these is a city number identifying the initial location of that judge.
The data for the last case will be followed by a line consisting of the integer `-1'.

Output

 For each test case, display the case number (1, 2,...) and the shortest total distance traveled by the rental cars conveying the judges to the contest. Then display the list of routes used by the judges, each route on a separate line, in the same order as the ordering of starting cities given in the input. Each route consists of the cities that the corresponding judge must visit, listed in the order in which they are visited, starting with the judge's starting city and ending with the contest city. Any other cities along the route are listed in the order in which they are visited during the judge's travels. Separate the numbers in the route with `-', and precede each route by three spaces.

If multiple sets of routes have the same minimum distance, choose a set that requires the fewest number of cities. If several sets of cities of the same cardinality may be used, choose the set that comes lexicographically first when ordered by city number (e.g., {2, 3, 6} rather than {2, 10, 5}). If multiple routes are still available, output any set of routes that meets the requirements.
Follow the format of the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2102 - Bit Compressor   

Description

The aim of data compression is to reduce redundancy in stored or communicated data. This increases effective data density and speeds up data transfer rates. One possible method to compress any binary message is the following:

Replace any maximal sequence of n 1's with the binary version of n whenever it shortens the length of the message.

For example, the compressed form of the data 11111111001001111111111111110011 becomes 10000010011110011. The original data is 32 bits long while the compressed data is only 17 bits long.

The drawback of this method is that sometimes the decompression process yields more than one result for the original message, making it impossible to obtain the original message. Write a program that determines if the original message can be obtained from the compressed data when the length of the original message (L), the number of 1's in the original message (N) and the compressed data are given. The original message will be no longer than 16 Kbytes and the compressed data will be no longer than 40 bits.

Input

The input file contains several test cases. Each test case has two lines. The first line contains L and N and the second line contains the compressed data.

The last case is followed by a line containing two zeroes.

Output

For each test case, output a line containing the case number (starting with 1) and a message `YES', `NO' or `NOT UNIQUE'. `YES' means that the original message can be obtained. `NO' means that the compressed data has been corrupted and the original message cannot be obtained. `NOT UNIQUE' means that more than one message could have been the original message. Follow the format shown in the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2103 - Ferries   

Description

Millions of years ago massive fields of ice carved deep grooves in the mountains of Norway. The sea filled these grooves with water. The Norwegian people call them fjords. This landscape of mountains and water is beautiful, but it makes traveling difficult. The usual scheme is: drive some kilometers, wait for a ferry, cross a fjord with the ferry, drive some more kilometers, and so on until the destination has been reached. To reach a destination as early as possible, most people have the following strategy: drive as fast as allowed (the maximum speed is 80 km/h) to the next ferry, and wait until it goes. Repeat until the destination has been reached.

Since driving fast requires more fuel than driving slow, this strategy is both expensive and harmful to the environment. The new generation of cruise control systems is designed to help. Given the route you want to go, these systems will gather information about the ferries involved, calculate the earliest possible time of arrival at the final destination, and calculate a driving scheme that avoids driving faster than needed. The systems will calculate your road speed so that you board the next ferry the moment it leaves.

Given a route (a sequence of road-pieces and crossings with ferries), you must write a program to calculate the minimal time it takes to complete this route. Moreover, your program must find a driving scheme such that the maximal driving speed at any point during the trip is as small as possible.

Input

The input file contains one or more test cases. Each test case describes a route. A route consists of several sections, each section being either a piece of road or a crossing. The first line in the description contains a single number s (s > 0), which is the number of sections in the route. The next s lines contain the descriptions of the sections. Every line describing a section starts with two names: the place of departure and the place of arrival, followed by either the word ‘road’ or the word ‘ferry’ indicating what kind of section it is. If the section is a road, its length (a positive integer) is given in km. For example:

Dryna Solholmen road 32

Lines describing ferry sections have more information. Following the word “ferry”, the duration of the ferry crossing, in minutes (a positive integer) is given. This is followed by the frequency f (f > 0) of the ferry, that is, the number of times the ferry departs in a single hour. The next f integers give the departure times of the ferry, in ascending order. For example:

Manhiller Fodnes ferry 20 2 15 35

The ferry travels from Manhiller to Fodnes in 20 minutes, and it leaves twice an hour (on 0h15, 0h35, 1h15, 1h35,…). The beginning of the entire trip always starts at a full hour. The sections in a route are consecutive, that is, if a section goes from A to B then the next section starts at B. Every route in the input can be traveled in no more than 10 hours.

The input is terminated by the number zero on a line by itself.

Output

Output for each test case is a single line containing three items. The first item is the test case number. The second is the total travel time for an optimal scheme in the form hh:mm:ss. The third item is the maximal road speed in an optimal scheme rounded to two digits to the right of the decimal point.

Place a blank line after the output of each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2104 - Network   

Description

A packet-switching network handles information in small units, breaking long messages into multiple packets before routing. Although each packet may travel along a different path, and the packets comprising a message may arrive at different times or out of order, the receiving computer reassembles the original message correctly.

The receiving computer uses a buffer memory to hold packets that arrive out of order. You must write a program that calculates the minimum buffer size in bytes needed to reassemble the incoming messages when the number of messages (N ), the number of packets (M ), the part of the messages in each packet, the size of each message, and the order of the incoming packets are given.

When each packet arrives, it may be placed into the buffer or moved directly to the output area. All packets that are held in the buffer are available to be moved to the output area at any time. A packet is said to ``pass the buffer" when it is moved to the output area. A message is said to ``pass the buffer" when all of its packets have passed the buffer.

The packets of any message must be ordered so the data in the sequence of packets that pass the buffer is in order. For example, the packet containing bytes 3 through 5 of a message must pass the buffer before the packet containing bytes 6 through 10 of the same message. Messages can pass the buffer in any order, but all packets from a single message must pass the buffer consecutively and in order (but not necessarily at the same time). Note that unlike actual buffering systems, the process for this problem can look ahead at all incoming packets to make its decisions.

The packets consist of data and header. The header contains three numbers: the message number, the starting byte number of data in the packet, and the ending byte number of data in the packet respectively. The first byte number in any message is 1.

For example, the figure below shows three messages (with sizes of 10, 20, and 5 bytes) and five packets. The minimum buffer size for this example is 10 bytes. As they arrive, packet #1 and packet #2 are stored in the buffer. They occupy 10 bytes. Then packet #3 passes the buffer directly. Packet #4 passes the buffer directly and then packet #2 exits the buffer. Finally, packet #5 passes the buffer directly and packet #1 exits the buffer.

Input

The input file contains several test cases. The first line of each test case contains two integers N (1 ≤ N ≤ 5) and M (1 ≤ M ≤ 1000) . The second line contains N integers that are the sizes of messages in bytes; the first number denotes the size of message #1, the second number denotes the size of message #2, and so on. Each of the following M lines describes a packet with three integers: the message number and the starting and ending byte numbers of data in the packet. No packet contains more 64 bytes of data.

The last test case is followed by a line containing two zeroes.

Output

For each test case, print a line containing the test case number (beginning with 1) followed by the minimum buffer size in bytes required to reassemble the original messages. Put a blank line after the output for each test case. Use the format of the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2105 - Clues   

Description

Dr. Wolf is an employee of Academic Cipher Machinery (ACM). His work is to secure a plenty of electronic documents by using a cipher machine invented by ACM. Given a document, the cipher machine is capable of making it encrypted whenever an arbitrary prime number, called the key prime, is provided. In mathematics, a prime number is a positive integer which has exactly two distinct positive divisors: 1 and itself. Of course, an encrypted document can be decrypted if the corresponding key prime is available.

As a consequence, Dr. Wolf picked many key primes for those documents to be secured. This seems to be an easy task. However, Dr. Wolf found that it is very difficult for him to remember so many key primes. Therefore, he decided to write down some information of the key primes in a notebook. To ensure safety, only a clue is recorded for each key prime. Let k0 be a key prime. Dr. Wolf produces a clue C for k0 according to the following strategy. Initially, C is an empty sequence. In Step 1, select an integer r ≥ 1 as well as r − 1 prime numbers k1, k2, . . ., kr−1 that are not larger than k0, and then include r into C. In Step 2, for each ki, 0 ≤ ir − 1, either include ki into C, or partition ki into smaller positive integers (adding up to exactly ki) and then include the smaller integers into C. Finally, in Step 3, rearrange the integers in C non-decreasingly. For example, a clue for k0 = 13 is made as follows. In Step 1, select r = 4 and (k1, k2, k3) = (5, 5, 7), and include 4 into C. In Step 2, partition k0 = 13 into (2, 4, 7), partition k1 = 5 into (1, 4), partition k2 = 5 into (2, 3), and partition k3 = 7 into (1, 1, 5). After Step 2, we have C = (4, 2, 4, 7, 1, 4, 2, 3, 1, 1, 5). Finally, in Step 3, we obtain a clue C = (1, 1, 1, 2, 2, 3, 4, 4, 4, 5, 7).

Dr. Wolf would use clues to recover the original key primes. Unfortunately, Dr. Wolf found that there is a drawback in his strategy: the key prime that can be inferred from a given clue may not be unique! For example, consider the clue C = (1, 1, 1, 2, 2, 3, 4, 4, 4, 5, 7). We may conclude k0 = 13 by letting r = 4 and (k0, k1, k2, k3) = (2+4+7, 1+4, 2+3, 1+1+5) = (13, 5, 5, 7). However, we may also conclude k0 = 17 by letting r = 4 and (k0k1k2k3) = (2+4+7+4, 1+2, 3, 1+1+5) = (17, 3, 3, 7), or conclude k0 = 29 by letting r = 2 and (k0k1) = (2+3+4+4+4+5+7, 1+1+1) = (29, 3). To overcome this drawback, Dr. Wolf calls a clue of a key prime k0 good if the largest key prime that can be inferred from it is k0. In the above example, C = (1, 1, 1, 2, 2, 3, 4, 4, 4, 5, 7) is good if k0 = 29. In order to produce good clues, Dr. Wolf needs a program that computes the largest key prime that can be inferred from a given clue. Therefore, Dr. Wolf seeks for your help.

Input

Technical Specification

1. The number of integers in a clue, n: 3  n  14.
2. Each integer in a clue ranges from 1 to 10000.

There are at most 25 test cases. Each test case describes a clue C = (c1, c2, . . ., cn) in two lines. The first line contains the integer n, where 3 ≤ n ≤ 14. The second line contains the n integers c1, c2, . . ., cn, where 1 ≤ c1 c2 ≤ . . . ≤ cn ≤ 10000. The last test case is followed by a line containing a number −1.

Output

 For each test case, print a line containing the test case number (beginning with 1) followed by

the largest key prime that can be inferred from the clue C. If no key prime can be inferred,

print “not a valid clue”. (Dr. Wolf may make mistakes in Step 2, during the production of

a clue.) Use the format of the sample output.

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




2106 - Consanguine Calculations   

Description

Every person's blood has 2 markers called ABO alleles. Each of the markers is represented by one of three letters: A, B, or O. This gives six possible combinations of these alleles that a person can have, each of them resulting in a particular ABO blood type for that person.

 


Combination ABO Blood Type
AA A
AB AB
AO A
BB B
BO B
OO O

 


Likewise, every person has two alleles for the blood Rh factor, represented by the characters + and -. Someone who is ``Rh positive" or ``Rh+" has at least one + allele, but could have two. Someone who is ``Rh negative" always has two - alleles.

The blood type of a person is a combination of ABO blood type and Rh factor. The blood type is written by suffixing the ABO blood type with the + or - representing the Rh factor. Examples include A+, AB-, and O-.

Blood types are inherited: each biological parent donates one ABO allele (randomly chosen from their two) and one Rh factor allele to their child. Therefore 2 ABO alleles and 2 Rh factor alleles of the parents determine the child's blood type. For example, if both parents of a child have blood type A-, then the child could have either type A- or type O- blood. A child of parents with blood types A+ and B+ could have any blood type.

In this problem, you will be given the blood type of either both parents or one parent and a child; you will then determine the (possibly empty) set of blood types that might characterize the child or the other parent.

Note: an uppercase letter ``Oh" is used in this problem to denote blood types, not a digit (zero).

Input

The input consists of multiple test cases. Each test case is on a single line in the format: the blood type of one parent, the blood type of the other parent, and finally the blood type of the child, except that the blood type of one parent or the child will be replaced by a question mark. To improve readability, whitespace may be included anywhere on the line except inside a single blood type specification.

The last test case is followed by a line containing the letters E, N, and D separated by whitespace.

Output

For each test case in the input, print the case number (beginning with 1) and the blood type of the parents and the child. If no blood type for a parent is possible, print ``IMPOSSIBLE". If multiple blood types for parents or child are possible, print all possible values in a comma-separated list enclosed in curly braces. The order of the blood types inside the curly braces does not matter.

The sample output illustrates multiple output formats. Your output format should be similar.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2107 - Containers   

Description

A seaport container terminal stores large containers that are eventually loaded on seagoing ships for transport abroad. Containers coming to the terminal by road and rail are stacked at the terminal as they arrive.

Seagoing ships carry large numbers of containers. The time to load a ship depends in part on the locations of its containers. The loading time increases when the containers are not on the top of the stacks, but can be fetched only after removing other containers that are on top of them.

The container terminal needs a plan for stacking containers in order to decrease loading time. The plan must allow each ship to be loaded by accessing only topmost containers on the stacks, and minimizing the total number of stacks needed.

For this problem, we know the order in which ships must be loaded and the order in which containers arrive. Each ship is represented by a capital letter between A and Z (inclusive), and the ships will be loaded in alphabetical order. Each container is labeled with a capital letter representing the ship onto which it needs to be loaded. There is no limit on the number of containers that can be placed in a single stack.

Input

The input file contains multiple test cases. Each test case consists of a single line containing from 1 to 1000 capital letters representing the order of arrival of a set of containers. For example, the line ABAC means consecutive containers arrive to be loaded onto ships A, B, A, and C, respectively. When all containers have arrived, the ships are loaded in strictly increasing order: first ship A, then ship B, and so on.

A line containing the word end follows the last test case.

Output

For each input case, print the case number (beginning with 1) and the minimum number of stacks needed to store the containers before loading starts. Your output format should be similar to the one shown here.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2108 - Grand Prix   

Description

You are the chief designer of a road race that will be held in a hilly area. The racecourse consists of N connected straight line segments; that is, the end of the k th segment coincides with the beginning of the (k + 1) st segment. During planning, these segments are laid out on a planar surface, so 2-dimensional Cartesian coordinates identify the endpoints. The first segment begins at the origin. Figure 1 shows the planar view of a racecourse with 6 segments.

 

The actual race is run on the side of a hill. For simplicity, assume the hill makes an angle Θ with the horizontal plane, as illustrated in Figure 2.

The plane of the hill and the horizontal plane intersect in the y -axis. Each 2-dimensional Cartesian coordinate (xi, yi) corresponds to a 3-dimensional form (xi', yi', zi') , with zi' representing the height of the endpoint of the i th linear segment. The height of the origin is 0.

This particular race is intended for novice drivers, so the racecourse must not include any segments that require downhill travel. That is, if the height of the endpoint of segment k is zk' , then the height of the endpoint of each segment after segment k must not be less than zk' . Formally we can write zk'zm' , for mk .

If a proposed racecourse includes downhill segments, it might be possible to transform it into a racecourse with no downhill segments by rotating the planar view of the entire course about the origin, without changing the angle between consecutive pairs of segments. However there may be proposed racecourses that cannot be made acceptable by such a rotation.

In this problem you must determine if a proposed racecourse is acceptable (that is, if it does not contain any downhill segments). If it is not acceptable, you must determine the minimum angle through which the racecourse must be rotated to make it acceptable, if that is possible.

 

Input

 The input consists of multiple test cases. Each test case is a description of a proposed racecourse and the slope of the hillside on which it will be run. The first line of each description contains two integers N (1N ≤ 10000) and θ (0o≤ θ ≤45oN denotes the number of segments in the course and θ denotes the angle (in degrees) that the hillside makes with the horizontal plane. Each of the next N lines contains a pair of integers (xiyi, (1≤iN, which are the endpoints of the linear segments comprising the racecourse. The first segment begins at the origin, and segment k + 1begins at the endpoint of segment k . No segment has zero length.

The last test case is followed by a line containing two zeroes.

Output

 For each test case, print a line containing the test case number (beginning with 1). If the proposed course is acceptable without rotation, print ``Acceptable as proposed". If the course is not acceptable as proposed, but can be made acceptable by rotating it about the origin, print ``Acceptable after clockwise rotation of X degrees" or ``Acceptable after counterclockwise rotation of X degrees". The value X should be an unsigned number. For our purposes, a clockwise rotation would rotate the positive y -axis toward the positive x -axis. If both a clockwise and a counterclockwise rotation can make the course acceptable, choose the one with the smaller angle. If both rotations have the same angle, then choose the clockwise rotation. If the course cannot be made acceptable by any rotation, print ``Unacceptable". Display the angles of rotation rounded to two fractional digits.

Print a blank line after the output for each test case. Use an output format similar to that shown in the sample output below.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2109 - Anti Brute Force Lock   

Description

 Lately, there is one serious problem with Panda Land Safe Box: several safes have been robbed! The safes are using old 4-digits rolling lock combination (you only have to roll the digit, either up or down, until all four of them match the key). Each digit is designed to roll from 0 to 9. Rolling-up at 9 will make the digit become 0, and rolling-down at 0 will make the digit become 9. Since there are only 10000 possible keys, 0000 through 9999, anyone can try all the combinations until the safe is unlocked.



 

What's done is done. But in order to slow down future robbers' attack, Panda Security Agency (PSA) has devised a new safer lock with multiple keys. Instead of using only one key combination as the key, the lock now can have up to N keys which has to be all unlocked before the safe can be opened. These locks works as the following:
  • Initially the digits are at 0000.
  • Keys can be unlocked in any order, by setting the digits in the lock to match the desired key and then pressing the UNLOCK button.
  • A magic JUMP button can turn the digits into any of the unlocked keys without doing any rolling.
  • The safe will be unlocked if and only if all the keys are unlocked in a minimum total amount of rolling, excluding JUMP (yes, this feature is the coolest one).
  • If the number of rolling is exceeded, then the digits will be reset to 0000 and all the keys will be locked again. In other word, the state of the lock will be reset the cracking is failed.

PSA is quite confident that this new system will slow down the cracking, giving them enough time to identify and catch the robbers. In order to determine the minimum number of rolling needed, PSA wants you to write a program. Given all the keys, calculate the minimum number of rolls needed to unlock the safe.

 

Input

 The first line of input contains an integer T , the number of test cases follow. Each case begins with an integer N (1≤N≤500) , the number of keys. The next N lines, each contains exactly four digits number (leading zero allowed) representing the keys to be unlocked.

Output

For each case, print in a single line the minimum number of rolls needed to unlock all the keys.


Explanation for the 2nd case:
  • Turn 0000 into 1111, rolls: 4
  • Turn 1111 into 1155, rolls: 8
  • Jump 1155 into 1111, we can do this because 1111 has been unlocked before.
  • Turn 1111 into 5511 rolls: 8
Total rolls = 4 + 8 + 8 = 20

Sample Input  Download

Sample Output  Download

Tags




Discuss




2110 - Jollybee Tournament   

Description

In Jollybee Chess Championship 2008, there are a number of players who have withdrawn themselves from the championship of 64 players (in this problem, we generalized it into 2N players). Due to the nature of the competition, which is a regular knock-out tournament, and also the short notice of the withdrawals, some matches had been walkover matches (also known as a w/o, a victory due to the absent of the opponent).

If both players are available then there will be a normal match, one of them will advance to the next phase. If only one player is available then there will be a walkover match, and he/she will automatically advance. If no player is available then there will be no match.
In the left figure, the player #3 and #4 are withdrawn from the tournament, leaving a total of one w/o match (at match #3).
Given the list of players who withdraw right before the tournament start, calculate how many w/o matches to happen in the whole tournament, assuming that all of the remaining players play until the end of the tournament (winning or knocked-out).

Input

 The first line of input contains an integer T , the number of test cases to follow. Each case begins with two integers, N (1≤N≤10) and M (0≤M≤2N. The next line contains M integers, denoting the players who have withdrawn themselves right before the tournament. The players are numbered from 1 to 2N , ordered by their position in the tournament draw.

Output

 For each case, print in a single line containing the number of walkover matches.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2111 - Degrees of Separation   

Description

In our increasingly interconnected world, it has been speculated that everyone on Earth is related to everyone else by no more than six degrees of separation. In this problem, you must write a program to find the maximum degree of separation for a network of people.

For any two people, the degree of separation is the minimum number of relationships that must be traversed to connect the two people. For a network, the maximum degree of separation is the largest degree of separation between any two people in the network. If there is a pair of people in the network who are not connected by a chain of relationships, the network is disconnected.

As shown below, a network can be described as a set of symmetric relationships each of which connects two people. A line represents a relationship between two people. Network A illustrates a network with 2 as the maximum degree of separation. Network B is disconnected.

Network A: Max. degree of separation = 2 Network B: Disconnected

Input

The input consists of data sets that describe networks of people. For each data set, the first line has two integers: P (2≤P≤50), the number of people in the network, and R (R≥1), the number of network relationships. Following that first line are R relationships. Each relationship consists of two strings that are names of people in the network who are related. Names are unique and contain no blank spaces. Because a person may be related to more than one other person, a name may appear multiple times in a data set.

The final test case is followed by a line containing two zeroes.

Output

For each network, display the network number followed by the maximum degree of separation. If the network is disconnected, display `DISCONNECTED'. Display a blank line after the output for each network. Use the format illustrated in the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2112 - Air Conditioning Machinery   

Description

You are a technician for the Air Conditioning Machinery company (ACM). Unfortunately, when you arrive at a customer site to install some air conditioning ducts, you discover that you are running low on supplies. You have only six duct segments, and they are all of the same kind, called an ``elbow.''

You must install a duct in a confined space: a rectangular prism whose sides are multiples of a unit length. Think of the confined space as consisting of an array of unit cubes. Each elbow occupies exactly four unit cubes, as shown in Figure 1 below. A unit cube can be occupied by at most one elbow. Each elbow has exactly two openings, as indicated by the gray squares in the elbow shown in Figure 1. You may assemble the elbows into longer ducts, but your duct must be completely contained inside the given space. One way to connect two elbows is shown in Figure 2. Your task is to connect an inflow to an outflow. The inflow and the outflow are located on the exterior surface of the confined space, aligned with the unit cubes, as shown in Figure 3. To keep expenses down, you must accomplish this task while using the minimum number of elbows.

Input

The input consists of several test cases, each of which consists of a single line containing eleven input values separated by blanks. The input values for each test case are as follows.

The first three input values are integers (xmax , ymax , and zmax ) that indicate the size of the confined space in the x , y , and z dimensions, respectively. Each unit cube in the confined space can be identified by coordinates (x, y, z) where 1≤xxmax , 1≤yymax , and 1≤zzmax . xmax , ymax , and zmax are all positive and not greater than 20.

The next three input values are integers that indicate the location of the inflow by identifying the x , y , and z coordinates of the unit cube that connects to the inflow.

The next input value is a two-character string that indicates the direction of the inward flow, using one of the following codes: + x, - x, + y, - y, + z, - z . The inflow connection is on the face of the unit cube that receives this inward flow. For example, if the data specifies an inflow direction of + y , the inflow connection is on the face of the unit cube that faces in the negative y direction.

The next three input values are integers that indicate the location of the outflow by identifying the x , y , and z coordinates of the unit cube that connects to the outflow.

The last input value is a two-character string that indicates the direction of the outward flow, using the same codes described above. The outflow connection is on the face of the unit cube that generates this outward flow. For example, if the data specifies an outflow direction of + y , the outflow connection is on the face of the unit cube that faces in the positive y direction.

The last line of the input file consists of a single zero to indicate end of input.

Output

For each test case, print the case number (starting with 1) followed by the minimum number of elbows that are required to connect the inflow to the outflow without going outside the confined space. If the task cannot be accomplished with your supply of six elbow segments, print the word `Impossible' instead. Use the format in the sample data.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2113 - The Sky is the Limit   

Description

The city of Banff hired an advertising agency to promote the city's attractions to potential visitors. One of the planned slogans stated that the mountain ranges around the city form the most beautiful skyline in Canada. But the Institute for Consumer Protection in Canada (ICPC) decided that ``the most beautiful skyline" was a subjective and unverifiable claim, and could therefore be considered misleading.

The advertising agency then came up with the slogan ``Banff - the longest skyline in Canada." Although not as catchy, it is hopefully verifiable, and therefore admissible under Canada's tricky advertising laws.

This is where you come in. What the advertising agency needs is a program that determines the length of a skyline. Consider each mountain as a two-dimensional triangle having two upper sides the same length. A skyline is the outline of one or more mountains. The skyline's length is the total length of the outline. The left illustration below shows three mountains. The right illustration shows (with bold lines) the skyline and (with dashed lines) the portion of the mountains' upper edges that are not part of the skyline. Note that parts of the horizon line that lie between mountains are not considered part of the skyline.

Input

Each input file contains one or more test cases, which are descriptions of mountain ranges. Each description starts with a line containing a positive integer N , which specifies the number of mountains in the range. Each of the next N lines describes a mountain with three integers X , H , and B , which specify the horizontal position of the mountain's peak relative to some fixed point, the height of the peak, and the width of the base of the mountain, respectively. The base of each mountain coincides with a horizontal line. The values satisfy the conditions N≤100 , H > 0 , and B > 0 .

The last test case is followed by a line containing a zero.

Output

For each test case, print the case number (beginning with 1) and the length of the skyline. Print the length rounded to the nearest integer, with 0.5 rounded up. Print a blank line after the output of each test case. Use the format shown in the sample output below.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2114 - Interstar Transport   

Description

By 2100, space travel will be a reality for the Milky Way (Solar Galaxy) residents. The Interstar Transport Travel agency operates scheduled direct space transports (flights) between some of the most popular planet destinations in the Milky Way. The cost of these scheduled direct transports are predetermined in Galaro (Galaxy Currency unit) and are published in many different languages. For travel to planets that is not on the schedule, there are slower, yet free, space flights from the closest planet that is on the direct transport list. To help travelers plan their itinerary, the Interstar Transport wants to offer a mobile application that can find the best traveling option, based on the total cost of the direct transports on the itinerary. Given the starting and destination planets on the itinerary, find the sequence of direct transports that has the lowest total traveling cost. Output all the planets in sequence that one must pass through on this best route. If two or more routes exist with the same cost, then the route that goes through the least number of intermediate planets is considered a better route. There will always exist a unique best route for any of the given test cases.

Technical Specification

  1. The number of planets on the direct transport list is at most s, 1 ≤ s ≤ 26. The planets are labeled using capital letters of the English alphabets, i.e., “A”, “B”, “C”, ..., “Z”, in no particular order.
  2. The Interstar Transport operates at most p, 1 ≤ p ≤ 200, direct transports between planets. There is at most one (could be none) direct transport between any two distinct planets.
  3. The cost of any transport is given as a natural number less than or equal to 100 Galaros.

 

Input

The first line of the input file contains two integers, s and p, separated by a space. The next p lines each contains two letters, ei and ej , followed by a natural number, dij , indicating that there exists a direct transport between planets ei and ej with a cost of dij . The next line contains an integer n ≤ 20, indicating the number of queries to follow. For each of the next n lines, each line contains two letters ek and em, indicating a user is looking for a best (lowest cost) way to get from planet ek to planet em.

 

Output

For each of the n queries in the input, output on one line the best route to take, in the sequence of starting planet, the intermediate planets in sequence along the route and the destination planet; all separated by one blank space.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2115 - Huffman Codes   

Description

Dan McAmbi is a member of a crack counter-espionage team and has recently obtained the partial contents of a file containing information vital to his nation's interests. The file had been compressed using Huffman encoding. Unfortunately, the part of the file that Dan has shows only the Huffman codes themselves, not the compressed information. Since Huffman codes are based on the frequencies of the characters in the original message, Dan's boss thinks that some information might be obtained if Dan can reverse the Huffman encoding process and obtain the character frequencies from the Huffman codes. Dan's gut reaction to this is that any given set of codes could be obtained from a wide variety of frequency distributions, but his boss is not impressed with this reasoned analysis. So Dan has come to you to get more definitive proof to take back to his boss.

Huffman encoding is an optimal data compression method if you know in advance the relative frequencies of letters in the text to be compressed. The method works by first constructing a Huffman tree as follows. Start with a forest of trees, each tree a single node containing a character from the text and its frequency (the character value is used only in the leaves of the resulting tree). Each step of the construction algorithm takes the two trees with the lowest frequency values (choosing arbitrarily if there are ties), and replaces them with a new tree formed by joining the two trees as the left and right subtrees of a new root node. The frequency value of the new root is the sum of the frequencies of the two subtrees. This procedure repeats until only one tree is left. An example of this is shown below, assuming we have a file with only 5 characters -- A, B, C, D and E -- with frequencies 10%, 14%, 31%, 25% and 20%, respectively.


After you have constructed a Huffman tree, assign the Huffman codes to the characters as follows. Label each left branch of the tree with a 0 and each right branch with a 1. Reading down from the root to each character gives the Huffman code for that character. The tree above results in the following Huffman codes: A - 010, B - 011, C - 11, D - 10 and E - 00.

For the purpose of this problem, the tree with the lower frequency always becomes the left subtree of the new tree. If both trees have the same frequencies, either of the two trees can be chosen as the left subtree. Note that this means that for some frequency distributions, there are several valid Huffman encodings.

The same Huffman encoding can be obtained from several different frequency distributions: change 14% to 13% and 31% to 32%, and you still get the same tree and thus the same codes. Dan wants you to write a program to determine the total number of distinct ways you could get a given Huffman encoding, assuming that all percentages are positive integers. Note that two frequency distributions that differ only in the ordering of their percentages (for example 30% 70% for one distribution and 70% 30% for another) are not distinct.

Input

The input consists of several test cases. Each test case consists of a single line starting with a positive integer n (2≤n≤20) , which is the number of different characters in the compressed document, followed by n binary strings giving the Huffman encoding of each character. You may assume that these strings are indeed a Huffman encoding of some frequency distribution (though under our additional assumptions, it may still be the case that the answer is 0 -- see the last sample case below).

The last test case is followed by a line containing a single zero.

Output

For each test case, print a line containing the test case number (beginning with 1) followed by the number of distinct frequency distributions that could result in the given Huffman codes.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2116 - Balloons in a Box   

Description

You must write a program that simulates placing spherical balloons into a rectangular box.

The simulation scenario is as follows. Imagine that you are given a rectangular box and a set of points. Each point represents a position where you might place a balloon. To place a balloon at a point, center it at the point and inflate the balloon until it touches a side of the box or a previously placed balloon. You may not use a point that is outside the box or inside a previously placed balloon. However, you may use the points in any order you like, and you need not use every point. Your objective is to place balloons in the box in an order that maximizes the total volume occupied by the balloons.

You are required to calculate the volume within the box that is not enclosed by the balloons.

Input

The input consists of several test cases. The first line of each test case contains a single integer n that indicates the number of points in the set (1 ≤ n ≤ 6). The second line contains three integers that represent the (x, y, z) integer coordinates of a corner of the box, and the third line contains the (x, y, z) integer coordinates of the opposite corner of the box. The next n lines of the test case contain three integers each, representing the (x, y, z) coordinates of the points in the set. The box has non-zero length in each dimension and its sides are parallel to the coordinate axes.

The input is terminated by the number zero on a line by itself.

Output

For each test case print one line of output consisting of the test case number followed by the volume of the box not occupied by balloons. Round the volume to the nearest integer. Follow the format in the sample output given below.

Place a blank line after the output of each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2117 - Island Hopping   

Description

The company Pacific Island Net (PIN) has identified several small island groups in the Pacific that do not have a fast internet connection. PIN plans to tap this potential market by offering internet service to the island inhabitants. Each groups of islands already has a deep-sea cable that connects the main island to the closest internet hub on the mainland (be it America, Australia or Asia). All that remains to be done is to connect the islands in a group to each other. You must write a program to help them determine a connection procedure.


For each island, you are given the position of its router and the number of island inhabitants. In the figure, the dark dots are the routers and the numbers are the numbers of inhabitants. PIN will build connections between pairs of routers such that every router has a path to the main island. PIN has decided to build the network such that the total amount of cable used is minimal. Under this restriction, there may be several optimal networks. However, it does not matter to PIN which of the optimal networks is built.

PIN is interested in the average time required for new customers to access the internet, based on the assumption that construction on all cable links in the network begins at the same time. Cable links can be constructed at a rate of one kilometer of cable per day. As a result, shorter cable links are completed before the longer links. An island will have internet access as soon as there is a path from the island to the main island along completed cable links. If mi is the number of inhabitants of the ith island and ti is the time when the island is connected to the internet, then the average connection time is:

Input

The input consists of several descriptions of groups of islands. The first line of each description contains a single positive integer n, the number of islands in the group (n ≤ 50). Each of the next n lines has three integers xi, yi, mi, giving the position of the router (xi, yi) and number of inhabitants mi (mi > 0) of the islands. Coordinates are measured in kilometers. The first island in this sequence is the main island.

The input is terminated by the number zero on a line by itself.

Output

For each group of islands in the input, output the sequence number of the group and the average number of days until the inhabitants are connected to the internet. The number of days should have two digits to the right of the decimal point. Use the output format in the sample given below.

Place a blank line after the output of each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2118 - AGTC   

Description

Let x and y be two strings over some finite alphabet A. We would like to transform x into y allowing only operations given below:

Deletion: a letter in x is missing in y at a corresponding position.

Insertion: a letter in y is missing in x at a corresponding position.

Change: letters at corresponding positions are distinct

Certainly, we would like to minimize the number of all possible operations.

Illustration

A G T A A G T * A G G C
| | |       |   |   | |
A G T * C * T G A C G C


Deletion: * in the bottom line
Insertion: * in the top line
Change: when the letters at the top and bottom are distinct

This tells us that to transform x = AGTCTGACGC into y = AGTAAGTAGGC we could be required to perform 5 operations (2 changes, 2 deletions and 1 insertion). If we want to minimize the number operations, we should do it like
A G T A A G T A G G C
| | |     |   |   | |
A G T C T G * A C G C

and 4 moves would be required (3 changes and 1 deletion).

In this problem we would always consider strings x and y to be fixed, such that the number of letters in x is m and the number of letters in y is n where nm.

Assign 1 as the cost of an operation performed. Otherwise, assign 0 if there is no operation performed.

Write a program that would minimize the number of possible operations to transform any string x into a string y.

Input

Input contains several datasets. Each dataset consists of the strings x and y prefixed by their respective lengths, one in each line.

Output

For each dataset, an integer representing the minimum number of possible operations to transform any string x into a string y.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2119 - Wordfish   

Description

You have been tasked to infiltrate a tight-lipped society for fun and profit: the ACM ICPC regional judges. Through the PC2 ``submission" software, you know that classified information is accessible through the log-ins of the judges tasked to a particular ``regional site". However, you are not certain that any particular judge has access to all the relevant information, so several log-ins will be required. You have been handed down a list of usernames, and the passwords used can be derived from these usernames, as follows:

Input

The input will only have capital letters (denoting the usernames) and carriage returns. Each line (thus each username) will not be longer than twenty characters, and there will not be more than 12 ``judges" whose log-ins you will need to infiltrate. Strangely, no username uses any letter more than once.

Output

For each username, you must produce a line containing the password which that username uses. The password for a given username is determined from the twenty-one lexicographically consecutive permutations of the username, the eleventh (middle) of which is the username itself. For example, if the username is WORDFISH, the lexicographic permutations of WORDFISH contain, in order:

..., WOISHRFD, WOISRDFH, WOISRDHF, WOISRFDH, WOISRFHD, WOISRHDF, WOISRHFD, WORDFHIS, WORDFHSI, WORDFIHS, WORDFISH, WORDFSHI, WORDFSIH, WORDHFIS, WORDHFSI, WORDHIFS, WORDHISF, WORDHSFI, WORDHSIF, WORDIFHS, WORDIFSH, ...

The password is then the permutation among the twenty-one lexicographically consecutive permutations of the username which has the largest minimum absolute distance between consecutive letters (and the first amongst the lexicographically ordered, if several permutations have the largest minimum absolute distance), followed by that minimum absolute distance. For the username WORDFISH, the password is WORDHSFI31 .

1 Disclaimer: The above story is completely fictional, and in no way represents any fact, regarding ACM regional judges, their passwords or world domination.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2120 - Simplified GSM Network   

Description

Mobile phones have changed our lifestyle dramatically in the last decade. Mobile phones have a variety of protocols to connect with one another. One of the most popular networks for mobile phones is the GSM (Global System for Mobile Communication) network.

In a typical GSM network, a mobile phone connects with the nearest BTS (Base Transceiver Station). A BSC (Base Station Center) controls several BTSs. Several BSCs are controlled by one MSC (Mobile Services Switching Center), and this MSC maintains a connection with several other MSCs, a PSTN (Public Switched Telecom Network) and an ISDN (Integrated Services Digital Network).

This problem uses a simplified model of the conventional GSM network. Our simplified network is composed of up to fifty BTS towers. When in use, a mobile phone always connects to its nearest BTS tower. The area covered by a single BTS tower is called a cell. When an active mobile phone is in motion, as it crosses cell boundaries it must seamlessly switch from one BTS to another. Given the description of a map consisting of cities, roads and BTS towers, you must determine the minimum number of BTS switches required to go from one city to another.


Figure: Cities here are represented by squares and BTS towers by trapezoids. Solid lines are roads. The dotted lines show 9 different cells. The minimum number of switches required to go from city 1 to city 6 is (2+1+0)=3. Note that city 7 is isolated and cannot be reached.

Each tower and each city location is to be considered as a single point in a two-dimensional Cartesian coordinate system. If there is a road between two cities, assume that the road is a straight line segment connecting these two cities. For example, in the figure, traveling on the road from city 1 to city 2 will cross two cell boundaries and thus requires two switches. Traveling from city 2 to city 5 crosses one cell boundary and traveling from city 5 to city 6 requires no switch. Traveling this route from city 1 to city 6 requires three total switches. Note than any other path from city 1 to city 6 requires more than three switches. If there is more than one possible way to get from one city to another, your program must find the optimal route.

Input

The input file contains several test cases. The first line of each test case contains four integers: B(1 ≤ B ≤ 50), the number of BTS towers; C(1 ≤ C ≤ 50), the number of cities; R(0 ≤ R ≤ 250), the number of roads; and Q(1 ≤ Q ≤ 10), the number of queries. Each of the next B lines contains two floating-point numbers x and y, the Cartesian coordinates of a BTS tower. Each of the next C lines contains two floating-point numbers xi, yi that indicate the Cartesian coordinates of the ith city (1 ≤ iC). Each of the next R lines contains two integers m and n (1 ≤ m, n C), which indicate that there is a road between the m-th and the n-th city. Each of the next Q lines contains two integers s and d (1 ≤ s, dC), the source and destination cities.

No coordinate will have an absolute value greater than 1000. No two towers will be at the same location. No two cities will be at the same location, and no city will lie on a cell boundary. No road will be coincident with a cell boundary, nor contain a point lying on the boundary of three or more cells.

The input will end with a line containing four zeros.

Output

For each input set, you should produce Q + 1 lines of output, as shown below. The first line should contain the number of the test case. Q lines should follow, one for each query, each containing an integer indicating the minimum number of switches required to go from city s to city d. If it is not possible to go from city s to city d, print the line `Impossible' instead.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2121 - Assemble   

Description

Recently your team noticed that the computer you use to practice for programming contests is not good enough anymore. Therefore, you decide to buy a new computer.

To make the ideal computer for your needs, you decide to buy separate components and assemble the computer yourself. You need to buy exactly one of each type of component.

The problem is which components to buy. As you all know, the quality of a computer is equal to the quality of its weakest component. Therefore, you want to maximize the quality of the component with the lowest quality, while not exceeding your budget.

Input

On the first line one positive number: the number of testcases, at most 100. After that per testcase:

  • One line with two integers: 1 ≤ n ≤ 1000, the number of available components and 1 ≤ b ≤ 1000000000, your budget.
  • n lines in the following format: ``type name price quality'', where type is a string with the type of the component, name is a string with the unique name of the component, price is an integer (0 ≤ price < 1000000) which represents the price of the component and quality is an integer (0 ≤ quality ≤ 1000000000) which represents the quality of the component (higher is better). The strings contain only letters, digits and underscores and have a maximal length of 20 characters.

It will always possible to construct a computer with your budget.

Output

Per testcase:

  • One line with one integer: the maximal possible quality.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2122 - Find Terrorists   

Description

The Prime Minister and his Accumulated Council of Ministers(ACM) are trying hard to find all possible terrorist locations. In his dream, the Prime Minister gets a message from God suggesting that the answer to all terrorist problems are numbers(say one such number is X) such that the number of factors of X(including 1 and X) is prime. These numbers supposedly contain the encrypted locations of terrorists. Since the ACM has no programmer, the Prime Minister needs your help in finding out such numbers.

Note:- 1 is not considered a prime number .

Input

The first line of input will contain an integer T ≤ 20 denoting the number of test cases. T lines follow, one per test case.

Each test case will be a line formatted as "L H" where L and H are integers and 0 ≤ H ≤ 10000

Output

Output one line per case a space separated list of all integers(sorted ascending) lying between L and H(both inclusive) such that the number of factors of each integer is prime.In case no such integer exist output -1.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2123 - Clicking Checkboxes   

Description

Creating a good and easy Graphical user interface is the heart of operating a computer in modern days. One important part of this interface is enabling users to give inputs using mouse and keyboard. Many different types of forms are there to take inputs from users. Such as (a) Text Box (b) Radio Button (c) Check Box (d) Combo Box etc. In this problem we will concentrate on check box.

Check boxes are used when a user needs to select more than one choice. Such a checkbox is shown in the figure on the left below. The problem with checkbox is that when someone has to choose n options or names he has to make n clicks, which can be very annoying when n is high. So the new software giant toggle is using a new type of checkbox, which shows good performance when number of boxes to be checked is high. In normal check box, a box is checked or unchecked if and only if it is clicked but in toggle checkbox when a box is clicked then all the boxes below it is also gets its status. That is if a box is originally not checked then if someone clicks this box then this box and all the boxes below it will be checked. Similarly if a box is checked and someone clicks on it then it will become unchecked and so will all the boxes below it. So the selection made on the left can be made by only five clicks (The boxes that has to be clicked are marked with red or dark square on the right figure) in toggle checkbox (We are calling naming new type of checkbox as “toggle checkbox”).

Figure 1: 12 clicks are required in ordinary checkbox Figure 2: 5 clicks are required in toggle checkbox.

The researchers of toggle have shown that toggle checkboxes show better performance when at least 50% boxes are to be checked. For example for the selection shown in the above picture we needed 12 clicks to check 12 boxes in normal checkbox but only five clicks were required for toggle checkboxes. So in this situation toggle boxes show better performance. In many other selection, toggle checkbox would also show strictly better performance. Your job is to count in how many selection patterns (where at least m boxes out of the n boxes in the checkbox are to be selected) toggle check box would show better performance and in how many selection patterns ordinary checkbox would show better performance.

Input

The input file contains 1000 lines of inputs. The description of each line is given below:

Each line contains two integers n (0 < 64) and m (0 ≤ n). These two values indicate that you have to consider a checkbox with n boxes to check and consider only the input patterns where at least m of them are checked. Assume that initially all the boxes are unchecked.

Input is terminated by a line containing two zeroes. This line should be processed.

Output

For each line of input produce one line of output.

This line contains the serial of output followed by two integers TC and NC. Here TC is the total number of selection patterns where toggle checkbox requires less clicks and NC is the total number of selection patterns where ordinary or normal checkboxes require less clicks.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2124 - Postmaster's Wish   

Description

A post master wishes to automate the sorting operation at his post office, since he finds that on an average the number of people assigned to the sorting operation are either heavily loaded or idle, ultimately resulting in loss of man hours that could have been efficiently used. He comes up with an idea of an automatic sorting machine that has a fixed capacity to hold the input letters and that sorts the letters at a fixed output rate. Depending upon the arrival of letters to the sorter, once the sorter is full of letters, the excess letters that would cause the sorting box to overflow have to be dropped into a bin to be manually sorted afterwards.

You are working for a company that has been called by the postmaster for a meeting to demonstrate a software simulation of the sorter. The following scenarios need to be shown in the simulation to him:

  • a) Sorter box is completely filled.
  • b) Sorter box is drained out.
  • c) Sorter box overflows.

At the beginning of every second:

  • A certain number of messages arrive, and they are added to the sorter bin of a fixed capacity C. Excess messages cause overflow into the manual sorter bin.
  • From the letters that are pending to be sorted, the sorter acts and sorts R letters.

Input

Input consists of multiple testcases.

The first line of each testcase contains three integers: C R M (1 ≤ M ≤ 100; 1 ≤ R C ≤ 20,000) representing the capacity of the sorter, the fixed-rate of sorting of the sorter and the number of messages.

The following M lines contain one integer each, i-th line representing the number of letters that arrived, at time i. Each of these integers will be in the inclusive range [0,1000].

Input ends with a line containing three zeros.

Output

Output to each test case must begin with a line containing "Case #:". Each test-case must contain M lines, with exactly 5 integers each, which the state of the sorter after every unit of time. The five integers represent the following:

Current time (The i-th line will be just i).

Letters received (Same as the input for the i-th line).

Letters sorted (Number of letters the sorter sorted at this unit of time; must be less than or equal to R).

Sorter balance (Number of pending letters in the sorter; must be less than or equal to C).

Number of letters dumped into the manual sorter bin.

There should be a blank line after each test-case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2125 - Triangle Hazard   

Description

In the picture below you can see a triangle ABC. Point D, E and F divides the sides BC, CA and AB into m1:m2, m3:m4 and m5:m6 ratios respectively. A, D; B, E and C, F are connected. AD and BE intersects at P, BE and CF intersects at Q and CF and AD intersects at R.

So now a new triangle PQR is formed. Given triangle ABC it is very easy to find triangle PQR, but given triangle PQR it is not straight forward to find ABC. Your task is now to do that.

Input

First line of the input file contains an integer N (0 < N < 25001) which denotes how many sets of inputs are there. Input for each set contains six floating-point number Px, Py, Qx, Qy, Rx, Ry. (0 ≤ Px, Py, Qx, Qy, Rx, Ry ≤ 10000) in one line and six positive integers m1, m2, m3, m4, m5, m6 (m1 < m2, m3 < m4 and m5 < m6) in another line. These six numbers denote that the coordinate of points P, Q and R are (Px, Py), (Qx, Qy) and (Rx,Ry) respectively. P, Q and R will never be collinear and will be distinct and there will always be a triangle ABC for the given input triangle PQR. Also note that P, Q and R will be given in counter clockwise order in the input.

Output

For each line of input produce one line of output. This line contains six floating-point numbers. These six integers denote the coordinates of A, B and C. That is the first two integers denote the coordinate of A, the third and fourth integers denote the coordinate of B and fifth and sixth integers denotes the coordinate of C. A, B and C will appear counter clockwise order. All the output numbers should have eight digits after the decimal point.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2126 - Picnic Planning   

Description

The Contortion Brothers are a famous set of circus clowns, known worldwide for their incredible ability to cram an unlimited number of themselves into even the smallest vehicle. During the off-season, the brothers like to get together for an Annual Contortionists Meeting at a local park. However, the brothers are not only tight with regard to cramped quarters, but with money as well, so they try to find the way to get everyone to the party which minimizes the number of miles put on everyone's cars (thus saving gas, wear and tear, etc.). To this end they are willing to cram themselves into as few cars as necessary to minimize the total number of miles put on all their cars together. This often results in many brothers driving to one brother's house, leaving all but one car there and piling into the remaining one. There is a constraint at the park, however: the parking lot at the picnic site can only hold a limited number of cars, so that must be factored into the overall miserly calculation. Also, due to an entrance fee to the park, once any brother's car arrives at the park it is there to stay; he will not drop off his passengers and then leave to pick up other brothers. Now for your average circus clan, solving this problem is a challenge, so it is left to you to write a program to solve their milage minimization problem.

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

Each case will consist of one problem instance. The first line will contain a single integer n indicating the number of highway connections between brothers or between brothers and the park. The next n lines will contain one connection per line, of the form name1 name2 dist, where name1 and name2 are either the names of two brothers or the word Park and a brother's name (in either order), and dist is the integer distance between them. These roads will all be 2-way roads, and dist will always be positive. The maximum number of brothers will be 20 and the maximum length of any name will be 10 characters. Following these n lines will be one final line containing an integer s which specifies the number of cars which can fit in the parking lot of the picnic site. You may assume that there is a path from every brother's house to the park and that a solution exists for each problem instance.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.

For each test case, the output should consist of one line of the form

Total miles driven: xxx

where xxx is the total number of miles driven by all the brothers' cars.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2127 - Sharing Chocolate   

Description

Chocolate in its many forms is enjoyed by millions of people around the world every day. It is a truly universal candy available in virtually every country around the world.

You find that the only thing better than eating chocolate is to share it with friends. Unfortunately your friends are very picky and have different appetites: some would like more and others less of the chocolate that you offer them. You have found it increasingly difficult to determine whether their demands can be met. It is time to writte a program that solves the problem once and for all!

Your chocolate comes as a rectangular bar. The bar consists of same-sized rectangular pieces. To share the chocolate you may break one bar into two pieces along a division between rows or columns of the bar. You may then repeatedly break the resulting pieces in the same manner. Each of your friends insists on a getting a single rectangular portion of the chocolate that has a specified number of pieces. You are a little bit insistent as well: you will break up your bar only if all of it can be distributed to your friends, with none left over.

For exampla, Figure 9 shows one way that a chocolate bar consisting of 3 × 4 pieces can be split into 4 parts that contain 6, 3, 2, and 1 pieces respectively, by breanking it 3 times (This corresponds to the first sample input.)

Input

The input consists of multiple test cases each describing a chocolate bar to share. Each description starts with a line containing a single integer n (1 ≤ n ≤ 15), the number of parts in which the bar is supposed to be split. This is followed by a line containing two integers x and y (1 ≤ x, y ≤ 100), the dimensions of the chocolate bar. The next line contains n positive integers, giving the number of pieces that are supposed to be in each of the n parts. The input is terminated by a line containing the integer zero.

Output

For each test case, first display its case number. Then display whether it is possible to break the chocolate in the desired way: display ``Yes" if it is possible, and ``No" otherwise. Follow the format of the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2128 - Schedule Pairs of Jobs   

Description

In a factory, there are n pairs of jobs, (pi , qi ), i = 1, 2, . . . , n, to be scheduled. Each job, pi or qi , needs 1 unit of time to process. All the jobs pi , i = 1, 2, . . . , n, must be scheduled before of all the jobs qi , i = 1, 2, . . . , n. The order among the jobs pi , i = 1, 2, . . . , n, as well as the order among the jobs qi , i = 1, 2, . . . , n, is not important. However, it is required that the time between pi and qi , measured from the starting time of pi to the starting time of qi , should be at most di , for i = 1, 2, . . . , n.

Given a sequence of n positive integers d1 , d2 , . . . , dn , we want to know whether these n pairs of jobs can be scheduled in the time interval [0, 2n] or not. We say that the problem is solvable if the n pairs of jobs can be scheduled in a time interval of length 2n units, in such a way that the time between pi and qi is at most di , for i = 1, 2, . . . , n.

For example, for n = 3, the sequence 1, 3, 5 is solvable, since we can schedule these 3 pairs of jobs as follows:

The sequence 3, 3, 4, 6 is also solvable, since we can schedule the jobs in the following way:

In this problem, you are going to design a computer program to schedule pairs of jobs with the above constraints.

Technical Specification

Assume that n < 16, and each di < 231 . For simplicity, assume that d1d2 ≤ · · · ≤ dn , Σi=1~k dik2 for 1 ≤ k < n, and Σi=1~di=n2. Note that, in this case, if the problem is solvable then the time between each pair of jobs (pi , qi ) is exactly di . If the solution is not unique, try to schedule the jobs so that the job qi with smaller index is finished as early as possible. For example, let the input requirements be 3 3 4 6. Then print out the solution p4 p1 p2 p3 q1 q2 q4 q3.

Input

Input file contains a set of test cases. Each test case contains a positive integer n, followed by n integers di, 1 ≤ i ≤ n. The last test case is followed by a line containing only one integer 0.

Output

Print the the job in ascending order of their starting time. Print one line for each test case and for readability print a space before each “p” and “q”. If the pairs of jobs cannot be scheduled, then print the message “no solution” in that line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2129 - Lots of Sunlight   

Description

The Apartment Construction Management (ACM) has several new high-rise apartment buildings in suburban Shanghai. With the booming economy, ACM expects a considerable profit on apartment leases. Because their apartments receive more direct sunlight, the company claims that these are nicer than others in the area. No other buildings obstruct the sunlight path to apartments in ACM's tall buildings.

ACM wants to verify this claim by telling potential residents exactly how much sunlight a given apartment receives. To offer customers a representative sample of sunlight hours, the company wants to advertise the sunlight hours for April 6, 2005. On that day in Shanghai, the sun rises at 5:37 am, and sets at 6:17 pm.

As shown above, apartments are in a series of buildings aligned east to west. The last two digits of the apartment number identify the building, starting with 01 for the east-most building. The other digits encode the apartment floor, with 1 as the ground floor.

The sun rises in the east and travels at a constant radial speed across the sky, until setting in the west. The only shadows are created by buildings (i.e. each building can cast a shadow on one or more other buildings). An apartment is considered to receive sunlight when either its eastern or western exterior wall is fully covered in sunlight or when the sun is directly overhead.

Input

The input file contains a series of descriptions of apartment complexes. Each description starts with a line containing a single integer n (1 ≤ n < 100) that is the number of apartment buildings in the complex. The next line has two integers w, the width (in east-west direction), and h, each apartment's height in meters. Next is a list of integers m(1), d (1), m(2), d (2), ..., d (n - 1), m(n), where m(i) is the number of apartments in apartment building i, and d (i) is the distance, in meters, between the apartment building i and apartment building i + 1.

The apartment complex description is followed by an integer list of apartments to query for sunlight hours and is terminated by a zero. The input file is terminated by a line consisting of the integer zero.

Output

For each apartment complex description, output its number in the sequence of descriptions. Then for each query, output the corresponding sunlight hours, using the 24-hour time format. Truncate all times down to the nearest second. If the query refers to an apartment that does not exist, indicate that the apartment does not exist. Follow the format shown in the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2130 - March of the Penguins   

Description

Somewhere near the south pole, a number of penguins are standing on a number of ice floes. Being social animals, the penguins would like to get together, all on the same floe. The penguins do not want to get wet, so they have use their limited jump distance to get together by jumping from piece to piece. However, temperatures have been high lately, and the floes are showing cracks, and they get damaged further by the force needed to jump to another floe. Fortunately the penguins are real experts on cracking ice floes, and know exactly how many times a penguin can jump off each floe before it disintegrates and disappears. Landing on an ice floe does not damage it. You have to help the penguins find all floes where they can meet.

A sample layout of ice floes with 3 penguins on them.

Input

On the first line one positive number: the number of testcases, at most 100. After that per testcase:

  • One line with the integer N (1 ≤ N ≤ 100) and a floating-point number D (0 ≤ D ≤ 100000), denoting the number of ice pieces and the maximum distance a penguin can jump.
  • N lines, each line containing xi, yi, ni and mi, denoting for each ice piece its X and Y coordinate, the number of penguins on it and the maximum number of times a penguin can jump off this piece before it disappears (-10000 ≤ xi, yi ≤ 10000, 0 ≤ ni ≤ 10, 1 ≤ mi ≤ 200).

Output

Per testcase:

  • One line containing a space-separated list of 0-based indices of the pieces on which all penguins can meet. If no such piece exists, output a line with the single number -1.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2131 - Text Formatting   

Description

Your chief judge is getting long in the tooth and it is getting increasingly difficult for him to read through the densely-written messages of complaints about the problems and scores. The chief judge prefers to have more and uniform spacing between the words, and you have been drafted to write a program to format lines of text accordingly.

Your task is to write a program to read a number of lines of text and format each line independently such that:

 

  1. successive words on a formatted line are separated by exactly two blank spaces, and
  2. words are NOT split between lines, and
  3. width of the formatted text does not exceed a specified value.

 

Leading and trailing blank spaces on each given line should be ignored.

As an example:

Your chief judge is geting long in the tooth.
Have a nice day.
Your chief judge
is geting long in
the tooth.
Have a nice day.
01234567890123456789

The first input line is formatted into three (3) lines of width bounded by 20 places, and words separated by two blank spaces in each line. The second input line is formatted independently on the fourth output line.

Input

Input to this problem starts with an integer K , K > 0 , that represents the number of messages. The number K is given on a separate line followed by a description of the K messages. The description of each message starts with a line that contains two integers. The first integer W , W ≥ 20 , represents the desired width of the formatted text, and the second integer N , N > 0 , represents the number of lines in the message. A single blank space separates the two integers. The message, which consists of N lines, follows with each line consisting of a sequence of one or more words separated by blank spaces. The length of each word is less than or equal to W . That is, a word like ``supercalifragilistic-expialidocious" is only to be expected as part of the input if W ≥ 35 .

Output

For each message the output consists of one line. The line starts with the message number (the first message being ``Message 1"), followed by a ``: " (colon followed by space), as shown in the Sample Output below. This is followed by the number of lines that the formatted text would occupy.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2132 - Self-divisible Numbers   

Description

An integer number is said to be self-divisible if each digit divides the number formed by all digits up to and including that digit evenly. If you find yourself puzzled by the previous sentence, you should not worry. You are not alone. I needed to scribble few examples to understand it myself.

Here are few of them:

1)
        213 is a self-divisible number because

        2 divides 2, 1 divides 21, and 3 divides 213.

2)
        201 is not a self-divisible number because

        2 divides 2, but 0 does not divide any number.

3)
        2534 is not a self-divisible number because

2 divides 2, 5 divides 25, but 3 does not divide 253.

Your task is to write a program to count the number of self-divisible numbers in a selected range. As an example, for the range of integers between 7 and 15, where

  • 7, 8, 9, 11, 12, and 15 are self-divisible
  • 10 is not self-divisible because it contains a zero, which cannot divide any number, and
  • 13 and 14 are not self-divisible because the 2nd digit in each number does not divide it.

your program must calculate a count of 6.

 

Input

Input to this problem starts with an integer N that represents the number of cases, N > 0 , on a separate line followed by a description of the N cases. Each case is described on a separate line by two positive integers S and F , where S is less than or equal to F , that represent the start and finish values of a range of integers. The two numbers are separated by a single blank space as shown in the Sample Input below. Each of the integers S and F consists of K digits, 0 < K < 400 , and the number of self-divisible numbers in the range between each pair is less than 1000000.

Output

For each case, the output consists of one line. The line starts with the case number starting with the value of one (1), followed by a ``:", as shown in the Sample Output below, and then followed by the number of self-divisible numbers in the range.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2133 - Challenging "Butts"   

Description

Darts (Some historical records suggest that the first standard dartboards were the bottoms of wine casks, hence the game's original name of ``butts".) is a very popular game in which darts are thrown at a circular target (dart board) hung on a wall. Dart boards are usually made of sisal fibers or boar bristles, low quality boards are sometimes made of paper. A regulation board is 45.72 cm in diameter, and is divided into sectors. Each sector is lined with metal wire. The numbers indicating the various scores of sectors on the dart board are normally made of wire, especially on tournament-quality boards, but may be printed on the board instead. In the standard game, the dart board is hung so that the bulls-eye is 1.73 m from the floor, eye-level for a six foot person. The oche, the line behind which the player must stand, is 2.37 m from the face of the board. When playing darts players often aim at the high scoring sectors, but for ordinary players it is hard to land a dart on the desired sector. The risk of aiming at a sector can thus be measured by the difference between the scores of adjacent sectors, where two sectors are said to be adjacent if they share an edge or an arc. A large such difference increases the risk and makes the game more challenging. The total risk of a dart board is the sum over the risks between all adjacent sectors. We have been asked by the sponsor of a programming competition to design a new, and challenging, dart board to occupy the touchy coaches during the contest.

The new dart board design consists of a circle that is divided into N sectors, N ≥ 3 , by lines running from the centre of the circle to its perimeter and a smaller concentric circle that subdivides each sector into two areas: as shown in the sketch for N equal to three (3).

Your task is to write a program to read ``2N " positive integer values and assign them to the ``2N " areas of the new dart board design such that the total risk is maximized. An example of such an assignment is:

The total risk of this dart board design with ``6" areas is 59.

Input

The first line of the input contains a single integer between 1 and 1000, inclusive, which is the number of dart boards that follow. The description of each dart board consists of two lines:

  1. The first line consists of an integer N , 300 ≥ N ≥ 3 , which identifies the number of sectors on the board.
  2. The second line consists of ``2N " positive integers, separated by single spaces, which represent the scores. Each integer is less than or equal to 10000.

Output

For each dart board the output is an integer, on a separate line, which represents the maximum risk of the board.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2134 - A Fitting Advertisement!   

Description

A skyline is the outline formed by a group of buildings against the sky. The ACM city in Second Life, which has been built with a beautiful skyline that's visible to anyone that approaches it, sold the rights to place advertisement at the approaches to the city to a company as long as it does so while preserving the shape of the city's skyline. The company wants to accept all requests for advertising that are of rectangular shape and can be fully placed, with sides parallel to edges of the skyline as shown shaded in the example below, within the interior of the skyline.

Each skyline of the ACM city is formed by N buildings, all with a width of one (1) but with different heights. The height of each building is between 0 and 1000, inclusive and the number of buildings N is between 1 and 400, inclusive. The example below shows a skyline with six (6) buildings, and an advertisement of size 3 by 5 (shown in gray) placed parallel to the sides of the skyline. Note that an advertisement may be rotated by 90o so that it can fit into the skyline. That is, advertisement of size 5 by 3 can be placed within the skyline by rotating it first. It is ``Second Life" after all.

Your task is to write a program to read the descriptions of a number of skylines and advertising requests, and decide for each request whether it should be accepted or rejected. Each request is to be checked independently as only one advertisement will be displayed at any time.

Input

The first line of the input contains a single integer C between 1 and 1000, inclusive, which is the number of cases that follow. Each case starts with a description of the skyline of the city from one approach that consists of two lines:

  1. The first line contains an integer N , 1 ≤ N ≤ 400 , that is the number of buildings in the skyline
  2. The second line contains the heights of the buildings

followed by a sequence of advertising requests. Each request consists of two integers on a single line, separated by a single space, which describe the length of the two sides of the rectangle that contains the advertisement. Both lengths are between 1 and 1000, inclusive. A request of two zeros separated by a single space (0 0) terminates the case.

Output

For each skyline the output starts with a line that contains the case number starting with the value of one (1), followed by a ``:", as shown in the Sample Output below, and then followed by a sequence of decisions of ``Accept" or ``Reject", on a separate line, for each request.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2135 - The Zits Code   

Description

Jeremy is not known for his organizational skills, but he is now determined to change. Jeremy's plan is to place notes around the house to remind him of tasks to be done and of the proper ways to do them. Jeremy's plan also includes encrypting the messages so that his parents (who don't understand anything!) do not nag him, but in a simple way so that he can recover the original message easily.

Jeremy's encryption scheme consists of two steps:

  1. Enter the message, of M characters, which includes the spaces between words, into a spiral that curls inwards in a clockwise direction, starting at the top-left corner of a square. The width and height of the square enclosing the spiral are chosen to be equal to the square root of P , where P is the smallest perfect square larger than or equal to M . If M is strictly less than P , then the remaining locations in the square are filled with the character `$'.
  2. Write the encrypted note by writing the characters one row at a time starting with the top row.

As an example, for the following message of 33 characters

abcd fgh jklmn pqrstu wxyz1 34567

Jeremy writes the following note:

abcd ftu wxgs67$yhr5$$z q43 1jp nmlk

based on entering his original message in a square of 6 rows and 6 columns as follows:

a b c d   f
t u   w x g
s 6 7 $ y h
r 5 $ $ z  
q 4 3   1 j
p   n m l k

Your task is to write a program to encrypt Jeremy's messages with the hope that he will acquire some organizational skills, in peace. In case you have forgotten, let me remind you that a number X is a perfect square if there exists a positive integer K , such that K2 equals X . For example, 16 is a perfect square but 18 is not a perfect square.

Input

Input to this problem starts with an integer N that represents the number of messages, N > 0 , on a separate line followed by a sequence of N messages. Each message consists of M characters, 1000 ≥ M > 0 , on a single line with no blank spaces at the end.

Output

For each message, the output consists of one line that contains the note with an encrypted message.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2136 - DNA Chopper   

Description

As the sole employee in a pharmaceutical company with programming exposure, you have been asked to oversee the process of cutting DNA strands into smaller pieces, which has been outsourced to a company by the name of Chopper!, and check for any attempt of over charging.

DNA (Deoxyribonucleic acid) strand is a long polymer of simple units called nucleotides, with a backbone made of sugars and phosphate atoms joined by ester bonds. Attached to each sugar is one of four types of molecules called bases. It is the sequence of these four bases along the backbone that encodes information needed to construct other components such as proteins and RNA molecules. The cost of cutting a DNA strand, with today's technology, is equal to the length of the strand, where a ``cut" refers to splitting a strand into two pieces. The cost of a single cut does not depend on the location where the cut is made. Chopper! claims to have developed the world-best-practice in sequencing the cuts of a DNA strand and to deliver the most savings to its customers.

Your task is to write a program to process the next batch of DNA strands and calculate the best price for slicing each of them into smaller strands of integer lengths. For each DNA strand you are given its length as an integer N , N ≤ 10000 , and a list of M , 2 ≤ M ≤ 15 , strands' lengths to be produced. The sum of the M integers equals the original strand length N .

The total cost of slicing a given strand depends on the choice of locations and the order of the M - 1 required cuts. As an example, for a given list of M (=4) lengths 2, 2, 5 and 5 and a DNA strand of length 14, we can:

  • first cut the strand in half then twice split a 2 and 5 from the remaining 7s for a cost of 28 (=14 + 7 + 7), or
  • first cut off a 5 from the end of the strand, then another 5, then split the remaining 4 in half for a cost of 27 (= 14 + 9 + 4).

Input

The input contains information about a number of DNA strands to be processed. The information for each strand consists of two lines:

  1. The first line consists of the two integers M and N ( 2 ≤ M ≤ 15 and 0 ≤ N ≤ 10000 ) that identify the number of required smaller strands and the length of DNA strand, respectively.
  2. The second consists of M positive integers (separated by blank spaces) that sum to N .

The input is terminated by a line of two zeros (0 0) for which no output is to be produced.

Output

For each input DNA strand the output is an integer, on a separate line, which represents the minimum cost for slicing the strand into the given list.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2137 - Automatic Marking   

Description

You must be familiar with binary trees and all their operations, but this problem deals with a less popular structure, which I shall call myTree. There are three possible organizations of a myTree:

  1. an empty tree. That is, a tree with no nodes.
  2. a tree whose root node has a single data item, say K, and two children. Each of its two children is a myTree. Any values in the left subtree are less than or equal to K, and any values in the right subtree are larger than K.
  3. a tree whose root node has two data items, say K1 and K2 , and three children. K1 < K2 . Each of its three children is a myTree. Any values in the left subtree are less than or equal to K1 , any values in the middle subtree are larger than K1 and smaller than or equal to K2 , and any values in the right subtree are larger than K2 .

All internal (non-terminal) nodes have two or three children, although some may be empty. One way to represent such a tree is to use level-order traversal, starting at the root node, with the content of each node enclosed in parentheses. An empty tree is represented by a pair of parentheses that encloses nothing. The following figure demonstrates an example of such a tree, along with its representation, with values in the nodes being uppercase characters chosen in the range of ``A" to ``Z", inclusive.

A lecturer of ``Data Structures 101" likes to test her students understanding of the myTree structure by asking them to identify all possible ways to assign a missing value in a given myTree.

Examples of such a question would be:

  1. a tree ``(M R) (C) (N P) (? U) () () () () () () () ()", for which the answer should be the letters ``S" and ``T".
  2. a tree ``(M R) (X) (N O) (? U) () () () () () () () ()", for which the answer should be ``This is not a myTree". The reason is that X > M .
  3. a tree ``(M R) (N O) (? U)", for which the answer should be ``This is not a myTree". The reason is that nodes with two values should have three children in a myTree structure, which is violated in this question.

Your task is to write a program to answer such a question.

Input

The input contains descriptions of a number of myTree structures to be processed. The information for each tree is given in a single line as a series of properly matched parentheses. Each pair of matched parentheses encloses zero, one, or two characters selected from uppercase letters in the range of ``A" to ``Z" and ``?". Each line contains exactly one ``?". The selected characters and parentheses are separated by single spaces.

The input is terminated by a line of a set of matched parentheses, which encloses a zero, for which no output is to be produced.

Output

For each input tree the output is a single line with:

  1. a listing of possible uppercase letters sorted in increasing order that can replace the ``?" in the given tree, or
  2. the string ``This is not a myTree", if the given data does not conform to the given specifications.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2138 - MODEX   

Description

Many well-known cryptographic operations require modular exponentiation. That is, given integers x , y and n , compute xy mod n . In this question, you are tasked to program an efficient way to execute this calculation.

Input

The input consists of a line containing the number c of datasets, followed by c datasets, followed by a line containing the number `0'.

Each dataset consists of a single line containing three positive integers, x , y , and n , separated by blanks. You can assume that 1 < x , n < 215 = 32768 , and 0 < y < 231 = 2147483648 .

Output

The output consists of one line for each dataset. The i -th line contains a single positive integer z such that

z = xy mod n

for the numbers x , y , z given in the i -th input dataset.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2139 - JONES   

Description

The time now is 12 noon and Indiana Jones is standing on the western bank of a river. He wants to reach the eastern bank as fast as possible. Across the river is a series of stones, arranged in a straight line, and each stone is 1 meter away from its immediate neighbours or the two river banks.

Let us divide the time into intervals of one minute each, such that Interval 0 starts at 12:00:00, Interval 1 starts at 12:01:00, and so on. At the start of each interval, Indiana Jones can hop once from a stone/river bank to any stone/bank that is not more than 1.5 meters away, or stay put. He can hop so fast that we assume the time taken per hop is negligible.

The tricky part is this: The stones may sink and resurface! Within a time interval, a stone may sink at the middle of the interval, remains submerged and may resurface at the middle of another interval. If Indiana Jones is standing on a sinking stone, he will drown. Of course, Indiana Jones cannot hop to a stone that is submerged. At 12 noon, all stones are above the water and Indiana Jones is ready to hop. He has already derived the pattern of sinking/resurfacing for each stone during the next few intervals. Our task is to find the fastest way to cross the river.

Figure 1 shows an example of sinking and resurfacing stones over time. The example contains three stones, each of which is first sinking, then resurfacing and then sinking. The fastest way for Indiana Jones to cross the river is shown as a black line.

 

Input

The input consists of a line containing the number c of datasets, followed by c datasets, followed by a line containing the number `0'.

The first line of each dataset contains two positive integers, separated by a blank. The first value s is the number of stones. The second value t is the number of intervals whose movement pattern Indiana Jones can predict. You can assume 1 ≤ s ≤ 500 and 1 ≤ t ≤ 500 . The following t lines of each dataset describe the behavior of the stones in each interval. The i -th line describes the behavior of the stones in Interval i , where 0 ≤ i < t . Within each line, there are s characters, separated by blanks. The j -th character indicates the movement of the j -th stone in the middle of the i -th interval as follow:

``s":
       The stone is sinking.:
``r":
       The stone is resurfacing.:
``u":
       The stone is not moving.:

 

Output

The output consists of one integer, which indicates the earliest interval at the beginning of which Indiana Jones can reach the eastern bank. If there is no way Indiana Jones can cross the river within t minutes, the output should be `-1'. Note that Indiana Jones actually has t + 1 chances to hop.

Notes for the sample: In this dataset, the fastest way to cross over is as follows:

  1. Stay put at the beginning of Interval 0.
  2. Stay put at the beginning of Interval 1.
  3. Stay put at the beginning of Interval 2.
  4. Jump from the western bank to the first stone at the beginning of Interval 3.
  5. Jump from the first stone to the second stone at the beginning of Interval 4.
  6. Jump from the second stone to the third stone at the beginning of Interval 5.
  7. Jump from the third stone to the eastern bank at the beginning of Interval 6.

Thus, Indiana Jones can reach the eastern bank the earliest at the beginning of Interval 6.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2140 - ACORN   

Description

In the first morning of every summer, when the first ray of sunlight breaks into the oak forest, Jayjay, the flying squirrel, quickly climbs to the top of an oak tree in the forest. From there, he starts his descent to the ground, and tries to gather as many acorns from the trees on his way down. Being a flying squirrel, Jayjay can choose, at any moment, to climb down the tree trunk or to fly from one tree to any other tree on his descending journey. However, he loses f feet of height every time he flies from one tree to another.

Suppose the forest has t oak trees, and all the trees have the same height of h feet. Given the height of every acorn on each tree, write a program to compute the maximal possible number of acorns Jayjay can collect by choosing a tree to climb and descend as described.

Figure 2 shows an example of t = 3 oak trees with three, six, and five acorns, respectively. The white circles and grey line indicate a path for Jayjay to collect the maximal possible number of eight acorns, assuming that the height he loses for each flight is f = 2 .

 

 

Input

The input consists of a line containing the number c of datasets, followed by c datasets, followed by a line containing the number `0'.

The first line of each dataset contains three integers, t , h , f , separated by a blank. The first integer t is the number of oak trees in the forest. The second integer h is the height (in feet) of all the oak trees. The third integer, f , is the height (in feet) that Jayjay loses every time he flies from one tree to another. You may assume that 1 ≤ t , h ≤ 2000 , and 1 ≤ f ≤ 500 .

The first line of each dataset is followed by t lines. The i -th line specifies the height of every acorn on the i -th tree. The line begins with a non-negative integer a that specifies how many acorns the i -th tree has. Each of the following a integers n indicates that an acorn is at height n on the i -th tree. The positive integers in each line are sorted in ascending order, and repetitions are allowed. Thus, there can be more than one acorn at the same height on the same tree. You can assume that 0 ≤ a ≤ 2000 , for each i .

Output

The output consists of one line for each dataset. The c -th line contains one single integer, which is the maximal possible number of acorns Jayjay can collect in one single descent for dataset c .

Note: This dataset and Jayjay's path to collect the maximal number of 8 acorns are shown in Figure 2.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2141 - TUSK   

Description

A conservation group found a way to scan the cross-section of elephant tusks like the one shown on the left. The scanned image of a tusk is a collection of bright spots, which can be treated as a set of points on the plane, where no three points form a straight line. The group made a database of many tusks and hope that the database can help in tracking illegal ivory trade.

To facilitate retrieval from the database, it is desirable to have a feature representation that remains unchanged even if a scanned image is translated or rotated. They decided to use the number of k -sets to represent a set of points, which is defined below.

Consider a set P of n points in the plane, where no three points form a straight line. Any line in the plane that does not contain a point in P will split the set into two sets X , Y , where X contains points on one side of the line and Y contains points on the other side. If the number of points in X is k , then we call the collection {X, Y} a k -set in P . Note that {X, Y} = {Y, X} , and thus a k -set is also an (n - k) -set. Given a set P and k , your task is to compute the number of different k -sets in P .

Input

The input consists of a line containing the number c of datasets, followed by c datasets, followed by a line containing the number `0'.

The first line of each dataset contains two integers, separated by a blank. The first integer gives the number n of points in P , and the second integer gives k , where (0 < k < n ≤ 2000) . The following n lines of each dataset each contains two non-negative integers, indicating the x and y -coordinates of the corresponding point. The x and y -coordinates range from 0 to 10000.

Output

The output consists of one line for each dataset. The c -th line contains the number of k -sets for dataset c .

Note: This dataset and the lines that form its 2-sets are shown in Figure 3.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2142 - SKYLINE   

Description

The skyline of Singapore as viewed from the Marina Promenade (shown on the left) is one of the iconic scenes of Singapore. Country X would also like to create an iconic skyline, and it has put up a call for proposals. Each submitted proposal is a description of a proposed skyline and one of the metrics that country X will use to evaluate a proposed skyline is the amount of overlap in the proposed sky-line.

As the assistant to the chair of the skyline evaluation committee, you have been tasked with determining the amount of overlap in each proposal. Each proposal is a sequence of buildings, { b1, b2,..., bn }, where a building is specified by its left and right endpoint and its height. The buildings are specified in back to front order, in other words a building which appears later in the sequence appears in front of a building which appears earlier in the sequence.

The skyline formed by the first k buildings is the union of the rectangles of the first k buildings (see Figure 4). The overlap of a building, bi , is defined as the total horizontal length of the parts of bi , whose height is greater than or equal to the skyline behind it. This is equivalent to the total horizontal length of parts of the skyline behind bi which has a height that is less than or equal to hi , where hi is the height of building bi . You may assume that initially the skyline has height zero everywhere.

Input

The input consists of a line containing the number c of datasets, followed by c datasets, followed by a line containing the number `0'.

The first line of each dataset consists of a single positive integer, n (0 < n < 100000) , which is the number of buildings in the proposal. The following n lines of each dataset each contains a description of a single building. The i -th line is a description of building bi . Each building bi is described by three positive integers, separated by spaces, namely, li , ri and hi , where li and rj (0 < li < ri ≤ 100000) represents the left and right end point of the building and hi represents the height of the building.

Output

The output consists of one line for each dataset. The c -th line contains one single integer, representing the amount of overlap in the proposal for dataset c . You may assume that the amount of overlap for each dataset is at most 2000000.

Note: In this test case, the overlap of building b1 , b2 and b3 are 6, 4 and 4 respectively. Figure 4 shows how to compute the overlap of building b3 . The grey area represents the skyline formed by b1 and b2 and the black rectangle represents b3 . As shown in the figure, the length of the skyline covered by b3 is from position 3 to position 5 and from position 11 to position 13, therefore the overlap of b3 is 4.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2143 - USHER   

Description

In a large church in New Zealand, after the church service, the priest gives an empty collection box that can hold c dollar coins to the ``light-fingered usher". The usher then passes the collection box to a nearby parishioner. When receiving the box a parishioner adds a few dollar coins, then passes it to another nearby parishioner. When the light-fingered usher receives the box, he quietly removes one dollar coin from the box, slips it into his pocket, and passes the box to a nearby parishioner.

The behavior of the usher is given by a set of parishioners to whom he may pass the box. The behavior of a parishioner is given by a set of rules, each consisting of a donation of at least two dollar coins, and another parishioner to whom the box is passed after he places the coins in the box. As soon as the box is full, containing c coins, it is immediately passed to the priest, even when a parishioner cannot finish entering all the coins specified by the chosen rule.

Your problem is to compute the maximal possible gain for the usher, which is achieved when the parishioners always choose a rule that leads to the biggest number of coins in the usher's pocket.

Input

The input consists of a line containing the number c of datasets, followed by c datasets, followed by a line containing the number `0'.

The first line of each dataset contains two numbers b and p , separated by a blank. The number b specifies the capacity of the box, and p the number of parishioners. You can assume that 1 ≤ b ≤ 1000000 and 1 ≤ p ≤ 500 . The next line specifies the behavior of the usher, represented by integers separated by a blank. The first integer specifies the number q of parishioners, to which the usher may pass the box. The next q integers each represent a parishioner to whom he may pass the box. The parishioners are numbered from 1 to p . Each line i (1 ≤ ip) of the next p lines of each dataset describes the behavior of parishioner i , and consists of integers separated by a blank. The first integer of the line specifies the number of rules for the parishioner. Each rule is represented by a pair of integers, the first of which specifies the number of coins to give, which must be equal or greater than 2. The second number indicates the parishioner to receive the box next, where the number 0 identifies the usher. When there are two or more rules, the parishioner may choose to apply any of them. You can assume that the number of rules per parishioner is at least 1 and less than or equal to 1000; there may be multiple rules with the same parishioner to receive the box.

Output

The output consists of one line for each dataset. The c -th line contains the maximal number of coins that the usher can obtain for dataset c .

Note: This dataset specifies that the box can hold up to 10 coins, and that there are two parishioners. The usher may pass the box to either one of the two parishioners, as indicated by the second line. Parishioner 1 has two rules, and can choose either one, when the box is passed to him. The first rule says to put down 6 dollar coins and pass the box to the usher (indicated by `0'), and the second rule is put down 4 dollar coins and pass the box to parishioner 2. The last line specifies one single rule for parishioner 2, who must put down 5 dollar coins, and then pass the box to the usher.

The usher can obtain the maximal amount of 2 dollars by passing the box to parishioner 2, who passes it back to the usher. At that point, there are 5 dollars on the box. After removing one dollar, the box goes with 4 dollars to parishioner 2, and back to the usher, now with 8 dollars. The usher removes another dollar, and the box goes to parishioners 2 with 7 dollars. Parishioner 2 starts to apply his rule, and manages to put three more coins into the box, after which the box is full and goes to the priest. The usher ends up with two dollar coins in his pocket.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2144 - RACING   

Description

Singapore will host a Formula One race in 2008. The race will be held on a 5.067km long street circuit, consisting of 14 left hand turns and 10 right hand turns. In the run up to the F1 race, the number of illegal night street racing activities have been on the rise. Such races consists of several rounds around a designated street circuit.

The authorities would like to deploy a new vehicle monitoring system in order to catch these illegal Saint Andrew's Road, part of the Formula One circuit racers. The system consists of a (Kenny Pek, Piccom) number of cameras mounted along various roads. For the system to be effective, there should be at least one camera along each of the possible circuits.

The Singapore road system can be represented as a series of junctions and connecting bidirectional roads (see Figure 5). A possible racing circuit consists of a start junction followed by a path consisting of three or more roads that eventually leads back to the start junction. Each road in a racing circuit can be traversed only in one direction, and only once.

Your task is to write a program that computes the optimal placement of the vehicle-monitoring cameras. You will be provided with a description of a connected road network to be monitored in terms of the roads and junctions. The junctions are identified by the bigger numbers in Figure 5. A camera can be deployed on the roads (and not the junctions).

The cost of deploying a camera depends on the road on which it is placed. The smaller numbers by the roads in Figure 5 indicate the cost of deploying a camera on that road. Your job is to select a set of roads that minimizes the total cost of deployment while ensuring that there is at least one camera along every possible racing circuit (i.e. loop in the road network).

Input

The input consists of a line containing the number c of datasets, followed by c datasets, followed by a line containing the number `0'.

The first line of each dataset contains two positive integers, n and m , separated by a blank, which represent the number of junctions and number of roads, respectively. You may assume that 0 < n < 10000 and 0 < m < 100000 . For simplicity, we label each of the n junctions from 1 to n . The following m lines of each dataset each describes one road. Each line consists of three positive integers which are the labels of two different junctions and the cost of deploying a camera on this road. The cost of deploying a camera is between 1 and 1000.

Output

The output consists of one line for each dataset. The c -th line contains one single number, representing the minimal cost of setting up the vehicle monitoring system such that there is at least one camera along every possible circuit.

Note: This data set depicts the situation shown in Figure 5. The two cameras show where cameras might be placed in order to monitor each circuit at minimal cost. Since each of the cameras have a cost of 3, the total minimal cost is 6.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2145 - Molar mass   

Description

An organic compound is any member of a large class of chemical compounds whose molecules contain carbon. The molar mass of an organic compound is the mass of one mole of the organic compound. The molar mass of an organic compound can be computed from the standard atomic weights of the elements.

When an organic compound is given as a molecular formula, Dr. CHON wants to find its molar mass. A molecular formula, such as C3H4O3 , identifies each constituent element by its chemical symbol and indicates the number of atoms of each element found in each discrete molecule of that compound. If a molecule contains more than one atom of a particular element, this quantity is indicated using a subscript after the chemical symbol.

In this problem, we assume that the molecular formula is represented by only four elements, `C' (Carbon), `H' (Hydrogen), `O' (Oxygen), and `N' (Nitrogen) without parentheses.

The following table shows that the standard atomic weights for `C', `H', `O', and `N'.

Atomic Name Carbon Hydrogen Oxygen Nitrogen
Standard Atomic Weight 12.01 g/mol 1.008 g/mol 16.00 g/mol 14.01 g/mol

For example, the molar mass of a molecular formula C6H5OH is 94.108 g/mol which is computed by 6 × (12.01 g/mol) + 6 × (1.008 g/mol) + 1 × (16.00 g/mol).

Given a molecular formula, write a program to compute the molar mass of the formula.

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case is given in a single line, which contains a molecular formula as a string. The chemical symbol is given by a capital letter and the length of the string is greater than 0 and less than 80. The quantity number n which is represented after the chemical symbol would be omitted when the number is 1 (2 ≤ n ≤ 99) .

Output

Your program is to write to standard output. Print exactly one line for each test case. The line should contain the molar mass of the given molecular formula.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2146 - Editor   

Description


Mr. Kim is a professional programmer. Recently he wants to design a new editor which has as many functions as possible. Most editors support a simple search function that finds one occurrence (or all occurrences successively) of a query pattern string in the text.

He observed that the search function in commercial editors does nothing if no query pattern is given. His idea of a new search function regards each substring of the given text as a query pattern string itself and his new function finds another occurrence in the text. The problem is that there can be occurrences of many substrings in the text. So, Mr. Kim decides that the new function finds only occurrences of the longest substring in the text in order to remedy the problem. A formal definition of the search function is as follows:

Given a text string S , find the longest substring in text string S such that the substring appears at least twice. The two occurrences are allowed to overlap.

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. For each test case, a text string S is given in one line. For every string, the length is less than or equal to 5,000 and the alphabet Σ is the set of lowercase English characters.

Output

Your program is to write to standard output. Print exactly one line for each test case. Print the length of the longest substring in text string S such that the substring appears at least twice.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2147 - Network   

Description

Consider a tree network with n nodes where the internal nodes correspond to servers and the terminal nodes correspond to clients. The nodes are numbered from 1 to n . Among the servers, there is an original server S which provides VOD (Video On Demand) service. To ensure the quality of service for the clients, the distance from each client to the VOD server S should not exceed a certain value k . The distance from a node u to a node v in the tree is defined to be the number of edges on the path from u to v . If there is a nonempty subset C of clients such that the distance from each u in C to S is greater than k , then replicas of the VOD system have to be placed in some servers so that the distance from each client to the nearest VOD server (the original VOD system or its replica) is k or less.

Given a tree network, a server S which has VOD system, and a positive integer k , find the minimum number of replicas necessary so that each client is within distance k from the nearest server which has the original VOD system or its replica.

For example, consider the following tree network.


In the above tree, the set of clients is {1, 6, 7, 8, 9, 10, 11, 13}, the set of servers is {2, 3, 4, 5, 12, 14}, and the original VOD server is located at node 12.

For k = 2 , the quality of service is not guaranteed with one VOD server at node 12 because the clients in {6, 7, 8, 9, 10} are away from VOD server at distance > k . Therefore, we need one or more replicas. When one replica is placed at node 4, the distance from each client to the nearest server of {12, 4} is less than or equal to 2. The minimum number of the needed replicas is one for this example.

Input

Your program is to read the input from standard input. The input consists of T test cases. The number of test cases (T ) is given in the first line of the input. The first line of each test case contains an integer n (3 ≤ n ≤ 1, 000) which is the number of nodes of the tree network. The next line contains two integers s (1 ≤ sn) and k (k ≥ 1) where s is the VOD server and k is the distance value for ensuring the quality of service. In the following n - 1 lines, each line contains a pair of nodes which represent an edge of the tree network.

Output

Your program is to write to standard output. Print exactly one line for each test case. The line should contain an integer that is the minimum number of the needed replicas.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2148 - PHONE   

Description

Mobile phones prevail in everyday life. Every mobile phone has a number pad for users to dial the telephone number. Figure 1 shows a typical layout of number pads, which can be represented as 4 by 3 rectangular cells. We know that some mobile phone numbers are easy to memorize, since entering in sequence of digits implies an easy-to-remember geometric figure.

For each phone number, we can make a corresponding geometric figure, Phone Plot, which is a sequence of connected line segments. Assume that a phone number with n digits is d1 d2 d3...dn-1 dn . The first line segment of Phone Plot is a line segment connecting the center points of pad d1 and pad d2 . The second line segment of Phone Plot connects the center points of pad d2 and d3 . In a similar way the k -th line segment connects the center points of pad dk and pad dk+1 , and the last segment connects dn-1 and dn .

Let us show a few examples. The Phone Plot for the number 1023289873 is shown as the thick lines in Figure 2(a). Figure 2(b) shows that the Phone Plot for a number 1159533969.

You should note that some connecting line segments may overlap other line segment collinearly.

We characterize a Phone Plot by the Minimal Number of Decomposing Segments(MNDS). MNDS is the minimal number of line segments to reconstruct the given Phone Plot. So we easily find that the MNDS of the number 1023289873 is 5, and the MNDS of 1159533969 is 3. If the Phone Plot is reduced to a single point for a number (e.g., 0000000000), then MNDS of such a point Phone Plot is defined 0.

We want to classify the phone number into three disjoint classes; EXCELLENT, GOOD and BAD by the complexity of Phone Plot. Thus if the MNDS of Phone Plot is at most 3, then this number is classified to EXCELLENT. If MNDS is exactly 4, then this number is classified to GOOD. If the MNDS is greater than or equal to 5, that number is classified to BAD.

According to this classification, we say 1023289873 is BAD and 1159533969 is EXCELLENT. Figure 3 shows another example with 5233999008. Since the MNDS of 5233999008 is 5, so this number is BAD.

You have to decide whether the phone number given is EXCELLENT or GOOD or BAD according to the MNDS of the Phone Plot.

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a string representing a phone number. The length of a phone number string is greater than 5 and less than 20.

Output

Your program is to write to standard output. For each test case, print EXCELLENT or GOOD or BAD in a line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2149 - Tile Code   

Description

The city of Songpa is now carrying out a project to build a bicycle transportation system called ‘green Songpa.’ By the end of this year, citizens and visitors alike will be able to pick up and drop off bicycles throughout the city. Recently, it was decided to attach a number tag to each bicycle for management use. The bicycles will be under control of the city’s traffic system.

The number tag contains a tile code of length n , which consists of 1×2 , 2×1 , and 2×2 tiles placed on a 2×n rectangular plate in a way that every cell of the plate is covered by exactly one tile. The plate is divided into 2n cells of size 1×1 . Of course, no two tiles are allowed to overlap each other. The 2×5 plate and a tile code of length 5 are shown in Figures 1 and 2, respectively. The code will always be read from left to right. However, there is no distinction between the top side and the bottom side of the code. The code may be turned upside down. The code shown in Figure 3 is essentially the same code as in Figure 2.

Given a positive integer n , the project director Dr. Yang wants to know how many tile codes of length n there are, that is, the number of ways to place the three kinds of tiles into a 2×n rectangular plate subject to the above conditions. Write a program that can help him.

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case is given in a single line, which contains a positive integer n , 3 ≤ n ≤ 30 .

Output

Your program is to write to standard output. Print exactly one line for each test case. The line should contain the number of tile codes of length n .

Sample Input  Download

Sample Output  Download

Tags




Discuss




2150 - Meteor   

Description

The famous Korean internet company nhn has provided an internet-based photo service which allows The famous Korean internet company users to directly take a photo of an astronomical phenomenon in space by controlling a high-performance telescope owned by nhn. A few days later, a meteoric shower, known as the biggest one in this century, is expected. nhn has announced a photo competition which awards the user who takes a photo containing as many meteors as possible by using the photo service. For this competition, nhn provides the information on the trajectories of the meteors at their web page in advance. The best way to win is to compute the moment (the time) at which the telescope can catch the maximum number of meteors.

You have n meteors, each moving in uniform linear motion; the meteor mi moves along the trajectory pi + t×vi over time t , where t is a non-negative real value, pi is the starting point of mi and vi is the velocity of mi . The point pi = (xi, yi) is represented by X -coordinate xi and Y -coordinate yi in the (X, Y) -plane, and the velocity vi = (ai, bi) is a non-zero vector with two components ai and bi in the (X, Y) -plane. For example, if pi = (1, 3) and vi = (-2, 5) , then the meteor mi will be at the position (0, 5.5) at time t = 0.5 because pi + t×vi = (1, 3) + 0.5×(-2, 5) = (0, 5.5) . The telescope has a rectangular frame with the lower-left corner (0, 0) and the upper-right corner (w, h) . Refer to Figure 1. A meteor is said to be in the telescope frame if the meteor is in the interior of the frame (not on the boundary of the frame). For example, in Figure 1, p2, p3, p4 , and p5 cannot be taken by the telescope at any time because they do not pass the interior of the frame at all. You need to compute a time at which the number of meteors in the frame of the telescope is maximized, and then output the maximum number of meteors.

Input

Your program is to read the input from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing two integers w and h (1 ≤ w, h ≤ 100, 000) , the width and height of the telescope frame, which are separated by single space. The second line contains an integer n , the number of input points (meteors), 1 ≤ n ≤ 100, 000 . Each of the next n lines contain four integers xi, yi, ai , and bi ; (xi, yi) is the starting point pi and (ai, bi) is the nonzero velocity vector vi of the i -th meteor; xi and yi are integer values between -200,000 and 200,000, and ai and bi are integer values between -10 and 10. Note that at least one of ai and bi is not zero. These four values are separated by single spaces. We assume that all starting points pi are distinct.

Output

Your program is to write to standard output. Print the maximum number of meteors which can be in the telescope frame at some moment.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2151 - Signals   

Description

Let DC (direct current) circuits be given. Each DC circuit generates a set of output signals. The DC circuits consist of a set of devices connected in parallel or in serial but they have no feedback loops. Each device generates a specific signal and the set of output signals of a circuit is determined by the kinds of devices and the topology of the device connection. For example, let two circuits named C1 and C2 be given as follows:

For C1, two signals, namely abc and adc can be generated. Given a circuit C, the output OUT(C) of it is defined as the set of signals which can be generated by C. For C1, the output of C1 is {abc, adc}, i.e. OUT(C1) = {abc, adc}. By the way, OUT(C2) is also {abc, adc}. For the above circuits, OUT(C1) = OUT(C2).

There is a special device called the pass device, namely 1, generating no signal at all. The circuit C3 contains a pass device. The parallel connections and serial connections of sub-circuits can be arbitrarily nested and composed as shown in circuit C4.

For C3, the output is {abc, ac}, i.e. OUT(C3) = {abc, ac}; for C4, the output is {abc, aabc, aadc}, i.e. OUT(C4) = {abc, aabc, aadc}.

The problem is to determine the relation of two given circuits. The names of normal devices are given by lowercase letters depending on the signals generated by them. The name of the pass device is 1. The parallel connection of two circuits C and D is denoted by C| D and the serial connection of two circuits C and D in a row is denoted by CD . The parentheses can be used as needed to clarify the topology of connections, but no spaces are allowed in a circuit description.

For example, the denotations of the above circuits are given as follows:

Circuit Circuit Representation
C1 a(b|d)c
C2 (ab|ad)c
C3 a(b|1)c
C4 a(b|a(b|d))c

 

There can be redundant parentheses around the representation of sub-circuits. For instance, C1 can be represented by (a((b)|((d)))c) instead of a(b|d)c.

The comparison result of two circuits is denoted by =, <, >, 0, and 1. Given two circuits C and D , the relation between them is determined as follows:

The Relation of the Circuits Representation of the Relation
OUT(C) = OUT(D) =
OUT(C) is a proper subset of OUT(D) <
OUT(D) is a proper subset of OUT(C) >
OUT(C) and OUT(D) are disjoint 0
otherwise 1

Assume that every circuit generates at least one signal. In other words, there’s no circuit whose output is {} though it is allowed for nested circuits such as 1 or (1|1).

Input

Your program is to read the input from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case is given by two circuit representations separated by one or more spaces. The length of a circuit representation is less than 50; and the number of test cases is less than 30.

Output

Your program is to write to standard output. For an input test case representing two circuits C and D in sequence, print a character representing the relation of C and D in one line. Hence, the number of output lines is equal to the number of test cases.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2152 - Puzzle   

Description

Jisung is the student representative of the Department of Computer Engineering in ACM University. A few days later, the annual festival will be held for the students in the department. He is preparing some events for the festival. Since Jisung likes to make and solve puzzles, he decides to devise some interesting puzzle for the festival.

The followings are the rules for the puzzle made by Jisung:

(1) The players will be given an integer n . Then they should use the first n capital letters from the Roman alphabet. For example, if n = 4, the four characters A, B, C, and D will be used to solve this puzzle.

(2) The players will be given s forbidden strings. No forbidden string contains another forbidden string as a substring. The winner is the student who makes the longest string that does not include a forbidden string as a substring.

(3) If such a longest string does not exist, i.e., if we can make arbitrarily long strings that satisfy the above condition, or if we cannot make any string that satisfies the above condition, “No” should be answered.

For example, suppose the given number n = 2 , i.e., the players can use the two characters A and B. Assume that the forbidden strings are {AAA, AB, BA, BB}. In this case, the longest string that does not include any of the four forbidden strings as substrings is AA. But if the given forbidden strings are {AAA, BBB, ABAB, BBAA}, we cannot make such a longest string since arbitrarily long concatenations of ABA, i.e., ABAABAABA ... do not include any forbidden string.

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing two integers n (1 ≤ n ≤ 26) and s (1 ≤ s ≤ 1, 000) which represent the number of characters and the number of forbidden strings, respectively. From the second line to (s + 1) -st line of the test case, the forbidden strings are given one by one. The length of a forbidden string does not exceed 50.

Output

Your program is to write to standard output. Print exactly one line for each test case. Print the longest string that does not include any forbidden string as a substring if it exists, otherwise, just print “No” as output. When there exists more than one such longest string with the same length, print the lexicographically largest string among them.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2153 - Turtle Graphics   

Description

You are going to draw a figure on a monitor using a keyboard of a computer. The figure which you want to draw is a polygonal chain which consists of horizontal or vertical line segments only. In order to draw the figure, you should press some keys successively. A sequence of keys consists of pairs of a direction key and a digit key. The direction keys consist of four keys which are labeled as `N', `S', `E', and `W'. The symbols `N', `S', `E', and `W' represent North, South, East, and West respectively. The digit keys consist of 10 keys which are labeled as `0', `1' , ... , `9'.

Initially, the cursor is located at the center of a monitor screen. If you will enter ``S4E3", i.e. you’ll press the keys `S', `4', `E', and `3' in order, an L-shaped chain will appear on the monitor. When you first press the two keys `S' and `4', a vertical line segment with length 4 from the current cursor position, i.e. the center of the screen, to the south is drawn and the cursor is located at the endpoint of that segment. When you press next the two keys `E' and `3', a horizontal line segment with length 3 from the current cursor position to the east is drawn.

Your computer program always keeps the polygonal chain simple. In other words, the polygonal chain on the monitor doesn’t have either a cycle or an overlapped segment. Whenever the program finds a cycle or an overlap in the drawing, it instantly gets rid of it. For example, if you enter ``E6S2W5S2E2N7", two intersection points p and q occur in order by the last segment (see Figure 1). The program first gets rid of the cycle (p, d, e, f ) containing the intersection p , then the cycle (q, b, c, p) containing q as shown in Figure 1. Hence, the resulting chain on the monitor is the same as the chain by ``E3N3". If you enter ``E4S2W3S2E6N6W4S7", the program gets rid of the cycle (p, b, c, d, e, f, g, h) created by the first intersection point p as shown in Figure 2 (a). After removing this cycle, the other intersections disappear. The resulting chain is the same as that by ``E3S5". If you enter ``N5S9"(resp. ``! N9S5"), the resulting chain is identical to that by ``S4"(resp. ``N4") as shown in Figure 2 (b).

Given a sequence of keys, write a program for computing the resulting chain. You can assume that the size of the monitor screen is sufficiently large.

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case is given in a single line, which contains a string d1f1d2f2...dnfn , where di ∈ {`N', `S', `E', `W'}, fi ∈ {`0', `1', ... , `9'}, and 1 ≤ n ≤ 5, 000 .

Output

Your program is to write to standard output. Print exactly one line for each test case. Print two integers m and L , where m is the number of line segments on the resulting chain and L is the length of that chain, i.e. the total sum of the lengths of all line segments on the chain.

Sample Input  Download

Sample Output  Download

Tags




Discuss




2154 - Number   

Description

For given two sets S and T of numbers, let a matching of S and T be a set of pairs (s, t) , sS , tT such that each number in S is paired with at least one number in T and each number in T is paired with at least one number in S . For example, the following is a matching of two sets S = {2, 8, 9, 10, 11} , T = {0, 3, 4, 6, 7, 11} :

M1 = {(2, 0),(2, 3),(2, 4),(8, 6),(9, 7),(10, 11),(11, 11)}

Whereas the following is not a matching of S and T ,

M2 = {(2, 0),(8, 3),(9, 4),(10, 6),(11, 7)}

since the number 11 in set T is not paired with any number in S .

For a pair (a, b) in a matching, the cost of the pair is defined to be the absolute value of the difference between a and b . The cost of a matching is the sum of the cost of all pairs in the matching. For example, the cost of the matching M1 is 10.

Given two sets of numbers, compute the minimum cost matching of the two sets. For example, the matching M1 is a minimum cost matching of the given two sets S and T .

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case consists of three lines. The first line of each test case contains two integers. The first integer, n1 , is the number of integers in the first set, and the second integer, n2 , is the number of integers in the second set, where 1 ≤ n1, n2 ≤ 50, 000 . The second line of each test case contains n1 integers for the first set and the third line contains n2 integers for the second set. The integers in each set are arranged in increasing order. All input integers are between 0 and 100,000.

Output

Your program is to write to standard output. Print exactly one line for each test case. The line should contain the cost of the minimum cost matching of the two sets of integers.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3001 - Fence Repair   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




3002 - The Blocks Problem   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




3003 - (*) Tic Tac Toe   

Description

The game of Tic Tac Toe is played on an n-by-n grid (where n is usually but not necessarily three). Two players alternate placing symbols on squares of the grid. One player places Xes and the other player places Os. The player placing Xes always goes first. When the grid contains a vertical, horizontal, or diagonal sequence of at least m consecutive squares all containing the same symbol, the game ends and the winner is the player who placed the last symbol. When all the squares of the grid are filled, if neither player has won, the game ends in a draw.

Your task is to analyze the state of a Tic Tac Toe board, and determine whether the game is still in progress, or if it has completed, who won, or if the game ended in a draw. You should also detect erroneous states of the Tic Tac Toe board that could never occur during an actual game.

Input

The first line of input contains a single integer, the number of test cases to follow. The first line of each test case contains the two integers n and m, separated by spaces, with 1 <= m <= n <= 1000. The following n lines of the test case each contain one row of the Tic Tac Toe board. Each of these lines contains exactly n characters, and each of these characters is either an X, an O, or a period (.), indicating an empty square.

Output

For each test case, output a single line containing the appropriate string X WINS, O WINS, or DRAW if the game is over, the string IN PROGRESS if the game has not yet finished, or ERROR if the state of the board could never occur during a game.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3004 - Fire!   

Description

Joe works in a maze. Unfortunately, portions of the maze have caught on fire, and the owner of the maze neglected to create a fire escape plan. Help Joe escape the maze.

Given Joe's location in the maze and which squares of the maze are on fire, you must determine whether Joe can exit the maze before the fire reaches him, and how fast he can do it.

Joe and the fire each move one square per minute, vertically or horizontally (not diagonally). The fire spreads all four directions from each square that is on fire. Joe may exit the maze from any square that borders the edge of the maze. Neither Joe nor the fire may enter a square that is occupied by a wall.

Input

The first line of input contains a single integer, the number of test cases to follow. The first line of each test case contains the two integers R and C, separated by spaces, with 1 <= R,C <= 1000. The following R lines of the test case each contain one row of the maze. Each of these lines contains exactly C characters, and each of these characters is one of:

  • #, a wall
  • ., a passable square
  • J, Joe's initial position in the maze, which is a passable square
  • F, a square that is on fire

There will be exactly one J in each test case.

Output

For each test case, output a single line containing IMPOSSIBLE if Joe cannot exit the maze before the fire reaches him, or an integer giving the earliest time Joe can safely exit the maze, in minutes.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3005 - Nice Prefixes   

Description

Consider strings formed from characters from an alphabet of size K. For example, if K = 4, our alphabet might be {a,b,c,d}, and an example string is bbcac.

 

For a string S, define count(S, k) to be the number of occurrences of the symbol k in S. For example, count(bbcac, b) = 2 and count(bbcac, a) = 1.

A prefix of a string S is any string obtained from S by deleting some (possibly none) of the trailing characters of S. For example, the prefixes of acb are the empty string, a, ac, and acb.

A string S has "nice prefixes" if for every prefix P of S and for every two characters k1 and k2 in the alphabet, |count(P, k1) - count(P, k2)| <= 2. For example, bbcac has nice prefixes, but abbbc does not because count(abbb, b) = 3 and count(abbb, c) = 0.

Count the number of strings of length L on an alphabet of size K that have nice prefixes. This number can be large, so print its remainder when divided by 1000000007.

Input

The first line of input contains a single integer, the number of test cases to follow. Each test case is a single line containing the two integers L and K, separated by spaces, with 1 <= L <= 1018 and 1 <= K <= 100.

Output

For each test case, output a single line containing the number of strings of length L on an alphabet of size K that have nice prefixes, modulo 1000000007.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3006 - Convex Hull   

Description

Finding the convex hull of a set of points is an important problem that is often part of a larger problem. There are many algorithms for finding the convex hull. Since problems involving the convex hull sometimes appear in the ACM World Finals, it is a good idea for contestants to know some of these algorithms.

 

Finding the convex hull of a set of points in the plane can be divided into two sub-tasks. First, given a set of points, find a subset of those points that, when joined with line segments, form a convex polygon that encloses all of the original points. Second, output the points of the convex hull in order, walking counter-clockwise around the polygon. In this problem, the first sub-task has already been done for you, and your program should complete the second sub-task. That is, given the points that are known to lie on the convex hull, output them in order walking counter-clockwise around the hull.

Input

The first line of input contains a single integer, the number of test cases to follow. The first line of each test case contains a single integer 3 <= n <= 100000, the number of points. The following n lines of the test case each describe a point. Each of these lines contains two integers and either a Y or an N, separated by spaces. The two integers specify the x- and y-coordinates of the point. A Y indicates that the point is on the convex hull of all the points, and a N indicates that it is not. The x- and y-coordinates of each point will be no less than -1000000000 and no greater than 1000000000. No point will appear more than once in the same test case. The points in a test case will never all lie on a line.

Output

For each test case, generate the following output. First, output a line containing a single integer m, the number of points on the convex hull. Next output m lines, each describing a point on the convex hull, in counter-clockwise order around the hull. Each of these lines should contain the x-coordinate of the point, followed by a space, followed by the y-coordinate of the point. Start with the point on the hull whose x-coordinate is minimal. If there are multiple such points, start with the one whose y-coordinate is minimal.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3007 - Slalom   

Description

You are competing in a ski slalom, and you need to select the best skis for the race. The format of the race is that there are N pairs of left and right gates, where each right gate is W metres to the right of its corresponding left gate, and you may neither pass to the left of the left gate nor to the right of the right gate. The ith pair of gates occurs at distance yi down the hill, with the horizontal position of the ith left gate given by xi. Each gate is further down the hill than the previous gate (i.e. yi < yi+1 for all i).

 

You may select from S pairs of skis, where the jth pair has speed sj. Your movement is governed by the following rule: if you select a pair of skis with speed sj, you move with a constant downward velocity of sj metres per second. Additionally, at any time you may move at a horizontal speed of at most vh metres per second.

You may start and finish at any two horizontal positions. Determine which pair of skis will allow you to get through the race course, passing through all the gates, in the shortest amount of time.

Input

The first line of input contains a single integer, the number of test cases to follow.

 

The first line of each test case contains the three integers W, vh, and N, separated by spaces, with 1 <= W <= 108, 1 <= vh <= 106, and 1 <= N <= 105.

The following N lines of the test case each contain two integers xi and yi, the horizontal and vertical positions respectively of the ith left gate, with 1 <= xi, yi <= 108.

The next line of the test case contains an integer S, the number of skis, with 1 <= S <= 106.

The following S lines of the test case each contain one integer sj, the speed of the jth pair of skis, with 1 <= sj <= 106.

Output

Output one line for each test case. If it is impossible to complete the race with any pair of skis, print the line IMPOSSIBLE. Otherwise, print the vertical speed sj of the pair of skis that allows you to get through the race course in the shortest time.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3008 - Another lottery   

Description

Even in times of an economic crisis, people in Byteland still like to participate in lotteries. With a bit of luck, they might get rid of all their sorrows and become rich.

The most popular lottery in Byteland consists of m rounds. In each round, everyone can purchase as many tickets as he wishes, and among all tickets sold in this round, one ticket is chosen randomly, each one with the same probability. The owner of that ticket wins the prize money of this round. Since people in Byteland like powers of 2, the prize money for the winner of round i amounts to 2i Bytelandian Dollars.

Can you determine for each participant in the lottery the probability that he will win more money than anybody else?

Input

The input consists of several test cases. Each test case starts with a line containing two integers n and m, the number of participants in the lottery and the number of rounds in the lottery. You may assume that 1 ≤ n ≤ 10000 and 1 ≤ m ≤ 30.

  The following n lines contain the description of the tickets bought by the participant. The ith such line contains m non-negative integers c1, ..., cm, where cj (1 ≤ jm) is the amount of tickets of round j bought by partipant i. The total number of tickets sold in each round is between 1 and 109.

The input ends with a line containing 2 zeros.

Output

For each test case, print n lines of output, where line i contains the probability as a reduced fraction that participant i wins the most money. See the sample output for details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3009 - Ballot evaluation   

Description

Before the 2009 elections at the European Parliament, Bill and Ted have asked their friends to make guesses about the outcome of the ballot. Now, the results have been published, so Bill and Ted want to check who was right. But checking the results of their many friends would take a very long time, and they need the evaluation to be done by a computer. Since they are not so good at programming, they ask you for help.

Input

The data provided by Bill and Ted has the following format:

The first line consists of the number p of parties followed by the number g of guesses (with 1 ≤ p ≤ 50 and 1 ≤ g ≤ 10000). Then follow p lines, each line consisting of a unique party name of length ≤ 20 (only containing letters a-z, A-Z and digits 0-9) and the achieved vote percentage of this party with one digit after the decimal point. After the parties follow g lines, each consisting of a guess. A guess has the form P1 + P2 + ... + Pk COMP n, where P1 to Pk are party names, COMP is one of the comparison operators <, >, <=, >= or = and n is an integer between 0 and 100, inclusively. Each party name occurs at most once in each guess.

Output

For each guess, sum up the vote percentages of the parties and compare them with the specified integer n. Then, print a line stating whether the guess was correct. See the sample output for details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3010 - Dark roads   

Description

Economic times these days are tough, even in Byteland. To reduce the operating costs, the government of Byteland has decided to optimize the road lighting. Till now every road was illuminated all night long, which costs 1 Bytelandian Dollar per meter and day. To save money, they decided to no longer illuminate every road, but to switch off the road lighting of some streets. To make sure that the inhabitants of Byteland still feel safe, they want to optimize the lighting in such a way, that after darkening some streets at night, there will still be at least one illuminated path from every junction in Byteland to every other junction.

What is the maximum daily amount of money the government of Byteland can save, without making their inhabitants feel unsafe?

Input

The input file contains several test cases. Each test case starts with two numbers m and n, the number of junctions in Byteland and the number of roads in Byteland, respectively. Input is terminated by m=n=0. Otherwise, 1 ≤ m ≤ 200000 and m-1 ≤ n ≤ 200000. Then follow n integer triples x, y, z specifying that there will be a bidirectional road between x and y with length z meters (0 ≤ x, y < m and xy). The graph specified by each test case is connected. The total length of all roads in each test case is less than 231.

Output

For each test case print one line containing the maximum daily amount the government can save.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3011 - Elias gamma coding   

Description

The Elias gamma code is a simple code which can be used to encode a sequence of positive integers. We will use a modified code which is also able to encode zeros. To encode an integer n, do the following:

  1. Let k be the number of bits of n
  2. Write k-1 zeros followed by a 1
  3. Write n in binary
Examples
Number Binary Number of bits Prefix Code
0  0 10 
1  1 11 
2  10 01  0110 
3  11 01  0111 
4  100 001  001100 
5  101 001  001101 
6  110 001  001110 
7  111 001  001111 
8  1000 0001  00011000 

A sequence of integers is encoded by writing the codes of the individual integers of the sequence in the same order as the integers appear in the sequence. The prefix of k additional bits before the binary representation of each integer is needed to be able to decode the encoded integers. So when reading the encoding of a sequence of integers, if we read k-1 zeros followed by a one, it means that there are k bits following which are the binary representation of the next encoded integer.

If we want to shorten the length of the encoding of a sequence of integers, there may be still some room for improvement; we will consider the following two optimizations:

  1. If there is a prefix which indicates that k bits are following, but there is no integer in the sequence with k bits, we can use this prefix to indicate that k+1 bits are following. If there already was a prefix which indicates that k+1 bits are following, this prefix is not needed anymore, and it can be used to indicate that k+2 bits are following, and so on.
  2. We can add a leading zero to the binary representation of all integers in the sequence with k bits, which then become integers with k+1 bits, and then the first optimization can be used. This optimization seems especially useful if there are few integers with k bits, but many integers with more than k bits.

When we are minimizing the length of the encoding of a sequence of integers, we only care about how many integers in the sequence have a certain number of bits. Let ci denote the number of integers in a sequence with i bits.

Let us look at the following example: c1 = 2, c2 = 4, c3 = 0, c4 = 1 (which, for example, could correspond to a sequence 2, 1, 3, 8, 0, 2, 3). With the original elias gamma coding, the encoding of the sequence would have length 2 × (1 + 1) + 4 × (2 + 2) + 0 × (3 + 3) + 1 × (4 + 4) = 28. By using optimization 1 we can save 1 bit by using prefix 001 for the integer with 4 bits. Then, we could use optimization 2 and add leading zeros to the integers with 1 bit, making them use 2 bits. Then, we use optimization 1 and use prefix 1 for the integers with 2 bits, prefix 01 for the integer with 4 bits, and we get the new length of 6 × (1 + 2) + 1 × (2 + 4) = 24.

Both optimizations can possibly be used several times. Note that for the second optimization, it is not easy to decide when and how to use it. The goal is to combine these two optimizations in the best possible way, that means we want to find an encoding of a given sequence of integers that has minimum length among all encodings using elias gamma coding with any combination of these two optimizations.

Input

The input file contains several test cases. Each test case starts with a line containing an integer n, (1 ≤ n ≤ 128). The next line contains the values c1, ..., cn (0 ≤ ci ≤ 10000). Input is terminated by n=0.

Output

For each test case print one line with the minimum length of an encoding of the given input sequence.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3012 - Food portion sizes   

Description

The university canteen does not want any student to leave the canteen hungry. Therefore, as long as a student is hungry, he can get another portion of food for free. The canteen uses a fixed food portion size, because it would take too much time to first ask a student how much food he wanted. It can happen that a student doesn't finish his last portion of food and the remainder has to be thrown away.

To minimize costs, the manager of the canteen wants to determine a food portion size S such that the amount of food that is wasted is small, but also the number of times the students have to fetch another portion of food is not too big. Note that these two goals can be conflicting:

  • By choosing a very small food portion size, one does not waste food, but simultaneously the number of times the students have to fetch food is big.
  • By choosing a large food portion size, one can make sure each student has to fetch only one portion, but at the same time it may happen that a large quantity of food is wasted.

The manager of the canteen has collected data about how many units of food each student eats. The problem to be solved can now be formulated mathematically as follows: Let x be the amount of food that is wasted, and y the number of times the students go to fetch food. Then, the goal is to minimize a × x + b × y, where a, b are weights that represent the relative importance of the two opposing goals. Note that x and y depend on the food portion size S and the quantities of food each student eats. We impose the additional constraint that no student should have to go more than 3 times to fetch food.

Input

The input file contains several test cases. Each test case starts with a line containing an integer n, (1 ≤ n ≤ 1000), the number of students eating in the canteen. The next line contains the values a and b (1 ≤ a, b ≤ 10). The third line of each test case consists of n integers y1, ..., yn (1 ≤ yi ≤ 100), where yi is the amount of food student i eats. Input is terminated by n=0.

Output

For each test case print one line containing the costs resulting from an optimal choice of the food portion size. Print each value as a reduced fraction. If the result is an integer, do not print the denominator 1. See the sample output for details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3013 - Generate random numbers   

Description

John von Neumann suggested in 1946 a method to create a sequence of pseudo-random numbers. His idea is known as the "middle-square"-method and works as follows: We choose an initial value a0, which has a decimal representation of length at most n. We then multiply the value a0 by itself, add leading zeros until we get a decimal representation of length 2 × n and take the middle n digits to form ai. This process is repeated for each ai with i>0. In this problem we use n = 4.

 

Example 1: a0=5555, a02=30858025, a1=8580,...

Example 2: a0=1111, a02=01234321, a1=2343,...

Unfortunately, this random number generator is not very good. When started with an initial value it does not produce all other numbers with the same number of digits.

Your task is to check for a given initial value a0 how many different numbers are produced.

Input

The input contains several test cases. Each test case consists of one line containing a0 (0 < a0 < 10000). Numbers are possibly padded with leading zeros such that each number consists of exactly 4 digits. The input is terminated with a line containing the value 0.

Output

For each test case, print a line containing the number of different values ai produced by this random number generator when started with the given value a0. Note that a0 should also be counted.

Sample Input  Download

Sample Output  Download

Tags




Discuss




3014 - Hotel booking   

Description

A transport company often needs to deliver goods from one city to another city. The transport company has made a special deal with a hotel chain which allows its drivers to stay in the hotels of this chain for free. Drivers are only allowed to drive up to 10 hours a day. The transport company wants to find a route from the starting city to the destination city such that a driver can always spend the night in one of the hotels of the hotel chain, and that he needs to drive at most 10 hours from one hotel to the next hotel (or the destination). Of course, the number of days needed to deliver the goods should also be minimized.

Input

The input file contains several test cases. Each test case starts with a line containing an integer n, (2 ≤ n ≤ 10000), the number of cities to be considered when planning the route. For simplicity, cities are numbered from 1 to n, where 1 is the starting city, and n is the destination city. The next line contains an integer h followed by the numbers c1, c2, ..., ch indicating the numbers of the cities where hotels of the hotel chain are located. You may assume that 0 ≤ hmin(n, 100). The third line of each test case contains an integer m (1 ≤ m ≤ 105), the number of roads to be considered for planning the route. The following m lines describe the roads. Each road is described by a line containing 3 integers a, b, t (1 ≤ a, bn and 1 ≤ t ≤ 600), where a, b are the two cities connected by the road, and t is the time in minutes needed by the driver to drive from one end of the road to the other. Input is terminated by n = 0.

Output

For each test case, print one line containing the minimum number of hotels the transport company has to book for a delivery from city 1 to city n. If it is impossible to find a route such that the driver has to drive at most 10 hours per day, print -1 instead.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4000 - Airplane Parking   

Description

During this economic crisis time, Jack has started an incredible new business related to air travel, a parking-lot for airplane. He bought a very large land to park airplanes. However the land is very narrow, so that the only way airplanes can go in or go out of the parking lot must be in the Last-In First-Out fashion (see picture below). He only has spaces in the parking lot so he cannot take some airplane at the end out so that other airplanes can move.

 

 

Because of the limitation of the parking lot, it is not possible to accommodate all requests for parking. Each request consists of the planned arrival time and planned departure time, which are the times the airplane arrives at the parking lot. An example below shows a request table for 4 planes.
 

 

In this case, it is possible to accommodate airplane 1, 2, and 4. But it is not possible to accommodate both airplanes 2 and 3.

It is possible that different planes plan to arrive or depart the parking lot at the same time. Jack has the best crews working with him, so that they will manage to arrange the plane to the parking lot in the best way that if it is possible to park and take out the planes they will be able to do it. Consider another example.

Although airplane 5 and 6 arrive at the same time, Jack's crews know that airplane 5 will have to be out before airplane 6, so when both airplanes arrive they put airplane 6 in first, following by airplane 5.

Given a list of parking requests, you want to find the maximum number of airplanes that can be parked in this parking lot, provided that they can only depart in the Last-In First-Out fashion.

 

Input

The first line contains an integer T, the number of test cases (1 < T < 5). Each test case is in the following format.

The first line starts with an integer N (1 < N < 300) denoting the number of airplanes. The next N lines describe the request table. Each line 1 + i, for 1 < i < N, contains two integer Si and Ti , (0 < Si < Ti < 1,000,000,000) which are the planned arrival time and planned departing time for airplane i. 

Output

For each test case, you program must output a single line consisting of one integer, the maximum number of airplanes that can be parked in Jack's parking lot.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4001 - In­circles Again   

Description

In the figure below you can see triangle ABC and its in­circle (Circle that touches all the sides of a triangle internally). The radius of this in circle is r. Three other circles are drawn. Each of them touches two sides of this triangle and the in circle of ABC. The radiuses of these circles are r1, r2 and r3.

 Given the values of r, r1, r2 and r3 you will have to find the area of triangle ABC.

Input

The input file can contain up to 1000 lines of inputs. Each line contains four positive floating point numbers which denotes the values of r, r1, r2 and r3 respectively.

Input is terminated by a line containing four negative integers.

Output

For each line of input produce one line of output. This line contains serial of output followed by a floating­point number which denotes the area of triangle ABC. This floating­point number may have two digits after the decimal point. You can assume that for the given values of r, r1, r2 and r3 it will always be possible to construct a triangle ABC. If required you can assume that pi = 3.141592653589793 and also use double precision floating­point numbers for floating­point calculations. You can assume that there will be no such input for which small precision errors will cause difference in printed output. Look at the output for sample input for details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4002 - Rating Hazard   

Description

 

A very important aspect of web portals is customer reviews. The customers can rate any product in the web portal. Generally, a customer can rate a product from one star to five star. Based on  the rating of all the customers the average customer rating for a product is shown. Look at the figure on the left to get a clear idea. For example if three customers rate a product as 3 star, 4 star and 4 star respectively then the average rating will be (3+4+4)/3 = 3.67 (Rounded to two digits after the decimal point). In the figure on the left 847 customers have rated a product and 597, 189, 26, 11 and 24 customers have rated the product as 5 star, 4 star, 3 star, 2 star and 1 star respectively. So the average rating is: (597x5+189x4+11x2+24)/847=456316411(Rounded to eight digits after the decimal point).

Most web portals display the total number of people who have rated the product (As more people rates the product the more reliable the rating is) but do not display the numeric value of the average rating. In the web portal of warzone (A renowned web portal) the total number of customers that have rated a product (In the figure above the total 847 customers have rated the product) and the average rating is stored in two different tables. The average rating is stored, rounded to n (0

 

Input

The input file can contain up to 2000 lines of inputs. Each line contains a non­negative floating point number v (1 ≤ v ≤ 5). This number will have minimum one digit and maximum eight digits after the decimal point. If this number has n digits after the decimal point then you have to assume that the value of the average is given rounded to n digits after the decimal point.

Input is terminated by a line containing a negative number.

 

Output

For each line of input produce one line of output. This line contains the serial of output followed by an integer T which denotes the minimum number of voter that is required for this average rating. 

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




4003 - Your Ways   

Description

 You live in a small well-planned rectangular town in Phuket. The size of the central area of the town is H  kilometers x W kilometers. The central area is divided into HW unit blocks, each of size 1 x 1 km2. There are H + 1 streets going in the West to East direction, and there are W + 1 avenue going in the North-South direction. The central area can be seen as a rectangle on the plane, as shown below. 


 

We can identify each intersection by its co-ordinate on the plane.  For example, on the Figure above the bottom-left corner is intersection (0,0), and the top-right corner is intersection (6,3).

Your house is at the bottom-left corner (i.e., intersection (0,0)) and you want to go to the university at the top-right corner (i.e., intersection (W,H)). More over, you only want to go to the university with wasting any efforts; therefore, you only want to walk from West-to-East and South-to-North directions. Walking this way, in the example above there are 84 ways to reach the university.

You want to go to the university for K days. Things get more complicated when each morning, the city blocks parts of streets and avenues to do some cleaning. The blocking is done in such a way that it is not possible to reach parts of the streets or avenues which is blocked from some other part which is blocked as well through any paths containing only West-to-East and South-to-North walks.

You still want to go to the university using the same West-to-East and South-to-North strategy. You want to find out for each day, how many ways you can reach the university by only walking West-to-East and South-to-North. Since the number can be very big, we only want the result modulo 2552.

Input

The first line contains an integer T, the number of test cases (1 < T < 5). Each test case is in the following format.

The first line of each test case contains 3 integers: W, H, and K (1 < W < 1,000; 1 < H < 1,000; 1 < K < 10,000). W and H specify the size of the central area. K denotes the number of days you want to go to the university.

The next K lines describe the information on broken parts of streets and avenues. More specifically, line 1 + i, for 1 < i < K, starts with an integer Qi (1 < Qi < 100) denoting the number of parts which are blocked. Then Qi sets of 4 integers describing the blocked parts follow. Each part is described with 4 integers, A, B, Cand D (0 <  A  <  C  <  W; 0 <  B  <  D  <  H) meaning that the parts connecting intersection (A,B) and (C,D) is blocked. It is guaranteed that that part is a valid part of the streets or avenues, also C - A < 1, and D - B < 1, i.e., the part is 1 km long.

Output

 For each test case, for each day, your program must output the number of ways to go to the university modulo 2552 on a separate line. i.e., the output for each test case must contains K lines.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4004 - Hexagonal Sticks   

Description

In this problem, we will consider an infinite hexagonal grid. The grid consists of equal regular hexagonal cells arranged in the fashion shown below. The figure also elucidates the coordinate  system used to identify each cell. Each cell of the grid can be empty or blocked.

Figure A

There are few sticks placed randomly on this grid. The length of each stick is one ‘hexagonal  unit’. This means, the end points of a stick lies on the centers of neighboring cells. Your job is to  move the sticks so that a closed regular hexagonal figure is formed.

The diagrams below show some closed hexagonal figures made of sticks.

Figure B

You will be given the initial coordinates of the sticks that are placed on the grid. You will also be  given the coordinates of the cells that are blocked. In each move you can do one of the  followings:

- Select one stick and throw it out
- Select one stick and rotate it 60 degrees clockwise/anti-clockwise about one of the end points
- Select one stick and push it along the length of the stick

The sticks can never occupy a cell that is blocked. However, two sticks can occupy the same  cells at the same time.

Figure C

Consider the scenario shown above. We have an obstacle situated at coordinate (1, 1) and a stick  at coordinate (0, 0) ­> (1, 0). The four possible moves that can be made are depicted below

Figure D

After all the moves are made, you have to ensure a closed regular hexagonal shape is formed  with no other sticks lying around. This means the grid should contain exactly 6*x sticks where x  is positive integer. Can you do this in minimum number of moves?

Input

The first line of input is an integer T(T<50) that indicates the number of test cases. Each case starts with a non­negative integer S(S<9) that gives you the number of sticks available.
The next S lines give you the coordinates of the sticks. The coordinates of the sticks will be of the format x1 y1 x2 y2, which means there is a stick from (x1, y1) to (x2, y2). The coordinates will be valid and the length of each stick will be one hexagonal unit as mentioned above.
The next line will give you a non­negative integer B(B<20) that indicates the number of obstacles.
Each of the next B lines will give you the coordinates of the obstacles. The coordinate will be of the format x1 y1. It is guaranteed that the given blocks will not overlap with any given sticks.
All the coordinates (sticks and blocks) will have values in the range [­4, 4].
Note: Remember that we are dealing with infinite grids. So in the optimal result, it could be possible that the hexagonal sticks lie outside [­4, 4].

Output

For each case, output the case number first followed by the minimum number of moves required. If it is impossible to form a hexagonal grid, output “impossible” instead. Adhere to the sample input/output for exact format.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4005 - Buy Your House   

Description

You are going to buy a house and hence communicated with a real estate development company, which has just started their business and you are going to be the first buyer. So they are offering you something special.

The real estate company has a rectangular shaped land of width W and height H. They are using co­ordinate system for measuring lands. (0, 0) is the lower left corner of their land and any point which has distance x from lower edge of the land and distance y from left edge of the land is known as (x, y) in the co­ordinate system.

The real estate company has already built some houses in that piece of land. All of them are rectangular shaped and their edges are parallel to edges of the main land. The location of a house can be addressed by four integers x1, y1, x2, y2. Where (x1, y1) is the lower left corner and (x2, y2) upper right corner of the house.

The special offer is that you can choose any rectangular shaped region that contains exactly one house with any amount of adjacent open space. You may not have enough money to afford open space and choose to buy only the region that a house occupies. If you have enough money, you can keep open space in front of your house for gardening! 

But still there are some restrictions. For the ease of their future use of rest of their land you can only choose a rectangular shaped region and the edges of which are parallel to the edges of the main land. The corners of your selected region should be integer coordinates. It can be (3, 2) but cannot be (3.5, 2). You cannot chose a region for which part of a house is inside the region and another part of that house is outside the region. You cannot choose a region having more than one house and a region having no house. How many ways you can choose your land following the above rules?

 

Input

Input will start with an integer T (T is around 500), the number of test cases. Each of the test cases starts with two integers W and H (1 <= W, H <= 1000000000), width and height of the land and the next line contains an integer N (1 <= N <= 50), the number of houses in the land.  Each of the next N lines will contain four integer x1, y1, x2, y2 ( 0 <= x1 < x2 <= W and  0 <= y1 < y2 <= H ), which describes the location of the house. Note that no house can overlap with another house and all the given coordinates will be non negative integers.

Output

For each input, print a single line of the form “Case #: W”, where ‘#’ will be replaced by the case number and W will be replaced by the number of ways you can choose your land. Here W can be very large, so you should print the number of ways modulo 1000000007 as W.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4006 - Synnerg Lifeform   

Description

In a science laboratory, scientists found a new kind of tiny lifeforms and named them “synnergs”. Until now, few knowledge about synnergs are known. Some of these knowledge are as follow.

  • There are more than one types of synnerg. 
  • Any new born synnerg have the same lifetime. 
  • Two synnergs (of certain types) can extend their lifetimes by unifying themselves together which will also transform them into a new target synnerg. The lifetime of this new target is the summation of both sources' lifetimes multiplied with an amplification factor. The type of this new target may vary from its sources.  From many experiments, scientists found a set of rules to describe the unification of each synnerg pair . Some of these rules can be shown as the following table.
  • When scientists arrange two or more of new born synnergs into a sequence, each synnerg in this sequence will try to unify itself with the one on its left or its right (and make the sequence shorter).   This unification process will continue again and again (recursively).  There might be lots of possible ways to unify an input sequence which also affect  the lifetime of each unified synnerg.

For example of unification steps, please see the following table.

In the first example, at the first step there is a sequence of 4 new born synnergs “a a b b” where their lifetimes are “1 1 1 1” respectively. In the second step, these synnergs unify themselves into a sequence of two synnergs “aa[a a] bb[b b]” (using rule no.1 and 3) where aa's lifetime is 2=(1+1)*1 and bb's lifetime is 6=(1+1)*3. In the third step, “aa bb” unify themselves into “x[aa bb] (using rule no. 4) where its lifetime is 16=(6+2)*2.

In the second example, at the first step, the beginning sequence is the same sequence in the first example. But they alternatively unify themselves into “AA[a a] bb[b b]” (using rule no.2 and 3 instead) where their lifetimes are 34=(1+1)*17 and 6(1+1)*3 respectively. This sequence is also the final sequence which means that it is unable to unify furthermore but it is not a completely unified sequence. However, this alternative final sequence has longer life time comparing to the final sequence in the first example.

The third and fourth example also show the alternative ways of unifying the sequence “a c a c”. Please be notify that each rule is not sensitive to the order of its sources.

Goal 

The scientists would like you to create a program that can find all highest lifetime synnergs that can be created by unifying a given sequence of newborn synnergs. The solution may not always be the one that is completely unified. Only part or sub sequence unification is also acceptable.

Input

Input is a standard input which contains 2 parts of data which are separated by a blank line.

The first part is a set of unification rules. 

  • Each line in this first part contains one of unification rule.
  • Each rule consists of 4 fields separated by spaces. 
  • The first 3 fields are target, source #1 and source #2 respectively. Each fields is a synnerg name which is represented by a string of at most 20 alpha­numeric characters. 
  • The last field is the amplification factor which is a positive integer less than or equal to 100.

The second part is a set of input sequences of synnergs.

  • Each line in this second part contains one input sequence of synnergs
  • Each input sequence is a sequence of synnergs separated by spaces.The blank line after the second part is the termination of the input.

The blank line after the second part is the termination of the input.

Output

 For each sequence of input, write 2 parts of output as follows

  • In the first line, write the total of number of highest synnergs followed by a space and then the maximum lifetime of these synnergs.
  • In the following lines, write each of the solutions in each line. Each solution contains 3 fields separated by spaces. These fields are a synnerg, its starting and finishing offset. If there are two or more solutions, they must be sorted by ascending order. The priority of comparison in sorting is the 2nd field, the 3rd field and the 1st field (or the starting offset, the finishing offset and the synnerg). For comparisons in sorting, the 2nd and 3rd field comparison is based on numerical values, and the 1st field is based on alphabetical/lexicographical (ASCII) order.

 

More Explanations

There are 6 rules and 5 input sequences in this sample input.

For the first case, even though there is a completed unification “x[aa[a a] bb[b b]]” (starting from 1 to 4),  its lifetime is only 16 (= {(1+1)*1 + (1+1)*3}*2) times of a newborn, which is less than 34 of “AA[a a]” starting from 1 to 2.

For the second case, there are 2 solutions. The first is “AA” starting from 1 to 2. The second is “x” starting from 1 to 5.For the third case, there is only one solution. “x” now is the only winner (with 70 points).

For the fourth and the fifth cases, (parts of) the results has been unified according to the last rule. Since each rule is not sensitive to the order of its sources, any rule is applicable if both of its source are found. (“c c a 3” equals “c a c 3”.)

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




4007 - Nowhere Money   

Description

 

In Nowhere town, people use “coin and slot” as their money. There are 2 types of coins called size1 and size2. Size2 coin is twice the thickness of size1. People stack their coins in slots and use them as money. There are many size of slots. The slot of size n is able to stack up n size1 coins. Only filled­up slot is considered as legal money. The value of each filled­up slot is the distinct ways its can stack coins inside. For example, for size­1 slot, there is only one way to stack a single size1 coin inside. For size­2 slot, there are 2 ways to stack two size1 coins or one size2 coin inside. And for size­5 slot, there are 8 ways to stack coins inside, which can be illustrated as follow: 1 1 1 1 1, 1 1 1 2, 1 1 2 1, 1 2 1 1, 2 1 1 1, 1 2 2, 2 1 2, 2 2 1. So the value of filled up slot with size­1, size­2 and size­5 are 1, 2 and 8 (monetary) units respectively (regardless of the type of coins or the ways they are stacked). 

Mr.Thinktwice is an owner of a grocery store in this town. He noticed that customers are likely to go to the shop that can return the (money) change in the form that suits their customer. And from his little survey, he found that most customers would like to get their amount of change in the form according to these 2 simple constraints.

  1. The number of slots is minimum.
  2. The size of each slot must be different from each other by at least 2. 
    -This means that customers does not want any slots with the same size and it will be easier for them to distinguish these differences if the sizes are not too close.

So Mr.Thinktwice ask you to write a program that can give him a series of slot sizes for a given amount of change according to the previous constraints. Moreover, the series must be sorted in descending order. For more specific, any amount of change can be written in this formula.

For example:

Input

Input is a standard input which contains a set of integer. Each line of the input is an amount of change which represents by a positive integer less than or equal to 5,000,000,000,000,000,000 or  5 x 1018.  The input is terminated when the EOF (End­Of­File) is reached.

Output

For each amount of change, generate 4 lines of output data. The first line is the amount of change itself. The second line is a series of slot sizes (in descending order) separated by spaces. (The maximum slot size is less than or equal to 90.) The third line is a series of corresponding slot values. The fourth line is a blank line.

Note: The output about end of second and third line need contain one space. The standard of outputs will let the judge system show “Presentation Error".

Sample Input  Download

Sample Output  Download

Tags




Discuss




4008 - Highway Patrol   

Description

 

Crimes in city of Megacity are going high. To fight the crimes, the authorities have created a highway patrol. The city consists of a number of one­way roads. At the ends of each road, there is a base station for the patrol troops. Each base station has a number of troops. At the beginning,  each station sends a troop along all the outgoing highways from that station. The troop patrols the highway and whenever it reaches the station on the other side of the highway, it waits there, and the troop that has been waiting there the most, is sent along the highway that has not been patrolled the longest time. 

Soon, they faced some difficulties, cause, the frequency of patrolling a highway is more and more dependent on the number of highways that started and ended at the base station. If the number of highways started at a base station is more than the number of highways ended there, the roads are patrolled less frequently. And if, no highways end at some base station, then, the highways started from there, will not be patrolled more than once.

In this situation, the highway patrol decided to remove some highways from the patrolling schedule, so that, at each base station, the number of highways started and ended at any base station will be equal. The rest of the highways will be monitored using video surveillance. But, due to some security issues, there are some highways that have to be patrolled. 

Now, given the cost of patrolling highways, and that of installing video surveillance, find the minimum cost of monitoring the whole city. Please keep in mind that, video surveillance can not substitute the highway patrol completely. So, there has to be at least one highway that will be patrolled. 

 

Input

 First line of the input contains an integer T(T≤ 70), the number of test cases. This is followed by T test cases. Each test case starts with two integers N(1 ≤ N ≤ 100) and M(1 ≤ M ≤ 1000), the number of base stations and highways. This is followed by M lines, each containing 5 integers, u,v,p,s,x(1 ≤ u,v ≤ N,0 ≤ p,s ≤ 1000000) where u and v means, the highway starts from base station u, and ends at v, p is the cost of patrolling and s is the cost of installing video surveillance. If the highway must be patrolled, then x will be one. Otherwise it will be zero.

Output

For each test case, output the case number, followed by the minimum cost to monitor the highways. If it is not possible to patrol satisfying the given constraints, output “impossible” (without quotes). 

Sample Input  Download

Sample Output  Download

Tags




Discuss




4009 - A Spy in the Metro   

Description

 

Secret agent Maria was sent to Algorithms City to carry out an especially dangerous mission. After several thrilling events we find her in the first station of Algorithms City Metro, examining the time table. The Algorithms City Metro consists of a single line with trains running both ways, so its time table is not complicated.Maria has an appointment with a local spy at the last station of Algorithms City Metro.

Maria knows that a powerful organization is after her. She also knows that while waiting at a station, she is at great risk of being caught. To hide in a running train is much safer, so she decides to stay in running trains as much as possible, even if this means traveling backward and forward. Maria needs to know a schedule with minimal waiting time at the stations that gets her to the last station in time for her appointment. You must write a program that finds the total waiting time in a best schedule for Maria. 

The Algorithms City Metro system has N stations, consecutively numbered from 1 to N. Trains move in both directions: from the first station to the last station and from the last station back to the first station. The time required for a train to travel between two consecutive stations is fixed since all trains move at the same speed.Trains make a very short stop at each station, which you can ignore for simplicity. Since she is a very fast agent, Maria can always change trains at a station even if the trains involved stop in that station at the same time.

 

Input

The input file contains several test cases. Each test case consists of seven lines with information as follows.

Line 1.

The integer N ( 2 ≤ N ≤ 50), which is the number of stations.

Line 2.

The integer T ( 0 ≤ T ≤ 200), which is the time of the appointment.

Line 3.

N - 1 integers: t1, t2,..., tN - 1 ( 1 ≤ ti ≤ 70), representing the travel times for the trains between two consecutive stations: t1 represents the travel time between the first two stations, t2 the time between the second and the third station, and so on.

Line 4.

The integer M1 ( 1 ≤ M1 ≤ 50), representing the number of trains departing from the first station.

Line 5.

 

M1 integers: d1, d2,..., dM1 ( 0 ≤ di ≤ 250 and di < di + 1), representing the times at which trains depart from the first station.

Line 6.

The integer M2 ( 1≤M2≤50), representing the number of trains departing from the N-th station.

Line 7.

M2 integers: e1, e2,..., eM2 ( 0 ≤ ei ≤ 250 and ei < ei + 1) representing the times at which trains depart from the N-th station.

The last case is followed by a line containing a single zero.

 

 

Output

For each test case, print a line containing the case number (starting with 1) and an integer representing the total waiting time in the stations for a best schedule, or the word `impossible' in case Maria is unable to make the appointment. Use the format of the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4010 - Low Cost Air Travel   

Description

Air fares are crazy! The cost of a ticket is determined by numerous factors, and is usually not directly related to the distance traveled. Many travelers try to be creative, sometimes using only parts of tickets with stops in various cities to achieve lower-cost travel. However, the airlines are aware of this behavior, and usually require that the travel covered by a ticket be completed in order and without intervening travel. For example, if you have a ticket for travel from City-1 to City-2 then to City-3, you are not allowed to use only the portion of the ticket for travel from City-2 to City-3. You must always start at the first city on the ticket. In addition, you are not allowed to travel from City-1 to City-2, fly elsewhere and return, and then continue your journey from City-2 to City-3.

Let's consider an example. Suppose you are allowed to purchase three types of tickets:

Ticket #1:

City-1 to City-3 to City-4

$225.00

Ticket #2:

City-1 to City-2

$200.00

Ticket #3:

City-2 to City-3

$50.00

Suppose you wanted to travel from City-1 to City-3. There are two ways to get there using only the available ticket choices:

Purchase Ticket #1 for $225.00 and use only the first leg of the ticket.

Purchase Ticket #2 for $200.00 and Ticket #3 for $50.

The first choice is the cheapest.

Given a set of airline ticket offers, and one or more trip itineraries, you must determine how to purchase tickets in order to minimize the cost of travel. Each trip will be possible.

 

 

Input

Input consists of multiple test cases, each describing a set of ticket offers and a set of trip itineraries.

Each case begins with a line containing NT, the number of ticket offers, followed by NT offer descriptions, one to a line. Each description consists of a positive integer specifying the price of the ticket, the number of cities in the ticket's route, and then that many cities. Each city in a case has an arbitrary, but unique, integer identification number. Note that several tickets may be purchased from the same offer.

The next line contains NI, the number of trips that are to have their cost minimized. NI lines follow, giving the itineraries for each trip. Each line consists of the number of cities in the itinerary (including the starting city), followed by that many city identification numbers, given in the order they are to be visited.

There will be no more than 20 ticket offers or 20 itineraries in a test case. Each offer and itinerary lists from 2 to 10 cities. No ticket price exceeds $10,000. Adjacent cities in a route or itinerary will be distinct. Tickets and trips are numbered sequentially in each set, starting with 1.

The last case is followed by a line containing a zero.

Output

For each trip, output two lines containing the case number, the trip number, the minimum cost of the trip, and the numbers of the tickets used for the trip, in the order they will be used. Follow the output format shown below. The output will always be unique.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4011 - Covering Whole Holes   

Description

Can you cover a round hole with a square cover? You can, as long as the square cover is big enough. It obviously will not be an exact fit, but it is still possible to cover the hole completely.

The Association of Cover Manufacturers (ACM) is a group of companies that produce covers for all kinds of holes - manholes, holes on streets, wells, ditches, cave entrances, holes in backyards dug by dogs to bury bones, to name only a few. ACM wants a program that determines whether a given cover can be used to completely cover a specified hole. At this time, they are interested only in covers and holes that are rectangular polygons (that is, polygons with interior angles of only 90 or 270 degrees). Moreover, both cover and hole are aligned along the same coordinate axes, and are not supposed to be rotated against each other - just translated relative to each other.

Input

The input consists of several descriptions of covers and holes. The first line of each description contains two integers h and c ( 4$ le$h$ le$50 and 4$ le$c$ le$50), the number of points of the polygon describing the hole and the cover respectively. Each of the following h lines contains two integers x and y, which are the vertices of the hole's polygon in the order they would be visited in a trip around the polygon. The next c lines give a corresponding description of the cover. Both polygons are rectangular, and the sides of the polygons are aligned with the coordinate axes. The polygons have positive area and do not intersect themselves.

The last description is followed by a line containing two zeros.

Output

For each problem description, print its number in the sequence of descriptions. If the hole can be completely covered by moving the cover (without rotating it), print `Yes' otherwise print `No'. Recall that the cover may extend beyond the boundaries of the hole as long as no part of the hole is uncovered. Follow the output format in the example given below.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4012 - Remember the A La Mode!   

Description

Hugh Samston owns the ``You Want It, Hugh Got It" catering service, which has been asked to supply desserts for the participants in this year's ICPC World Finals. Hugh will provide pie slices topped with ice cream at the various social functions scheduled throughout the week. As with any other dedicated entrepreneur, Hugh would like to offer the best service possible, so he has ordered a wide variety of pies and ice creams to satisfy even the most eclectic tastes.

Hugh plans to serve each pie slice with a single scoop of ice cream, leaving the exact combination up to the whim of the customer. But of course, as with any other dedicated entrepreneur, Hugh would also like to make as much profit as possible from this enterprise. He knows ahead of time how much profit he can make on each combination of pie slice and ice cream scoop, as well as which combinations of pie and ice cream should never be put together (example: Peppermint Banana Chunk ice cream on Key Lime pie).

Given this information, along with the number of slices and scoops he has of each variety of pie and ice cream, Hugh figures he can determine both the minimum and maximum profits he can expect. Since he hopes to be the caterer at subsequent World Finals, he would like a general program to solve this and future problems.

Input

Input will consist of multiple problem instances. Each problem instance will start with a line containing two integers P (P$ le$50) and I (I$ le$50), indicating the number of types of pie and ice cream, respectively. The next line will contain P integers indicating the number of slices available for each of the pie types. The line after that will contain I integers indicating the number of scoops available for each of the ice cream types. The total number of pie slices will always equal the total number of ice cream scoops available, and it is assumed that all pie slices and ice cream scoops will be used.

Each problem instance will end with P lines each containing I floating point numbers indicating the profit for each pie/ice cream combination: the first value indicates the profit if a slice of pie type 0 is topped with a scoop of ice cream type 0; the next value indicates the profit if a slice of pie type 0 is topped with a scoop of ice cream type 1, and so on. A profit value of `-1' indicates that no combinations of that pie type and ice cream type should ever be sold. All other integers (number of slices for each type of pie and number of scoops for each type of ice cream) will be less than or equal to 100 and the profit on each one of the pie/ice cream combinations (other than `-1') will be larger than 0 and less than or equal to 10, with at most two digits after the decimal point.

The last problem instance is followed by a line containing two zeroes.

Output

For each problem instance, output the problem number (starting at 1) followed by the minimum and maximum profits, using the format shown in the sample output. Display all numbers with two fractional digits. All problem instances are guaranteed to have at least one solution using all of the pie slices and ice cream scoops.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4013 - Lattice Squares   

Description

Count the number of distinct squares you can draw using only integer co-ordinates for its 4 corners with the following restrictions.

  • The edges should be parallel to the x and y axes
  • The x and y co-ordinate of each corner should be within the range 0 to 2*n (range includes 0 and 2*n).
  • None of the corners should lie in the central 2*k by 2*k square. It means both x and y co-ordinates of the corners should not lie in the range (n-k) to (n+k) (range inclusive of both ends) at the same time.

Two squares are distinct if and only if at least one of its corners is different.

Note that the edges can go through the central forbidden square. The only condition is that the corners itself should not lie in the central forbidden square.

The above figure shows the case n = 2 and k = 1. In the figure the central 2 x 2 square is forbidden and the forbidden lattice points are marked with red. When drawing a square you cannot use these points (marked red) for any of the corners. You are allowed to use only the points marked with black. So the only allowed square you can draw is the 4 x 4 square. Hence the answer for this case is 1.

 

Input

The first line contains one integer t, the number of testcases. (1 <= t <= 50)

This will be followed by t test cases. Each case is specified in a separate line containing two space separated integers n and k.

Constraints:

  • The numbers n and k will be between 1 and 500.
  • k will be strictly less than n (k

Output

For each testcase print the number of distinct squares you can draw under the given constraints.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4014 - Trip Compulsion   

Description

Being a very quirky person, you've modeled your large neighbourhood as a set of numbered junctions and two-way roads connecting these junctions. Somewhat disturbingly, you've actually measured the length of each road in nanometers! Whenever you take a trip from one junction to another, you always note down the lengths of the longest road and the shortest road in your trip and then compute the difference between the two. One day, before you set out on a trip, you're overwhelmed by a strong desire to find out what the lowest possible difference is among all trips that have the same starting and ending junction as yours. Of course, computing all this on paper will take you ages and your trip is a little urgent (you must leave in the next 5 hours), so you decide to write a program.

Input

The first line contains T, the number of test cases. The first line of each test case contains two space separated numbers - N (the number of junctions) and R (the number of roads). The second line of each test case contains the two space separated numbers - start (the starting junction of your trip) and end (the ending junction of your trip). Each of the next R lines contains three space separated numbers - from (the starting junction of a road), to (the ending junction of a road) and length (the length of the two-way road connecting from and to).

 

Constraints:

1 <= T <= 10
2 <= N <= 2000
0 <= R <= 3000
0 <= start, end, from, to < N
1 <= length <= 2,000,000,000
start and end will be different.

 

 

Output

For each test case, output a single line containing one integer - the lowest possible difference. If no trip is possible between start and end, output a single line saying "NO PATH" (quotes for clarity).

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




4015 - Visible Lattice   

Description

Consider a N*N*N lattice. One corner is at (0,0,0) and the opposite one is at (N,N,N). How many lattice points are visible from corner at (0,0,0)? A point X is visible from point Y iff no other lattice point lies on the segment joining X and Y.

Input

The first line contains the number of test cases T. The next T lines contain an interger N.

Constraints :

T <= 100    1 <= N <= 100  

Output

Output T lines, one corresponding to each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4016 - XOR Sum   

Description

Given an array of N numbers, we wish to choose a contiguous sub-sequence of the array, so that the bitwise XOR of all chosen numbers is maximum. Bitwise XOR is defined as follows: every bit in the answer is obtained by applying XOR logic on the corresponding bits of the set of numbers. For example 7, 8 and 5 are XORed as follows,

Numbers in binary:  0111  1000  0101  -----  1010 

So the answer is 10 (in decimal). The same answer can be obtained in C/C++/Java by using the XOR operator as 7^8^5.

Input

The first line contains the number of test cases T. The first line of each test-case contains one integer, N (size of the array). The next N lines of each test-case contain integers denoting the elements of the array.

Constraints:

1 <= T <= 10
1 <= N <= 100,000
All input integers will be non-negative and fit into 32 bit signed integer.

Output

For each test case, output a single line containing the maximum sum that can be obtained.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4017 - Find The Number   

Description

ABC University has k departments. Each department is assigned a department number. There are many students in each department. The university assigns roll numbers to each student such that the number is divisible by the department number. For example if department number is 5, the students can only get roll numbers 5, 10, 15, etc. The purpose is to identify the department of a student easily from his roll number. So if a number is divisible by more than one department number, then that number will not be assigned to any student (so that there will not be any ambiguity). For example if we have departments 5 and 7, then 35, 70, 105, etc are not used because they are divisible by both numbers. Everything was going fine until one day, someone hacked into the University database and erased the roll number column in the students table! The Database administrator knows that, 

  • All valid roll numbers (the valid roll numbers are numbers divisible by one and only one department number) less than 1015 were there in the Database.
  • All the records were sorted by roll number before the hacker erased them, and the hacking did not change the order of records

Now given the position (1 based index) of the record in the database, can you find out the roll number corresponding to that record quickly?

Input

The first line contains one integer t, the number of testcases (1 <= t <= 50).

This will be followed by 't' test cases, each containing 2 lines.

  • The first line of each test case gives two numbers k and n separated by space.
  • The second line contains k space separated integers specifying the department numbers of each department.

Constraints:

  • 1<=k<=12
  • The department numbers will be between 2 and 10^5 (range inclusive of both ends).
  • n will fit into a 32 bit signed integer.
  • The input will be such that, the answer will always be less than 1015.
  • There will not be two departments with same number.
  • One department number will not be divisible by another.

Output

For each test case print the roll number corresponding to the nth record in the database. Output of each test-case should be on a separate line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4018 - Love for Pizza   

Description

My brother and I love pizza. My brother ordered a pizza today with a number of toppings. Some of those toppings I love, like mushrooms, while there are some others that I hate, like olives. Even among the toppings I like (or the ones that I don't like), I like some more than the other, depending on the amount.

Now my brother will let me take a wedge of any size from the pizza. This means I am allowed to make two cuts from the center of the pizza to its circumference, and can keep one of the two resulting pieces. If either cut goes through a topping, the entire topping belongs to that piece which contains the centre of the topping. I am not allowed to cut exactly through the centre of a topping. Each topping will thus remain entirely on one of the pieces. I would like to cut and choose the best piece possible for myself.

Input

Input contains multiple test-cases. The first line of the input contains T, the number of test cases, followed by T testcases. The first line of each test case contains one integer N, the number of toppings. It is followed by N lines containing three space-separated integers each. Each line described a single topping. The first integer denotes my preference for the topping. The next two integers denote respectively the x and y co-ordinates of the centre of the topping.

Input Constraints:

1 ≤ T ≤ 25
1 ≤ N ≤ 105
-105preference ≤ 105
The point (x,y) will lie within the pizza, which is assumed to be a circle centered at (0, 0) with a radius of 109.
The point will not be the centre itself.
Multiple toppings may be centred at the same point.
A set of test cases will not exceed 4MB in file size.

Output

Output a single line per test-case, indicating the sum of the preferences of all the toppings on the best piece. The best piece is the one that has the maximum sum possible.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4019 - Succession   

Description

Vito was involved in a lot of businesses in different areas of New York - from simple olive oil to more dangerous products. Competition was literally cut-throat, and Vito was at his most vulnerable while travelling. So he decided that some of the roads that he travelled on had to be "sanitized" so that he could travel between any two of his areas using only sanitized roads. Since sanitization was an extremely costly process, his Consigliere decided to sanitize the minimum number of roads needed.

All was fine until Vito grew old and decided to hand the reins over to his son Michael. However, his Capos weren't too happy about this as they wanted a part of the business too. So it was decided that Michael would get to pick exactly K areas for himself while the Capos would keep the rest. Michael worked out the business value of each area (including some loss-making areas). He now wants to pick his K areas such that the total business value is maximized and he can travel between any two of his areas using only sanitized roads. Of course, during his travel he does not want to go through an area that is not his. You've been Michael's associate for a long time and you see your chance to impress him and become a full member by telling him what the highest possible value is. Just to prove you're no fluke, you also want to tell him exactly how many ways there are of achieving this. (No big numbers for the Boss, so you will only tell him the remainder this number leaves when divided by 1000000007).

Input

The first line contains T, the number of test cases. The first line of each test case contains three space separated numbers N (the number of areas Vito had), K (the number of areas Michael must choose) and R (the number of sanitized roads). The next line contains N integers, where the ith integer is the business value of the ith area. Each of the next R lines contains two space separated numbers - from and to (both 0-based). It implies that there is a two-way sanitized road between area from and area to.

Input Constraints:

1 <= T <= 100
1 <= K <= N <= 100
-1000 <= value of any business area <= 1000
0 <= from, to < N
No two roads will connect the same pair of areas. from and to will be distinct.
The R roads will be such that it is possible to travel between every pair of areas using only sanitized roads, and removing even one of the roads will make it impossible to travel between every pair of areas using only sanitized roads.

Output

Output T lines, one corresponding to each test. On every line, output two space separated numbers. The first number is the highest possible business value. The second number is the number of ways in which this can be done.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4020 - Assembling Services   

Description

Input

 

Output

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




4021 - Box Relations   

Description

 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




4022 - Exclusive-OR   

Description

 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




4023 - Help Bubu   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




4024 - Jiajia's Robot   

Description

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




4025 - String LD   

Description

 Stringld(left delete) is a function that gets a string and deletes its leftmost character (for instance Stringld(``acm") returns ``cm").

You are given a list of distinct words, and at each step, we apply stringld on every word in the list. Write a program that determines the number of steps that can be applied until at least one of the conditions become true:

  1. A word becomes empty string, or
  2. a duplicate word is generated.

For example, having the list of words aababac, and caac, applying the function on the input for the first time results in abbac, and aac. For the second time, we get bac, and ac. Since in the second step, we have two ac strings, the condition 2 is true, and the output of your program should be 1. Note that we do not count the last step that has resulted in duplicate string. More examples are found in the sample input and output section.

Input

There are multiple test cases in the input. The first line of each test case is n (1n100) , the number of words.

Each of the next n lines contains a string of at most 100 lower case characters.

The input terminates with a line containing `0'.

Output

For each test case, write a single line containing the maximum number of stringld we can call.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4026 - Painting   

Description

Ethan wants to draw a painting on an m×n board. He can draw some strips on the board using a paintbrush of width one. In each step, he must choose a new color and paint a full column or a full row. He has a great image to be drawn on the board, but he doesn't know which color to use first. You must help him in finding out the order of colors.

 

Input

There are multiple test cases in the input. The first line of each test case contains two integers m and n , the size of the board (0 < mn < 100) . Following the first line, there are m lines with n integers denoting the color in each cell. All the colors are positive integer numbers less than 10000. The input is terminated with a single line containing two consecutive zeros.

Output

For each test case, write a single line containing the order of colors used to paint the board. If there are several answers, output the one which is lexicographically smallest (considering each number as a symbol).

Sample Input  Download

Sample Output  Download

Tags




Discuss




4027 - Another Brick in the Wall   

Description

After years as a brick-layer, you've been called upon to analyze the instability of brick walls. The instability of a wall can be approximated by the maximum damage to a wall in case of taking one brick out. A brick will fall if all bricks that are directly underneath it are removed. Note that if the space underneath a brick is partially empty, it does not fall. You are given the description of all bricks in a wall, and must determine the instability of the wall as described in the following sections.

Input

There are multiple test cases in the input. Each test case consists of a single line, ``M N (1MN≤100) where M and N indicate the height and width (in units), respectively, of the input wall.

Each of the next M lines is a string of N digits which specifies a row in the wall. Each brick in a row is represented by a substring of the row (like s ) such that every digit in s is the same, which is equal to the length of s too. For example, 333 and 22 are two bricks of length 3 and 2 respectively, but 111 specifies three bricks of length one. A 0 in a row means there is no brick in that place of wall. Note that the height of each brick is one. The input terminates with a line containing `0 0'. You may assume that the input is correct. This means:

  1. There is no brick such that the length of the brick does not conform to the digits in the brick (like 222 in the row 12221).
  2. No brick can fall initially.

Output

For each test case, write a single line containing maximum sum of the bricks' lengths that will fall if we take one brick out (including that brick).

Sample Input  Download

Sample Output  Download

Tags




Discuss




4028 - Blast the Enemy!   

Description

A new computer game has just arrived and as an active and always-in-the-scene player, you should finish it before the next university term starts. At each stage of this game, you have to shoot an enemy robot on its weakness point. The weakness point of a robot is always the ``center of mass" of its 2D shape in the screen. Fortunately, all robot shapes are simple polygons with uniform density and you can write programs to calculate exactly the center of mass for each polygon.

Let's have a more formal definition for center of mass (COM). The center of mass for a square, (also circle, and other symmetric shapes) is its center point. And, if a simple shape C is partitioned into two simple shapes A and B with areas SA and SB , then COM(C) (as a vector) can be calculated by

COM(C) = $displaystyle {frac{{S_{A} 	imes COM(A) + S_{B} 	imes COM(B)}}{{S_{A} + S_{B}}}}$.

As a more formal definition, for a simple shape A with area SA :

COM(A) = $displaystyle {frac{{int int_{A} vec{a}.ds}}{{S_{A}}}}$

 

Input

The input contains a number of robot definitions. Each robot definition starts with a line containing n , the number of vertices in robot's polygon (n≤100) . The polygon vertices are specified in the next n lines (in either clockwise or counter-clock-wise order). Each of these lines contains two space-separated integers showing the coordinates of the corresponding vertex. The absolute value of the coordinates does not exceed 100. The case of n = 0 shows the end of input and should not be processed.

Output

The i -th line of the output should be of the form ``Stage #i : x y " (omit the quotes), where (xy ) is the center of mass for the i -th robot in the input. The coordinates must be rounded to exactly 6 digits after the decimal point.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4029 - deltree   

Description

You have just run out of disk space and decided to delete some of your directories. Rationally, you will first have an exploration of what you have in your file system. And more rationally, you will do this exploration through a command line interface. The interface used in this problem is called ``MSDOS-", since it is something like MSDOS with fewer features. The commands of MSDOS- are as follows:

  • cd directory >
    Assuming directory > 
    to be the name of a relative descendant of current directory, this command changes the current directory to directory > . For example, when the current directory is ``AB" and one of its descendants is ``CD", the execution of ``cd CD" will change the current directory to ``ABCD".
  • cd 

    This command changes the current directory to ``" (the root of the file system). For example, when the current directory is ``AB", the execution of ``cd " will change the current directory to ``".

  • cd ..

    Assuming the current directory to be anything except ``", this command changes the current directory to its parent directory. For example, when the current directory is ``AB", the execution of ``cd .." will change the current directory to ``A".

  • cd  directory >

    This command is equivalent to the execution of the following two commands:

    cd

    cd directory >

  • dir

    This command lists the name of files and directories directly in the current directory, each on a separate line. These filedirectory names are made up of (lowercase and uppercase) letters, digits, and dots (``."). Directory names precede the file names in the list, and each one, comes alone in a single line. On the contrary, each file name is accompanied by its size separated by a space. A sample output of ``dir" is as follows:

    HW1 HW1.old Syllab.pdf 10000 notes.txt 3241  

  • deltree directory >

    Assuming directory > to be the name of a relative descendant of current directory, this command tries to delete directory > and all its descendant files and subdirectories (and thus, freeing that much of space). For example, when the current directory is ``AB" and one of its descendants is ``CD", the execution of ``deltree CD" will try to delete directory ``ABCD" and all of its descendant files and directories.

  • deltree  directory >

    This command is equivalent to the execution of the following two commands:

    cd

    deltree directory >

  • exit

    This command terminates the command line interface.

A ``scenario" is an exploration (a consistent series of ``cd" and ``dir" commands and their results, starting from root) followed by exactly one ``deltree" command. Given a scenario, you are to find the maximum space guaranteed to be freed by executing its ``deltree" command.

Input

Input contains multiple independent scenarios. There is an empty line after each scenario. The input ends with an ``exit" command. There is a ``>" sign before each command in the input (with no spaces in between). The length of each file name does not exceed 50. You may assume that the input is correct.

Output

Write the result of the i -th scenario as a single integer on the i -th line of output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4030 - Solar Eclipse   

Description

A new Solar Eclipse is going to happen in Mars. Scientists from different parts of the world are travelling to Mars to watch and study this phenomenon. You just managed to calculate exactly the best point of Mars lands for your study of the eclipse, and want to land your flying saucer on that place. But, you notice that there are already other spacecrafts landed on near that area.

In the bird's eye view, all the spacecrafts (including yours) are circles with constant radius R . Logically, you hate to land your spacecraft on the others (no intersection of areas is allowed, but touching the other crafts is acceptable), though, the other saucers did not obey this rule on their own landings (i.e. their circles might have positive-area intersections with each other). In order to land your own craft on Mars, you want to find the place which minimizes the distance between the center of your flying saucer and your already calculated best point (and obeys the no-intersection rule). That's what you should do in this problem.

Input

The input has multiple test cases. Each test case starts with a line containing an integer n (number of already landed spacecrafts), and a real number R . The land is small enough for us to be modeled by a two-dimensional plane, and (0,0) is conventionally the best point for us to land. Each of the next n lines specifies the location of a landed flying saucer by giving two real numbers x and y as the coordinates of its center.

The input ends with a case of n = R = 0 which must not be processed. Assume n100 R > 0 , and their absolute value does not exceed 1000.

Output

Write the result of the i -th test case on the i -th line of the output. You should just write the minimum possible distance between the center of your landed craft and the origin of the plane, rounded to exactly 6 digits after the decimal point.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4031 - Grey Area   

Description

Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator.

epsfbox{p4157.eps}
Figure 1: A histogram

Figure 1 is an example of histogram automatically produced by his histogram generator. A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each.

Dr. Grey's histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively.

In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness.

Input

The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format.

n w
v1
v1
.
.
vn

n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times.

w 
is the interval width. A value v is in the first (i.e. leftmost) interval if 0$ le$v < w , the second one if w$ le$v < 2w , and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset.

You may assume the following.

1$ le$n$ le$100  
10$ le$w$ le$50  
0$ le$vi$ le$100 for 1$ le$i$ le$n

You can also assume that the maximum value is no less than w . This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros.

Output

For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is:

  1×1 + $ {frac{{2}}{{3}}}$×$ {frac{{3}}{{5}}}$ + $ {frac{{1}}{{3}}}$×$ {frac{{1}}{{5}}}$ +0×$ {frac{{1}}{{5}}}$ + 0.01
= 1 + $ {frac{{2}}{{5}}}$ + $ {frac{{1}}{{15}}}$ + 0.01
= 1.47666...

Each output value should be in a decimal fraction and may have an error less than 10-5 .

Sample Input  Download

Sample Output  Download

Tags




Discuss




4032 - Expected Allowance   

Description

Hideyuki is allowed by his father Ujisato some 1000 yen bills every month for his pocket money. In the first day of every month, the number of bills is decided as follows. Ujisato prepares n pieces of m -sided dice and declares the cutback k . Hideyuki rolls these dice. The number of bills given is the sum of the spots of the rolled dice decreased by the cutback. Fortunately to Hideyuki, Ujisato promises him to give at least one bill, even if the sum of the spots does not exceed the cutback. Each of the dice has spots of 1 through m inclusive on each side, and the probability of each side is the same.

In this problem, you are asked to write a program that finds the expected value of the number of given bills.

For example, when n = 2 m = 6 and k = 3 , the probabilities of the number of bills being 1, 2, 3, 4, 5, 6, 7, 8 and 9 are $ {frac{{1}}{{36}}}$ + $ {frac{{2}}{{36}}}$ + $ {frac{{3}}{{36}}}$,$ {frac{{4}}{{36}}}$,$ {frac{{5}}{{36}}}$,$ {frac{{6}}{{36}}}$,$ {frac{{5}}{{36}}}$,$ {frac{{4}}{{36}}}$,$ {frac{{3}}{{36}}}$,$ {frac{{2}}{{36}}}$ and $ {frac{{1}}{{36}}}$ , respectively. Therefore, the expected value is ($ {frac{{1}}{{36}}}$ + $ {frac{{2}}{{36}}}$ + $ {frac{{3}}{{36}}}$)×1 + $ {frac{{4}}{{36}}}$×2 + $ {frac{{5}}{{36}}}$×3 + $ {frac{{6}}{{36}}}$×4 + $ {frac{{5}}{{36}}}$×5 + $ {frac{{4}}{{36}}}$×6 + $ {frac{{3}}{{36}}}$×7 + $ {frac{{2}}{{36}}}$×8 + $ {frac{{1}}{{36}}}$×9 , which is approximately 4.11111111.

Input

The input is a sequence of lines each of which contains three integers n m and k in this order. They satisfy the following conditions.

1$ le$n
2$ le$m
0$ le$k < nm
nm×mn < 100000000(108)

 

The end of the input is indicated by a line containing three zeros.

Output

The output should be comprised of lines each of which contains a single decimal fraction. It is the expected number of bills and may have an error less than 10-7 . No other characters should occur in the output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4033 - Stopped Watches   

Description

In the middle of Tyrrhenian Sea, there is a small volcanic island called Chronus. The island is now uninhabited but it used to be a civilized island. Some historical records imply that the island was annihilated by an eruption of a volcano about 800 years ago and that most of the people in the island were killed by pyroclastic flows caused by the volcanic activity. In 2003, a European team of archaeologists launched an excavation project in Chronus Island. Since then, the project has provided many significant historic insights. In particular the discovery made in the summer of 2008 astonished the world: the project team excavated several mechanical watches worn by the victims of the disaster. This indicates that people in Chronus Island had such a highly advanced manufacturing technology.

Shortly after the excavation of the watches, archaeologists in the team tried to identify what time of the day the disaster happened, but it was not successful due to several diffculties. First, the extraordinary heat of pyroclastic flows severely damaged the watches and took away the letters and numbers printed on them. Second, every watch has a perfect round form and one cannot tell where the top of the watch is. Lastly, though every watch has three hands, they have a completely identical look and therefore one cannot tell which is the hour, the minute, or the second (It is a mystery how the people in Chronus Island were distinguishing the three hands. Some archaeologists guess that the hands might be painted with different colors, but this is only a hypothesis, as the paint was lost by the heat). This means that we cannot decide the time indicated by a watch uniquely; there can be a number of candidates. We have to consider different rotations of the watch. Furthermore, since there are several possible interpretations of hands, we have also to consider all the permutations of hands.

You are an information archaeologist invited to the project team and are asked to induce the most plausible time interval within which the disaster happened, from the set of excavated watches.

In what follows, we express a time modulo 12 hours. We write a time by the notation hh : mm : ss , where hh mm , and ss stand for the hour (hh = 00, 01, 02,..., 11) , the minute (mm = 00, 01, 02,..., 59) , and the second (ss = 00, 01, 02,..., 59) , respectively. The time starts from 00:00:00 and counts up every second 00:00:00, 00:00:01, 00:00:02, ... , but it reverts to 00:00:00 every 12 hours.

The watches in Chronus Island obey the following conventions of modern analog watches.

  • A watch has three hands, i.e. the hour hand, the minute hand, and the second hand, though they look identical as mentioned above.
  • Every hand ticks 6 degrees clockwise in a discrete manner. That is, no hand stays between ticks, and each hand returns to the same position every 60 ticks.
  • The second hand ticks every second.
  • The minute hand ticks every 60 seconds.
  • The hour hand ticks every 12 minutes.

 

At the time 00:00:00, all the three hands are located at the same position.

Because people in Chronus Island were reasonably keen to keep their watches correct and pyroclastic flows spread over the island quite rapidly, it can be assumed that all the watches were stopped in a short interval of time. Therefore it is highly expected that the time the disaster happened is in the shortest time interval within which all the excavated watches have at least one candidate time.

You must calculate the shortest time interval and report it to the project team.

 

Input

The input consists of multiple datasets, each of which is formatted as follows.

n
s1 t1 v1
s2 t2 v2
...
sn tn vn
The first line contains a single integer n 
(2$ le$n$ le$10) , representing the number of the watches. The three numbers si ti ui in each line are integers such that 0$ le$sitiui$ le$59 and they specify the positions of the three hands by the number of ticks relative to an arbitrarily chosen position.

Note that the positions of the hands of a watch can be expressed in many different ways. For example, if a watch was stopped at the time 11:55:03, the positions of hands can be expressed differently by rotating the watch arbitrarily (e.g. 59 55 3, 0 56 4, 1 57 5, etc.) and as well by permuting the hour, minute, and second hands arbitrarily (e.g. 55 59 3, 55 3 59, 3 55 59, etc.).

The end of the input is indicated by a line containing a single zero.

Output

For each dataset, output the shortest time interval within which all the watches given in the dataset have at least one candidate time. The output must be written in a single line in the following format for each dataset.

hh$ 	t :$mm$ 	t :$ss$ 	t $h'h'$ 	t :$m'm'$ 	t :$s's'

Each line contains a pair of times hh$ 	t :$mm$ 	t :$ss and h'h'$ 	t :$m'm'$ 	t :$s's' , indicating that the shortest interval begins at hh$ 	t :$mm$ 	t :$ss and ends at h'h'$ 	t :$m'm'$ 	t :$s's' inclusive. The beginning time and the ending time are separated by a single space and each of them should consist of hour, minute, and second in two digits separated by colons. No extra characters should appear in the output.

In calculating the shortest interval, you can exploit the facts that every watch has at least one candidate time and that the shortest time interval contains 00:00:00 only if the interval starts from 00:00:00 (i.e. the shortest interval terminates before the time reverts to 00:00:00).

If there is more than one time interval that gives the shortest, output the one that first comes after 00:00:00 inclusive.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4034 - Digits on the Floor   

Description

Taro attempts to tell digits to Hanako by putting straight bars on the floor. Taro wants to express each digit by making one of the forms shown in Figure 2.

Since Taro may not have bars of desired lengths, Taro cannot always make forms exactly as shown in Figure 2. Fortunately, Hanako can recognize a form as a digit if the connection relation between bars in the form is kept. Neither the lengths of bars nor the directions of forms affect Hanako's perception as long as the connection relation remains the same. For example, Hanako can recognize all the awkward forms in Figure 3 as digits. On the other hand, Hanako cannot recognize the forms in Figure 4 as digits. For clarity, touching bars are slightly separated in Figures 2, 3 and 4. Actually, touching bars overlap exactly at one single point.

 

epsfbox{p4160a.eps}

 

Figure 2: Representation of digits

 

epsfbox{p4160b.eps}

 

Figure 3: Examples of forms recognized as digits

In the forms, when a bar touches another, the touching point is an end of at least one of them. That is, bars never cross. In addition, the angle of such two bars is always a right angle.

To enable Taro to represent forms with his limited set of bars, positions and lengths of bars can be changed as far as the connection relations are kept. Also, forms can be rotated.

Keeping the connection relations means the following.

 

epsfbox{p4160c.eps}

 

Figure 4: Forms not recognized as digits (these kinds of forms are not contained in the dataset)

 


  • Separated bars are not made to touch.
  • Touching bars are not made separate.
  • When one end of a bar touches another bar, that end still touches the same bar. When it touches a midpoint of the other bar, it remains to touch a midpoint of the same bar on the same side.
  • The angle of touching two bars is kept to be the same right angle (90 degrees and -90 degrees are considered different, and forms for 2 and 5 are kept distinguished).

 


Your task is to find how many times each digit appears on the floor. The forms of some digits always contain the forms of other digits. For example, a form for 9 always contains four forms for 1, one form for 4, and two overlapping forms for 7. In this problem, ignore the forms contained in another form and count only the digit of the ``largest" form composed of all mutually connecting bars. If there is one form for 9, it should be interpreted as one appearance of 9 and no appearance of 1, 4, or 7.

Input

The input consists of a number of datasets. Each dataset is formatted as follows.


n      
x1a y1a x1b y1b
x2a y2a x2b y2b
$ vdots$
xna yna xnb xnb

In the first line, n 
represents the number of bars in the dataset. For the rest of the lines, one line represents one bar. Four integers xa ya xb yb , delimited by single spaces, are given in each line. xa and ya are the x- and y - coordinates of one end of the bar, respectively. xb and yb are those of the other end. The coordinate system is as shown in Figure 5. You can assume 1$ le$n$ le$1000 and 0$ le$xayaxbyb$ le$1000 .

The end of the input is indicated by a line containing one zero.

 


epsfbox{p4160d.eps}

 

Figure 5: The coordinate system

 


You can also assume the following conditions.

 

  • More than two bars do not overlap at one point.
  • Every bar is used as a part of a digit. Non-digit forms do not exist on the floor.
  • A bar that makes up one digit does not touch nor cross any bar that makes up another digit.
  • There is no bar whose length is zero.

 

Output

For each dataset, output a single line containing ten integers delimited by single spaces. These integers represent how many times 0, 1, 2,... , and 9 appear on the floor in this order. Output lines must not contain other characters.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4035 - Spherical Mirrors   

Description

A long time ago in a galaxy, far, far away, there were N spheres with various radii. Spheres were mirrors, that is, they had reflective surfaces ...


You are standing at the origin of the galaxy (0, 0, 0), and emit a laser ray to the direction (u, v, w) 
. The ray travels in a straight line.

When the laser ray from I hits the surface of a sphere at Q , let N be a point outside of the sphere on the line connecting the sphere center and Q . The reflected ray goes to the direction towards R that satisfies the following conditions: (1) R is on the plane formed by the three points I , Q and N , (2) $ angle$IQN = $ angle$NQR , as shown in Figure 6.

 

epsfbox{p4161.eps}

 

Figure 6: Laser ray reflection

After it is reflected several times, finally it goes beyond our observation. Your mission is to write a program that identifies the last reflection point.

Input

The input consists of multiple datasets, each in the following format.

N      
u v w  
x1 y1 z1 r1
$ vdots$
xN yN zN rN

 
The first line of a dataset contains a positive integer N 
which is the number of spheres. The next line contains three integers u v and w separated by single spaces, where (uvw) is the direction of the laser ray initially emitted from the origin.

Each of the following N lines contains four integers separated by single spaces. The i -th line corresponds to the i -th sphere, and the numbers represent the center position (xiyizi) and the radius ri .

Nuvwxiyizi and ri satisfy the following conditions.

1$ le$N$ le$100
-100$ le$uvw$ le$100
-100$ le$xiyizi$ le$100
5$ le$ri$ le$30
u2 + v2 + w2 > 0

You can assume that the distance between the surfaces of any two spheres is no less than 0.1. You can also assume that the origin (0, 0, 0) is located outside of any sphere, and is at least 0.1 distant from the surface of any sphere.

The ray is known to be reflected by the sphere surfaces at least once, and at most five times. You can assume that the angle between the ray and the line connecting the sphere center and the reflection point, which is known as the angle of reflection (i.e. $ 	heta$ in Figure 6), is less than 85 degrees for each point of reflection.

The last dataset is followed by a line containing a single zero.

Output

For each dataset in the input, you should print the x - y - and z - coordinates of the last reflection point separated by single spaces in a line. No output line should contain extra characters. No coordinate values in the output should have an error greater than 0.01.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4036 - Traveling Cube   

Description

On a small planet named Bandai, a landing party of the starship Tadamigawa discovered colorful cubes traveling on flat areas of the planet surface, which the landing party named beds. A cube appears at a certain position on a bed, travels on the bed for a while, and then disappears. After a longtime observation, a science officer Lt. Alyssa Ogawa of Tadamigawa found the rule how a cube travels on a bed.

A bed is a rectangular area tiled with squares of the same size.

  • One of the squares is colored red,
  • one colored green,
  • one colored blue,
  • one colored cyan,
  • one colored magenta,
  • one colored yellow,
  • one or more colored white, and
  • all others, if any, colored black.

 

Initially, a cube appears on one of the white squares. The cube's faces are colored as follows.


top red
bottom cyan
north green
south magenta
east blue
west yellow

 


The cube can roll around a side of the current square at a step and thus rolls on to an adjacent square. When the cube rolls on to a chromatically colored (red, green, blue, cyan, magenta or yellow) square, the top face of the cube after the roll should be colored the same. When the cube rolls on to a white square, there is no such restriction. The cube should never roll on to a black square.

Throughout the travel, the cube can visit each of the chromatically colored squares only once, and any of the white squares arbitrarily many times. As already mentioned, the cube can never visit any of the black squares. On visit to the final chromatically colored square, the cube disappears. Somehow the order of visits to the chromatically colored squares is known to us before the travel starts.

Your mission is to find the least number of steps for the cube to visit all the chromatically colored squares in the given order.

Input

The input is a sequence of datasets. A dataset is formatted as follows:

w d
c11 .. cw1
...
c1d ... cwd
v1v2v3v4v5v6

 

The first line is a pair of positive integers w and d separated by a space. The next d lines are w -character-long strings c11 ... cw1, ... c1d ... cwd with no spaces. Each character cij is one of the letters rgbcmywand k, which stands for red, green, blue, cyan, magenta, yellow, white and black respectively, or a sign #. Each of rgbcmy and # occurs once and only once in a dataset. The last line is a six-character-long stringv1v2v3v4v5v6 which is a permutation of ``rgbcmy".

The integers w and d denote the width (the length from the east end to the west end) and the depth (the length from the north end to the south end) of a bed. The unit is the length of a side of a square. You can assume that neither w nor d is greater than 30.

Each character cij shows the color of a square in the bed. The characters c11 cw1 c1d and cwd correspond to the north-west corner, the north-east corner, the south-west corner and the southeast corner of the bed respectively. If cij is a letter, it indicates the color of the corresponding square. If cij is a #, the corresponding square is colored white and is the initial position of the cube.

The string v1v2v3v4v5v6 shows the order of colors of squares to visit. The cube should visit the squares colored v1v2v3v4v5 and v6 in this order. The end of the input is indicated by a line containing two zeros separated by a space.

 

Output

For each input dataset, output the least number of steps if there is a solution, or ``unreachable" if there is no solution. In either case, print it in one line for each input dataset.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4037 - Mystic Craft   

Description

In the Ancient Clash of Mystic Pandas (ACM Pandas) game, the player plays the role of a Panda Knight who needs to defend Panda Land by defeating evil Panda Wizards. As the wizards have special magical powers, they need to be defeated using specific types of Mystic Sticks (regular bamboo sticks are ineffective against them). To obtain a Mystic Stick, Panda Knight needs to craft it by infusing his regular bamboo stick with several different kinds of magic shards according to the known recipe for that particular type of Mystic Stick.

Normally, all kinds of shards can be purchased for 1 gold/piece from the Panda Magic Store (therefore Panda Knight will have no problem of acquiring the shards, as long as he has enough gold to buy them all from the Store). However due to the recent invasion, to conceal the shards from the incoming Panda Wizards, Panda Magic Store has packaged all the shards into inconspicuous Mystery Boxes. A Mystery Box contains a random piece of magic shard which type can be determined prior to buying and opening the box, which Panda Knight can also buy for the same price (1 gold/box).

As his Panda Knight character is not rich, Mr. Wah is concerned about the possibility that he unable to buy all the necessary shards due to not getting the required amount of a specific type of shard. He needs your help! Your task as Mr. Wah's best programmer friend is to compute the probability that he will be able to get all the shards and craft the Mystic Stick, so that he can plan his playing strategy accordingly. You can safely assume that all the required shards are available on the store via the Mystery Boxes, that the boxes will only contain the needed types of shard, and that each type of shard has equal probability of being contained inside any particular Mystery Box.

Input

The first line of input contains an integer T (1 <= T <= 100), the number of test cases follow. Each test case begins with two integers G and N (1 <= N <= G <= 32) in one line, denoting the amount of Panda Knight's gold and the number of needed magic shard types respectively. The next line contains N integers, denoting how many magic shards of each type (1 <= M1 ... MN <= 32; M1 + ... + MN <= G) are needed to craft the Mystic Stick.

Output

For each of the test cases, print the test case number followed by the probability (in percentage, correct to 6 decimal places – Mr. Wah is paranoid about this game) that Panda Knight will be able to craft the Mystic Stick, with the format as shown by the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4038 - Top 10   

Description

Given a dictionary containing less than N = 20000 words labeled from 1 to N. Each word consists of lowercase characters (from 'a' to 'z') with arbitrary length. The total number of characters in the dictionary is at most 100,000. Your task is to answer at most Q = 100000 queries. Each query qi is also a word (as defined above). For each query, you have to print the "Top 10" words in the dictionary with the following rules:

  • All the words in the "Top 10" have to contain the substring qi.
  • All the words in the "Top 10" have to be sorted in this order:
    1. The words with shorter length come first, if they have equal length then
    2. The lexicographically smaller words come first, otherwise
    3. The words with smaller label come first.
  • If the number of words in the dictionary that contains the substring qi is less than 10 then print all the words otherwise, print only the top-10 words (note: the words are printed using their labels).
  • If there is no word in the dictionary that contains the substring qi then print "-1" (without the quotes).

Input

The first line contains the number N. The next N lines contains the N words in the dictionary (the ith line is the word with label i). The next line contains the number Q followed by the Q lines containing the queries.

Output

For each query, print one line containing the labels of the "Top 10" words (separated by a space) in the dictionary using the rules defined above.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4039 - Random Simple Polygon   

Description

Given N (3 <= N <= 10,000) non-collinear triplewise points on a 2-D plane, select K (3 <= K <= N) points and order them such that the ordered points form a simple K-sided polygon. A polygon is called simple if no pair of its sides cross each other.

Input

First line of the input contains a positive integer T (1 <= T <= 10), the number of cases. Follows afterwards are the description of each case. For each case, the first line contains two integers N and K. Each of Nfollowing lines contains two integers, xi, yi (1 <= xi, yi <= 1,000,000), one of the given points. For simplicity, all points are numbered from 1 to N according to the order of appearance in the input. There is no blank line separating each case.

Output

For each case, output K integers, each on a line, the selected points in the order how the K-sided simple polygon is constructed. If there are more than one possible ordered selection that fits the criteria, output any one. It is always possible to form at least one simple K-sided polygon. There is no blank line separating each case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4040 - Alien   

Description

It is 2050 and human live with alien. There are two kind of alien: good alien and evil alien. Good alien were our friend because they help us to develop good technology for our earth. Evil alien were very very bad, they develop heavy and dangerous weapons that can destroy earth. Alien were very hard to kill because of their ultra regeneration skill. Luckily, we have developed a kind of bomb that can kill alien in an instant. This weapon is very expensive so we must use it wisely.

Given a map of 10 × 10, each element in the map will be:

  • '.' represents empty region.
  • 'g' represents good alien.
  • 'e' represents evil alien.

Calculate how many evil alien that can be killed without killing any good alien, and how many bombs we need to do that. A bomb has a 3 × 3 area of effect, so all of the 8 adjacent neighbors will also be destroyed. You can put bomb anywhere in the map, even if there is an alien in that cell. For example,



e..
.Xe
..e


Bombing at X will kill three evil aliens.

Our spy has reported that the number of alien groups from each side is less than 16.

Input

First line in the input will be T (1 ≤ T ≤ 100) number of cases. Each case will have a map of 10 × 10 represent the city. Between each city will be separated by a blank line.

Output

For each case, output two numbers: a and b, where a is the maximum number of evil aliens that you can kill and b is the minimum number of bombs you need to do that.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4041 - A+B   

Description

Given two integers A and B that are not necessarily in base-10, find the smallest possible A + B in base-10.

For example,

A = 213, possibly base-4 (39 in base-10)
B = 4721, possibly base-8 (2513 in base-10)

A + B = 39 + 2513 = 2552

Input

First line of the input contains a positive integer T (1 <= T <= 100), the number of cases. Each case contains two positive integers A and BA and B will contain at most 5 digits, each digit will be between 0 and 9, inclusive, and no leading zeroes.

Output

For each case, output an integer in base-10 denoting the smallest possible A + B.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4042 - 1:1000000000000...   

Description

Do you know Lotto? Lotto is a game of probability. Six numbers are drawn from a range of numbers (such as 42, 47, 47, 49, 51, and 54). Michigan, for instance, has a 6-out-of-47 game (6/47), meaning that six numbers are drawn from possible 47. Florida's Lotto is 6/53, meaning that six numbers are drawn from a possible 53.

To play Lotto, indicate your six chosen numbers by marking the numbered squares on a play slip. Then take the play slip to a lottery retailer (or agent). The retailer enters your selection in the on-line terminal, which produces your game ticket. The ticket, not the play slip, is the official receipt and must be presented and validated in the event of a win. Always check to make sure that the correct date and numbers are on the game ticket before you leave. Lottery agents are found in convenience stores, gas stations, and grocery stores.

The cost for one chance at Lotto is still $1 in many states. So for one chance, or play, at Lotto, you would pay $1. For five plays -- that is, to play five sets of numbers--you would pay $5. Illinois offers a bargain: two plays for $1.

Typically, Lotto drawings are held twice a week, usually on Wednesday and Saturday nights. However, this may not be true for every state.

The lottery officials use special ball-drawing machines, and the balls are numbered. The machine randomly shoots out six selected balls; these balls display the winning numbers for that evening's lottery drawing. If all six of your numbers exactly match the numbers drawn, you win the jackpot. In Lotto, your numbers don't need to be listed in any particular order, as long as they match those drawn. (taken from http://entertainment.howstuffworks.com/how-to-play-the-lottery1.htm)

In most case of lottery they don't draw same number, but in our problem here same number are allowed. So here, you can play number "42 42 45 45 45" which is not allowed in common lottos.

They say there's more chance of you getting hit by a car on your way to buy a lotto ticket than the chance of winning one. Is the probability to win really that small? You are about to help me find out.

Input

Input starts with an integer T (1 <= T <= 10), the number of test cases. T input blocks follows. Each input blocks starts with an integer M (1 <= M <= 50), meaning that the game involves M distinct numbers particularly from 1 to M. You don't know how the ball-drawing machine works, but you do know that for there is a constant probability for each number to pop up. The second line of each input blocks will consists of M real-numbers P1P2P3P4, ..., PM, where Pi denotes the probability of ball with number i to pop-up. You can safely assume that the total probability is equal to 1.

The third line of input is an integer Q (1 <= Q <= 100), the number of queries. Q lines follow with each line begins with an integer N (1 <= N <= M). So if N is 6, you are playing 6-out-of-M game in this particular query.N numbers follows, those are your chosen number. You are to determine what is the probability of that number winning the lottery. Since the probabilities can be very low, output them in scientific notation: a x 10^bwhere a should be between 1.00000 and 9.99999, inclusive. Output a in 5 decimal places.

Output

For each query, you are to determine the probability of that number winning the lottery.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4043 - The Unique MST   

Description

Given a connected undirected graph, tell if its minimum spanning tree is unique. 

Definition 1 (Spanning Tree): Consider a connected, undirected graph G = (V, E). A spanning tree of G is a subgraph of G, say T = (V', E'), with the following properties: 
1. V' = V. 
2. T is connected and acyclic. 

Definition 2 (Minimum Spanning Tree): Consider an edge-weighted, connected, undirected graph G = (V, E). The minimum spanning tree T = (V, E') of G is the spanning tree that has the smallest total cost. The total cost of T means the sum of the weights on all the edges in E'. 

Input

The first line contains a single integer t (1 <= t <= 20), the number of test cases. Each case represents a graph. It begins with a line containing two integers n and m (1 <= n <= 100), the number of nodes and edges. Each of the following m lines contains a triple (xi, yi, wi), indicating that xi and yi are connected by an edge with weight = wi. For any two nodes, there is at most one edge connecting them.

Output

For each input, if the MST is unique, print the total cost of it, or otherwise print the string 'Not Unique!'

Sample Input  Download

Sample Output  Download

Tags




Discuss




4044 - Network of Schools   

Description

A number of schools are connected to a computer network. Agreements have been developed among those schools: each school maintains a list of schools to which it distributes software (the “receiving schools”). Note that if B is in the distribution list of school A, then A does not necessarily appear in the list of school B 
You are to write a program that computes the minimal number of schools that must receive a copy of the new software in order for the software to reach all schools in the network according to the agreement (Subtask A). As a further task, we want to ensure that by sending the copy of new software to an arbitrary school, this software will reach all schools in the network. To achieve this goal we may have to extend the lists of receivers by new members. Compute the minimal number of extensions that have to be made so that whatever school we send the new software to, it will reach all other schools (Subtask B). One extension means introducing one new member into the list of receivers of one school. 

Input

The first line contains an integer N: the number of schools in the network (2 <= N <= 100). The schools are identified by the first N positive integers. Each of the next N lines describes a list of receivers. The line i+1 contains the identifiers of the receivers of school i. Each list ends with a 0. An empty list contains a 0 alone in the line.

Output

Your program should write two lines to the standard output. The first line should contain one positive integer: the solution of subtask A. The second line should contain the solution of subtask B.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4045 - Toll! Revisited   

Description

Sindbad the Sailor sold 66 silver spoons to the Sultan of Samarkand. The selling was quite easy; but delivering was complicated. The items were transported over land, passing through several towns and villages. Each town and village demanded an entry toll. There were no tolls for leaving. The toll for entering a village was simply one item. The toll for entering a town was one piece per 20 items carried. For example, to enter a town carrying 70 items, you had to pay 4 items as toll. The towns and villages were situated strategically between rocks, swamps and rivers, so you could not avoid them.

Figure 1: To reach Samarkand with 66 spoons, traveling through a town followed by two villages, you must start with 76 spoons.

Figure 2: The best route to reach X with 39 spoons, starting from A, is A->b->c->X, shown with arrows in the figure on the left. The best route to reach X with 10 spoons is A->D->X, shown in the figure on the right. The figures display towns as squares and villages as circles.

Predicting the tolls charged in each village or town is quite simple, but finding the best route (the cheapest route) is a real challenge. The best route depends upon the number of items carried. For numbers up to 20, villages and towns charge the same. For large numbers of items, it makes sense to avoid towns and travel through more villages, as illustrated in Figure 2.   You must write a program to solve Sindbad’s problem. Given the number of items to be delivered to a certain town or village and a road map, your program must determine the total number of items required at the beginning of the journey that uses a cheapest route. You will also have to find the cheapest route. If there is more than one such route, print the lexicographically smallest one (A-n-d is smaller than a-n-d).

Input

The input consists of several test cases. Each test case consists of two parts: the roadmap followed by the delivery details.

The first line of the roadmap contains an integer n, which is the number of roads in the map (0 <= n). Each of the next n lines contains exactly two letters representing the two endpoints of a road. A capital letter represents a town; a lower case letter represents a village. Roads can be traveled in either direction.

Following the roadmap is a single line for the delivery details. This line consists of three things: an integer p (0 < p < 1000000000) for the number of items that must be delivered, a letter for the starting place, and a letter for the place of delivery. The roadmap is always such that the items can be delivered.

The last test case is followed by a line containing the number -1.

Output

The output consists of three lines for each test case. First line displays the case number, second line shows the number of items required at the beginning of the journey and third line shows the path according to the problem statement above. Actually, the path contains all the city/village names that Sindbad sees along his journey. Two consecutive city/village names in the path are separated by a hyphen.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4046 - Bonus Adjustment   

Description

A bonus plan is one of the most effective tools to motivate employees, therefore most companies take it seriously to decide the amount of the bonus for each employee. BonBonus is a company striving on automatic bonuses calculation software and serves many international companies. For international companies, each employee has two reporting lines, one for the regional office and the other for the functional head. And each employee's performance is based on the evaluations of the regional office and the functional head. For example, Mr. Doe is working in Taiwan office as a marketing manager, then his bonus is decided by the evaluations of Taiwan office and the marketing division in the head quarter.

Let us skip all the complicated details of the bonus calculation. The final output of the BonBonus program is a two dimensional m×n table, where each row corresponds to a region and each column corresponds to a functional coding, and the entry in ai, j is the bonus for the employee in the region i and for the function j . As usual, there is no negative bonus. Naturally, the row sums and column sums are the performance for regions and functions. Companies usually announce the performance of regions and functions while they keep the individual's bonus secret.

BonBonus was doing very well until a phone call brought the stormy bad news. A company ran the BonBonus program and happily announced the performance for each region and each function. Later, they found out that the entries in the table were not all integers, it had at most two digits after the decimal point. ``Not every country has cents! And we have already announced the performance for regions and functions," shouted at the other end of the phone line. ``Didn't you notice the fractional number problem when you announced them?" asked the BonBonus chief technology officer. ``The row sums and column sums are all integers!" replied with the mixture of anger and amusement. ``How may I help you?" explored the CTO. ``You make all the entries integers! Keep the row sums and column sums intact. And moreover, the difference between the final adjusted bonus and the true bonus must be strictly less than one! And you have 24 hours to fix the problem." That was the last sentence of the phone call. As you had expected, many companies do business in countries without cents. The phone calls rushed in and you, the guru of programming, was called in. ``You fix the problem," demanded the CTO. ``But, sir. Can it be fixed?" you asked. ``If it cannot be fixed, then you have an even bigger problem," said the CTO. You remained silent as if you were pondering. ``Fix it and you will get a bonus which will make you beyond happiness." ``Okay, sir. I will try my best." You are to write a program to solve the problem above.

Technical Specification

  1. Each company has at least 2 regions and functions and at most 50 regions and functions, i.e., 2 ≤ nm ≤ 50 .
  2. The entries for the original table are greater than or equal to zero and less than or equal to 100 with at most two digits after the decimal point, i.e., 0 ≤ aij ≤ 100 .

Input

The first line of the input file contains an integer indicating the number of test cases to follow. The first line for each test case contains two integers m n separated by a space and the following m lines contain nnumbers each. And the j -th number in the i -th line is aij

Output

Output the adjusted bonuses for each case in order. Use a space to separate each column and a line to separate each row. Or output two characters ``no" if no such adjustment exists for that case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4047 - Morning Walk   

Description

Kamal is a Motashota guy. He has got a new job in Chittagong. So, he has moved to Chittagong from Dinajpur. He was getting fatter inDinajpur as he had no work in his hand there. So, moving to Chittagong has turned to be a blessing for him. Every morning he takes a walk through the hilly roads of charming city Chittagong. He is enjoying this city very much. There are so many roads in Chittagong and every morning he takes different paths for his walking. But while choosing a path he makes sure he does not visit a road twice not even in his way back home. An intersection point of a road is not considered as the part of the road. In a sunny morning, he was thinking about how it would be if he could visit all the roads of the city in a single walk. Your task is to help Kamal in determining whether it is possible for him or not.

Input

Input will consist of several test cases. Each test case will start with a line containing two numbers. The first number indicates the number of road intersections and is denoted by N (2 ≤ N ≤ 200). The road intersections are assumed to be numbered from 0 to N-1. The second number Rdenotes the number of roads (0 ≤ R ≤ 10000). Then there will be R lines each containing two numbers c1 and c2 indicating the intersections connecting a road.

Output

Print a single line containing the text “Possible” without quotes if it is possible for Kamal to visit all the roads exactly once in a single walk otherwise print “Not Possible”.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4048 - Channel Allocation   

Description

When a radio station is broadcasting over a very large area, repeaters are used to retransmit the signal so that every receiver has a strong signal. However, the channels used by each repeater must be carefully chosen so that nearby repeaters do not interfere with one another. This condition is satisfied if adjacent repeaters use different channels. 

Since the radio frequency spectrum is a precious resource, the number of channels required by a given network of repeaters should be minimised. You have to write a program that reads in a description of a repeater network and determines the minimum number of channels required.

Input

The input consists of a number of maps of repeater networks. Each map begins with a line containing the number of repeaters. This is between 1 and 26, and the repeaters are referred to by consecutive upper-case letters of the alphabet starting with A. For example, ten repeaters would have the names A,B,C,...,I and J. A network with zero repeaters indicates the end of input. 

Following the number of repeaters is a list of adjacency relationships. Each line has the form: 

A:BCDH 

which indicates that the repeaters B, C, D and H are adjacent to the repeater A. The first line describes those adjacent to repeater A, the second those adjacent to B, and so on for all of the repeaters. If a repeater is not adjacent to any other, its line has the form 

A: 

The repeaters are listed in alphabetical order. 

Note that the adjacency is a symmetric relationship; if A is adjacent to B, then B is necessarily adjacent to A. Also, since the repeaters lie in a plane, the graph formed by connecting adjacent repeaters does not have any line segments that cross. 

Output

For each map (except the final one with no repeaters), print a line containing the minumum number of channels needed so that no adjacent channels interfere. The sample output shows the format of this line. Take care that channels is in the singular form when only one channel is required.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4049 - Halloween Costumes   

Description

Gappu has a very busy weekend ahead of him. Because, next weekend is Halloween, and he is planning to attend as many parties as he can. Since it’s Halloween, these parties are all costume parties, Gappu always selects his costumes in such a way that it blends with his friends, that is, when he is attending the party, arranged by his comic-book-fan friends, he will go with the costume of Superman, but when the party is arranged contestbuddies, he would go with the costume of ‘Chinese Postman’.

Since he is going to attend a number of parties on the Halloween night, and wear costumes accordingly, he will be changing his costumes a number of times. So, to make things a little easier, he may put on costumes one over another (that is he may wear the uniform for the postman, over the superman costume). Before each party he can take off some of the costumes, or wear a new one. That is, if he is wearing the Postman uniform over the Superman costume, and wants to go to a party in Superman costume, he can take off the Postman uniform, or he can wear a new Superman uniform. But, keep in mind that, Gappu doesn’t like to wear dresses without cleaning them first, so, after taking off the Postman uniform, he cannot use that again in the Halloween night, if he needs the Postman costume again, he will have to use a new one. He can take off any number of costumes, and if he takes off k of the costumes, that will be the last k ones (e.g. if he wears costume A before costume B, to take off A, first he has to remove B).

Given the parties and the costumes, find the minimum number of costumes Gappu will need in the Halloween night.

Input

First line contains T (T ≤ 2500), the number of test cases.

Each test case starts with two integers, N and M(1≤N,M≤100), the number of parties, and number of different types of costumes. Next line contains N integers, ci (1 ≤ ci ≤ M), the costume he will be wearing in party i. He will attend the party 1 first, then party 2, and so on.

There is a blank line before each test case.

Output

For each test case, output the minimum number of required costumes. Look at the output for sample input for details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4050 - Yahtzee   

Description

The game of Yahtzee involves 5 dice, which are thrown in 13 rounds. A score card contains 13 categories; each round may be scored in a category of the player's choosing, but each category may be scored only once in the game. The 13 categores are scored as follows:

  • ones - sum of all ones thrown
  • twos - sum of all twos thrown
  • threes - sum of all threes thrown
  • fours - sum of all fours thrown
  • fives - sum of all fives thrown
  • sixes - sum of all sixes thrown

  • chance - sum of all dice

  • three of a kind - sum of all dice, provided at least three have same value
  • four of a kind - sum of all dice, provided at least four have same value
  • five of a kind - 50 points, provided all five dice have same value
  • short straight - 25 points, provided four of the dice form a sequence (that is, 1,2,3,4 or 2,3,4,5 or 3,4,5,6)
  • long straight - 35 points, provided all dice form a sequence (1,2,3,4,5 or 2,3,4,5,6)
  • full house - 40 points, provided three of the dice are equal and the other two dice are also equal. (for example, 2,2,5,5,5)

 

Each of the last six categories may be scored as 0 if the criteria are not met.

The score for the game is the sum of all 13 categories plus a bonus of 35 points if the sum of the first six categores (ones to sixes) is 63 or greater.

Your job is to compute the best possible score for a sequence of rounds.

Input

Each line of input contains 5 integers between 1 and 6, indicating the values of the five dice thrown in each round. There are 13 such lines for each game, and there may be any number of games in the input data.

Output

Your output should consist of a single line for each game containing 15 numbers: the score in each category (in the order given), the bonus score (0 or 35), and the total score. If there is more than one categorization that yields the same total score, any one will do.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4051 - Dangerous Tunnels   

Description

Somewhere in the world, there are two tribes separated by mountains. The two tribes are named Kulolo and Gulolo, respectively, where Kulolo is at a higher altitude and Gulolo is at a lower altitude. Due to the limitation of geography, Gulolo has fewer resources than Kulolo. In order to transport resources from Kulolo to Gulolo efficiently, several tunnels were built inside the mountains between these two tribes. There are also some rest stations built for people to take a break during the transportation in the tunnels. More specifically, each terminal of a tunnel is either Kulolo, Gulolo, or a rest station.

The structure of those tunnels is not stable. A dangerous degree has been estimated for each tunnel, due to its stability, in advance. A tunnel with a higher dangerous degree is considered to be more dangerous; that is, it is more probably to collapse. Kinglolo, the chief of Kulolo, would like to select some paths through the tunnels to Gulolo with little risk. In Kinglolo's opinion, the dangerous degree of a path is equal to the maximum dangerous degree of the tunnels in the path; and the dangerous degree of a set of paths is equal to the maximum dangerous degree of the paths in it. For example, consider Figure 1. The dangerous degrees of P1, P2 , and P3 are, respectively, 3, 5, and 6. And, the dangerous degree of {P2, P3} is 6.

Since all tunnels are narrow, a limited quantity of resources can be transported along a path in one day. Therefore, every day, depending on the amount of resources needed to be transported, a different number, say k, of paths is required. Moreover, to avoid congestion, these k selected paths cannot pass any rest station in common. For example, in Figure 1, P2 and P3


Figure 1: An example.

can be selected at the same time; however, P1 and P2 cannot be selected at the same time, since they both pass r2 . Kulolo has a higher altitude than all rest stations while Gulolo has a lower altitude than all rest stations. Kinglolo is a thoughtful chief. It is ensured that the altitudes of the rest stations on each selected path are non-increasing, so that the path is more suitable for transportation. For example, in Figure 1, the path (Kulolo, r3 , r1 , Gulolo) will never be selected, since r1 is higher than r3 .

People in Kulolo believe that Kinglolo is the most brilliant man in the world, since he always selects a set of k paths that is as little dangerous as possible (i.e., the maximum dangerous degree of the selected paths is minimized). Now, given the data of the constructed tunnels, you are asked to find k paths that Kinglolo may select. In summary, the k selected paths, if exist, should satisfy the following:

1. all paths are from Kulolo to Gulolo,
2. no two paths pass the same rest station,
3. the altitudes of the rest stations on each path are non-increasing, and
4. the maximum dangerous degree of the paths is minimized.

For simplicity, only the maximum dangerous degree of the selected paths should be reported.

Technical Specification

1. The number of rest stations, n : 0 < n ≤ 200 .
2. The number of tunnels, t : t > 0 .
3. The dangerous degree of a tunnel, d : 1 ≤ d ≤ 100000 .
4. The number of paths which should be selected, k : 1 ≤ k ≤ 10.

Input

The input consists of multiple test cases. The first line of each case contains a positive integer n (0 < n ≤ 200) which indicates that there are n rest stations r1, r2,..., rn . For ease of description, Kulolo and Gulolo are denoted by r0 and rn+1 , respectively. We assume that ri is higher than rj for any 0 ≤ i < jn + 1 . The second line of each case contains a positive integer t (t > 0) that specifies the number of tunnels. Each of the following t lines contains three integers p, q, d (0 ≤ pn + 1, 0 ≤ qn + 1, pq, 1 ≤ d ≤ 100000) separated by white space, which indicate there is a tunnel with dangerous degree d connecting rp and rq . Then, a line containing a positive integer k (1 ≤ k ≤ 10) is provided, which is the number of paths that should be selected. You can assume that there is at most one tunnel between any two rest stations. The last test case is followed by a line containing a zero.

Output

For each test case, print a line containing the test case number (beginning with 1) followed by the maximum dangerous degree of the k paths that Kinglolo may select. If the solution does not exist, print ``no solution". Use the format of the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4052 - Trip Planning   

Description

You are going on a long trip. Initially, you stay at hotel 0. Along the way, there are n hotels. The only place you are allowed to stop are at these hotels. The distance from hotel i - 1 to hotel i is ai . You can choose which of the hotels you stop at. You must stop at the final hotel, which is your destination.

You would ideally like to travel 100 kilometers a day. However, this may not be possible. It depends on the spacing of the hotels. There is no limit on the distance you traveled in a day. If you travel x kilometers during a day, the penalty for that day is (x - 100)2 . You want to plan your trip so as to minimize the total penalty -- that is, the sum, over all travel days, of the daily penalty. Write a program to determine the optimal sequence of hotels at which to stop.

Input

The input file contains a set of test data. Each test data consists of two parts. The first part is the number of hotels n . The second part is a sequence of n integers a1, a2,..., an . Each ai is the distance between hotel i - 1 and hotel i . Assume that 0 < ai < 200 . They may be written in many lines. Assume that n < 1000 , and n = 0 signals the end of the test data.

Output

The first line of the output is the minimum penalty p . The second line of the output is the indexes of the hotels to stop at. If the solution is not unique, print the one with fewer stops. If there are more then one solutions with the same number of stops, print the one which is the lexicographically smallest one. For example (1 2 4) < (1 3 4) . Print 30 stops in each line, except the last line which may contain less stops. Print a blank line between datasets.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4053 - Flea circus   

Description

Sometimes, if you are searching for ladybugs, all you find are tree fleas. An old tree near the anthill serves as a home of two fleas who sometimes steal honeydew from aphids living on the tree. On the old tree, branches connect the forks (spaces where two or more branches meet) and leaves where the fleas can rest. Fleas are so small that the ants cannot see them and thus fleas are safe. Because of their size, the fleas satiate their appetite pretty quickly and then have a lot of energy to jump. They decide to jump toward each other complying with the following rules:

There is exactly one way for the fleas to go from one leaf or fork in the tree to another leaf or fork without ever turning back. Each of the fleas starts jumping along such a route to the current location of the other flea.
The fleas can only jump from one fork or leaf of the tree to another fork or leaf if they are connected by a branch.
If the two fleas land at the same time in the same place then they decide to sit and chat for quite a while.
If the two fleas land at the same time in two neighboring places on the tree (forks or leaves) then they keep jumping forever.
The input file contains multiple test cases. Each test case starts with an integer n, the number of leaves and forks in the tree, 1≤n≤5000. We assume that leaves and forks are numbered from 1 to n. Each of the following n-1 lines describe tree branches; each branch is described by two integers a and b, meaning that the branch connects the fork or leaf labeled a and the fork or leaf labeled b. In the (n+1)-st line there is one integer l, 1≤l≤500, saying how many starting positions of the fleas you are to consider for the tree. Each of the following l lines contains two positive integers (not greater than n). These numbers define the tree places in which the fleas start their jumping. Input is terminated by the case with n equal to 0.
Your program should output l lines for each test case. The i-th line for a case should look like

The fleas meet at p.

where p identifies the place where the fleas meet, or

The fleas jump forever between p and r.

where p and r are two neighboring places on the tree with p ≤ r

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




4054 - Lining Up   

Description

“How am I ever going to solve this problem?” said the pilot.

Indeed, the pilot was not facing an easy task. She had to drop packages at specific points scattered in a dangerous area. Furthermore, the pilot could only fly over the area once in a straight line, and she had to fly over as many points as possible. All points were given by means of integer coordinates in a two-dimensional space. The pilot wanted to know the largest number of points from the given set that all lie on one line. Can you write a program that calculates this number?

Your program has to be efficient!

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
The input consists of N pairs of integers, where 1 < N < 700. Each pair of integers is separated by one blank and ended by a new-line character. The list of pairs is ended with an end-of-file character. No pair will occur twice.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
The output consists of one integer representing the largest number of points that all lie on one line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4055 - Trainsorting   

Description

Erin is an engineer. She drives trains. She also arranges the cars within each train. She prefers to put the cars in decreasing order of weight, with the heaviest car at the front of the train.

Unfortunately, sorting train cars is not easy. One cannot simply pick up a car and place it somewhere else. It is impractical to insert a car within an existing train. A car may only be added to the beginning and end of the train.

Cars arrive at the train station in a predetermined order. When each car arrives, Erin can add it to the beginning or end of her train, or refuse to add it at all. The resulting train should be as long as possible, but the cars within it must be ordered by weight.

Given the weights of the cars in the order in which they arrive, what is the longest train that Erin can make?

Input

The first line is the number of test cases to follow. The test cases follow, one after another; the format of each test case is the following:

The first line contains an integer 0 <= n <= 2000, the number of cars. Each of the following n lines contains a non-negative integer giving the weight of a car. No two cars have the same weight.

Output

Output a single integer giving the number of cars in the longest train that can be made with the given restrictions.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4056 - GATTACA   

Description

The Institute of Bioinformatics and Medicine (IBM) of your country has been studying the DNA sequences of several organisms, including the human one. Before analyzing the DNA of an organism, the investigators must extract the DNA from the cells of the organism and decode it with a process called ``sequencing''.


A technique used to decode a DNA sequence is the ``shotgun sequencing''. This technique is a method applied to decode long DNA strands by cutting randomly many copies of the same strand to generate smaller fragments, which are sequenced reading the DNA bases (A, C, G and T) with a special machine, and re-assembled together using a special algorithm to build the entire sequence.


Normally, a DNA strand has many segments that repeat two or more times over the sequence (these segments are called ``repetitions''). The repetitions are not completely identified by the shotgun method because the re-assembling process is not able to differentiate two identical fragments that are substrings of two distinct repetitions.


The scientists of the institute decoded successfully the DNA sequences of numerous bacterias from the same family, with other method of sequencing (much more expensive than the shotgun process) that avoids the problem of repetitions. The biologists wonder if it was a waste of money the application of the other method because they believe there is not any large repeated fragment in the DNA of the bacterias of the family studied.


The biologists contacted you to write a program that, given a DNA strand, finds the largest substring that is repeated two or more times in the sequence.

Input

The first line of the input contains an integer T specifying the number of test cases ( 1 <= T <= 100 ). Each test case consists of a single line of text that represents a DNA sequence S of length n ( 1 <= n <= 1000 ).


You can suppose that each sequence S only contains the letters A, C, G and T.

Output

For each sequence in the input, print a single line specifying the largest substring of S that appears two or more times repeated in S , followed by a space, and the number of ocurrences of the substring in S .


If there are two or more substrings of maximal length that are repeated, you must choose the least according to the lexicographic order.


If there is no repetition in S , print ``No repetitions found!''

Sample Input  Download

Sample Output  Download

Tags




Discuss




4057 - Menu   

Description

Alfred wants to plan what to cook in the next days. He can cook various dishes. For each dish the costs of the ingredients and the benefit value is known. If a dish is cooked the second time in a row, the benefit value for the second time is 50 percent of the benefit value of first time, if it is prepared for the third or higher time in a row, the benefit value is 0. For example cooking a dish with benefit value v three times in a row leads to a total benefit value of 1.5*v.
Help him to build the menu which maximizes the benefit value under the constraint that his budget is not exceeded.

Input

The input consists of several test cases. Each test case begins with 3 integers in a line: The number of days k (1<=k<=21) Alfred wants to plan for, the number of dishes n (1<=n<=50) he can cook and his budget m (0<=m<=100).
The following n lines describe the dishes Alfred can cook. The i-th line contains two integers: the costs c (1<=c<=50) and the benefit value v (1<=v<=10000) of the i-th dish.
The end of the input is signaled by a test case with k = n = m = 0. You don't need to process this test case.

Output

For each output, print the maximum benefit value reachable with 1 digit after the decimal point. Then print k integers with i-th integer being the number of the dish to cook on day i. Dishes are numbered from 1 to n. Print at least one space or new line character after each integer.
If there are several possible menus reaching the maximum benefit value, select the one with minimum costs, if there are several with minimum costs, you can print any of them.
If every menu exceeds the budget, print only the benefit value of 0.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4058 - Count the people   

Description

Consider a square area with edge length N. The lower left corner is (0,0) and the upper right corner is (N,N). There is one person stand on each point (x,y). (0 <= x,y <= N) x and y are integers. Suppose you are the one at (0,0), please calculate the number of people you can see directly. For example, the edge length of the sqaure is 2. You can see (0,1),(1,0),(1,2),(2,1) and (1,1) directly.

Input

There are multiple test cases. The first line contains an integer T (T <= 100) which represents the number of test case. The next T lines, each line contains an interger N (0 < N <= 1000), which represents the length of the square.

Output

Please output the number of people for each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4059 - Count the people Extreme!!!!!   

Description

Consider a square area with edge length N. The lower left corner is (0, 0) and the upper right corner is (NN). There is one person stand on each point (xy). (0 ≤ xyN) x and y are integers. Suppose you are the one at (0, 0), please calculate the number of people you can see directly. For example, the edge length of the sqaure is 2. You can see (0, 1), (1, 0), (1, 2), (2, 1) and (1, 1) directly.


Input

There are multiple test cases. The first line contains an integer T (T ≤ 100) which represents the number of test case. The next T lines, each line contains an interger N (0 < N ≤ 1000000), which represents the length of the square.

Output

Please output the number of people for each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4060 - Walking on a Grid   

Description

You will be given a square grid of size N × N. The top-left square has a coordinate of (1, 1) and that of bottom-right is (N, N). Your job is to walk from (1, 1) to (N, N). Very easy, right? That’s why you have to follow some rules when walking.

  1. You can only move left, right or down.
  2. (i, j-1) is left of (i, j), (i, j+1) is right of (i, j) and (i+1, j) is down of (i, j).
  3. You can never move outside the grid.
  4. You can not step on a cell more than once.
  5. Every cell has an integer associated with it.
  6. You have to make sure the sum of integers of the path is maximized.
  7. You can step on at most k negative integers from source to destination.

Input

Each case will start with two integers N and k. N ≤ 75 and k ≤ 5. Each of the next N lines will contain N integers each given in row major order. That is, the first integer of the first row is (1, 1) and the last integer of last row is (N, N). Input terminates with two zeros on a line.

Output

For every case output the case number. If it’s not possible to reach the destination meeting the above rules then output “impossible”, else print the maximum sum of integers of the path.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4061 - My T-shirt suits me   

Description

Our friend Victor participates as an instructor in an environmental volunteer program. His boss asked Victor to distribute N T-shirts to M volunteers, one T-shirt each volunteer, where N is multiple of six, and N>=M. There are the same number of T-shirts of each one of the six available sizes: XXL, XL, L, M , S, and XS. Victor has a little problem because only two sizes of the T-shirts suit each volunteer.


You must write a program to decide if Victor can distribute T-shirts in such a way that all volunteers get a T-shirt that suit them. If N != M, there can be some remaining T-shirts.

Input

The first line of the input contains the number of test cases. For each test case, there is a line with two numbers N and M. N is multiple of 6, 1<=N<=36, and indicates the number of T-shirts. Number M, 1<=M<=30, indicates the number of volunteers, with N>=M. Subsequently, M lines are listed where each line contains, separated by one space, the two sizes that suit each volunteer (XXL, XL, L, M , S, or XS).

Output

For each test case you are to print a line containing YES if there is, at least, one distribution where T-shirts suit all volunteers, or NO, in other case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4062 - Right triangle pool   

Description

Mirko and Slavko have built a grand new pool in front of their weekend getaway.
The pool is an isosceles right triangle, with legs of length 250.


Everything was perfect, girls were coming, the DJ was coming, and the parties were wild.
But, a problem arose when they started serving food at the parties. Mirko is vegetarian, while Slavko thinks a party without sausages is no party at all. Therefore they had to divide the pool into two parts.
The pool is placed into a coordinate system (as in the figure above) and divided into two parts of equal area by a line segment with both endpoints on the edges of the pool.
Write a program that, given one endpoint of the dividing line segment, calculates the coordinates of the other endpoint.

Input

Each case contains two integers, the coordinates of one endpoint of the dividing line segment.
That point will be on one of the edges of the pool.

Output

Output the coordinates of the other endpoint, rounded to two decimal digits.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4063 - Mister George visit   

Description

Last week Mister George visited Croatia. Since Mister George is a very important person, while he was in a street, the police disallowed entry to that street, but vehicles that entered the street before Mister George could continue driving.
While Mister George was visiting, Luka drove his truck around town. But because of some of the streets being closed off, he couldn't make his delivery in time and almost lost his job. Although it is late  now, he is wondering how he could have planned his delivery better i.e. what would have been the least time needed to make his delivery while Mister George was visiting. He knows the route mister George took.
The city is modeled with intersections and two-way streets connecting them. For each street, Luka knows how much time he needs to traverse it (mister George needs the same amount of time).
For example, if Mister George starts traversing a street during minute 10 and needs 5 minutes to exit it, this street will be blocked during minutes 10, 11, 12, 13 and 14. Luka can enter the street during minutes 9 and earlier, or 15 and later.
Write a program that calculates the least amount of time Luka needs to make his delivery, if he starts driving K minutes after the arrival of Mister George .

Input

For each case,the first line contains two integers N and M (2 ≤ N ≤ 1000, 2 ≤ M ≤ 10 000), the number of intersections and the number of streets. The intersections are numbered 1 to N.
The second line contains four integers A, B, K and G (1 ≤ A, B ≤ N, 0 ≤ K ≤ 1000, 0 ≤ G ≤ 1000).
These are, in order:
· The intersection where Luka starts;
· The intersection Luka must get to;
· The difference in starting times between mister George and Luka (Luka starts at intersection A exactly K minutes after mister George starts his route);
· The number of intersections on Mister George's route.
The third line contains G integers, the labels of intersections mister George will visit. Every pair of adjacent integers denotes a street he will traverse. That street will exist and Mister George will traverse every street at most once.
Each of the following M lines contains three integers A, B and L, meaning that there is a street between intersection A and B, and it takes L minutes to traverse. L will be between 1 and 1000.

Output

Output the least amount of time (in minutes) Luka needs to make his delivery.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4064 - Attractive game   

Description

In the nearby kindergarten they recently made up an attractive game of strength and agility that kids love.
The surface for the game is a large flat area divided into N×N squares.
The children lay large spongy cues onto the surface. The sides of the cubes are the same length as the sides of the squares. When a cube is put on the surface, its sides are aligned with some square. A cube may be put on another cube too.
Kids enjoy building forts and hiding them, but they always leave behind a huge mess. Because of this, prior to closing the kindergarten, the teachers rearrange all the cubes so that they occupy a rectangle on the surface, with exactly one cube on every square in the rectangle.
In one moving, a cube is taken off the top of a square to the top of any other square.
Write a program that, given the state of the surface, calculates the smallest number of moves needed to arrange all cubes into a rectangle.

Input

The first line contains the integers N and M (1 ≤ N ≤ 100, 1 ≤ M ≤ N2), the dimensions of the surface and the number of cubes currently on the surface.
Each of the following M lines contains two integers R and C (1 ≤ R, C ≤ N), the coordinates of the square that contains the cube.

Output

Output the smallest number of moves. A solution will always exist.

 

In the first example, it suffices to move one of the cubes from (1, 1) to (1, 2) or (2, 1).
In the third example, a cube is moved from (2, 3) to (3, 3), from (4, 2) to (2, 5) and from (4, 4) to (3, 5).

Sample Input  Download

Sample Output  Download

Tags




Discuss




4065 - Points in Figures: Rectangle   

Description

Given a list of rectangles and a list of points in the x-y plane, determine for each point which figures (if any) contain the point.

Input

There will be n( <=10) rectangles descriptions, one per line. The first character will designate the type of figure (``r'' for rectangle). This character will be followed by four real values designating the x-y coordinates of the upper left and lower right corners.

The end of the list will be signalled by a line containing an asterisk in column one.

The remaining lines will contain the x-y coordinates, one per line, of the points to be tested. The end of this list will be indicated by a point with coordinates 9999.9 9999.9; these values should not be included in the output.

Points coinciding with a figure border are not considered inside.

 

Output

For each point to be tested, write a message of the form:

Point i is contained in figure j
for each figure that contains that point. If the point is not contained in any figure, write a message of the form:
Point i is not contained in any figure
Points and figures should be numbered in the order in which they appear in the input.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4066 - Fortune Card Game   

Description

A popular card game called ``fortune" is getting popular in country X. Fig. 1 shows one of the cards. In each card, a positive integer number (20 in the figure) is listed as the address of the card. A symbol is drawn beside the address. There are five kinds of symbols, which are listed below the card. For convenience, let each symbol be represented by an English letter from `A'-`E'. The bottom of a card contains another number called ``next fortune number."



Figure 1: A sample fortune card and symbols.
In a set of fortune cards, many cards can have same address; that is, address 20 is not limited to appear only in one card. However, there will be no cards that are identical, i.e., no two cards with same address, symbol, and next fortune number.

The fortune card game is played as follows. A player starts with cards that have address 1. The goal of the game is trying to complete a ``spell" that is composed by the symbols. For example, let a spell be ``BADDAD". In the first move, the player will look for cards that have address 1 with a star symbol (which matches `B' in the spell). The next fortune numbers of these cards are the new addresses for the next move. The player can select one card to advance to a new address x. The selected card is then put back to the cards for next move but the fortune number is written down.

Let the example be continued. In the next move, the player needs to look for the cards that have new address x with the cross symbol (which matches the second `A' in the spell). Again, the player selects one card to advance to another new address. This procedure continues until the spell ``BADDAD" is completed. Once the player completes a spell, he wins a score by adding all the next fortune numbers of the selected card, which have been written down.

Given a spell and a set of fortune cards, please output the maximum score that can be played in this card game.


Technical Specification


N - the number of test cases, N10 .
C - the number of cards, C800 .
L - the length of a spell, L150 .

Input

Test data begins with an integer N which is the number of test cases. Each test case begins with an integer C , which is the number of cards. Following the number C is C lines of card information. Each card is represented by (Address Symbol NextF ortuneNumber). The address and next fortune number are between 1 and 800. The symbols are capital letters from `A' to `E'. The last line of a test case is a spell. The spell is a string composed by capital letters from `A' to `E'. The length of the spell (L ) is less than 150.

Output

For each test case, please output the maximum score that can be collected for each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4067 - Trip Planning   

Description

You are going on a long trip. Initially, you stay at hotel 0. Along the way, there are n hotels. The only place you are allowed to stop are at these hotels. The distance from hotel i - 1 to hotel i is ai . You can choose which of the hotels you stop at. You must stop at the final hotel, which is your destination.

You would ideally like to travel 100 kilometers a day. However, this may not be possible. It depends on the spacing of the hotels. There is no limit on the distance you traveled in a day. If you travel x kilometers during a day, the penalty for that day is (x - 100)2 . You want to plan your trip so as to minimize the total penalty -- that is, the sum, over all travel days, of the daily penalty. Write a program to determine the optimal sequence of hotels at which to stop.

Input

The input file contains a set of test data. Each test data consists of two parts. The first part is the number of hotels n . The second part is a sequence of n integers a1, a2,..., an . Each ai is the distance between hotel i - 1 and hotel i . Assume that 0 < ai < 200 . They may be written in many lines. Assume that n < 1000 , and n = 0 signals the end of the test data.

Output

The first line of the output is the minimum penalty p . The second line of the output is the indexes of the hotels to stop at. If the solution is not unique, print the one with fewer stops. If there are more then one solutions with the same number of stops, print the one which is the lexicographically smallest one. For example (1 2 4) < (1 3 4) . Print 30 stops in each line, except the last line which may contain less stops. Print a blank line between datasets.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4068 - Squares   

Description

For any positive integer N , N = a1$scriptstyle wedge$2 + a2$scriptstyle wedge$2 +...+ an$scriptstyle wedge$2 that is, any positive integer can be represented as sum of squares of other numbers.

Your task is to print the smallest `n ' such that N = a1$scriptstyle wedge$2 + a2$scriptstyle wedge$2 +...+ an$scriptstyle wedge$2 .

Input

The first line of the input will contain an integer `t ' which indicates the number of test cases to follow.

Each test case will contain a single integer `N ' (1$ le$N$ le$10000) on a line by itself.

Output

Print an integer which represents the smallest `n ' such that

N = a1$scriptstyle wedge$2 + a2$scriptstyle wedge$2 +...+ an$scriptstyle wedge$2 .

 


Explanation for sample test cases:

 


5 - > number of test cases

1 = 1$scriptstyle wedge$2 (1 term)

2 = 1$scriptstyle wedge$2 + 1$scriptstyle wedge$2 (2 terms)

3 = 1$scriptstyle wedge$2 + 1$scriptstyle wedge$2 + 1$scriptstyle wedge$2 (3 terms)

1 = 2$scriptstyle wedge$2 (1 term)

2 = 5$scriptstyle wedge$2 + 5$scriptstyle wedge$2 (2 terms)

Sample Input  Download

Sample Output  Download

Tags




Discuss




4069 - The Swallowing Ground   

Description

Now that the wicked is punished, there is still work to do. For example, the ground needs to seal itself up. (Otherwise, good people will accidentally fall into Hell, which is not good.)

The ground swallowed Don Giovanni by collapsing: Part of the ground collapsed--fell off to Hell--and this created a gap that swallowed Don Giovanni. The only way the ground can be fixed is by sliding landmasses to close up the gap. Here is an example. The left diagram shows the ground with a ravine. Assume that the ground extends infinitely to the north and to the south, and there are seams on the east and west ends; so the northern block can slide southward, and the southern block can slide northward. The right diagram shows the gap closed.

tex2html_wrap220

Here is another example. The ravine in the left diagram cannot be closed perfectly by sliding the ground northward and southward. The right diagram shows the result of the best effort: there is still a hole.

tex2html_wrap222

Write a program to determine if the gap can be closed. The ground is a grid with rows (a row runs east-west) and columns (a column runs north-south). Holes are cells on the grid, and the gap consists of holes.

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

The first line contains the number of columns W of the ground to be considered. Then W lines follow, specifying the boundary of the gap by columns: a line represents a column, and the order of the lines follows the east-to-west order. Each line contains tex2html_wrap_inline228, the north-most row of the gap in this column, and tex2html_wrap_inline230, the south-most row of the gap in this column. Row numbers are integers between -100 and 100 inclusive.

The input specifies a valid gap: the holes separate the ground into exactly a northern block and a southern block. There are no holes embedded inside a block. There are no islands.

Note:The sample input below corresponds to the first diagram.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.

Output the line

yes

if the gap can be closed by sliding blocks north and south; and

no

otherwise.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4070 - Mapmaker   

Description

The Cybersoft Computer Company (a leader in programming languages) has hired you to work on a new programming language named A--. Your task is to work on the array mapping tasks of the language. You will take an array reference such as x[5,6] and map it to an actual physical address. In preparation for doing this, you will write a program that will read in several array declarations and references and give the physical address of each reference. The physical address output by the program should be an integer number in base 10.

 

The physical address of an array reference tex2html_wrap_inline34 is calculated from the formula tex2html_wrap_inline36 , where the constants tex2html_wrap_inline38 are calculated as specified below.

 

 

tabular20

Input

The first line of the input file contains two positive integers. The first integer specifies N, the number of arrays defined in the data file, and the second integer specifies R, the number of array references for which addresses should be calculated. The next N lines each define an array, one per line, and the following R lines contain one array reference per line for which an address should be calculated.

 

Each line which defines an array contains, in the following order, the name of the array (which is limited to 10 characters), a positive integer which specifies the base address of the array, a positive integer which specifies the size in bytes of each array element, and D, the number of dimensions in the array (no array will have fewer than 1 or more than 10 dimensions). This is followed on the same line by D pairs of integers which represent the lower and upper bounds, respectively, of dimensions tex2html_wrap_inline90 of the array.

 

Each line which specifies an array reference contains the name of the array followed by the integer indexes tex2html_wrap_inline92 where D is the dimension of the array.

Output

The output file should contain the array references and the physical addresses. There should be one array reference and physical address per line. The formatting guidelines below must be adhered to.

 

For each line of output:

 

  1. Output the name of the array
  2. Output a left square bracket
  3. Output each index value (each pair of indexes should have a single comma and space between them)
  4. Output a right square bracket, a space, an equal sign, and another space
  5. Output the physical address


Sample Input  Download

Sample Output  Download

Tags




Discuss




4071 - Cantor Fractions   

Description

Background

   In the late XIXth century the German mathematician George Cantor argued that the set of positive fractions Q+ is equipotent to the set of positive integers N, meaning that they are both infinite, but of the same class. To justify this, he exhibited a mapping from N to Q+ that is onto. This mapping is just traversal of the N x N plane that covers all the pairs:


   The first fractions in the Cantor mapping are:


Problem

   Write a program that finds the i-th Cantor fraction following the mapping outlined above.

Input

   The inputs consists of several lines with a positive integer number i each one.

Output

   The output consists of a line per input case, that contains the i-th fraction, with numerator and denominator separed by a slash (/). The fraction should not be in the most simple form.

Sample Input  Download

Sample Output  Download

Tags




Discuss




4072 - Hotel booking   

Description

A transport company often needs to deliver goods from one city to another city. The transport company has made a special deal with a hotel chain which allows its drivers to stay in the hotels of this chain for free. Drivers are only allowed to drive up to 10 hours a day. The transport company wants to find a route from the starting city to the destination city such that a driver can always spend the night in one of the hotels of the hotel chain, and that he needs to drive at most 10 hours from one hotel to the next hotel (or the destination). Of course, the number of days needed to deliver the goods should also be minimized.

Input

The input file contains several test cases. Each test case starts with a line containing an integer n, (2 ≤ n ≤ 10000), the number of cities to be considered when planning the route. For simplicity, cities are numbered from 1 to n, where 1 is the starting city, and n is the destination city. The next line contains an integer h followed by the numbers c1, c2, ..., ch indicating the numbers of the cities where hotels of the hotel chain are located. You may assume that 0 ≤ h ≤ min(n, 100). The third line of each test case contains an integer m (1 ≤ m ≤ 105), the number of roads to be considered for planning the route. The following m lines describe the roads. Each road is described by a line containing 3 integers a, b, t (1 ≤ a, b ≤ n and 1 ≤ t ≤ 600), where a, b are the two cities connected by the road, and t is the time in minutes needed by the driver to drive from one end of the road to the other. Input is terminated by n = 0.

Output

For each test case, print one line containing the minimum number of hotels the transport company has to book for a delivery from city 1 to city n. If it is impossible to find a route such that the driver has to drive at most 10 hours per day, print -1 instead.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5000 - Pi   

Description

Professor Robert A. J. Matthews of the Applied Mathematics and Computer Science Department at the University of Aston in Birmingham, England has recently described howthe positions of stars across the night skymay be used to deduce a surprisingly accurate value of π. This result followed from the application of certain theorems in number theory.

Here, we don'thave the night sky, but can use the same theoretical basis to form an estimate for π

Given any pair of whole numbers chosen from a large, random collection of numbers, the probability that the twonumbers have no common factor other than one (1) is 6/π2

For example, using the small collection of numbers: 2, 3, 4, 5, 6; there are 10 pairs that can be formed: (2,3), (2,4), etc. Six of the 10 pairs: (2,3), (2,5), (3,4), (3,5), (4,5) and (5,6) have no common factor other than one. Using the ratio of the counts as the probability we have:

6/π~ 6/10

π ~ 3.162

In this problem, you'll receive a series of data sets. Each data set contains a set of pseudo-random positive integers. For each data set, find the portion of the pairs which may be formed that have nocommon factor other than one (1), and use the method illustrated above to obtain an estimate for π. Report this estimate for each data set.

Input

The input consists of a series of data sets.

The first line of each data set contains a positive integer value, N, greater than one (1) and less than 50.

There is one positive integer per line for the next N lines that constitute the set for which the pairs are to be examined. These integers are each greater than 0 and less than 32768.

Each integer of the input stream has its first digit as the first character on the input line.

The set size designator, N, will be zero to indicate the end of data.

Output

A line with a single real value is to be emitted for each input data set encountered. This value is the estimate for π for the data set. An output format like the sample below should be used. Answers must be rounded to six digits after the decimal point.

For some data sets, it may be impossible to estimate a value for π. This occurs when there are no pairs without common factors. In these cases, emit the single-line message:

No estimate for this data set.

Exactly, starting with the first character, "N", as the first character on the line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5001 - Play with Floor and Ceil   

Description

For any two integers x and k there exists two more integers p and q such that:


It’s a fairly easy task to prove this theorem, so we’d not ask you to do that. We’d ask for something even easier! Given the values of x and k, you’d only need to find integers p and q that satisfies the given equation. 

Input

The first line of the input contains an integer, T (1≤T≤1000) that gives you the number of test cases. In each of the following T lines you’d be given two positive integers x and k. You can safely assume that x and k will always be less than 108.

Output

For each of the test cases print two integers: p and q in one line. These two integers are to be separated by a single space. If there are multiple pairs of p and q that satisfy the equation, any one would do. But to help us keep our task simple, please make sure that the values,  and fit in a 64 bit signed integer.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5002 - Minesweeper   

Description

Have you ever played Minesweeper? It's a cute little game which comes within a certain Operating System which name we can't really remember. Well, the goal of the game is to find where are all the mines within a MxN field. To help you, the game shows a number in a square which tells you how many mines there are adjacent to that square. For instance, supose the following 4x4 field with 2 mines (which are represented by an * character):

*...
....
.*..
....

If we would represent the same field placing the hint numbers described above, we would end up with:

*100
2210
1*10
1110

As you may have already noticed, each square may have at most 8 adjacent squares.

Input

The input will consist of an arbitrary number of fields. The first line of each field contains two integers n and m (0 < n,m <= 100) which stands for the number of lines and columns of the field respectively. The next n lines contains exactly m characters and represent the field. Each safe square is represented by an "." character (without the quotes) and each mine square is represented by an "*" character (also without the quotes). The first field line where n = m = 0 represents the end of input and should not be processed.

Output

For each field, you must print the following message in a line alone:

Field #x:

Where x stands for the number of the field (starting from 1). The next n lines should contain the field with the "." characters replaced by the number of adjacent mines to that square. There must be an empty line between field outputs.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5003 - Knight Moves   

Description

A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.

Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.

Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.

Input

The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.

Output

For each test case, print one line saying "To get from xx to yy takes n knight moves.".

Sample Input  Download

Sample Output  Download

Tags




Discuss




5004 - Odd Sum   

Description

Given a range [a, b], you are to find the summation of all the odd integers in this range. For example, the summation of all the odd integers in the range [3, 9] is 3 + 5 + 7 + 9 = 24.

Input

There can be at multiple test cases. The first line of input gives you the number of test cases, T ( 1<=T<=100). Then T test cases follow. Each test case consists of 2 integers a and b ( 0<=a<=b<=100) in two separate lines.

Output

For each test case you are to print one line of output - the serial number of the test case followed by the summation of the odd integers in the range [a, b].

Sample Input  Download

Sample Output  Download

Tags




Discuss




5005 - You can say 11   

Description

Your job is, given a positive number N, determine if it is a multiple of eleven.

Input

The input is a file such that each line contains a positive number. A line containing the number 0 is the end of the input. The given numbers can contain up to 1000 digits.

Output

The output of the program shall indicate, for each input number, if it is a multiple of eleven or not.

Sample Input  Download

Sample Output  Download

Tags

5005



Discuss




5006 - All in All   

Description

You have devised a new encryption technique which encodes a message by inserting between its characters randomly generated strings in a clever way. Because of pending patent issues we will not discuss in detail how the strings are generated and inserted into the original message. To validate your method, however, it is necessary to write a program that checks if the message is really encoded in the final string.

Given two strings s and t, you have to decide whether s is a subsequence of t, i.e. if you can remove characters from t such that the concatenation of the remaining characters is s.

Input

The input contains several testcases. Each is specified by two strings s, t of alphanumeric ASCII characters separated by whitespace and the lengths of s, t are less than 100,000. Input is terminated by EOF.

Output

For each test case output, if s is a subsequence of t.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5007 - Ternary   

Description

You will be given a decimal number. You will have to convert it to its ternary (Base 3) equivalent.

Input

The input file contains at most 100 lines of inputs. Each line contains a non-negative decimal integer N(N<1,000,000,001). Input is terminated by a line containing a negative value. This line should not be processed.

Output

For each line of input produce one line of output. This line contains the ternary equivalent of decimal value N.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5008 - Triangle Wave   

Description

In this problem you are to generate a triangular wave form according to a specified pair of Amplitude and Frequency.

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

Each input set will contain two integers, each on a separate line. The first integer is the Amplitude; the second integer is the Frequency.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.

For the output of your program, you will be printing wave forms each separated by a blank line. The total number of wave forms equals the Frequency, and the horizontal ``height'' of each wave equals the Amplitude. The Amplitude will never be greater than nine.

The waveform itself should be filled with integers on each line which indicate the ``height'' of that line.

NOTE: There is a blank line after each separate waveform, excluding the last one.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5009 - The jackpot   

Description

As Manuel wants to get rich fast and without too much work, he decided to make a career in gambling. Initially, he plans to study the gains and losses of players, so that, he can identify patterns of consecutive wins and elaborate a win-win strategy. But Manuel, as smart as he thinks he is, does not know how to program computers. So he hired you to write programs that will assist him in elaborating his strategy.

Your first task is to write a program that identifies the maximum possible gain out of a sequence of bets. A bet is an amount of money and is either winning (and this is recorded as a positive value), or losing (and this is recorded as a negative value).

Input

The input set consists of a positive number N ≤ 10000 , that gives the length of the sequence, followed by N integers. Each bet is an integer greater than 0 and less than 1000.

The input is terminated with N = 0.

Output

For each given input set, the output will echo a line with the corresponding solution. If the sequence shows no possibility to win money, then the output is the message "Losing streak."

Sample Input  Download

Sample Output  Download

Tags




Discuss




5010 - Hashmat the brave warrior   

Description

 Hashmat is a brave warrior who with his group of young soldiers moves from one place to another to fight against his opponents. Before fighting he just calculates one thing, the difference between his soldier number and the opponent's soldier number. From this difference he decides whether to fight or not. Hashmat's soldier number is never greater than his opponent.

Input

The input contains two integer numbers in every line. These two numbers in each line denotes the number of soldiers in Hashmat's army and his opponent's army or vice versa. The input numbers are not greater than 232. Input is terminated by End of File.

Output

 For each line of input, print the difference of number of soldiers between Hashmat's army and his opponent's army. Each output should be in seperate line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5011 - Zeros and Ones   

Description

Given a string of 0's and 1's up to 1000000 characters long and indices i and j, you are to answer a question whether all characters between position min(i,j) and position max(i,j) (inclusive) are the same.

Input

There are multiple cases on input. The first line of each case gives a string of 0's and 1's. The next line contains a positive integer n giving the number of queries for this case. The next n lines contain queries, one per line. Each query is given by two non-negative integers, i and j. For each query, you are to print Yes if all characters in the string between position min(i,j) and position max(i,j) are the same, and No otherwise.

Output

Each case on output should start with a heading as in the sample below. The input ends with an empty string that is a line containing only the new line character, this string should not be processed. The input may also with end of file. So keep check for both.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5012 - Maximum Sum   

Description

A problem that is simple to solve in one dimension is often much more difficult to solve in more than one dimension. Consider satisfying a boolean expression in conjunctive normal form in which each conjunct consists of exactly 3 disjuncts. This problem (3-SAT) is NP-complete. The problem 2-SAT is solved quite efficiently, however. In contrast, some problems belong to the same complexity class regardless of the dimensionality of the problem.

 Given a 2-dimensional array of positive and negative integers, find the sub-rectangle with the largest sum. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. A sub-rectangle is any contiguous sub-array of size tex2html_wrap_inline33 or greater located within the whole array. As an example, the maximal sub-rectangle of the array:

displaymath35

 

is in the lower-left-hand corner:

displaymath37

 

and has the sum of 15.

Input

The input consists of an tex2html_wrap_inline39 array of integers. The input begins with a single positive integer N on a line by itself indicating the size of the square two dimensional array. This is followed by tex2html_wrap_inline43 integers separated by white-space (newlines and spaces). These tex2html_wrap_inline43 integers make up the array in row-major order (i.e., all numbers on the first row, left-to-right, then all numbers on the second row, left-to-right, etc.). N may be as large as 100. The numbers in the array will be in the range [-127, 127].

Output

The output is the sum of the maximal sub-rectangle.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5013 - Grade List   

Description

ATH is the TA of algorithm course. In the end of semester, Professor Wang send him a text file with homework and exam grades and some information of students(i.e. student id, name, gender, etc...). However, he just want to sum up the grades of homework and exam to evaluate the final score.

This work is a piece of cake for him, but he is too busy to finish this work. Thus, he decided to let you write this program for him.

Input

Each line represents the information of a student and each information will be seperated by one or more spaces. The information of first two columns are the grades of homework and exam, and there are at most 1000 characters in a line.

Output

For each line of inputs, print " Student #i: j" without quotes. Where i is the index (start from 1) of students, and j is the final score of such student.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5014 - Month Bill   

Description

Tiyano is a master student and he does many part-time jobs in order to earn his pocket money. However, earning money is too hard, he figured out that control the money usage of each day is a good way for saving money. He listed the costs of each day and he bought at most 5 items per day. Now, he needs to calculate the total cost for each day.
Unfortunately, Tiyano is a lazy TA, so he wants to use this exercise to get the answer from you.

Input

For each line in the test case represents the costs of items in a day and there are at most 5 items in a day.

Output

For each line, print the "Day i: j" for each day, where i is the number of day (start from 1) and j is the total cost of such day.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5015 - Average   

Description

Calculating the average is an easy work, but how many digits after decimal point need to show is an annoying problem.

SSLin is another TA of algorithm course, and his professor might want to see the average of grades with 5 digits after decimal point, and before submit grades to online system, the average of grades need to round to integer for convenience. 

SSLin do not want to calculate the average again and again. Therefore, he asks Tiyano to write a program to calculate the average grade after given x digits after decimal. However, everyone knows that Tiyano is very very lazy, he also puts this problem into execrise and waiting for your answer.

Input

The first line has a number T which is the total number of testcase

For each testcase, there are 2 values n <= 1000 represents the number of scores and 0 <= x <= 12 is the digits after decimal point of average in output. 

And the following line contains n scores range from 0 to 100.

Output

For each testcase, print the average value rounding to x digits after decimal point in a line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5016 - Poker   

Description

Stud is a popular poker gamble and TPC get a Poker Online Game project from Gamanix Company.

In this game, each player have 5 cards, and they do the gambling by comparing the combination type of cards.

Your job is writing a program to determine what kind of combination types for someone's cards.

There are the rules of combination types

1.Straight Flush  (同花順)  五張的花色相同且五張的點數是連續的或AKOJT
2.Four of a Kind  (四條)    有四張點數相同
3.Full House       (葫蘆)    有三張點數相同且另兩張點數相同
4.Flush          (同花)    五張的花色相同
5.Straight      (順子)    五張的點數是連續的或AKOJT
6.Three of a Kind (三條)    有三張點數相同
7.Two Pairs      (兩對)    有兩對兩張點數相同
8.Pair          (一對)    有兩張點數相同
9 Zilch      (散牌)    沒有任何特殊牌型

Input

The first line of the input will contains an integer T (1<=T<=100) represent the number of testcase. The next T lines will contains five cards in each line. Cards are represented as a two character code. The the first character is the suit (C=Clubs, D=Diamonds, H=Hearts, S=Spades), and the second character is the face-value (A=Ace, 2-9, T=10, J=Jack, Q=Queen, K=King) .

Output

For each line of the five cards, please output the type of the cards.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5017 - ``Accordian'' Patience   

Description

You are to simulate the playing of games of ``Accordian'' patience, the rules for which are as follows:

 

Deal cards one by one in a row from left to right, not overlapping. Whenever the card matches its immediate neighbour on the left, or matches the third card to the left, it may be moved onto that card. Cards match if they are of the same suit or same rank. After making a move, look to see if it has made additional moves possible. Only the top card of each pile may be moved at any given time. Gaps between piles should be closed up as soon as they appear by moving all piles on the right of the gap one position to the left. Deal out the whole pack, combining cards towards the left whenever possible. The game is won if the pack is reduced to a single pile.

Situations can arise where more than one play is possible. Where two cards may be moved, you should adopt the strategy of always moving the leftmost card possible. Where a card may be moved either one position to the left or three positions to the left, move it three positions.

Input

Input data to the program specifies the order in which cards are dealt from the pack. The input contains pairs of lines, each line containing 26 cards separated by single space characters. The final line of the input file contains a # as its first character. Cards are represented as a two character code. The first character is the face-value (A=Ace, 2-9, T=10, J=Jack, Q=Queen, K=King) and the second character is the suit (C=Clubs, D=Diamonds, H=Hearts, S=Spades).

Output

One line of output must be produced for each pair of lines (that between them describe a pack of 52 cards) in the input. Each line of output shows the number of cards in each of the piles remaining after playing ``Accordian patience'' with the pack of cards as described by the corresponding pairs of input lines.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5018 - Prime Number Testing   

Description

There are many useful application of prime numbers. Determine whether a number is a prime number is an important job! Please write a program to check a positive interger N is a prime number or not.

Input

The input file contains several cases. Each case will be on a line by itself and will consist of a number N (2 <= N <= 2^31-1). The input ends with a 0 on a single line. Please do not do any output for this number.

Output

Please print "YES" (without quote) if N is a pirme number, otherwise print "NO" (without quote).

Sample Input  Download

Sample Output  Download

Tags




Discuss




5019 - How many primes?   

Description

Now, your task is to calculate the numbers of the prime numbers between 1 and an integer N.

Input

The input file contains several cases. The first line contains an integer T ( 1 <= T <= 1,000) represent the number of cases. The next T lines, there will be an integer N ( 1 <= N <= 1,000,000) on a single line.

Output

Please output the number of prime numbers between 1 and N.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5020 - Prime Words   

Description

A prime number is a number that has only two divisors: itself and the number one. Examples of prime numbers are: 1, 2, 3, 5, 17, 101 and 10007.

In this problem you should read a set of words, each word is composed only by letters in the range a-z and A-Z. Each letter has a specific value, the letter a is worth 1, letter b is worth 2 and so on until letter z that is worth 26. In the same way, letter A is worth 27, letter B is worth 28 and letter Z is worth 52.

You should write a program to determine if a word is a prime word or not. A word is a prime word if the sum of its letters is a prime number.

Input

The input consists of a set of words. Each word is in a line by itself and has L letters, where 1 ≤ L ≤ 20. The input is terminated by enf of file (EOF).

Output

For each word you should print: It is a prime word., if the sum of the letters of the word is a prime number, otherwise you should print: It is not a prime word..

Sample Input  Download

Sample Output  Download

Tags




Discuss




5021 - Prime Distance   

Description

The branch of mathematics called number theory is about properties of numbers. One of the areas that has captured the interest of number theoreticians for thousands of years is the question of primality. A prime number is a number that is has no proper factors (it is only evenly divisible by 1 and itself). The first prime numbers are 2,3,5,7 but they quickly become less frequent. One of the interesting questions is how dense they are in various ranges. Adjacent primes are two numbers that are both primes, but there are no other prime numbers between the adjacent primes. For example, 2,3 are the only adjacent primes that are also adjacent numbers.

Your program is given 2 numbers: L and U (1<=L

Input

Each line of input will contain two positive integers, L and U, with L < U. The difference between L and U will not exceed 1,000,000.

Output

UFor each L and U, the output will either be the statement that there are no adjacent primes (because there are less than two primes between the two given numbers) or a line giving the two pairs of adjacent primes.

Sample Input  Download

Sample Output  Download

Tags




Discuss




5022 - Prime Factors   

Description

Webster defines prime as:

 


prime (prim) n.[ME, fr. MF, fem. of prin first, L primus; akin to L prior] 1 :first in time: original 2 a : having no factor except itself and one $langle$3 is a   number $
angle$ b : having no common factor except one $langle$ 12 and 25 are relatively  $
angle$ 3 a : first in rank, authority or significance : principal b : having the highest quality or value $langle$  television time $
angle$ [from Webster's New Collegiate Dictionary]

 


The most relevant definition for this problem is 2a: An integer g>1 is said to be prime if and only if its only positive divisors are itself and one (otherwise it is said to be composite). For example, the number 21 is composite; the number 23 is prime. Note that the decompositon of a positive number g into its prime factors, i.e.,

egin{displaymath}g = f_1 	imes f_2 	imes dots 	imes f_n
end{displaymath}


is unique if we assert that fi > 1 for all i and $f_i le f_j$ for i<j.

One interesting class of prime numbers are the so-called Mersenne primes which are of the form 2p- 1. Euler proved that 231 - 1 is prime in 1772 -- all without the aid of a computer.

Input

vaThe input will consist of a sequence of numbers. Each line of input will contain one number g in the range -231 < g <231, but different of -1 and 1. The end of input will be indicated by an input line having a value of zero.

Output

For each line of input, your program should print a line of output consisting of the input number and its prime factors. For an input number $g>0, g = f_1 	imes f_2 	imes
dots 	imes f_n$, where each fi is a prime number greater than unity (with $f_i le f_j$ for i<j), the format of the output line should be


egin{displaymath}g mbox{	t = } f_1 mbox{	t x } f_2 mbox{	t x } dots mbox{	t x } f_n
end{displaymath}


When g < 0, if $ mid g mid = f_1 	imes f_2 	imes dots 	imes f_n$, the format of the output line should be

egin{displaymath}g mbox{	t = -1 x } f_1 mbox{	t x } f_2 mbox{	t x } dots
mbox{	t x } f_n
end{displaymath}


Sample Input  Download

Sample Output  Download

Tags




Discuss




6001 - Send a Table   

Description

When participating in programming contests, you sometimes face the following problem: You know how to calcutale the output for the given input values, but your algorithm is way too slow to ever pass the time limit. However hard you try, you just can't discover the proper break-off conditions that would bring down the number of iterations to within acceptable limits.

Now if the range of input values is not too big, there is a way out of this. Let your PC rattle for half an our and produce a table of answers for all possible input values, encode this table into a program, submit it to the judge, et voila: Accepted in 0.000 seconds! (Some would argue that this is cheating, but remember: In love and programming contests everything is permitted).

Faced with this problem during one programming contest, Jimmy decided to apply such a 'technique'. But however hard he tried, he wasn't able to squeeze all his pre-calculated values into a program small enough to pass the judge. The situation looked hopeless, until he discovered the following property regarding the answers: the answers where calculated from two integers, but whenever the two input values had a common factor, the answer could be easily derived from the answer for which the input values were divided by that factor. To put it in other words:

Say Jimmy had to calculate a function Answer(x, y) where x and y are both integers in the range [1, N].  When he knows Answer(x, y), he can easily derive Answer(k*x, k*y), where k is any integer from it by applying some simple calculations involving Answer(x, y) and k. For example if N=4, he only needs to know the answers for 11 out of the 16 possible input value combinations: Answer(1, 1), Answer(1, 2), Answer(2, 1), Answer(1, 3), Answer(2, 3), Answer(3, 2), Answer(3, 1), Answer(1, 4), Answer(3, 4), Answer(4, 3) and Answer(4, 1). The other 5 can be derived from them (Answer(2, 2), Answer(3, 3) and Answer(4, 4) from Answer(1, 1), Answer(2, 4) from Answer(1, 2), and Answer(4, 2) from Answer(2, 1)). Note that the function Answer is not symmetric, so Answer(3, 2) can not be derived from Answer(2, 3).

Now what we want you to do is: for any values of N from 1 upto and including 50000, give the number of function Jimmy has to pre-calculate.

Input

The input file contains at most 600 lines of inputs. Each line contains an integer less than 50001 which indicates the value of N. Input is terminated by a line which contains a zero. This line should not be processed.

Output

For each line of input produce one line of output. This line contains an integer  which indicates how many values Jimmy has to pre-calculate for a certain value of N.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6002 - Deer-Proof Fence   

Description

Uncle Magnus has planted some young saplings on his farm as part of his reforestation project. Unfortunately, deer like to eat tender sapling shoots and leaves, making it necessary to build protective fences around them. Since deer and other sapling nibblers can reach partway over the fence, every fence must lie at least a minimum distance (a margin) from each sapling.

Deer-proof fencing is quite expensive, so Uncle Magnus wants to minimize the total length of fencing used. Your job is to write a program that computes the minimum length of fencing that is required to enclose and protect the saplings. Fences may include both straight and curved segments. You may design a single fence that encloses all saplings or multiple fences that enclose separate groups of saplings.

Figure 6 shows two example configurations, each consisting of three saplings with different margin requirements. In the top configuration, which corresponds to the first sample input, the minimum-length solution consists of two separate fences. In the bottom configuration, which corresponds to the second sample input, the minimum-length solution consists of a single fence.

Input

The input consists of multiple test cases. The first line of each test case contains integers N (0 < N<=9), which is the number of saplings, and M (0 < M<=200), which is the margin required around each sapling. This line is followed by N additional lines. Each of these N lines contains two integers x and y that describe the Cartesian coordinates of a sapling ( | x|<=100 and | y|<=100). No two saplings are in the same location. For simplicity the saplings can all be considered as points and the thickness of deer-proof fences can be considered zero.

The last test case is followed by a line containing two zeros.

Output

For each test case, print the case number (starting with 1) followed by the minimum total length of fencing required to protect the saplings with the given margin. Print the length with two digits to the right of the decimal point. Follow the format of the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6003 - War   

Description

A war is being lead between two countries, A and B. As a loyal citizen of C, you decide to help your country’s espionage by attending the peace-talks taking place these days (incognito, of course). There are n people at the talks (not including you), but you do not know which person belongs to which country. You can see people talking to each other, and through observing their behaviour during their occasional one-to-one conversations, you can guess if they are friends or enemies. In fact what your country would need to know is whether certain pairs of people are from the same country, or they are enemies. You may receive such questions from C’s government even during the peace-talks, and you have to give replies on the basis of your observations so far. Fortunately nobody talks to you, as nobody pays attention to your humble appearance.

Abstract

Now, more formally, consider a black box with the following operations:

  • setFriends(x, y): shows that x and y are from the same country

  • setEnemies(x, y): shows that x and y are from different countries

  • areFriends(x, y): returns true if you are sure that x and y are friends

  • areEnemies(x, y): returns true if you are sure that x and y are enemies

The first two operations should signal an error if they contradict with your former knowledge. The two relations ‘friends’ (denoted by ~) and ‘enemies’ (denoted by *) have the following properties:

    ~ is an equivalence relation, i.e.

  1. If x ~ y and y ~ z then x ~ z (The friends of my friends are my friends as well.)
  2. If x ~ y then y ~ x                (Friendship is mutual.)

  3. x ~ x                                   (Everyone is a friend of himself.)

  4. * is symmetric and irreflexive

  5. If x * y then y * x                (Hatred is mutual.)
  6. Not x * x                             (Nobody is an enemy of himself.)

  7. Also

  8. If x * y and y * z then x ~ z  (A common enemy makes two people friends.)
  9. If x ~ y and y * z then x * z  (An enemy of a friend is an enemy.)

Operations setFriends(x, y) and setEnemies(x, y) must preserve these properties.

Input

The first line contains a single integer, n, the number of people.

Each of the following lines contains a triple of integers, c x y, where c is the code of the operation:

            c = 1, setFriends

            c = 2, setEnemies

            c = 3, areFriends

            c = 4, areEnemies

and x and y are its parameters, which are integers in the range [0, n), identifying two (different) people. The last line contains 0 0 0.

All integers in the input file are separated by at least one space or line break.

Output

For every ‘areFriends’ and ‘areEnemies’ operation write 0 (meaning no) or 1 (meaning yes) to the output. Also for every ‘setFriends’ or ‘setEnemies’ operation which contradicts with previous knowledge, output a –1 to the output ; note that such an operation should produce no other effect and execution should continue. A successful ‘setFriends’ or ‘setEnemies’ gives no output.

All integers in the output file must be separated by at least one space or line break.

Constraints

n < 10000, the number of operations is unconstrained.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6004 - Polygons on the Grid   

Description

The ultimate Tantra is said to have been kept in the most distinguished temple deep in the sacred forest somewhere in Japan. Paleographers finally identified its location, surprisingly a small temple in Hiyoshi, after years of eager research. The temple has an underground secret room built with huge stones. This underground megalith is suspected to be where the Tantra is enshrined.

The room door is, however, securely locked. Legends tell that the key of the door lock was an integer, that only highest priests knew. As the sect that built the temple decayed down, it is impossible to know the integer now, and the Agency for Cultural Affairs bans breaking up the door. Fortunately, a figure of a number of rods that might be used as a clue to guess that secret number is engraved on the door.

Many distinguished scholars have challenged the riddle, but no one could have ever succeeded in solving it, until recently a brilliant young computer scientist finally deciphered the puzzle. Lengths of the rods are multiples of a certain unit length. He found that, to find the secret number, all the rods should be placed on a grid of the unit length to make one convex polygon. Both ends of each rod must be set on grid points. Elementary mathematics tells that the polygon's area ought to be an integer multiple of the square of the unit length. The area size of the polygon with the largest area is the secret number which is needed to unlock the door.

For example, if you have five rods whose lengths are 1, 2, 5, 5, and 5, respectively, you can make essentially only three kinds of polygons, shown in Figure 7. Then, you know that the maximum area is 19.

 

Figure 7: Convex polygons consisting of five rods of lengths 1, 2, 5, 5, and 5 16

Your task is to write a program to find the maximum area of convex polygons using all the given rods whose ends are on grid points.

Input

The input consists of multiple datasets, followed by a line containing a single zero which indicates the end of the input. The format of a dataset is as follows.


r1    r2     ...     rn

n is an integer which means the number of rods and satisfies 3n6. ri is an integer which means the length of the i-th rod and satisfies 1<=ri<=300.

Output

For each dataset, output a line containing an integer which is the area of the largest convex polygon. When there are no possible convex polygons for a dataset, output ``-1''.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6005 - Sunny Mountains   

Description

During their honeymoon, Mrs and Mr Smith went to the Himalayas. How they were surprised when they observed that, during the sunset, all the snow touched by the sunbeams turned red.

Such a magnificent landscape leaves everyone plenty of emotion, but Mr Smith's number obsession overcame all this. He rapidly began evaluating distances, which made Mrs Smith quite upset.

Your work is to help him calculate the size, in meters, of the mountainsides that became red as the sun sets. Mr Smith's honeymoon depends on you! Please be quick and efficient.

For the sake of simplicity, consider that, during the sunset, the sunbeams are horizontal and assume that the landscape is described by the set of coordinates of the mountain peaks and cols. This can be depicted by the following figure. A landscape, in this context, is then a sequence of peaks and cols (i.e., only a col follows a peak and conversely).

Note that, in this picture, the sunny mountainsides are emphasized by bold lines and the coordinates of the landscape are emphasized by bold points.

Thus, the goal of this problem is to calculate the total length in meters of the bold lines.

For this task consider that: (1) for all coordinates (x, y), 0 <= x <= 30000 and 0 <= y <= 8848; (2) the unit is the meter; (3) all the X-coordinates are pair-wise distinct; (4) the leftmost point has 0 as X-coordinate and the rightmost point has 0 as Y-coordinate; (5) The total number of coordinates given is n <= 100.

Input

The first line of input contains C (0 < C < 100 ), the number of test cases that follows.

Each test case starts with a line containing the number N of coordinate pairs. The remaining  N lines for each test case contain the coordinates defining the landscape. Each of these lines contains two integers, x and y, separated by a single space. The first integer, x, is the X-coordinate, and the second, y, is the Y-coordinate of the considered point.

Output

The output is formed by a sequence of lines, one for each test case. Each line contains a single real number with exactly two decimal digits. This number represents the length in meters of the sunny mountainsides for the corresponding test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6006 - Lowest Pyramid   

Description

You are constructing a triangular pyramid with a sheet of craft paper with grid lines. Its base and sides are all of triangular shape. You draw the base triangle and the three sides connected to the base on the paper, cut along the outer six edges, fold the edges of the base, and assemble them up as a pyramid.

You are given the coordinates of the base's three vertices, and are to determine the coordinates of the other three. All the vertices must have integral X- and Y-coordinate values between -100 and +100 inclusive. Your goal is to minimize the height of the pyramid satisfying these conditions. Figure 3 shows some examples.

Input

The input consists of multiple datasets, each in the following format.

X0 Y0 X1 Y1 X2 Y2

They are all integral numbers between -100 and +100 inclusive. (X0, Y0) , (X1, Y1) , (X2, Y2) are the coordinates of three vertices of the triangular base in counterclockwise order.

The end of the input is indicated by a line containing six zeros separated by a single space.

Output

For each dataset, answer a single number in a separate line. If you can choose three vertices (Xa, Ya) , (Xb, Yb) and (Xc, Yc) whose coordinates are all integral values between -100 and +100 inclusive, and triangles (X0, Y0) - (X1, Y1) - (Xa, Ya) , (X1, Y1) - (X2, Y2) - (Xb, Yb) , (X2, Y2) - (X0, Y0) - (Xc, Yc) and (X0, Y0) - (X1, Y1) - (X2, Y2) do not overlap each other (in the XY-plane), and can be assembled as a triangular pyramid of positive (non-zero) height, output the minimum height among such pyramids. Otherwise, output `-1'.

You may assume that the height is, if positive (non-zero), not less than 0.00001. The output should not contain an error greater than 0.00001.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6007 - 9 Puzzle   

Description

Alex has a puzzle her father gave her last Christmas. It has nine numbered squares arranged in a 3×3 matrix (three rows and three columns) and it's mechanically designed to allow the following types of movements:

  • A horizontal right move shifts one position to the right each of the squares in the corresponding horizontal row (circularly).
  • A vertical up move shifts one position upwards each of the squares in the corresponding vertical column (circularly).

Alex's troublemaker little brother Jim snuck last night into his sister's bedroom and somehow tore the puzzle apart and put it back together. However, when Jim assembled the puzzle back, he might have done it in a configuration different from the original configuration of the puzzle.

The next morning, when Alex found her puzzle had been scrambled, she called you to help her to reset her puzzle to its original configuration (shown below) as quickly as possible, so her father won't realize that the puzzle was torn and scrambled. Of course, you should do it using only valid movements, as above described.

1 2 3
4 5 6
7 8 9

Your task is to write a program that, given a configuration, finds a way to set the puzzle to its original configuration spending the minimum possible number of moves to accomplish it, if the given puzzle is solvable. If this is not the case, the program should point it out.

Input

The problem input consists of several cases, each one defined by three lines that describe a puzzle configuration. That is, lines correspond to a top-down description of the rows of the given configuration, and each line consist of three digits, separated by one blank character.

The end of the input is indicated by a line with a number 0.

Output

For each puzzle in the input, you must print a line containing S , the minimum number of moves required to set the puzzle to its original configuration, followed by a space and 2*S characters indicating any sequence of S moves that solves the puzzle.

A move is described by two characters: the first one must be H or V (H specifies a horizontal move, and V a vertical move), and the second one must be 1, 2, or 3 to indicate the row or the column to move.

If the puzzle is not solvable, you must output a line with the text ``Not solvable''.

Hint: Consider each state as a node of the graph, transistion is an edge of graph.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6008 - Census   

Description

This year, there have been many problems with population calculations, since in some cities, there are many emigrants, or the population growth is very high. Every year the ACM (for Association for Counting Members) conducts a census in each region. The country is divided into N^2 regions, consisting of an N x N grid of regions. Your task is to find the least, and the greatest population in some set of regions. Since in a single year there is no significant change in the populations, the ACM modifies the population counts by some number of inhabitants.

Input

In the first line you will find N (0 <= N <= 500), in following the N lines you will be given N numbers, which represent, the initial population of city C [i, j]. In the following line is the number Q (Q <= 40000), followed by Q lines with queries: 

There are two possible queries: 

- "x1 y1 x2 y2" which represent the coordinates of the upper left and lower right of where you must calculate the maximum and minimum change in population. 

- "x y v" indicating a change of the population of city C [x, y] by value v.

Output

For each query, "x1 y1 x2 y2" print in a single line the greatest and least amount of current population. Separated each output by a space. 

Notice: There is only a single test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6009 - String Cutting   

Description

Let's consider a string s of length n (0 < n < 10000) containing only characters from a to z. We define a cut ci (0 < i < n) is an action splitting the string s into 2 substrings s1 and s2 so that s1 consists of first i characters of s and s2 consists of remaining characters from s. Each cut is associated with a cost which equals to the total number of characters consisted in either s1 or s2 but not in both. For example, let s = `abcbacbd', the cut c5 will break s into s1 = `abcba' and s2 = `cbd' with the cost of 2.

The original string can be cut into k + 1 substrings after applying k cuts sequentially to the string and its subsequent substrings. In order to simply describe these k cuts, we specify the position of the cuts with regard to the original string.

Let's consider an example where we sequentially apply 3 cuts at positions 5, 3 and 6 to the string s = `ababccd'. After the first cut at position 5, we have two substrings s1 = `ababc' and s2 = `cd' with the cost of 3. The second cut at position 3 breaks s1 into two substrings s11 = `aba' and s12 = `bc' with the cost of 2. The last cut at position 6 breaks s2 into two substrings s21 = `c' and s22 = `d' with the cost of 2. The total cost for the 3 cuts is 3+2+2=7. Given a string and their cuts, your task is to write a program to compute the total cost for the cut.

Input

The input consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 20. The following lines describe the data sets.

For each data set, the first line contains the integer number k (1<=k<=1000). The second line contains k positive integer numbers describing the position of k cuts. The third line contains the string which will be cut.

Output

For each test case, write in one line the total cost of the cuts.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6010 - Fun Game   

Description

A few kids are standing around an old tree playing a game. The tree is so huge that each kid can only see the kids close to him/her.

The game consists many ‘turns’. At the beginning of each turn of the game, a piece of paper is given to a randomly chosen kid. This kid writes the letter “B” if he is a boy or the letter “G” if a girl. Then he chooses a direction to pass the paper (clockwise or counter-clockwise), and gives the paper to his neighbor in that direction. The kid getting the paper writes down his sex too, and gives the paper to his neighbor in the same direction. In this way, the paper goes through the kids one by one, until one kid stops passing the paper and announces the end of this turn.

For example, there are five kids around the tree, and their genders are shown in Figure-1. The paper first goes to Kid1, after writing a “B” he passes it to Kid2, and Kid2 to Kid3. After Kid3 writes down a “G”, she ends up this turn, and we get the paper with a string “BBG”.

After N turns, we get N pieces of paper with strings of “B”s and/or “G”s. One of the kids will get all these papers, and has to figure out at least how many kids are around the tree playing the game. It's known that there are at least two kids. Please write a program to help him.

Input

There are several test cases. Each case starts with a line containing an integer N, the number of papers (2 ≤ N ≤ 16). Each of the following N lines contains a string on a paper, which is a nonempty string of letter “B”s and/or “G”s. Each string has no more than 100 letters.

A test case of N = 0 indicates the end of input, and should not be processed.

Output

For each test case, output the least possible number of kids in a line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6011 - Color a Tree   

Description

http://acmicpc-live-archive.uva.es/nuevoportal/data/problem.php?p=3138  

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6012 - Glass Beads   

Description

http://uva.onlinejudge.org/external/7/719.html 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6013 - Babel   

Description

http://uva.onlinejudge.org/external/114/11492.html 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6014 - Determine the Shape   

Description

http://uva.onlinejudge.org/external/118/11800.html 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6015 - Crossing Streets   

Description

http://acmicpc-live-archive.uva.es/nuevoportal/data/problem.php?p=3274 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6016 - Destroying the bus stations   

Description

http://acmicpc-live-archive.uva.es/nuevoportal/data/problem.php?p=4322

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6017 - The Closest Pair Problem   

Description

http://uva.onlinejudge.org/external/102/10245.html 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6018 - Intersecting line segments   

Description

http://uva.onlinejudge.org/external/8/866.html 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6019 - Enjoyable Commutation   

Description

http://acmicpc-live-archive.uva.es/nuevoportal/data/problem.php?p=3624 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6020 - Trip Routing   

Description

http://uva.onlinejudge.org/external/1/186.html 

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss




6021 - Painter   

Description

You probably never heard of the painter Peer. He is not well known, much to his regret. Peer was one of the inventors of monochromy, which means that each of his paintings has a single color, but in different shades. He also believed in the use of simple geometric forms.

During his triangle period, Peer drew triangles on a rectangular canvas, making sure their borders did not intersect. He would then choose a color, and fill the regions. Peer would paint the outermost region (the canvas itself) with the lightest shade of the color chosen. Then step by step, he would fill more inner regions with a darker shade of the same color. The image below is one of his ``Forms in Green" paintings

 

In a way the process was quite mechanical. The only thing Peer considered difficult was to decide, after drawing the triangles, how many different shades he would need. You must write a program to do that calculation for him. Your program will have a collection of triangles as its input. It should calculate the number of different shades needed to paint the regions according to the given rule.

Your program must also detect the rare times that Peer makes a mistake and draws triangles that intersect. Two triangles are considered intersecting if the edges of one triangle have at least one point in common with the edges of the other. In that case, the collection of triangles is invalid.

Input

The input file contains multiple test cases. The first line of each test case contains a single non-negative integer n (n ≤ 100000) , which is the number of triangles in the test case. The following n lines of the test case contain the descriptions of triangles in the format x1 y1 x2 y2 x3 y3 , where xi , yi are integers (- 100000 < xi, yi < 100000) that are the coordinates of the vertices of the triangles. The three points are guaranteed not to be collinear.

The last test case is followed by `-1' on a line by itself.

Output

For each test case, print the case number (beginning with 1) and the number of shades needed to fill the regions if the test case is valid. Print the word `ERROR' if the test case is invalid (two or more triangles in the test case intersect).

Sample Input  Download

Sample Output  Download

Tags




Discuss




6022 - Subway Timing   

Description

Like most modern cities, Stockholm has a well-developed public transportation system. The heart of public transportation in Stockholm is the subway. A topological map of the subway system illustrates the different subway lines and how they are connected, as illustrated in Figure 8. For this problem you should assume that a subway map is always tree-shaped, even though this is not quite true for Stockholm because of the cycle formed by the green and blue lines.


Figure 8: Stockholm subway map

A topological map says very little about the geometry of a subway system, such as the distances (and consequently travel times) between different subway stations. For instance, as most students in Stockholm know, the distance between “Tekniska Högskolan” (The Royal Institute of Technology) and “Universitetet” (Stockholm University) is quite large, even though there is no indication of this on the map.

You must write a program that can augment a topological map by writing down the time required to travel between every pair of adjacent subway stations. Fortunately, those travel times are known, so you do not have to measure the times yourself. But the actual travel times are given in seconds, while the times must be written on the map as estimates of integral numbers of minutes.

A natural way of estimating times might be to simply round all the travel times to the nearest minute. However, this can cause huge cumulative errors. For instance, in the Stockholm map, this estimation method could result in an error as large as 15 minutes in the total travel time between some pairs of stations. In order to counter this, your program may choose to round some travel times up and round other travel times down. The rounding must be done in such a way that the largest cumulative error between any pair of stations is minimized.

Input

The input consists of several test cases. Each test case starts with an integer N (1 ≤ N ≤ 100), which is the number of subway stations. The N stations are identified using the integers from 1 to N. Each of the next N − 1 lines contains three integers a, b and t (1 ≤ a, bN, and 1 ≤ t ≤ 300), indicating that stations a and b are adjacent and that it takes t seconds to travel between them. For simplicity, ignore the time a train spends standing still at a station.

The last test case is followed by the integer zero on a line by itself.

Output

For each test case, print the case number (starting with 1) then the largest rounding error in seconds of travel time between any pair of stations when the times for adjacent pairs of stations are rounded optimally. Follow the format of the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6023 - ACM Puzzles   

Description

The Association of Children Machines (ACM) is planning to build up a new type of puzzle for children. All the puzzles will have dimension (3×N) and has some or all of the following pieces. Some pieces can occur more than once. Since the puzzles made by ACM are in very high demand so many other companies have released counterfeit products which look just like puzzles made by ACM.

 

To prevent such counterfeit products ACM has taken up a measure which they hope will help the sellers to prevent the counterfeit products in their shop. As all puzzles are initially available in a box in a solved format and a (3×N) puzzle can have zillions of solutions for larger values of N. All the puzzles from ACM factory will have only some specific solutions when sold; they will be unique and only small fractions of all possible solutions. So it is more likely that the counterfeit products won’t have these orientations. You have to help them in the initial part: given the value of N you will have to find how many different solutions are there with the given pieces. You are not allowed to rotate the pieces while solving the puzzle but you can use any piece any number of time. Of course some of the pieces are mere rotation of another but they also cannot be rotated to make it look like the other. For example the piece with shape upside down T (the brown piece) cannot be rotated to look like a normal T (the pink piece).

Input

The input file contains several lines of input. Each line contains an integer N (0

Output

For each value of N produce one line of output. This line contains the serial of output followed by an integer which denotes the value (S % 1000000000000). Here S denotes the number of solutions for a (3×N) puzzle. Look at the output for sample input for details. 

Sample Input  Download

Sample Output  Download

Tags




Discuss




6024 - Undetectable Tour   

Description

Mickey is assigned a task to help the puppies to escape by travelling from the south-west corner of a grid to the north-east corner undetected by the set of motion detectors deployed by Cruella. There are k motion detectors (1<=k<=300) which are placed on the grid points and can detect any motion within a given distance, d , from the detector. Here we adopt L1 metrics for distance measurements, i.e., the distance between two points (x1, y1) and (x2, y2) is | x1 - x2| + | y1 - y2| . For example, consider the 9×9 grid in the figure below, if the detecting distance of the two detectors, marked with a solid circle, is 3, there exists a tour from (0, 0) to (8, 8) (for example the diagonal is an undetectable tour); however, if the distance is four, there would be no such tour. 

Cruella decides to make it more difficult to escape by setting the detecting distance of the detectors randomly. For each grid, Cruel would flip coins to decide the detecting distance for all the detectors in that grid. Given the probability distribution of the detecting distance d and a series of grids, your task is to write a program to decide for each input grid the probability that it contains an undetectable tour.

Each grid is N×N where 3<=N<=10000 , and each grid point in the grid is denoted by a pair of integers, (x, y) , where 0<=x , y<=N - 1 . The probability distribution is specified by a sequence of ordered pair (d1, p1),(d2, p2),...,(dm, pm) where 1<=m<=100, 1<=di<=2(N - 1) , and each pi has at most three digits after the decimal point. To make it a probability distribution we also have the property that Σpi = 1 .

 

Input

The first line of the input file contains an integer indicating the number of test cases to follow, there will be at most 5 test cases. For each test case, the first line contains two integers, N and m separated by a space. Followed by m lines to specify the probability distribution, each line consists di, pi . Followed by k lines of the positions of detectors in the form x ,y which is the coordination of the detector. The case ends with a line containing `-1'. 

Output

For each test case, output the probability that the grid contains a undetectable tour. 

Sample Input  Download

Sample Output  Download

Tags




Discuss




6025 - Sightseeing   

Description

A traveller, Yuan-Ling is visiting Tainan City. This city is located Southern TAIWAN, famous for traditionally old cities. There are several historic sites in Tainan city, some of which are connected by shopping streets. For convenience, we can view the historic sites and streets as a graph such that historic sites are represented by nodes and streets are represented by edges. The edges have nonnegative weights representing distance or time. Yuan-Ling would like to traverse all the streets, starting and ending at historic site ``Tainan Main Station". Your task is to help Yuan-Ling seek a closed walk that minimizes the total weight (the sum of the edges' weights in the walk) such that all the streets are traversed at least once. We call such a walk as a minimum closed walk. A walk is a list v0, e1, v1,..., ek, vk of nodes and edges such that, for 1<=i<=k , the edge ei has endpoints vi-1 and vi . Note that a walk may repeat nodes and edges. A walk is closed if its end-nodes are the same. 

Given a graph G = (V, E) , we use 1, 2,...,| V| to represent the nodes. Each edge (u, v) is associated with the weight w(u, v) that is a positive integer. Your task is to write a computer program to compute the weight of a minimum closed walk that traverses all the edges at least once.

Technical Specification

  1. G = (V, E) is connected.
  2. 2<=| V|<=100 . 
  3. 1<=| E|<=4950 
  4. For each edge (u, v) , 1<=w(u, v)<=1000 .

Input

The first line of the input file contains an integer indicating the number of test cases to follow. The input consists of a number of test cases. Each test case consists of a graph G = (V, E) , which has the following format: the first line contains two numbers, n(= | V|) and m(= | E|) , separated by a single space. The next m lines contain the description of m edges and the corresponding weights such that one line contains two end-nodes of an edge and the corresponding weight. Each line is represented by three positive numbers separated by a single space; the first number representing one end-node, the second representing the other end-node, and the third representing its weight. Finally, a 0 at the (m + 2) th line indicates the end of this test case.

The next test case starts after the previous ending symbol `0'. A `-1' signals the end of the whole inputs.

Output

The output contains one line for each test case. Each line contains an integer, which is the weight of a minimum closed walk that traverses all the edges at least once. 

Sample Input  Download

Sample Output  Download

Tags




Discuss




6026 - Magnetic Train Tracks   

Description

The rail roads of Japan are being redesigned. So the governent is planning to install ultra-modern Magnetic trains instead of the current normal trains. As fuel price have gone high and nations have shut down their nuclear plants so the price of electricity/battery is also sky high. To reduce power consumption the Japanese government is trying to descourage people from riding trains – as a result the ticket price is also kept sky high and it is strictly proportional to the square of the distance between two stations.

All the trains move in clockwise or counter clockwise order in a closed triangular track. These triangular tracks can be formed by connecting any three stations in clockwise or counterclockwise order. For simplicity you can assume that a station is denoted by a point in a two dimensional Cartesian Coordinate system. But these triangular tracks and ticket pricing policy can create new troubles. As the ticket price between two stations is proportional to the square of the distance, people often avoid the shortest route to destination and rather choose the longer one through another station. This causes more electricity expense per passenger and creates unwanted crowd in the stations. So the government would prefer not to make such tracks.

For example in the figure on the following you can see a closed triangular track marked with green. If someone wants to go from station D to station E he can go directly by riding a clockwise train or can go via station C by riding a counter clockwise train: That is he first buys ticket from station D to C and then he buys ticket of station C to E. But in the current ticket pricing system the route via C (which is also much longer) will be cheaper. So this site CED is not a place to build a track. For the similar reasons AEB is a valid site for building track. On a valid track the shortest distance between any two stations is also the unique cheapest route between them. Given the coordinate of all stations you will have to find the number of sites (a group of three places) for valid tracks.

Input

The input file contains at most 15 sets of inputs. The description of each set is given below:

Each set starts with an n (2i, yi (0≤xi, yi≤10000) which denotes the Cartesian coordinate of the i-th station. You can assume that a track can be built via through any three stations, no three places will be collinear to avoid the problem of degenerate tracks and the connecting railroad between two stations can always be represented by the straight line connecting them.

Output

For each set of input produce two line of output. The first line contains the serial of output and the second line displays the total number of sites where a track can be built. Look at the output for sample input for details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6027 - Nested Squares   

Description

Simple ASCII characters can form a figure containing nested squares: as shown in Figure-1 below. Here the outer most square is formed by character a, the next square is formed by character b and the innermost square is formed by character c.

Such a square can be denoted uniquely by a characteristics string “abc”: that is the first character forms the outermost square, the next character forms the next square and so on. So a string of length 50000 can actually denote a (99999X99999) square grid, which will require around 9 Gigabyte of memory to be stored normally. In this problem you will be asked to print a small portion of such a huge square.

The different characters that form a (N*N) square are numbered in row major order, the upper left character is at position (1,1) and the lower right character is at position (N,N). This is shown in Figure 2.
 

Input

The first line contains an integer N(0

The first line of each set contains a string S (1≤|S|≤50000) and an integer Q (1≤Q≤50). Here S is the characteristic string of a nested square pattern and |S| is the length of string S. This string contains only alphabets and decimal digits. The integer Q denotes the total number of query.

Each of the next Q lines contain four integers r1, c1, r2, c2, which actually denotes a bounding box whose upper left corner is (r1, c1) and lower right corner is (r2, c2). You can assume that (1 ≤ r1, c1, r2, c2 ≤ 2*|S|-1) , 0 ≤ r2-r1 ≤ 100 and 0 ≤ c2-c1 ≤ 100.

There is a blank line between two consecutive input cases.

Output

For each set of input produce several lines of output.

The first line of output for each set contains the serial of the set. Then for each query produce the serial of query followed by the contents within the required bounding box. 

Print a blank line after the output for each test case.

Look at the output for sample input for details.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6028 - Traveling Cube   

Description

On a small planet named Bandai, a landing party of the starship Tadamigawa discovered colorful cubes traveling on flat areas of the planet surface, which the landing party named beds. A cube appears at a certain position on a bed, travels on the bed for a while, and then disappears. After a longtime observation, a science officer Lt. Alyssa Ogawa of Tadamigawa found the rule how a cube travels on a bed.

A bed is a rectangular area tiled with squares of the same size.

  • One of the squares is colored red,
  • one colored green,
  • one colored blue,
  • one colored cyan,
  • one colored magenta,
  • one colored yellow,
  • one or more colored white, and
  • all others, if any, colored black.

Initially, a cube appears on one of the white squares. The cube's faces are colored as follows.

       top red 
bottom cyan
   north green 
   south magenta 
     east blue 
    west yellow

The cube can roll around a side of the current square at a step and thus rolls on to an adjacent square. When the cube rolls on to a chromatically colored (red, green, blue, cyan, magenta or yellow) square, the top face of the cube after the roll should be colored the same. When the cube rolls on to a white square, there is no such restriction. The cube should never roll on to a black square.

Throughout the travel, the cube can visit each of the chromatically colored squares only once, and any of the white squares arbitrarily many times. As already mentioned, the cube can never visit any of the black squares. On visit to the final chromatically colored square, the cube disappears. Somehow the order of visits to the chromatically colored squares is known to us before the travel starts.

Your mission is to find the least number of steps for the cube to visit all the chromatically colored squares in the given order.

Input

The input is a sequence of datasets. A dataset is formatted as follows:

w d  
c11 ... cw1
  ...       ...
c1d ... cwd
v1v2v3v4v5v6

The first line is a pair of positive integers w and d separated by a space. The next d lines are w -character-long strings c11 ... cw1, ... , c1d ... cwd with no spaces. Each character cij is one of the letters r, g, b, c, m, y, w and k, which stands for red, green, blue, cyan, magenta, yellow, white and black respectively, or a sign #. Each of r, g, b, c, m, y and # occurs once and only once in a dataset. The last line is a six-character-long string v1v2v3v4v5v6 which is a permutation of ``rgbcmy".

The integers w and d denote the width (the length from the east end to the west end) and the depth (the length from the north end to the south end) of a bed. The unit is the length of a side of a square. You can assume that neither w nor d is greater than 30.

Each character cij shows the color of a square in the bed. The characters c11 , cw1 , c1d and cwd correspond to the north-west corner, the north-east corner, the south-west corner and the southeast corner of the bed respectively. If cij is a letter, it indicates the color of the corresponding square. If cij is a #, the corresponding square is colored white and is the initial position of the cube.

The string v1v2v3v4v5v6 shows the order of colors of squares to visit. The cube should visit the squares colored v1, v2, v3, v4, v5 and v6 in this order. The end of the input is indicated by a line containing two zeros separated by a space.

Output

For each input dataset, output the least number of steps if there is a solution, or ``unreachable" if there is no solution. In either case, print it in one line for each input dataset.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6029 - Puzzle   

Description

Jisung is the student representative of the Department of Computer Engineering in ACM University. A few days later, the annual festival will be held for the students in the department. He is preparing some events for the festival. Since Jisung likes to make and solve puzzles, he decides to devise some interesting puzzle for the festival.

The followings are the rules for the puzzle made by Jisung:

 

(1)
The players will be given an integer n . Then they should use the first n capital letters from the Roman alphabet. For example, if n = 4 , the four characters ABC, and D will be used to solve this puzzle.
(2)
The players will be given s forbidden strings. No forbidden string contains another forbidden string as a substring. The winner is the student who makes the longest string that does not include a forbidden string as a substring.
(3)
If such a longest string does not exist, i.e., if we can make arbitrarily long strings that satisfy the above condition, or if we cannot make any string that satisfies the above condition, `No' should be answered.

For example, suppose the given number n = 2 , i.e., the players can use the two characters A and B. Assume that the forbidden strings are {AAAABBABB}. In this case, the longest string that does not include any of the four forbidden strings as substrings is AA. But if the given forbidden strings are {AAABBBABABBBAA}, we cannot make such a longest string since arbitrarily long concatenations of ABA, i.e., ABAABAABA ... do not include any forbidden string.

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing two integers n (1 ≤ n ≤ 26) and s (1 ≤ s ≤ 1,000) which represent the number of characters and the number of forbidden strings, respectively. From the second line to (s + 1) -st line of the test case, the forbidden strings are given one by one. The length of a forbidden string does not exceed 50.

Output

Your program is to write to standard output. Print exactly one line for each test case. Print the longest string that does not include any forbidden string as a substring if it exists, otherwise, just print `No' as output. When there exists more than one such longest string with the same length, print the lexicographically largest string among them.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6030 - Difficult Melody   

Description

You're addicted to a little game called `remember the melody': you hear some notes, and then you repeat it. In most cases, the longer the melody, the harder to repeat, but it isn't always true. Also, melodies of the same length are usually not equally easy to remember. To find a way to define the remember difficultyof a melody, you invented a statistics-based model:


 

Suppose you're investigating melodies of a particular length. If a melody appeared in p games, among which you successfully repeated q games, the smaller q/p , the more difficult the melody. If there is more than one melody having the minimal ratio, the one with larger p is considered more difficult. But there is an exception: if p is smaller than a threshold m , you simply ignore it (you can't call it difficult if you haven't tried it a lot of times, can you?). The melody appears in a game if its string representation is a consecutive substring occurring at least once in that game.

Write a program to find the most difficult melody of length k , given n games you've played.

 

Input

The input contains several test cases. Each case consists of three integers nmk (1<=m<=n100, 1<=k<=20) , the next n lines each contain two strings separated by exactly one space: the game, and whether you successfully repeated it. The first string will contain at least one at most 100 upper case letters `C', `D', `E', `F', `G', `A', `B'. The second string will be either `Yes' or `No' (case sensitive). The last test case is followed by a single zero, which should not be processed.

Output

For each test case, print the case number and the most difficult melody. If there is more than one solution, output the lexicographically smallest one. If there is no solution, output the string `No solution'.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6031 - Paper Presentation   

Description

2M scientists are supposed to present papers in a conference in a day. The day is divided into 2 slots, the morning slot and the evening slot. M scientists present their paper in the morning slot and the remaining in the evening slot. Both slots are separated by a lunch break.

Some scientists depend on a paper from some other scientists to be presented before theirs. So if Scientist A is presenting a paper on "Graph Theory" and Scientist B on "Max flow-Min cut", then A has to present before B. Lunch break is a time of merry making and partying, so attendees tend to forget the papers in the previous half. Due to this, the dependent scientist (B in this case) has to present the paper in the same slot as the scientist on whom he is dependent (A in this case). Given the dependencies, find the number of possible orderings of presenting the papers.

Input

The first line of input will contain an integer T ≤ 20 denoting the number of test cases. Each test case will be formatted as follows: The first line will contain an integer denoting 1 ≤ M ≤ 8. The next 2M lines will contain 2M characters each. Each character will either be ‘Y’ or ‘N’. If the i th line's j th character is ‘Y’ it means that scientist i is dependent on scientist j. ‘N’ signifies no dependence. A scientist will never be dependent on himself.

Output

Output one line per case that contains an integer denoting the number of possible ordering of scientists.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6032 - The Sky is the Limit   

Description

The city of Banff hired an advertising agency to promote the city's attractions to potential visitors. One of the planned slogans stated that the mountain ranges around the city form the most beautiful skyline in Canada. But the Institute for Consumer Protection in Canada (ICPC) decided that ``the most beautiful skyline" was a subjective and unverifiable claim, and could therefore be considered misleading.

The advertising agency then came up with the slogan ``Banff - the longest skyline in Canada." Although not as catchy, it is hopefully verifiable, and therefore admissible under Canada's tricky advertising laws.

This is where you come in. What the advertising agency needs is a program that determines the length of a skyline. Consider each mountain as a two-dimensional triangle having two upper sides the same length. A skyline is the outline of one or more mountains. The skyline's length is the total length of the outline. The left illustration below shows three mountains. The right illustration shows (with bold lines) the skyline and (with dashed lines) the portion of the mountains' upper edges that are not part of the skyline. Note that parts of the horizon line that lie between mountains are not considered part of the skyline.

Input

Each input file contains one or more test cases, which are descriptions of mountain ranges. Each description starts with a line containing a positive integer N , which specifies the number of mountains in the range. Each of the next N lines describes a mountain with three integers X , H , and B , which specify the horizontal position of the mountain's peak relative to some fixed point, the height of the peak, and the width of the base of the mountain, respectively. The base of each mountain coincides with a horizontal line. The values satisfy the conditions N ≤ 100 , H > 0 , and B > 0 .

The last test case is followed by a line containing a zero.

Output

For each test case, print the case number (beginning with 1) and the length of the skyline. Print the length rounded to the nearest integer, with 0.5 rounded up. Print a blank line after the output of each test case. Use the format shown in the sample output below.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6033 - Key Task   

Description

The Czech Technical University is rather old -- you already know that it celebrates 300 years of its existence in 2007. Some of the university buildings are old as well. And the navigation in old buildings can sometimes be a little bit tricky, because of strange long corridors that fork and join at absolutely unexpected places.

The result is that some first-graders have often diffculties finding the right way to their classes. Therefore, the Student Union has developed a computer game to help the students to practice their orientation skills. The goal of the game is to find the way out of a labyrinth. Your task is to write a verification software that solves this game.

The labyrinth is a 2-dimensional grid of squares, each square is either free or filled with a wall. Some of the free squares may contain doors or keys. There are four different types of keys and doors: blue, yellow, red, and green. Each key can open only doors of the same color.

You can move between adjacent free squares vertically or horizontally, diagonal movement is not allowed. You may not go across walls and you cannot leave the labyrinth area. If a square contains a door, you may go there only if you have stepped on a square with an appropriate key before.

Input

The input consists of several maps. Each map begins with a line containing two integer numbers R and C (1 ≤ R, C ≤ 100) specifying the map size. Then there are R lines each containing C characters. Each character is one of the following:

Character Meaning
Hash mark # Wall
Dot . Free square
Asterisk * Your position
Uppercase letter B Y R G Blue, yellow, red, or green door
Lowercase letter b y r g Blue, yellow, red, or green key
Uppercase X X Exit

 

    Note that it is allowed to have

  • more than one exit,
  • no exit at all,
  • more doors and/or keys of the same color, and
  • keys without corresponding doors and vice versa.

 

You may assume that the marker of your position (``*") will appear exactly once in every map. There is one blank line after each map. The input is terminated by two zeros in place of the map size.

Output

For each map, print one line containing the sentence ``Escape possible in S steps.", where S is the smallest possible number of step to reach any of the exits. If no exit can be reached, output the string ``The poor student is trapped!" instead. One step is defined as a movement between two adjacent cells. Grabbing a key or unlocking a door does not count as a step.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6034 - The Separator in Grid   

Description

Given a connected, undirected graph G = (V, E), where V is the vertex set consisting a collection of nodes, and E is the set of edges, each of which connects two nodes from V. A vertex subset S is a separator if the subgraph induced by the vertices in V, but not in S, has two connected components. We shall use the notation [S, W, B] to represent the partition, where the removal of the separator S will give two connected components W and B.

In this problem, we consider the separators in grids. Each node in a grid is connected to its eight neighbors (if they exist). In Figure-1, we illustrate a partition of a 6*6 grid with a 9-point separator (gray nodes in the figure). The nodes on the left of the separator are in set W (white nodes), and the nodes on the right of the separator are in set B (black nodes).

To simplify the problem, you can assume that all the separators referred in this problem satisfy the following restrictions:

1) It’s a minimal separator. A separator is minimal if no subset of it forms a separator.
2) It begins from a node on the top line of the grid, except the corner (i.e. 30 and 35 in the figures), and ends with a node on the bottom line of the grid, also except the corner (i.e. 0 and 5 in the figures).
3) On its way from top to bottom, it can go left, right or down, but never go up.

Now we describe a method to improve a given partition on a grid, through which we can reduce the number of nodes in the separator. This method contains two steps:

1) Select several nodes from B and add them into S. Any of the selected nodes must have a left neighbor which is in S.
2) Remove several nodes from S (excluding the nodes added in the former step), and add them into W.

After the improvement, we should ensure S is still a separator, and make the number of nodes in S as small as possible. As for Figure-1, we should add 14 and 20 into S, and remove 7, 13, 19 and 25 from S. After that, we obtain a new partition with a 7-point separator shown in Figure-2.

Your task is, given a partition on a grid, to determine the least number of nodes in the separator after the improvement.

Input

There are several test cases. Each case begins with a line containing two integers, N and M (3 ≤ M, N ≤ 200). In each of the following N lines, there are M characters, describing the initial partition of the M*N grid. Every character is ‘S’, ‘W’ or ‘B’. It is confirmed that each of these three characters appears at least once in each line, and ‘W’s are always on the left of ‘S’s.

A test case of N = 0 and M = 0 indicates the end of input, and should not be processed.

Output

For each test case, you should output one line containing one integer, which is the least number of nodes in the separator after the improvement.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6035 - Best Coalitions   

Description

Envy Inc. is a joint stock company, that is, a company in which every stockholder legally owns shares of stock that account for some percentage of the total shares of stock of the company. Due to the global economic crisis, the management rules of Envy Inc. define a particular way for distributing last year's profit: if a stockholder owns more than half of the shares of stock, he/she wins the total profit. Nothing fancy so far in this wild world!

Nevertheless, there are situations in which no stockholder owns more than 50% of the shares of stock of the company. So, in order to gain some profit, stockholders are allowed to form coalitions, i.e., groups of stockholders. The participation of the coalition, share-wise, is equivalent to the sum of its stockholders' percentile participation. Hence, if a coalition has more than half of the shares of stock, its members win the totality of last years profit. Then, the members of the coalition receive a part of the profit proportional to their individual participation in the coalition.

For instance, let us assume there are 5 stockholders: A, B, C, D and E, owning 20%, 12%, 14%, 29% and 25% of the stock of the company, respectively. The stockholder E could form several winning coalitions. For example, if E were to form a coalition with A and B, he/she would get 43.86% of last year's profit. If E were to form a coalition with B and C instead, he/she would get 49.02% of last year's profit. On the other hand, E could not form a winning coalition with only A.

Your problem is, given a distribution of shares of stock of Envy Inc., and a stockholder, to determine the maximum percentage of the last year's profit that the given stockholder may win.

Input

The input consists of several test cases, each one defining a percentile distribution of shares of stock, and the index of a stockholder to determine his/her optimal participation. More precisely, each test case is defined by several input lines:

the first line contains two integer values n ( 1 <= n
<= 100) and x ( 1 <= x <= n), separated by a blank, representing the number of stockholders in Envy Inc. and the index of a stockholder to determine his/her optimal participation, respectively;
each one of the following n lines has a single floating point value pi, rounded to 2 decimal places, which represents the percentage of stock ownership of stockholder i ( 1
<= i <= n). The floating point delimiter is `.' (i.e. the dot). You can assume that p1 +...+ pn = 100.

The end of the input is indicated by n = x = 0, an artificial case that must be ignored.

Output

For each given case, output a single line with the corresponding answer. The answer should be formatted and approximated to two decimal places. The floating point delimiter must be `.' (i.e. the dot). The rounding applies towards the nearest neighbor unless both neighbors are equidistant, in which case the result is rounded up (e.g. 78.312 is rounded to 78.31; 78.566 is rounded to 78.57; 78.345 is rounded to 78.35, etc.).

Sample Input  Download

Sample Output  Download

Tags




Discuss




6036 - Take the Land   

Description

The poor man went to the King and said, “Lord, I cannot maintain my family. Please give me some wealth so that I can survive with my wife and children.” The King replied, “I shall grant you a piece of land so that you can cultivate and grow food for your family. In the southern part of the Kingdom there is a rectangular forest. Trees have been planted there at regular intervals. Some of the trees have been cut for use. You are allowed to take any rectangular piece of land that does not contain any tree. You need not go to the forest to select the piece of land. I have a map containing 1s at places where there is a tree and 0s at points where the tree has been cut.”



Help the poor man to find out the largest piece of land. Area of the land is measured in units of number of trees that were there. Your program should take a matrix of 1s and 0s as input and output the area of the largest rectangular piece of land that contain no tree. Be careful about the efficiency of your program.

Input

The input file may contain multiple test cases. The first line of each test case contains two integers M and N (1<=M,N<=100) giving the number of rows and columns in the matrix that follows. Each of the next M lines contains N symbols (either 0 or 1). Two consecutive symbols in a line will be separated by a single space. The input terminates with two zeros for M and N.

Output

For each test case in the input print a line giving the area (in terms of the number of trees were there) of the largest rectangular piece of land containing no tree.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6037 - Stopped Watches   

Description

In the middle of Tyrrhenian Sea, there is a small volcanic island called Chronus. The island is now uninhabited but it used to be a civilized island. Some historical records imply that the island was annihilated by an eruption of a volcano about 800 years ago and that most of the people in the island were killed by pyroclastic flows caused by the volcanic activity. In 2003, a European team of archaeologists launched an excavation project in Chronus Island. Since then, the project has provided many significant historic insights. In particular the discovery made in the summer of 2008 astonished the world: the project team excavated several mechanical watches worn by the victims of the disaster. This indicates that people in Chronus Island had such a highly advanced manufacturing technology.

Shortly after the excavation of the watches, archaeologists in the team tried to identify what time of the day the disaster happened, but it was not successful due to several diffculties. First, the extraordinary heat of pyroclastic flows severely damaged the watches and took away the letters and numbers printed on them. Second, every watch has a perfect round form and one cannot tell where the top of the watch is. Lastly, though every watch has three hands, they have a completely identical look and therefore one cannot tell which is the hour, the minute, or the second (It is a mystery how the people in Chronus Island were distinguishing the three hands. Some archaeologists guess that the hands might be painted with different colors, but this is only a hypothesis, as the paint was lost by the heat). This means that we cannot decide the time indicated by a watch uniquely; there can be a number of candidates. We have to consider different rotations of the watch. Furthermore, since there are several possible interpretations of hands, we have also to consider all the permutations of hands.

You are an information archaeologist invited to the project team and are asked to induce the most plausible time interval within which the disaster happened, from the set of excavated watches.

In what follows, we express a time modulo 12 hours. We write a time by the notation hh : mm : ss , where hh , mm , and ss stand for the hour (hh = 00, 01, 02,..., 11) , the minute (mm = 00, 01, 02,..., 59) , and the second (ss = 00, 01, 02,..., 59) , respectively. The time starts from 00:00:00 and counts up every second 00:00:00, 00:00:01, 00:00:02, ... , but it reverts to 00:00:00 every 12 hours.

The watches in Chronus Island obey the following conventions of modern analog watches.


A watch has three hands, i.e. the hour hand, the minute hand, and the second hand, though they look identical as mentioned above.
Every hand ticks 6 degrees clockwise in a discrete manner. That is, no hand stays between ticks, and each hand returns to the same position every 60 ticks.
The second hand ticks every second.
The minute hand ticks every 60 seconds.
The hour hand ticks every 12 minutes.


At the time 00:00:00, all the three hands are located at the same position.

Because people in Chronus Island were reasonably keen to keep their watches correct and pyroclastic flows spread over the island quite rapidly, it can be assumed that all the watches were stopped in a short interval of time. Therefore it is highly expected that the time the disaster happened is in the shortest time interval within which all the excavated watches have at least one candidate time.

You must calculate the shortest time interval and report it to the project team.

Input

The input consists of multiple datasets, each of which is formatted as follows.


n
s1 t1 u1
s2 t2 u2
...
sn tn un


The first line contains a single integer n (2<=n<=10) , representing the number of the watches. The three numbers si , ti , ui in each line are integers such that 0 <= si, ti, ui <= 59 and they specify the positions of the three hands by the number of ticks relative to an arbitrarily chosen position.

Note that the positions of the hands of a watch can be expressed in many different ways. For example, if a watch was stopped at the time 11:55:03, the positions of hands can be expressed differently by rotating the watch arbitrarily (e.g. 59 55 3, 0 56 4, 1 57 5, etc.) and as well by permuting the hour, minute, and second hands arbitrarily (e.g. 55 59 3, 55 3 59, 3 55 59, etc.).

The end of the input is indicated by a line containing a single zero.

Output

For each dataset, output the shortest time interval within which all the watches given in the dataset have at least one candidate time. The output must be written in a single line in the following format for each dataset.


hh:mm:ss h'h':m'm':s's'


Each line contains a pair of times
hh:mm:ss and h'h':m'm':s's' , indicating that the shortest interval begins at hh:mm:ss and ends at h'h':m'm':s's' inclusive. The beginning time and the ending time are separated by a single space and each of them should consist of hour, minute, and second in two digits separated by colons. No extra characters should appear in the output.

In calculating the shortest interval, you can exploit the facts that every watch has at least one candidate time and that the shortest time interval contains 00:00:00 only if the interval starts from 00:00:00 (i.e. the shortest interval terminates before the time reverts to 00:00:00).

If there is more than one time interval that gives the shortest, output the one that first comes after 00:00:00 inclusive.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6038 - Underwater Snipers   

Description

King Motashota is in a war against the mighty Bachchaloks. He has formed a well-trained army of snipers, and planning to use them as much as possible. In one of the missions, he has S snipers. They will be dispatched to get rid of the soldiers guarding the bank of the river “Nodi'”.

From satellite images, Motashota has located positions of all enemy soldiers. Now, the plan is, snipers will take their positions. They are excellent swimmers, so, you can assume that they won't get caught, while taking position. Upon order from Motashota, they will start shooting enemy soldiers. A sniper can shoot a soldier, if euclidean distance between the soldier and sniper is no more than D. After the snipers get rid of all the soldiers, they can proceed with the operation. So, it is important for them to position the snipers in such a way that, all soldiers are within the range of at least one sniper.

In addition, when snipers start shooting, the guards will be alert, and thus, snipers can't change their position, they can only continue shooting from their position.

The river bank is defined by the horizontal line y = k. All points (x, y) where y > k is in the enemy territory, and if y < k, then it's on the water. You will be given location of N soldiers, strictly in the enemy territory, you have to place S snipers in the water, so that, they can kill all soldiers. For security reasons, the snipers should be as far from the bank as possible. For any sniper in position (xi, yi), the distance from the bank is |yi - k|. If, for all snipers, the minimum of them is M = min{|yi - k|}, you have to maximize M.

Both the soldiers and snipers are really superstitious. They will stay only in integer coordinates.

Input

First line contains an integer T (1 ≤ T ≤ 100), the number of test cases.

This is followed by T test cases. Each test case starts with four integers, k (-108k ≤ 108), N (1 ≤ N ≤ 10000), S (1 ≤ S ≤ 10000) and D (1 ≤ D ≤ 109), the position of the bank, number of guards and number of snipers, and the range of the snipers.

This is followed by N lines, each containing a pair of integers (xi, yi) the position of ith guard (-108xi ≤ 108, k < yi ≤ 108).

There is a blank line before each test case.

Output

For each test case, output the case number followed by an integer, M, which is defined in the statement. If the snipers can’t kill all guards, output “IMPOSSIBLE”.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6039 - Twenty Questions   

Description

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 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. There are at most 100 datasets.

Output

For each dataset, minimize the maximum number of questions by which every object is identifiable and output the result.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6040 - Jogging Trails   

Description

Gord is training for a marathon. Behind his house is a park with a large network of jogging trails connecting water stations. Gord wants to find the shortest jogging route that travels along every trail at least once.

Input

Input consists of several test cases. The first line of input for each case contains two positive integers: n (n ≤ 15), the number of water stations, and m (m < 1000), the number of trails. For each trail, there is one subsequent line of input containing three positive integers: the first two, between 1 and n, indicating the water stations at the end points of the trail; the third indicates the length of the trail, in cubits. There may be more than one trail between any two stations; each different trail is given only once in the input; each trail can be travelled in either direction. It is possible to reach any trail from any other trail by visiting a sequence of water stations connected by trails. Gord's route may start at any water station, and must end at the same station. A single line containing 0 follows the last test case.

Output

For each case, there should be one line of output giving the length of Gord's jogging route.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6041 - Gomoku   

Description

You are probably not familiar with the title, ``Gomoku", but you must have played it a lot. Gomoku is an abstract strategy board game and is also called Five in a Row, or GoBang. It is traditionally played with go pieces (black and white stones) on a go board ( 19 x 19 intersections). Nowadays, standard chessboard of Gomoku has 15 x 15 intersections. Black plays first, and players alternate in placing a stone of their color on an empty intersection. The winner is the first player to get an unbroken row of five or more stones horizontally, vertically, or diagonally.

 

epsfbox{p4836.eps}

For convenience, we coordinate the chessboard as illustrated above. The left-bottom intersection is (0,0). And the bottom horizontal edge is x-axis, while the left vertical line is y-axis.

I am a fan of this game, actually. However, I have to admit that I don't have a sharp mind. So I need a computer program to help me. What I want is quite simple. Given a chess layout, I want to know whether someone can win within 3 moves, assuming both players are clever enough. Take the picture above for example. There are 31 stones on it already, 16 black ones and 15 white ones. Then we know it is white turn. The white player must place a white stone at (5,8). Otherwise, the black player will win next turn. After that, however, the white player also gets a perfect situation that no matter how his opponent moves, he will win at the 3-rd move.

So I want a program to do similar things for me. Given the number of stones and positions of them, the program should tell me whose turn it is, and what will happen within 3 moves.

Input

The input contains no more than 20 cases.

Each case contains n + 1 lines which are formatted as follows.

 


n
x1 y1 c1
x2 y2 c2
......
xn yn cn

 


The first integer n indicates the number of all stones. n$ le$222 which means players have enough space to place stones. Then n lines follow. Each line contains three integers: xi and yi and ci. xi and yi are coordinates of the stone, and ci means the color of the stone. If ci = 0 the stone is white. If ci = 1 the stone is black. It is guaranteed that 0$ le$xi, yi$ le$14, and ci = 0 or 1. No two stones are placed at the same position. It is also guaranteed that there is no five in a row already, in the given cases.

The input is ended by n = 0.

Output

For each test case:

First of all, the program should check whose turn next. Let's call the player who will move next ``Mr. Lucky". Obviously, if the number of the black stone equals to the number of white, Mr. Lucky is the black player. If the number of the black stone equals to one plus the numbers of white, Mr. Lucky is the white player. If it is not the first situation or the second, print ``Invalid."

A valid chess layout leads to four situations below:

 

  1. Mr. Lucky wins at the 1st move. In this situation, print :

     


    Place TURN at (x, y) to win in 1 move.

     


    ``TURN" must be replaced by ``black" or ``white" according to the situation and (x, y) is the position of the move. If there are different moves to win, choose the one where x is the smallest. If there are still different moves, choose the one where y is the smallest.

  2. Mr. Lucky's opponent wins at the 2nd move. In this situation, print:

     


    Lose in 2 moves.

  3. Mr. Lucky wins at the 3rd move. If so, print:

     


    Place TURN at (x, y) to win in 3 moves.

     


    ``TURN" should replaced by ``black" or ``white", (x, y) is the position where the Mr. Lucky should place a stone at the 1st move. After he place a stone at (x, y), no matter what his opponent does, Mr. Lucky will win at the 3rd step. If there are multiple choices, do the same thing as described in situation 1.

  4. Nobody wins within 3 moves. If so, print:

     


    Cannot win in 3 moves.


Sample Input  Download

Sample Output  Download

Tags




Discuss




6046 - Test Case Tweaking   

Description

You are a judge of a programming contest. You are preparing a dataset for a graph problem to seek for the cost of the minimum cost path. You've generated some random cases, but they are not interesting. You want to produce a dataset whose answer is a desired value such as the number representing this year 2010. So you will tweak (which means ‘adjust’) the cost of the minimum cost path to a given value by changing the costs of some edges. The number of changes should be made as few as possible.

A non-negative integer c and a directed graph G are given. Each edge of G is associated with a cost of a non-negative integer. Given a path from one node of G to another, we can define the cost of the path as the sum of the costs of edges constituting the path. Given a pair of nodes in G, we can associate it with a non-negative cost which is the minimum of the costs of paths connecting them.

Given a graph and a pair of nodes in it, you are asked to adjust the costs of edges so that the minimum cost path from one node to the other will be the given target cost c. You can assume that c is smaller than the cost of the minimum cost path between the given nodes in the original graph.

For example, in Figure G.1, the minimum cost of the path from node 1 to node 3 in the given graph is 6. In order to adjust this minimum cost to 2, we can change the cost of the edge from node 1 to node 3 to 2. This direct edge becomes the minimum cost path after the change.

For another example, in Figure G.2, the minimum cost of the path from node 1 to node 12 in the given graph is 4022. In order to adjust this minimum cost to 2010, we can change the cost of the edge from node 6 to node 12 and one of the six edges in the right half of the graph. There are many possibilities of edge modification, but the minimum number of modified edges is 2.


Figure G. Examples 1 and 2 of graphs

Input

The input is a sequence of datasets. Each dataset is formatted as follows.

n m c
f1 t1 c1
f2 t2 c2

fm tm cm

The integers n, m and c are the number of the nodes, the number of the edges, and the target cost, respectively, each separated by a single space, where 2 ≤ n ≤ 100, 1 ≤ m ≤ 1000 and 0 ≤ c ≤ 100000.

Each node in the graph is represented by an integer 1 through n.

The following m lines represent edges: the integers fi, ti and ci (1 ≤ im) are the originating node, the destination node and the associated cost of the i-th edge, each separated by a single space. They satisfy 1 ≤ fi, tin and 0 ≤ ci ≤ 10000. You can assume that fiti and (fi, ti) ≠ (fj, tj) when ij.

You can assume that, for each dataset, there is at least one path from node 1 to node n, and that the cost of the minimum cost path from node 1 to node n of the given graph is greater than c.

The end of the input is indicated by a line containing three zeros separated by single spaces.

Output

For each dataset, output a line containing the minimum number of edges whose cost(s) should be changed in order to make the cost of the minimum cost path from node 1 to node n equal to the target cost c. Costs of edges cannot be made negative. The output should not contain any other extra characters.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6047 - The Islands   

Description

Wen Chen is the captain of a rescue boat. One of his important tasks is to visit a group of islands once a day to check if everything is all right. Captain Wen starts from the west-most island, makes a pass to the east-most island visiting some of the islands, then makes a second pass from the east-most island back to the first one visiting the remaining islands. In each pass Captain Wen moves steadily east (in the first pass) or west (in the second pass), but moves as far north or south as he needs to reach the islands. The only complication is that there are two special islands where Wen gets fuel for his boat, so he must visit them in separate passes. Figure 7 shows the two special islands in pink (1 and 3) and one possible path Captain Wen could take.

Calculate the length of the shortest path to visit all the islands in two passes when each island's location and the identification of the two special islands are given.

Input

The input consists of multiple test cases. The data for each case begins with a line containing 3 integers n (4 ≤ n ≤ 100), b1, and b2 (0 < b1, b2 < n - 1 and b1b2), where n is the number of islands (numbered 0 to n - 1) and b1 and b2 are the two special islands. Following this, there are n lines containing the integer x - and y -coordinates of each island (0 ≤ x, y ≤ 2000), starting with island 0. No two islands have the same x -coordinate and they are in order from west-most to east-most (that is, minimum x -coordinate to maximum x -coordinate).

Input for the last case is followed by a line containing 3 zeroes.

Output

For each case, display two lines. The first line contains the case number and the length of the shortest tour Captain Wen can take to visit all the islands, rounded and displayed to the nearest hundredth. The second line contains a space-separated list of the islands in the order that they should be visited, starting with island 0 and 1, and ending with island 0. Each test case will have a unique solution. Follow the format in the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6048 - The Two Men of the Japanese Alps   

Description

Two experienced climbers are planning a first-ever attempt: they start at two points of the equal altitudes on a mountain range, move back and forth on a single route keeping their altitudes equal, and finally meet with each other at a point on the route. A wise man told them that if a route has no point lower than the start points (of the equal altitudes) there is at least a way to achieve the attempt. This is the reason why the two climbers dare to start planning this fancy attempt.

The two climbers already obtained altimeters (devices that indicate altitude) and communication devices that are needed for keeping their altitudes equal. They also picked up a candidate route for the attempt: the route consists of consequent line segments without branches; the two starting points are at the two ends of the route; there is no point lower than the two starting points of the equal altitudes. An illustration of the route is given in Figure E.1 (this figure corresponds to the first dataset of the sample input).


Figure E.1: An illustration of a route

The attempt should be possible for the route as the wise man said. The two climbers, however, could not find a pair of move sequences to achieve the attempt, because they cannot keep their altitudes equal without a complex combination of both forward and backward moves. For example, for the route illustrated above: a climber starting at p1 (say A) moves to s, and the other climber (say B) moves from p6 to p5; then A moves back to t while B moves to p4; finally A arrives at p3 and at the same time B also arrives at p3. Things can be much more complicated and thus they asked you to write a program to find a pair of move sequences for them.

There may exist more than one possible pair of move sequences, and thus you are requested to find the pair of move sequences with the shortest length sum. Here, we measure the length along the route surface, i.e., an uphill path from (0, 0) to (3, 4) has the length of 5.

Input

The input is a sequence of datasets.

The first line of each dataset has an integer indicating the number of points N (2 ≤ N ≤ 100) on the route. Each of the following N lines has the coordinates (xi, yi) (i = 1, 2, ... , N) of the points: the two start points are (x1, y1) and (xN, yN); the line segments of the route connect (xi, yi) and (xi+1, yi+1) for i = 1, 2, ... , N - 1. Here, xi is the horizontal distance along the route from the start point x1, and yi is the altitude relative to the start point y1. All the coordinates are non-negative integers smaller than 1000, and inequality xi < xi+1 holds for i = 1, 2, .. , N - 1, and 0 = y1 = yNyi for i = 2, 3, ... , N - 1.

The end of the input is indicated by a line containing a zero.

Output

For each dataset, output the minimum sum of lengths (along the route) of move sequences until the two climbers meet with each other at a point on the route. Each output value may not have an error greater than 0.01.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6049 - Jumping monkey   

Description

You are a hunter chasing a monkey in the forest, trying to shoot it down with your all-powerful automatic machine gun. The monkey is hiding somewhere behind the branches of one of the trees, out of your sight. You can aim at one of the trees and shoot; your bullets are capable of going through the branches and killing the monkey instantly if it happens to be in that tree. If it isn't, the monkey takes advantage of the time it takes you to reload and takes a leap into a neighbouring tree without you noticing. It never stays in the same place after a shot. You would like to find out whether there is an strategy that allows you to capture the monkey for sure, irrespective of its initial location and subsequent jumps. If so, you need to determine the shortest sequence of shots guaranteeing this.


Figure 2

As an example, consider the situation in which there are only two neighboring trees in the forest (left hand side of Figure 2). It is then possible to make sure you capture the monkey by shooting twice at the same tree. Your first shot succeeds if the monkey happened to be there in the first place. Otherwise, the monkey was behind the other tree and it will necessarily have moved when you shoot for the second time.

However, depending on the shape of the forest it may not be possible for you to ensure victory. One example of this is if there are three trees, all connected to one another (right hand side of Figure 2). No matter where you aim at, there are always two possible locations for the monkey at any given moment. (Note that here we are concerned with the worst-case scenario where the monkey may consistently guess your next target tree).

Input

The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing two integers n and m (1 ≤ n ≤ 21); n is the number of trees in the forest, and m is the number of adjacency relations between trees. Each of the following m lines contains two distinct integers between 0 and n - 1 (inclusive), the identifiers of the trees in an adjacent pair. The order of both trees within a pair carries no meaning, and no pair appears more than once. You may further assume that no tree is adjacent to itself, and there is always a path between any two trees in the forest.

The test cases will finish with a line containing only two zeros (also preceded with a blank line).

Output

Print a line for each test case. The line should contain the single word ‘Impossible’ if the task is impossible. Otherwise, it must contain the shortest sequence of shots with the required property, in the format L: V1 V2VL, where L is the length of the sequence, and V1, V2, …, VL are space-separated integers containing the identifiers of the trees to shoot at in the right order. If several shortest sequences exist, print the lexicographically smallest one. (A sequence is smaller than another in lexicographic order if the first element on which they differ is smaller in the first one).

Sample Input  Download

Sample Output  Download

Tags




Discuss




6050 - Rendezvous   

Description

Treeland Security Agency (TSA) is a secret organization supposed to maintain the security in N cities of Treeland, which are identified by the numbers from 1 to N. The city with identifier 1 is the headquarters of TSA. For the safety of all agents working for TSA, to move from one city to another city one must follow a designated two-way road system which has a tree structure rooted at the headquarters. For every mission of TSA, two secret agents located in two different cities are assigned. After completing the mission, they have to gather at a designated city, called rendezvous, and travel together to the headquarters. The rendezvous is a city which appears in both agents’ shortest routes to the headquarters and is farthest from the headquarters. This year, the director of TSA has planned K missions that will be assigned to K pairs of secret agents. He is quite interested in finding the most popular rendezvous of the year, which is the rendezvous for the largest number of missions. Given a road system among N cities and a list of cities assigned to agents in K missions, your task is to write a program to determine the most popular rendezvous.

Input

The input file consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 25. The following lines describe the data sets. For each data set, the first line contains two integers N (N ≤ 100 000) and K (K ≤ 100 000). The ith line of the following − 1 lines contains two integers u and v (1 ≤ uv ≤ N) separated by a space indicating that there is a two-way road between city u and v. The j-th line the next K lines contains two integers x and y (1 ≤ x, yN) separated by space describing the two cities assigned to two secret agents in the j-th mission.

Output

For each data set, write in one line the identifier of the city which is the most popular rendezvous. In case there are more than one solution, write the smallest identifier.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6051 - The Tree Root   

Description

Tree is an important data structure. Searching is a basic operation in any data structure. In a tree searching mainly depends on its height. Consider the following three trees.

If you observe carefully, you will see that all trees are same except different nodes are used as roots. Here the height of the tree varies with the selection of the root. In the 1st tree root is '2' and height is 3. In 2nd one root is '1' and height is 2. And in last one root is '4' and height is 4. We will call '1' best root as it keeps the tree with the least possible height and '4' worst root for the opposite reason.

In this problem, you have to find out all best roots and worst roots for a given tree.

Input

Each dataset starts with a positive integer N (3 ≤ N ≤ 5000), which is the number of nodes in the tree. Each node in the tree has a unique id from 1 to N. Then successively for each i-th node there will be a positive integer Ki following id of Ki nodes which are adjacent to i. Input is terminated by EOF.

Output

For each dataset print two lines. In the 1st line show all the best roots in ascending order and in next line show all worst roots in ascending order. See sample output for exact format.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6052 - Plants vs. Zombies HD Super Pro   

Description

Plants versus Zombies HD Super Pro is a game played not on a grid, but on a connected graph G with no cycles (i.e., a tree). Zombies live on edges of the tree and chew through edges so that tree falls apart! Plants can be purchased and placed on vertices of the tree to protect the tree from falling apart. It is not possible to plant more than one plant on the same vertex. A plant protects one or more adjacent edges, depending on the strength and capabilities of the plant.

The Almanac offers you to buy any of three different types of plants:

  • PEASHOOTERS: These are your first line of defense and can shoot peas along any one edge (of your choosing) adjacent to the vertex upon which it is placed. Cost: $100 per plant.
  • SPLIT PEAS: These are hard working pea shooters and can shoot peas along any two edges (of your choosing) adjacent to the vertex upon which it is placed. Cost: $175 per plant.
  • STARFRUIT: Having just visited the dentist, a STARFRUIT is very upset and shoots stars along all edges adjacent to the vertex upon which it is placed. Cost: $500 per plant.

Your goal is to protect the tree from the Zombies by having every edge covered by at least one plant, and doing so spending the least amount of money. You can buy more than one of each type of plant, but you can only plant at most one plant on each vertex.

Input

The input starts with an integer T - the number of test cases (T ≤ 100). T cases follow, each starting with the integer N on the first line, the number of vertices in G (2 ≤ N ≤ 10,000). N − 1 line follows, each containing two space separated integers u and v (0 ≤ u, vN − 1, uv) - describing an edge.

Output

For each test case, print on a separate line the minimum cost of protecting the tree, formatted like in the sample output.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6053 - And Then, How Many Are There?   

Description

To Mr. Solitarius, who is a famous solo play game creator, a new idea occurs like every day. His new game requires discs of various colors and sizes.

To start with, all the discs are randomly scattered around the center of a table. During the play, you can remove a pair of discs of the same color if neither of them has any discs on top of it. Note that a disc is not considered to be on top of another when they are externally tangent to each other.


Figure. Seven discs on the table

For example, in figure, you can only remove the two black discs first and then their removal makes it possible to remove the two white ones. In contrast, gray ones never become removable.

You are requested to write a computer program that, for given colors, sizes, and initial placings of discs, calculates the maximum number of discs that can be removed.

Input

The input consists of multiple datasets, each being in the following format and representing the state of a game just after all the discs are scattered.

n
x1 y1 r1 c1
x2 y2 r2 c2

xn yn rn cn

The first line consists of a positive integer n representing the number of discs. The following n lines, each containing 4 integers separated by a single space, represent the colors, sizes, and initial placings of the n discs in the following manner:

  • (xi, yi), ri, and ci are the xy-coordinates of the center, the radius, and the color index number, respectively, of the i-th disc, and
  • whenever the i-th disc is put on top of the j-th disc, i < j must be satisfied.

You may assume that every color index number is between 1 and 4, inclusive, and at most 6 discs in a dataset are of the same color. You may also assume that the x- and y-coordinates of the center of every disc are between 0 and 100, inclusive, and the radius between 1 and 100, inclusive.

The end of the input is indicated by a single zero.

Output

For each dataset, print a line containing an integer indicating the maximum number of discs that can be removed.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6054 - Taxi Cab Scheme   

Description

Running a taxi station is not all that simple. Apart from the obvious demand for a centralised coordination of the cabs in order to pick up the customers calling to get a cab as soon as possible, there is also a need to schedule all the taxi rides which have been booked in advance. Given a list of all booked taxi rides for the next day, you want to minimise the number of cabs needed to carry out all of the rides.

For the sake of simplicity, we model a city as a rectangular grid. An address in the city is denoted by two integers: the street and avenue number. The time needed to get from the address a, b to c, d by taxi is |a - c| + |b - d| minutes. A cab may carry out a booked ride if it is its first ride of the day, or if it can get to the source address of the new ride from its latest, at least one minute before the new rides scheduled departure. Note that some rides may end after midnight.

Input

3On the first line of the input is a single positive integer N, telling the number of test scenarios to follow. Each scenario begins with a line containing an integer M, 0 < M < 500, being the number of booked taxi rides. The following M lines contain the rides. Each ride is described by a departure time on the format hh:mm (ranging from 00:00 to 23:59), two integers a b that are the coordinates of the source address and two integers c d that are the coordinates of the destination address. All coordinates are at least 0 and strictly smaller than 200. The booked rides in each scenario are sorted in order of increasing departure time.

Output

For each scenario, output one line containing the minimum number of cabs required to carry out all the booked taxi rides.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6056 - Network   

Description

A Telephone Line Company (TLC) is establishing a new telephone cable network. They are connecting several places numbered by integers from 1 to N. No two places have the same number. The lines are bidirectional and always connect together two places and in each place the lines end in a telephone exchange. There is one telephone exchange in each place. From each place it is possible to reach through lines every other place, however it need not be a direct connection, it can go through several exchanges. From time to time the power supply fails at a place and then the exchange does not operate. The officials from TLC realized that in such a case it can happen that besides the fact that the place with the failure is unreachable, this can also cause that some other places cannot connect to each other. In such a case we will say the place (where the failure occured) is critical. Now the officials are trying to write a program for finding the number of all such critical places. Help them.

Input

The input file consists of several blocks of lines. Each block describes one network. In the first line of each block there is the number of places N < 100. Each of the next at most N lines contains the number of a place followed by the numbers of some places to which there is a direct line from this place. These at most N lines completely describe the network, i.e., each direct connection of two places in the network is contained at least in one row. All numbers in one line are separated by one space. Each block ends with a line containing just 0. The last block has only one line with N = 0.

Output

The output contains for each block except the last in the input file one line containing the number of critical places.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6058 - Proving Equivalences   

Description

Consider the following exercise, found in a generic linear algebra textbook.

Let A be an n × n matrix. Prove that the following statements are equivalent:

(a) A is invertible.

(b) Ax = b has exactly one solution for every n × 1 matrix b.

(c) Ax = b is consistent for every n × 1 matrix b.

(d) Ax = 0 has only the trivial solution x = 0.

The typical way to solve such an exercise is to show a series of implications. For instance, one can proceed by showing that (a) implies (b), that (b) implies (c), that (c) implies (d), and finally that (d) implies (a). These four implications show that the four statements are equivalent.

Another way would be to show that (a) is equivalent to (b) (by proving that (a) implies (b) and that (b) implies (a)), that (b) is equivalent to (c), and that (c) is equivalent to (d). However, this way requires proving six implications, which is clearly a lot more work than just proving four implications!

I have been given some similar tasks, and have already started proving some implications. Now I wonder, how many more implications do I have to prove? Can you help me determine this?

Input

On the first line one positive number: the number of testcases, at most 100. After that per testcase:

  • One line containing two integers n (1 ≤ n ≤ 20000) and m (0 ≤ m ≤ 50000): the number of statements and the number of implications that have already been proved.
  • m lines with two integers s1 and s2 (1 ≤ s1, s2n and s1s2) each, indicating that it has been proved that statement s1 implies statement s2.

Output

Per testcase:

  • One line with the minimum number of additional implications that need to be proved in order to prove that all statements are equivalent.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6059 - Movie collection   

Description

Mr. K. I. has a very big movie collection. He has organized his collection in a big stack. Whenever he wants to watch one of the movies, he locates the movie in this stack and removes it carefully, ensuring that the stack doesn’t fall over. After he finishes watching the movie, he places it at the top of the stack.

Since the stack of movies is so big, he needs to keep track of the position of each movie. It is sufficient to know for each movie how many movies are placed above it, since, with this information, its position in the stack can be calculated. Each movie is identified by a number printed on the movie box.

Your task is to implement a program which will keep track of the position of each movie. In particular, each time Mr. K. I. removes a movie box from the stack, your program should print the number of movies that were placed above it before it was removed.

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 ≤ 100,000): the number of movies in the stack and the number of locate requests.

one line with m integers a1, …, am (1 ≤ ain) representing the identification numbers of movies that Mr. K. I. wants to watch.

For simplicity, assume the initial stack contains the movies with identification numbers 1, 2, …, n in increasing order, where the movie box with label 1 is the top-most box.

Output

Per test case:

one line with m integers, where the i-th integer gives the number of movie boxes above the box with label ai, immediately before this box is removed from the stack.

Note that after each locate request ai, the movie box with label ai is placed at the top of the stack.

Sample Input  Download

Sample Output  Download

Tags




Discuss




6500 - Colorful World and Monochromatic World   

Description

A famous advertisement slogan says, "If liver is healthy, then life is colorful. If liver is ill, then life is black and white." A healthy person and a ill person may get different feelings within the same view. In order to understand the difference, you are asked to transform a colorful image to a grayscale image. The transform formula for every pixels is:

ceil( (RED + GREEN + BLUE) / 3) = GRAY

RED, GREED, and BLUE stands for the intensity level of the colorful image. Similiarly, GRAY stands for the intensity level of the grayscale image.

Input

Input contains several test cases. Each case begins with two integers H and W (1 <= H, W <= 256) which presents the height and width of the colorful image. In following H lines, each line contains W pixels. A pixel is composed of three integer r, g, b (0 <= r, g, b <= 255) which presents the RED, GREEN, and BLUE intensity level. All integers in the same line are seperated by single space.

Output

Input and output format are identical. For each pixel in the output, assign the same intensity level to r, g and b with corresponding grayscale intensity level.

Sample Input  Download

Sample Output  Download

Tags




Discuss




8001 - Problem B   

Description

Input

每一行有一整數 N (1 ≤ N ≤ 26),輸入以 EOF 做結。

Output

對於每一行輸入,輸出一行答案。

Sample Input  Download

Sample Output  Download

Tags




Discuss




8002 - Problem C   

Description


Figure. ABCDEFGHIJKLMOPQRSTUVWXYZ

Input

每一行有兩個整數 NM (1 ≤ N ≤ 2, 1 ≤ M ≤ 9),輸入以 EOF 做結。

Output

對於每一行輸入,輸出一行恰包含一個大寫的英文字母。輸入保證其合法性,即不會出現沒有答案的 NM

Sample Input  Download

Sample Output  Download

Tags




Discuss




8003 - Problem D   

Description

Input

每一筆測資佔用一行,由包含大小寫英文字母的字串 S (|S| ≤ 100) 組成。輸入以 EOF 做結。

Output

對於每一筆輸入,輸出一個非負整數,一個數字佔用一行。

Sample Input  Download

Sample Output  Download

Tags




Discuss




8004 - Problem E   

Description

Hot Stone 以好吃的冰淇淋名聞遐邇。每天店還沒有開門就會有許多顧客在門口排隊等候店家開始營業,而在開賣之後人龍更往往排滿街口,影響到附近交通。雖然生意興隆老闆很開心,但過量的顧客也讓她感到困擾,因此她決定要改變販售方式以減少這樣的情形。

每天開始營業之後,排在隊伍最前頭,也就是第一位顧客,將可以免費獲得她想要的冰淇淋,而第二位顧客能以 1 元購得所需。從第三位顧客開始,花費的金錢將是前兩位顧客的和,依此類推。

 

 

兔子 kerker 今天也排在隊伍當中等候冰淇淋開賣,在開門時總共有 2 × N + M + 1 位顧客在隊伍中。其中 kerker 前面排了 N 個人, kerker 後面排了比在牠前面還多 M 個的人。現在請你算算每個人將會付出多少錢才能買到冰淇淋。

Input

每一筆測資佔用一行,由三個以空白隔開的整數 N, M, Q (1 ≤ N ≤ 5, 1 ≤ M ≤ 5, 1 ≤ Q < 2 × N + M + 1) 組成。輸入以 EOF 做結。

Output

對於每一筆輸入,輸出一行包含一個整數,代表隊伍中的第 Q 個人所要花費的金錢。

Sample Input  Download

Sample Output  Download

Tags




Discuss




8005 - Problem F   

Description

Input

每一筆測資佔用一行,由包含小寫英文字母和空白的字串 S (|S| ≤ 20) 組成。輸入以 EOF 做結。

Output

對於每一筆測資均輸出一行答案,具體輸出內容請參考 Sample Output。

Sample Input  Download

Sample Output  Download

Tags




Discuss




9001 - Add Big Numbers   

Description

Give two signed numbers, output their sum. Those two numbers may be too large to be represented by long long data type.  Need a data structure to store their data.

Input

The input consists of many lines. Each line has two numbers, which are between -6*10100 to 6*10100.

Output

For each case, output their sum.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9002 - Factorials   

Description

Calculate N! = 1×2×...×(N-1)×N.  Note the number may exceed the range of integer or long long data type.  Need to define a data structure to store the computed results.

Input

There are multiple test cases.  Each test case is in a line, containing a number N (1<= N <= 114).  The input terminates when N=0.

Output

For each case, output N!

Sample Input  Download

Sample Output  Download

Tags




Discuss




9003 - Power   

Description

Compute ab for the given integers a and b.

Input

The first line of input contains a positive integer t (t <= 100), which indicates the number of test cases.  For each case, there are two positive number a, b in a line (0 < a, b <= 250).

Output

For each test case, output in a single line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9004 - A+B in radix N   

Description

Output the sum of A+B in radix N.

Input

For each line, there are three positive integers, N, A and B. (2 <= N <= 16,  A, B is at most 100-digits) A and B are represented in radix N.

Output

For each line a case, output the sum of A+B in radix N.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9005 - AxB   

Description

Compute A*B.

Input

For each case a line, there will be two positive integers A and B < 10^100.

Output

For each case a line, output the answer A*B.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9006 - Carry In   

Description

Compute how many carries occur when calculating A + B.

Input

For each case a line, there will be two positive integers A and B < 10100.

Output

For each case a line, output how many times carries occur.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9007 - Fibonacci number   

Description

Given N, calculate the N'th Fibonacci number.

Input

For each case a line, there is a positive integer N. ( 1 <= N <= 1000 )
There are at most 20 cases.

Output

For each case a line, print the N'th Fibonacci number.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9008 - Encryption   

Description

We can encrypt a string into other string.  One method is to put a string into an n×n array first, where n is the smallest number such that n2 is equal to or larger than the length of the string.  Each character is put into a cell of the array, from the top left cell of the array and along neighboring cells in the counterclockwise order.  The encrypted string is the output of the row major order.  For example, the input string "Greed is good", whose length is 13, are put into a 4×4 array, as shown in the following figure.

The output string is "Googrd  e  sed i".

If the end of the encrypted string are spaces, don't output them.  For example, the output of "Bass GG" is "B Ga Gss".

Input

The input consists of multiple lines.  Each line is a test case, a string S with length <= 1000.  The number of test case is less than 100.

Output

For each test case, output the encrypted string of S.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9009 - Partial Sum   

Description

Given n integers and q queries, in which each query defines a range, find the sum of the n given integers within this range.

Input

The first line contains an integer t(1<=t<=20), which indicates the number of test cases. In each test case, the first line contains an integer n (n<=105), specifying how many integers will be given. The next line contains n integers, in which the ith integer represents ai (-50000 <= ai <= 50000). The followed line contains a positive integer q (q <= 104), denoting the number of queries. Next q lines define q queries, one per line. Each query is specified by two integers a and b(1<=a<=b<=n), meaning a range, in which the partial sum of the given integers are queried.

Output

For each query, output a line with the partial sum of the given integers within the queried range.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9010 - Polynomial Addition   

Description

Given two polynomials please calculate the result of adding these two polynomials.

A = Cnxn + Cn-1xn-1 + ... + C0 

B = C'mxm + C'm-1xm-1 + ... + C'0 

Input

The first line contains an integer t (1 <= t <= 20), which indicates the number of test cases in the input. For each case, the first line contains two integers n, m(n, m <= 1000). Integer n means the highest power of the first polynomial. Integer m means the highest power of the second polynomial. In the next 2 lines, the first line contains n+1 integers, which means the coefficients of the polynomial A from high to low. The second line contains m+1 integers, which means the coefficients of the polynomial B from high to low. All coefficients are less or equal than 105.

Output

For each case, output a line with the coefficients of the polynomial A+B. There is a space between two consecutive numbers.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9011 - Minesweeper   

Description

 The problem is about minesweeper. Given an N*N matrix A whose elements are either 0 or 1. Output the another N*N matrix B. Every element in B is the sum of the adjacency “8” elements in the same location in A. If an element is on the boundary, the adjacency elements may not be “8”.

Input

The input includes multiple test cases. In each test case, the first line contains one integer N. The next N lines follow. Every line contains N elements which are either 1 or 0.

1 <= N <=100

Output

Output N lines. Every line contains N integers. Every two numbers are separated by single space.

 

 

Sample Input  Download

Sample Output  Download

Tags




Discuss




9012 - Word Frequency   

Description

Given an article, find the number of appearance for queried strings.

Input

The input includes multiple test cases. In each test case, the first line contains two integers, N and M (0 < N < 10, 0 < M < 100).  N indicates the number of lines in the article, and M indicates the number of strings needs to search.  The next N lines are for the article, and the length of each line < 200.  The followed M lines contains M queried, one per line.  The alphabet of strings is (a-z, A-Z) and digit (0-9).

Output

For each string, output the string and the number of appearance in the article, separate by ‘:’. Uppercase and lowercase are treated as the same alphabet.
Print a blank line after the output of each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9013 - Longest Common Substring   

Description

Given two strings, find the length of the longest common substring.

Input

The first line of input contains a positive integer t (t <= 100), which indicates the number of test cases.  For each case, there are two strings in a line (length of the string < 1000).

Output

Output the length of the longest common substring.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9014 - Find the Longest Palindrome   

Description

Palindrome is a string that is identical to its reverse, like "level" or "aba". Given a string, find the longest palindrome in the string.

Input

The input consists of multiple lines. Each line contains a string.  The length of each string is less than 1000.  The number of test case is less than or equal to 700.

Output

In each test case, output the longest palindrome in the string. If there are many palindromes of the same length, output the first one in the string.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9015 - Palindrome   

Description

Palindrome is a string that is identical to its reverse, like "level" or "aba".  Check whether a given string is a palindrome or not.

Input

The input consists of multiple lines. Each line contains a string. The length of each string is less than 100000.  The number of test case is less than 1000.

Output

For each test case, output "Yes" if it's a palindrome or "No" if it's not a palindrome in a line.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9016 - String Reverse   

Description

Given a string S, output the reverse of S.

Input

The input consists of multiple lines.  Each line is a string S with length <= 1000000.  The number of test case is less than 100.

Output

Output the reverse of S.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9017 - Alphabetically order   

Description

Given two strings, output them in alphabetical order.
Note: the order is AaBbCcDd ... YyZz.

Input

For each case a line, there are two strings separated by a single space. The lengths of the strings are no more than 30.

Output

For each case a line, output the two strings in alphabetical order, separated by a single space.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9018 - Tree   

Description

Given the relationship of the nodes in a tree, construct the tree and output it in the pre-order.  Each node has unique integer identification (ID), but all IDs may not be consecutive.

Input

There are multiple test cases.  Each test case begins with an integer N (1 <= N <=1000), denoting the number of relations in the tree.  In the following N lines, each line contains two integers a and b (1 <= a,b <= 1000), which means node a is node b’s parent.   After that, the next line contains an integer R, which represents the root of the tree.  You can assume that all the nodes will be on the same tree.  The input is terminated by N = 0.

Output

For each test case, print the pre-order of the tree.  In each level, traverse the node with smaller ID first.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9019 - Territory Expansion   

Description

There are many countries in a map.  Each of them has a unique ID, which is a positive integer.  All of them want to expand their territories. A country can expand its territory if its neighboring land (up, down, left, and right) has not been occupied by any other countries.  The speeds of expanding territories of all countries are the same.  If two or more countries want to occupy the same land, the country with the smaller ID can occupy the land.  The expansion stops if no changes of the map can be made.

Input

The input file begins with an integer T (1 < T < 1000), indicating the number of test cases. Each test case begins with two integers N and M (0 < N < 300, 0 < M < 300), indicating the height and the width of the map.  Next N lines specify the occupancy of the map.  The number 0 means the land has not been occupied, and the number > 0 denotes the country ID, which is smaller than 10.

Output

For each case, output the final occupancy map.  Print a blank after each case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9020 - Is it a forest?   

Description

Given a graph, output "Yes" if it's a forest, otherwise "No".
Hint: You can use disjoint set or a DFS with adjacency list to solve this problem.

Input

For each case, The first line contains two positive integers N and M (2 <= N <= 1000000), and N denotes the number of node. In the next M lines, there will be two integers A and B, denoting the two end points of an edge (A, B).
Each case is separated by a blank line. The input is terminated by two zeros in place of N and M.

Output

For each case a line, output "Yes" if it's a forest, otherwise "No".

Sample Input  Download

Sample Output  Download

Tags




Discuss




9021 - Lowest common ancestor   

Description

Output the lowest common ancestor.

Input

The first line contains a positive integer t, which indicates how many cases in the input. For each case, the first line contains a positive integer N (1 <= N <= 100000), denoting the amount of node in the tree (labeled from 1 to N). The second line contains exactly N numbers. The first number denotes the parent of node 1, and the second number denotes the parent of node 2 ..., etc. The parent of the root will be labeled as -1.
Then multiple queries (query < 100) follow. Each line contains two positive integers A and B. The query is terminated by two zeros.
Each case is separated by a blank line.

Output

For each case a line, print the case number first, then output the node number of the least common ancestor for each query. Each answer should be separated by a single space.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9022 - Tree distance   

Description

Calculate the distance between two nodes.

Input

For each case, the first line contains a positive integer N (1 <= N <= 1000), denoting the number of node in the tree (labeled from 1 to N). The second line contains exactly N numbers. The first number denotes the parent of node 1, and the second number denotes the parent of node 2 ..., etc. The parent of the root will be labeled as -1.
Then follows multiple lines of query (query < 10000). Each line contains two positive integers A and B. The query is terminated by two zeros.

Do not assume it is a binary tree.

Output

For each case a line, print the case number first, then output the distance between A and B for each query. Each answer should be separated by a single space.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9023 - Count the Leaves   

Description

Given a tree, count the number of leaves in this tree. Each node has unique integer identification (ID), but all IDs may not be consecutive.

Input

There are multiple test cases.  Each test case begins with an integer N (1 <= N <=1000). In the following N lines, each line has two integer a and b (1 <= a,b <= 1000), indicating node a is node b’s parent.  The next line contains an integer R, which represents the root of the Tree.  You can assume that all the nodes will be on the same tree.  The input is terminated by N = 0.

Output

 Print the number of the leaves for each test case.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9024 - The Sum of a Tree Path   

Description

Given a binary tree, in which each node has an integer, determine whether there exists a tree path whose sum equal to the queried number. A tree path is a path from the root to a leaf node. The sum of a tree path is the summation of numbers in each node on a tree path. For example, in the tree shown below there are exactly three root-to-leaf paths. The sums of each path are 19, 8 and -6.

The binary tree above is represented by the expression (5(3(11()())(0()()))(1()(-12()()))). With this form, every tree node has an expression (integer()()). The range of the integer in the expression is between -100000 and 100000. And the length of the whole tree expression is at most 100 characters.

Input

The input consists of a sequence of test cases. Each test case occupies a newline. First, there is an integer indicating the query. Second, there is a space. Next, there is a binary tree representation and there are no spaces in the representation.

Output

For each test case, output “yes” or “no” in a new line to check whether the target does exist or not.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9025 - Tree Recovery   

Description

Given two strings which represent the pre-order traversal and the in-order traversal of a binary tree, generate the post-order traversal of the binary tree.

Input

The input consists of several test cases. Each test case has two strings in a line separated by a space. The first string is the pre-order traversal of the binary tree; the second string is the in-order traversal of the binary tree. Each string will contain only capital characters and the characters will be unique.

Output

For each test case, output a string to represent the post-order traversal of the binary tree.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9026 - Level-Order Traversal   

Description

Given a tree G(V, E) and its root, print its level-order traversal, where we visit all of the nodes at the same level before going to the lower ones. Each node is labeled by a unique integer number, and in case that the node has more than one child, the one who is labeled by smaller number should be visited first. The figure below illustrates the structure of two sample cases.

Figure. The illustration of two sample cases.

Input

The first line of input is a single integer T (T ≤ 100), denoting the number of test cases. Each test case started with an integer pair N (N ≤ 1000) and R, indicating the number of nodes and the root number respectively. The following N - 1 lines contain pairs of integers ui and vi (1 ≤ ui, viN), each in a line, which means ui and vi are adjacent.

Output

For each test case, output “Case i:” denoting the traversal of i-th test case on a line. Then, for each visited node, started from the root, print the labeled number. Every two successive numbers are separated by a space characters. Print a blank line between test cases.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9027 - K Characters   

Description


Given a string, output all different possible set of K characters in the string.  And sort them in the dictionary order.  For example, if K=2 and the given string is ‘CDBABBD’, output

AB
AC
AD
BB
BC
BD
CD
DD

Input

The first line of input contains a positive integer t (t <= 30), which indicates the number of test cases.  For each case, there are one strings and a positive integer K in a line. The length of the string is less than 100 and strings contain only 'A'-'K'; The number K, less than or equal to 10, indicates the length of substrings.

Output

For each test case, output all different possible set of K characters in the string.  And sort them in the dictionary order, one substring per line.  Print a blank line after each test case.

Sample Input  Download

Sample Output  Download

Tags

9424



Discuss




9028 - Fill   

Description

 

There are three jugs of volume a, b and c liters. The number a, b, and c are positive integers.  The first and the second jug are empty initially, and the third one is completely filled with water.  It is allowed to pour water from one jug into another until either the pouring jug is empty or the poured jug is full.  This operation can be performed zero, one, or more times.

 


Compute the minimum number of water pouring operations to be performed so that one of the jugs contains d’ liters of water.  The number d’ is a nonnegative integer, which is closest to but less than or equal to a given positive integer d.

Input

The first line of input contains the number of test cases. In the next T lines, T test cases follow.  Each test case is given in one line, containing four positive integers: a, b, c and d, 1 <= a, b, c, d <= 200.

Output

The output consists of two integers separated by a single space. The first integer equals the least total amount (the sum of all waters you pour from one jug to another) of poured water. The second integer equals d, if d liters of water could be produced by such transformations, or equals the closest smaller value d' that your program has found.


Sample Input  Download

Sample Output  Download

Tags




Discuss




9029 - All combinations   

Description

Given N different digits. You have to choose M digits from them to create all possible numbers in ascending order. For example, given 3 digits "4", "5", "6", and M = 2, the possible answers are "45", "46", "54", "56", "64", "65".

Input

The first line contains a positive integer T (T <= 20), which indicates how many cases in the input. Each case starts with two positive integers N and M (1 <= M <= N <= 10), which denote the amount of the digits and the amount of digits of desired numbers. The next line contains exactly n different digits (0~9) separated by blanks.

Output

For each case, first line outputs the case number. Then, output all the possible numbers in ascending order. (See the Sample Output)

Sample Input  Download

Sample Output  Download

Tags




Discuss




9030 - Blocks   

Description

Given N 1×1×1 cubes, arrange them to form a rectangular solid such that the surface area is minimized.

Input

The first line of the input contains an integer T, which is the number of test cases. Each of the next T lines contains an integer N (N ≤ 10000) denoting the number of cubes.

Output

For each case, output a line containing an integer which is the minimized surface area.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9031 - Subset sum   

Description

Given N numbers. You need to separate them A and B such that is minimum.

Input

Each case starts with a positive integer N (1 <= N <= 20), then the next line contains exactly N integers (range from -100000 to 100000).

A test case of N = 0 indicates the end of input, and should not be processed.

Output

Output one line per case that contains an integer denoting the minimum value of .

Sample Input  Download

Sample Output  Download

Tags




Discuss




9032 - Swamp maze   

Description

Given a map, find the shortest time from S (Start) to G (Goal). The size of the map is specified by two integers: N and M. Each integer grid cell of the map has a mark, whose meanings are explained as follows.

1.'.' denotes an empty space,
2.'@' denotes a swamp,
3.'#' denotes a wall,
4.'S' denotes the start point, and
5.'G' denotes the goal.

There are only one S and only one G in the map.  You can pass an empty space in 1 second, and pass a swamp in 2 seconds.  But you cannot pass a wall cell.  You are only allowed to move up, down, left, or right. 

Here is an example: A map is of size 3×5, whose marks are specified as follows

S@..#

..#..

@@@@G

The shortest time from S to G is 7 seconds

Input

The input file begins with an integer T (1 < T < 5000), indicating the number of test cases. Each test case begins with two integers N and M (0 < N < 100, 0 < M < 100), indicating the height and width of the map. In the following N lines, each line contains M characters describing the marks of the map.

Output

For each case, output the shortest time you need from the start point to the goal.  If there is no valid path from the start to the goal, output -1.

Sample Input  Download

Sample Output  Download

Tags




Discuss




9033 - Colorful map   

Description

The map is a 2-dimensional grid of squares, each square is filled with one color. You will be given a sequence of colors. You can move between adjacent squares vertically or horizontally in the given color order. '*' is where you start, and '#' is the goal.

For example, given the map as follow, and the color order "RGB":
BGRG#
RGBGR
*GRGB
There are two different ways to reach the goal:
xx456
123xx
0xxxx
and
xxxx8
123x7
0x456
So we know that the shortest path from '*' to '#' needs 6 steps.

Implement a BFS to find the smallest number of steps to reach the goal.

Input

The input consists of several maps. Each map begins with a line containing two integers N and M (1 <= N, M <= 10^3) specifying the map height and width. The next N lines will be M upper case letters, '*', or '#'. Each letter denotes one color.
The next line is a string that specifies the color order. One color won’t appear twice in the given order.

Each case is separated by a blank line. The input is terminated by two zeros.

Output

For each map, print one line containing the smallest possible number of step to reach the goal. If there's no way to reach the goal, output the string "No solution." instead. One step is defined as a movement between two adjacent cells.

Sample Input  Download

Sample Output  Download

Tags




Discuss