group_id
stringlengths
12
18
problem_description
stringlengths
85
3.02k
candidates
listlengths
3
20
aoj_1231_cpp
Problem H: Super Star During a voyage of the starship Hakodate-maru (see Problem A), researchers found strange synchronized movements of stars. Having heard these observations, Dr. Extreme proposed a theory of "super stars". Do not take this term as a description of actors or singers. It is a revolutionary theory in astronomy. According to this theory, stars we are observing are not independent objects, but only small portions of larger objects called super stars. A super star is filled with invisible (or transparent) material, and only a number of points inside or on its surface shine. These points are observed as stars by us. In order to verify this theory, Dr. Extreme wants to build motion equations of super stars and to compare the solutions of these equations with observed movements of stars. As the first step, he assumes that a super star is sphere-shaped, and has the smallest possible radius such that the sphere contains all given stars in or on it. This assumption makes it possible to estimate the volume of a super star, and thus its mass (the density of the invisible material is known). You are asked to help Dr. Extreme by writing a program which, given the locations of a number of stars, finds the smallest sphere containing all of them in or on it. In this computation, you should ignore the sizes of stars. In other words, a star should be regarded as a point. You may assume the universe is a Euclidean space. Input The input consists of multiple data sets. Each data set is given in the following format. n x 1 y 1 z 1 x 2 y 2 z 2 ... x n y n z n The first line of a data set contains an integer n , which is the number of points. It satisfies the condition 4 ≤ n ≤ 30. The locations of n points are given by three-dimensional orthogonal coordinates: ( x i , y i , z i ) ( i = 1,..., n ). Three coordinates of a point appear in a line, separated by a space character. Each value is given by a decimal fraction, and is between 0.0 and 100.0 (both ends inclusive). Points are at least 0.01 distant from each other. The end of the input is indicated by a line containing a zero. Output For each data set, the radius ofthe smallest sphere containing all given points should be printed, each in a separate line. The printed values should have 5 digits after the decimal point. They may not have an error greater than 0.00001. Sample Input 4 10.00000 10.00000 10.00000 20.00000 10.00000 10.00000 20.00000 20.00000 10.00000 10.00000 20.00000 10.00000 4 10.00000 10.00000 10.00000 10.00000 50.00000 50.00000 50.00000 10.00000 50.00000 50.00000 50.00000 10.00000 0 Output for the Sample Input 7.07107 34.64102
[ { "submission_id": "aoj_1231_10848858", "code_snippet": "//\n// main.cpp\n// poj 2069 Problem B : Super Star\n//\n// Created by nuu_tong on 2018/4/20.\n// Copyright © 2018年 apple. All rights reserved.\n//\n\n#include <iostream>\n#include <cmath>\n#include <cstdio>\nusing namespace std;\nstruct Point\n{\...
aoj_1246_cpp
Problem G: Concert Hall Scheduling You are appointed director of a famous concert hall, to save it from bankruptcy. The hall is very popular, and receives many requests to use its two fine rooms, but unfortunately the previous director was not very efficient, and it has been losing money for many years. The two rooms are of the same size and arrangement. Therefore, each applicant wishing to hold a concert asks for a room without specifying which. Each room can be used for only one concert per day. In order to make more money, you have decided to abandon the previous fixed price policy, and rather let applicants specify the price they are ready to pay. Each application shall specify a period [ i , j ] and an asking price w , where i and j are respectively the first and last days of the period (1 ≤ i ≤ j ≤ 365), and w is a positive integer in yen, indicating the amount the applicant is willing to pay to use a room for the whole period. You have received applications for the next year, and you should now choose the applications you will accept. Each application should be either accepted for its whole period or completely rejected. Each concert should use the same room during the whole applied period. Considering the dire economic situation of the concert hall, artistic quality is to be ignored, and you should just try to maximize the total income for the whole year by accepting the most profitable applications. Input The input has multiple data sets, each starting with a line consisting of a single integer n, the number of applications in the data set. Then, it is followed by n lines, each of which represents one application with a period [ i , j ] and an asking price w yen in the following format. i j w A line containing a single zero indicates the end of the input. The maximum number of applications in a data set is one thousand, and the maximum asking price is one million yen. Output For each data set, print a single line containing an integer, the maximum total income in yen for the data set. Sample Input 4 1 2 10 2 3 10 3 3 10 1 3 10 6 1 20 1000 3 25 10000 5 15 5000 22 300 5500 10 295 9000 7 7 6000 8 32 251 2261 123 281 1339 211 235 5641 162 217 7273 22 139 7851 194 198 9190 119 274 878 122 173 8640 0 Output for the Sample Input 30 25500 38595
[ { "submission_id": "aoj_1246_9706976", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)\n#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)\n#define ALL(v) (v).begin(), (v).end()\n#define UNIQUE(v) sort(ALL(v)...
aoj_1242_cpp
Problem C: Area of Polygons Yoko’s math homework today was to calculate areas of polygons in the xy -plane. Vertices are all aligned to grid points (i.e. they have integer coordinates). Your job is to help Yoko, not good either at math or at computer programming, get her home- work done. A polygon is given by listing the coordinates of its vertices. Your program should approximate its area by counting the number of unit squares (whose vertices are also grid points) intersecting the polygon. Precisely, a unit square “intersects the polygon” if and only if the in- tersection of the two has non-zero area. In the figure below, dashed horizontal and vertical lines are grid lines, and solid lines are edges of the polygon. Shaded unit squares are considered inter- secting the polygon. Your program should output 55 for this polygon (as you see, the number of shaded unit squares is 55). Figure 1: A polygon and unit squares intersecting it Input The input file describes polygons one after another, followed by a terminating line that only contains a single zero. A description of a polygon begins with a line containing a single integer, m (≥ 3), that gives the number of its vertices. It is followed by m lines, each containing two integers x and y , the coordinates of a vertex. The x and y are separated by a single space. The i -th of these m lines gives the coordinates of the i -th vertex ( i = 1, ... , m ). For each i = 1, ... , m - 1, the i -th vertex and the ( i + 1)-th vertex are connected by an edge. The m -th vertex and the first vertex are also connected by an edge (i.e., the curve is closed). Edges intersect only at vertices. No three edges share a single vertex (i.e., the curve is simple). The number of polygons is no more than 100. For each polygon, the number of vertices ( m ) is no more than 100. All coordinates x and y satisfy -2000 ≤ x ≤ 2000 and -2000 ≤ y ≤ 2000. Output The output should consist of as many lines as the number of polygons. The k -th output line should print an integer which is the area of the k -th polygon, approximated in the way described above. No other characters, including whitespaces, should be printed. Sample Input 4 5 -3 1 0 1 7 -7 -1 3 5 5 18 5 5 10 3 -5 -5 -5 -10 -18 -10 5 0 0 20 2 11 1 21 2 2 0 0 Output for the Sample Input 55 41 41 23
[ { "submission_id": "aoj_1242_10851351", "code_snippet": "#include<iostream>\n#include<cstdio>\n#include<algorithm>\n#include<cmath>\nusing namespace std;\nconst double eps=1e-8;\nstruct Point{double x,y;}p[1005];\nstruct seg{Point A,B;}s[1005];\nstruct SEG{int x,y;SEG(int _x=0,int _y=0){x=_x;y=_y;}}t[1005];...
aoj_1250_cpp
Problem C: Leaky Cryptography The ACM ICPC judges are very careful about not leaking their problems, and all communications are encrypted. However, one does sometimes make mistakes, like using too weak an encryption scheme. Here is an example of that. The encryption chosen was very simple: encrypt each chunk of the input by flipping some bits according to a shared key. To provide reasonable security, the size of both chunk and key is 32 bits. That is, suppose the input was a sequence of m 32-bit integers. N 1 N 2 N 3 ... N m After encoding with the key K it becomes the following sequence of m 32-bit integers. ( N 1 ∧ K ) ( N 2 ∧ K ) ( N 3 ∧ K ) ... ( N m ∧ K ) where ( a ∧ b ) is the bitwise exclusive or of a and b . Exclusive or is the logical operator which is 1 when only one of its operands is 1, and 0 otherwise. Here is its definition for 1-bit integers. 0 ⊕ 0 = 0 0 ⊕ 1 = 1 1 ⊕ 0 = 1 1 ⊕ 1 =0 As you can see, it is identical to addition modulo 2. For two 32-bit integers a and b , their bitwise exclusive or a ∧ b is defined as follows, using their binary representations, composed of 0's and 1's. a ∧ b = a 31 ... a 1 a 0 ∧ b 31 ... b 1 b 0 = c 31 ... c 1 c 0 where c i = a i ⊕ b i ( i = 0, 1, ... , 31). For instance, using binary notation, 11010110 ∧ 01010101 = 10100011, or using hexadecimal, d6 ∧ 55 = a3. Since this kind of encryption is notoriously weak to statistical attacks, the message has to be compressed in advance, so that it has no statistical regularity. We suppose that N 1 N 2 ... N m is already in compressed form. However, the trouble is that the compression algorithm itself introduces some form of regularity: after every 8 integers of compressed data, it inserts a checksum, the sum of these integers. That is, in the above input, N 9 = ∑ 8 i =1 N i = N 1 + ... + N 8 , where additions are modulo 2 32 . Luckily, you could intercept a communication between the judges. Maybe it contains a problem for the finals! As you are very clever, you have certainly seen that you can easily find the lowest bit of the key, denoted by K 0 . On the one hand, if K 0 = 1, then after encoding, the lowest bit of ∑ 8 i =1 N i ∧ K is unchanged, as K 0 is added an even number of times, but the lowest bit of N 9 ∧ K is changed, so they shall differ. On the other hand, if K 0 = 0, then after encoding, the lowest bit of ∑ 8 i =1 N i ∧ K shall still be identical to the lowest bit of N 9 ∧ K , as they do not change. For instance, if the lowest bits after encoding are 1 1 1 1 1 1 1 1 1 then K 0 must be 1, but if they are 1 1 1 1 1 1 1 0 1 then K 0 must be 0. So far, so good. Can you do better? You should find the key used for encoding. Input The input starts with a line containing only a positive integer S , indicating the number of datasets in the input. S is no more than 1000. It is followed by S datasets. Each dataset is composed of nine 32-bit integers corresponding to the first nine chunks of a communication. They are written in hexadecimal notati ...(truncated)
[ { "submission_id": "aoj_1250_4304282", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long int;\nusing ull = unsigned long long int;\nusing P = pair<ll, ll>;\n\nll decode(string s){\n ll res = 0;\n for(auto c : s){\n res <<= 4;\n if(isdigit(c)){\n ...
aoj_1245_cpp
Problem F: Gap Let’s play a card game called Gap. You have 28 cards labeled with two-digit numbers. The first digit (from 1 to 4) represents the suit of the card, and the second digit (from 1 to 7) represents the value of the card. First, you shuffle the cards and lay them face up on the table in four rows of seven cards, leaving a space of one card at the extreme left of each row. The following shows an example of initial layout. Next, you remove all cards of value 1, and put them in the open space at the left end of the rows: “11” to the top row, “21” to the next, and so on. Now you have 28 cards and four spaces, called gaps, in four rows and eight columns. You start moving cards from this layout. At each move, you choose one of the four gaps and fill it with the successor of the left neighbor of the gap. The successor of a card is the next card in the same suit, when it exists. For instance the successor of “42” is “43”, and “27” has no successor. In the above layout, you can move “43” to the gap at the right of “42”, or “36” to the gap at the right of “35”. If you move “43”, a new gap is generated to the right of “16”. You cannot move any card to the right of a card of value 7, nor to the right of a gap. The goal of the game is, by choosing clever moves, to make four ascending sequences of the same suit, as follows. Your task is to find the minimum number of moves to reach the goal layout. Input The input starts with a line containing the number of initial layouts that follow. Each layout consists of five lines - a blank line and four lines which represent initial layouts of four rows. Each row has seven two-digit numbers which correspond to the cards. Output For each initial layout, produce a line with the minimum number of moves to reach the goal layout. Note that this number should not include the initial four moves of the cards of value 1. If there is no move sequence from the initial layout to the goal layout, produce “-1”. Sample Input 4 12 13 14 15 16 17 21 22 23 24 25 26 27 31 32 33 34 35 36 37 41 42 43 44 45 46 47 11 26 31 13 44 21 24 42 17 45 23 25 41 36 11 46 34 14 12 37 32 47 16 43 27 35 22 33 15 17 12 16 13 15 14 11 27 22 26 23 25 24 21 37 32 36 33 35 34 31 47 42 46 43 45 44 41 27 14 22 35 32 46 33 13 17 36 24 44 21 15 43 16 45 47 23 11 26 25 37 41 34 42 12 31 Output for the Sample Input 0 33 60 -1
[ { "submission_id": "aoj_1245_10853948", "code_snippet": "#include <iostream>\n#include <cstring>\n#include <climits>\n#include <queue>\n#include <unordered_set>\n \nusing namespace std;\n \nclass State\n{\npublic:\n /**\n * 表格数字\n */\n int table[4][8];\n /**\n * 移动回数\n */\n int t...
aoj_1248_cpp
Problem A: The Balance Ms. Iyo Kiffa-Australis has a balance and only two kinds of weights to measure a dose of medicine. For example, to measure 200mg of aspirin using 300mg weights and 700mg weights, she can put one 700mg weight on the side of the medicine and three 300mg weights on the opposite side (Figure 1). Although she could put four 300mg weights on the medicine side and two 700mg weights on the other (Figure 2), she would not choose this solution because it is less convenient to use more weights. You are asked to help her by calculating how many weights are required. Figure 1: To measure 200mg of aspirin using three 300mg weights and one 700mg weight Figure 2: To measure 200mg of aspirin using four 300mg weights and two 700mg weights Input The input is a sequence of datasets. A dataset is a line containing three positive integers a , b , and d separated by a space. The following relations hold: a ≠ b , a ≤ 10000, b ≤ 10000, and d ≤ 50000. You may assume that it is possible to measure d mg using a combination of a mg and b mg weights. In other words, you need not consider “no solution” cases. The end of the input is indicated by a line containing three zeros separated by a space. It is not a dataset. Output The output should be composed of lines, each corresponding to an input dataset ( a , b , d ). An output line should contain two nonnegative integers x and y separated by a space. They should satisfy the following three conditions. You can measure d mg using x many a mg weights and y many b mg weights. The total number of weights ( x + y ) is the smallest among those pairs of nonnegative integers satisfying the previous condition. The total mass of weights ( ax + by ) is the smallest among those pairs of nonnegative integers satisfying the previous two conditions. No extra characters (e.g. extra spaces) should appear in the output. Sample Input 700 300 200 500 200 300 500 200 500 275 110 330 275 110 385 648 375 4002 3 1 10000 0 0 0 Output for the Sample Input 1 3 1 1 1 0 0 3 1 1 49 74 3333 1
[ { "submission_id": "aoj_1248_10852694", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nll EX_GCD(ll a, ll b, ll& x, ll& y) {\n\tll d = a;\n\tif (b != 0) {\n\t\td = EX_GCD(b, a % b, y, x);\n\t\ty -= (a / b) * x;\n\t}\n\telse {\n\t\tx = 1;\n\t\ty = 0;\n\t}\n\treturn ...
aoj_1249_cpp
Problem B: Make a Sequence Your company’s next product will be a new game, which is a three-dimensional variant of the classic game “Tic-Tac-Toe”. Two players place balls in a three-dimensional space (board), and try to make a sequence of a certain length. People believe that it is fun to play the game, but they still cannot fix the values of some parameters of the game. For example, what size of the board makes the game most exciting? Parameters currently under discussion are the board size (we call it n in the following) and the length of the sequence ( m ). In order to determine these parameter values, you are requested to write a computer simulator of the game. You can see several snapshots of the game in Figures 1-3. These figures correspond to the three datasets given in the Sample Input. Figure 1: A game with n = m = 3 Here are the precise rules of the game. Two players, Black and White, play alternately. Black plays first. There are n × n vertical pegs. Each peg can accommodate up to n balls. A peg can be specified by its x - and y -coordinates (1 ≤ x , y ≤ n ). A ball on a peg can be specified by its z -coordinate (1 ≤ z ≤ n ). At the beginning of a game, there are no balls on any of the pegs. Figure 2: A game with n = m = 3 (White made a 3-sequence before Black) On his turn, a player chooses one of n × n pegs, and puts a ball of his color onto the peg. The ball follows the law of gravity. That is, the ball stays just above the top-most ball on the same peg or on the floor (if there are no balls on the peg). Speaking differently, a player can choose x - and y -coordinates of the ball, but he cannot choose its z -coordinate. The objective of the game is to make an m -sequence. If a player makes an m -sequence or longer of his color, he wins. An m -sequence is a row of m consecutive balls of the same color. For example, black balls in positions (5, 1, 2), (5, 2, 2) and (5, 3, 2) form a 3-sequence. A sequence can be horizontal, vertical, or diagonal. Precisely speaking, there are 13 possible directions to make a sequence, categorized as follows. Figure 3: A game with n = 4, m = 3 (Black made two 4-sequences) (a) One-dimensional axes. For example, (3, 1, 2), (4, 1, 2) and (5, 1, 2) is a 3-sequence. There are three directions in this category. (b) Two-dimensional diagonals. For example, (2, 3, 1), (3, 3, 2) and (4, 3, 3) is a 3-sequence. There are six directions in this category. (c) Three-dimensional diagonals. For example, (5, 1, 3), (4, 2, 4) and (3, 3, 5) is a 3- sequence. There are four directions in this category. Note that we do not distinguish between opposite directions. As the evaluation process of the game, people have been playing the game several times changing the parameter values. You are given the records of these games. It is your job to write a computer program which determines the winner of each recorded game. Since it is difficult for a human to find three-dimensional sequences ...(truncated)
[ { "submission_id": "aoj_1249_10896082", "code_snippet": "#include<bits/stdc++.h>\n// #include<atcoder/all>\n// #include<boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\n// using namespace atcoder;\n// using bint = boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ull = unsigned long lo...
aoj_1253_cpp
Problem F: Dice Puzzle Let’s try a dice puzzle. The rules of this puzzle are as follows. Dice with six faces as shown in Figure 1 are used in the puzzle. Figure 1: Faces of a die With twenty seven such dice, a 3 × 3 × 3 cube is built as shown in Figure 2. Figure 2: 3 × 3 × 3 cube When building up a cube made of dice, the sum of the numbers marked on the faces of adjacent dice that are placed against each other must be seven (See Figure 3). For example, if one face of the pair is marked “2”, then the other face must be “5”. Figure 3: A pair of faces placed against each other The top and the front views of the cube are partially given, i.e. the numbers on faces of some of the dice on the top and on the front are given. Figure 4: Top and front views of the cube The goal of the puzzle is to find all the plausible dice arrangements that are consistent with the given top and front view information. Your job is to write a program that solves this puzzle. Input The input consists of multiple datasets in the following format. N Dataset 1 Dataset 2 ... Dataset N N is the number of the datasets. The format of each dataset is as follows. T 11 T 12 T 13 T 21 T 22 T 23 T 31 T 32 T 33 F 11 F 12 F 13 F 21 F 22 F 23 F 31 F 32 F 33 T ij and F ij (1 ≤ i ≤ 3, 1 ≤ j ≤ 3) are the faces of dice appearing on the top and front views, as shown in Figure 2, or a zero. A zero means that the face at the corresponding position is unknown. Output For each plausible arrangement of dice, compute the sum of the numbers marked on the nine faces appearing on the right side of the cube, that is, with the notation given in Figure 2, ∑ 3 i =1 ∑ 3 j =1 R ij . For each dataset, you should output the right view sums for all the plausible arrangements, in ascending order and without duplicates. Numbers should be separated by a single space. When there are no plausible arrangements for a dataset, output a zero. For example, suppose that the top and the front views are given as follows. Figure 5: Example There are four plausible right views as shown in Figure 6. The right view sums are 33, 36, 32, and 33, respectively. After rearranging them into ascending order and eliminating duplicates, the answer should be “32 33 36”. Figure 6: Plausible right views The output should be one line for each dataset. The output may have spaces at ends of lines. Sample Input 4 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 4 3 3 5 2 2 4 3 3 6 1 1 6 1 1 6 1 0 1 0 0 0 2 0 0 0 0 5 1 2 5 1 2 0 0 0 2 0 0 0 3 0 0 0 0 0 0 0 0 0 0 3 0 1 Output for the Sample Input 27 24 32 33 36 0
[ { "submission_id": "aoj_1253_10946393", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nenum POS {\n TOP = 1,\n FRONT,\n RIGHT,\n LEFT,\n BACK,\n BOTTOM\n};\n\n// dice[top][front][pos];\nint dice[7][7][7];\n\nvoid init() {\n int right[7][7] = {};\n right[1][2] = 3;...
aoj_1254_cpp
Problem G: Color the Map You were lucky enough to get a map just before entering the legendary magical mystery world. The map shows the whole area of your planned exploration, including several countries with complicated borders. The map is clearly drawn, but in sepia ink only; it is hard to recognize at a glance which region belongs to which country, and this might bring you into severe danger. You have decided to color the map before entering the area. “A good deal depends on preparation,” you talked to yourself. Each country has one or more territories, each of which has a polygonal shape. Territories belonging to one country may or may not “touch” each other, i.e. there may be disconnected territories. All the territories belonging to the same country must be assigned the same color. You can assign the same color to more than one country, but, to avoid confusion, two countries “adjacent” to each other should be assigned different colors. Two countries are considered to be “adjacent” if any of their territories share a border of non-zero length. Write a program that finds the least number of colors required to color the map. Input The input consists of multiple map data. Each map data starts with a line containing the total number of territories n , followed by the data for those territories. n is a positive integer not more than 100. The data for a territory with m vertices has the following format: String x 1 y 1 x 2 y 2 ... x m y m -1 “ String ” (a sequence of alphanumerical characters) gives the name of the country it belongs to. A country name has at least one character and never has more than twenty. When a country has multiple territories, its name appears in each of them. Remaining lines represent the vertices of the territory. A vertex data line has a pair of nonneg- ative integers which represent the x - and y -coordinates of a vertex. x - and y -coordinates are separated by a single space, and y-coordinate is immediately followed by a newline. Edges of the territory are obtained by connecting vertices given in two adjacent vertex data lines, and byconnecting vertices given in the last and the first vertex data lines. None of x - and y -coordinates exceeds 1000. Finally, -1 in a line marks the end of vertex data lines. The number of vertices m does not exceed 100. You may assume that the contours of polygons are simple, i.e. they do not cross nor touch themselves. No two polygons share a region of non-zero area. The number of countries in a map does not exceed 10. The last map data is followed by a line containing only a zero, marking the end of the input data. Output For each map data, output one line containing the least possible number of colors required to color the map satisfying the specified conditions. Sample Input 6 Blizid 0 0 60 0 60 60 0 60 0 50 50 50 50 10 0 10 -1 Blizid 0 10 10 10 10 50 0 50 -1 Windom 10 10 50 10 40 20 20 20 20 40 10 50 -1 Accent 50 10 50 50 35 50 35 25 -1 Pilot 35 25 35 50 10 50 -1 Blizid 20 20 40 20 20 ...(truncated)
[ { "submission_id": "aoj_1254_10852648", "code_snippet": "#include<iostream>\n#include<cstdio>\n#include<cstring>\n#include<cmath>\nusing namespace std;\nconst double eps=1e-5;\nstruct Point\n{ int x,y;\n Point(){}\n Point(int _,int __){x=_;y=__;}\n};\nbool operator == (const Point &x,const Point &y)...
aoj_1255_cpp
Problem H: Inherit the Spheres In the year 2xxx, an expedition team landing on a planet found strange objects made by an ancient species living on that planet. They are transparent boxes containing opaque solid spheres (Figure 1). There are also many lithographs which seem to contain positions and radiuses of spheres. Figure 1: A strange object Initially their objective was unknown, but Professor Zambendorf found the cross section formed by a horizontal plane plays an important role. For example, the cross section of an object changes as in Figure 2 by sliding the plane from bottom to top. Figure 2: Cross sections at different positions He eventually found that some information is expressed by the transition of the number of connected figures in the cross section, where each connected figure is a union of discs intersecting or touching each other, and each disc is a cross section of the corresponding solid sphere. For instance, in Figure 2, whose geometry is described in the first sample dataset later, the number of connected figures changes as 0, 1, 2, 1, 2, 3, 2, 1, and 0, at z = 0.0000, 162.0000, 167.0000, 173.0004, 185.0000, 191.9996, 198.0000, 203.0000, and 205.0000, respectively. By assigning 1 for increment and 0 for decrement, the transitions of this sequence can be expressed by an 8-bit binary number 11011000. For helping further analysis, write a program to determine the transitions when sliding the horizontal plane from bottom ( z = 0) to top ( z = 36000). Input The input consists of a series of datasets. Each dataset begins with a line containing a positive integer, which indicates the number of spheres N in the dataset. It is followed by N lines describing the centers and radiuses of the spheres. Each of the N lines has four positive integers X i , Y i , Z i , and R i ( i = 1, . . . , N ) describing the center and the radius of the i -th sphere, respectively. You may assume 1 ≤ N ≤ 100, 1 ≤ R i ≤ 2000, 0 < X i - R i < X i + R i < 4000, 0 < Y i - R i < Y i + R i < 16000, and 0 < Z i - R i < Z i + R i < 36000. Each solid sphere is defined as the set of all points ( x , y , z ) satisfying ( x - X i ) 2 + ( y - Y i ) 2 + ( z - Z i ) 2 ≤ R i 2 . A sphere may contain other spheres. No two spheres are mutually tangent. Every Z i ± R i and minimum/maximum z coordinates of a circle formed by the intersection of any two spheres differ from each other by at least 0.01. The end of the input is indicated by a line with one zero. Output For each dataset, your program should output two lines. The first line should contain an integer M indicating the number of transitions. The second line should contain an M -bit binary number that expresses the transitions of the number of connected figures as specified above. Sample Input 3 95 20 180 18 125 20 185 18 40 27 195 10 1 5 5 5 4 2 5 5 5 4 5 5 5 3 2 5 5 5 4 5 7 5 3 16 2338 3465 29034 710 1571 14389 25019 842 1706 8015 11324 1155 1899 4359 33815 888 2160 10364 20511 1264 2048 8835 23706 1906 2598 13041 23 ...(truncated)
[ { "submission_id": "aoj_1255_6790069", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define rep(i, s, t) for (int i = (int)(s); i < (int)(t); ++i)\n#define revrep(i, t, s) for (int i = (int)(t)-1; i >= (int)(s); --i)\n#define all(x) begin(x), end(x)\ntemplate <type...
aoj_1259_cpp
Problem C: Colored Cubes There are several colored cubes. All of them are of the same size but they may be colored differently. Each face of these cubes has a single color. Colors of distinct faces of a cube may or may not be the same. Two cubes are said to be identically colored if some suitable rotations of one of the cubes give identical looks to both of the cubes. For example, two cubes shown in Figure 2 are identically colored. A set of cubes is said to be identically colored if every pair of them are identically colored. A cube and its mirror image are not necessarily identically colored. For example, two cubes shown in Figure 3 are not identically colored. You can make a given set of cubes identically colored by repainting some of the faces, whatever colors the faces may have. In Figure 4, repainting four faces makes the three cubes identically colored and repainting fewer faces will never do. Your task is to write a program to calculate the minimum number of faces that needs to be repainted for a given set of cubes to become identically colored. Input The input is a sequence of datasets. A dataset consists of a header and a body appearing in this order. A header is a line containing one positive integer n and the body following it consists of n lines. You can assume that 1 ≤ n ≤ 4. Each line in a body contains six color names separated by a space. A color name consists of a word or words connected with a hyphen (-). A word consists of one or more lowercase letters. You can assume that a color name is at most 24-characters long including hyphens. A dataset corresponds to a set of colored cubes. The integer n corresponds to the number of cubes. Each line of the body corresponds to a cube and describes the colors of its faces. Color names in a line is ordered in accordance with the numbering of faces shown in Figure 5. A line color 1 color 2 color 3 color 4 color 5 color 6 corresponds to a cube colored as shown in Figure 6. The end of the input is indicated by a line containing a single zero. It is not a dataset nor a part of a dataset. Output For each dataset, output a line containing the minimum number of faces that need to be repainted to make the set of cubes identically colored. Sample Input 3 scarlet green blue yellow magenta cyan blue pink green magenta cyan lemon purple red blue yellow cyan green 2 red green blue yellow magenta cyan cyan green blue yellow magenta red 2 red green gray gray magenta cyan cyan green gray gray magenta red 2 red green blue yellow magenta cyan magenta red blue yellow cyan green 3 red green blue yellow magenta cyan cyan green blue yellow magenta red magenta red blue yellow cyan green 3 blue green green green green blue green blue blue green green green green green green green green sea-green 3 red yellow red yellow red yellow red red yellow yellow red yellow red red red red red red 4 violet violet salmon salmon salmon salmon violet salmon salmon salmon salmon violet violet violet salmon salmon violet violet ...(truncated)
[ { "submission_id": "aoj_1259_9220763", "code_snippet": "#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <unordered_set>\n#...
aoj_1258_cpp
Problem B: Book Replacement The deadline of Prof. Hachioji’s assignment is tomorrow. To complete the task, students have to copy pages of many reference books in the library. All the reference books are in a storeroom and only the librarian is allowed to enter it. To obtain a copy of a reference book’s page, a student should ask the librarian to make it. The librarian brings books out of the storeroom and makes page copies according to the requests. The overall situation is shown in Figure 1. Students queue up in front of the counter. Only a single book can be requested at a time. If a student has more requests, the student goes to the end of the queue after the request has been served. In the storeroom, there are m desks D 1 , ... , D m , and a shelf. They are placed in a line in this order, from the door to the back of the room. Up to c books can be put on each of the desks. If a student requests a book, the librarian enters the storeroom and looks for it on D 1 , ... , D m in this order, and then on the shelf. After finding the book, the librarian takes it and gives a copy of a page to the student. Then the librarian returns to the storeroom with the requested book, to put it on D 1 according to the following procedure. If D 1 is not full (in other words, the number of books on D 1 < c ), the librarian puts the requested book there. If D 1 is full, the librarian temporarily puts the requested book on the non-full desk closest to the entrance or, in case all the desks are full, on the shelf, finds the book on D 1 that has not been requested for the longest time (i.e. the least recently used book) and takes it, puts it on the non-full desk (except D 1 ) closest to the entrance or, in case all the desks except D 1 are full, on the shelf, takes the requested book from the temporary place, and finally puts it on D 1 . Your task is to write a program which simulates the behaviors of the students and the librarian, and evaluates the total cost of the overall process. Costs are associated with accessing a desk or the shelf, that is, putting/taking a book on/from it in the description above. The cost of an access is i for desk D i and m + 1 for the shelf. That is, an access to D 1 , ... , D m , and the shelf costs 1, ... , m , and m + 1, respectively. Costs of other actions are ignored. Initially, no books are put on desks. No new students appear after opening the library. Input The input consists of multiple datasets. The end of the input is indicated by a line containing three zeros separated by a space. It is not a dataset. The format of each dataset is as follows. m c n k 1 b 11 . . . b 1 k 1 . . . k n b n 1 . . . b nk n Here, all data items are positive integers. m is the number of desks not exceeding 10. c is the number of books allowed to put on a desk, which does not exceed 30. n is the number of students not exceeding 100. k i is the number of books requested by the i -th student, which does not exceed 50. b ij is the ID numbe ...(truncated)
[ { "submission_id": "aoj_1258_4181658", "code_snippet": "#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <array>\n#include <string>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <unordered_map>\n#include <unordered_set>\n#include <set>\n#include <tuple>\n#include <cmath...
aoj_1252_cpp
Problem E: Confusing Login Names Meikyokan University is very famous for its research and education in the area of computer science. This university has a computer center that has advanced and secure computing facilities including supercomputers and many personal computers connected to the Internet. One of the policies of the computer center is to let the students select their own login names. Unfortunately, students are apt to select similar login names, and troubles caused by mistakes in entering or specifying login names are relatively common. These troubles are a burden on the staff of the computer center. To avoid such troubles, Dr. Choei Takano, the chief manager of the computer center, decided to stamp out similar and confusing login names. To this end, Takano has to develop a program that detects confusing login names. Based on the following four operations on strings, the distance between two login names is determined as the minimum number of operations that transforms one login name to the other. Deleting a character at an arbitrary position. Inserting a character into an arbitrary position. Replacing a character at an arbitrary position with another character. Swapping two adjacent characters at an arbitrary position. For example, the distance between “ omura ” and “ murai ” is two, because the following sequence of operations transforms “ omura ” to “ murai ”. delete ‘o’ insert ‘i’ omura --> mura --> murai Another example is that the distance between “ akasan ” and “ kaason ” is also two. swap ‘a’ and ‘k’ replace ‘a’ with ‘o’ akasan --> kaasan --> kaason Takano decided that two login names with a small distance are confusing and thus must be avoided. Your job is to write a program that enumerates all the confusing pairs of login names. Beware that the rules may combine in subtle ways. For instance, the distance between “ ant ” and “ neat ” is two. swap ‘a’ and ‘n’ insert ‘e’ ant --> nat --> neat Input The input consists of multiple datasets. Each dataset is given in the following format. n d name 1 name 2 ... name n The first integer n is the number of login names. Then comes a positive integer d . Two login names whose distance is less than or equal to d are deemed to be confusing. You may assume that 0 < n ≤ 200 and 0 < d ≤ 2. The i -th student’s login name is given by name i , which is composed of only lowercase letters. Its length is less than 16. You can assume that there are no duplicates in name i (1 ≤ i ≤ n ). The end of the input is indicated by a line that solely contains a zero. Output For each dataset, your program should output all pairs of confusing login names, one pair per line, followed by the total number of confusing pairs in the dataset. In each pair, the two login names are to be separated only by a comma character (,), and the login name that is alphabetically preceding the other should appear first. ...(truncated)
[ { "submission_id": "aoj_1252_10850969", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing VI = vector<int>;\nusing VVI = vector<VI>;\nusing PII = pair<int, int>;\nusing LL = long long;\nusing VL = vector<LL>;\nusing VVL = vector<VL>;\nusing PLL = pair<LL, LL>;\nusing VS = vector<strin...
aoj_1260_cpp
Problem D: Organize Your Train In the good old Hachioji railroad station located in the west of Tokyo, there are several parking lines, and lots of freight trains come and go every day. All freight trains travel at night, so these trains containing various types of cars are settled in your parking lines early in the morning. Then, during the daytime, you must reorganize cars in these trains according to the request of the railroad clients, so that every line contains the “right” train, i.e. the right number of cars of the right types, in the right order. As shown in Figure 7, all parking lines run in the East-West direction. There are exchange lines connecting them through which you can move cars. An exchange line connects two ends of different parking lines. Note that an end of a parking line can be connected to many ends of other lines. Also note that an exchange line may connect the East-end of a parking line and the West-end of another. Cars of the same type are not discriminated between each other. The cars are symmetric, so directions of cars don’t matter either. You can divide a train at an arbitrary position to make two sub-trains and move one of them through an exchange line connected to the end of its side. Alternatively, you may move a whole train as is without dividing it. Anyway, when a (sub-) train arrives at the destination parking line and the line already has another train in it, they are coupled to form a longer train. Your superautomatic train organization system can do these without any help of locomotive engines. Due to the limitation of the system, trains cannot stay on exchange lines; when you start moving a (sub-) train, it must arrive at the destination parking line before moving another train. In what follows, a letter represents a car type and a train is expressed as a sequence of letters. For example in Figure 8, from an initial state having a train " aabbccdee " on line 0 and no trains on other lines, you can make " bbaadeecc " on line 2 with the four moves shown in the figure. To cut the cost out, your boss wants to minimize the number of (sub-) train movements. For example, in the case of Figure 8, the number of movements is 4 and this is the minimum. Given the configurations of the train cars in the morning (arrival state) and evening (departure state), your job is to write a program to find the optimal train reconfiguration plan. Input The input consists of one or more datasets. A dataset has the following format: x y p 1 P 1 q 1 Q 1 p 2 P 2 q 2 Q 2 . . . p y P y q y Q y s 0 s 1 . . . s x -1 t 0 t 1 . . . t x -1 x is the number of parking lines, which are numbered from 0 to x -1. y is the number of exchange lines. Then y lines of the exchange line data follow, each describing two ends connected by the exchange line; p i and q i are integers between 0 and x - 1 which indicate parking line numbers, and P i and Q i are either " E " (East) or " W " (West) which indicate the ends of the parking lines. Then x lines of ...(truncated)
[ { "submission_id": "aoj_1260_10851287", "code_snippet": "#include <cmath>\n#include <ctime>\n#include <cstdio>\n#include <cctype>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <set>\n#include <stack>\n#include <queue>\n#include <string>\n#in...
aoj_1261_cpp
Problem E: Mobile Computing There is a mysterious planet called Yaen, whose space is 2-dimensional. There are many beautiful stones on the planet, and the Yaen people love to collect them. They bring the stones back home and make nice mobile arts of them to decorate their 2-dimensional living rooms. In their 2-dimensional world, a mobile is defined recursively as follows: a stone hung by a string, or a rod of length 1 with two sub-mobiles at both ends; the rod is hung by a string at the center of gravity of sub-mobiles. When the weights of the sub-mobiles are n and m , and their distances from the center of gravity are a and b respectively, the equation n × a = m × b holds. For example, if you got three stones with weights 1, 1, and 2, here are some possible mobiles and their widths: Given the weights of stones and the width of the room, your task is to design the widest possible mobile satisfying both of the following conditions. It uses all the stones. Its width is less than the width of the room. You should ignore the widths of stones. In some cases two sub-mobiles hung from both ends of a rod might overlap (see the figure on the below). Such mobiles are acceptable. The width of the example is (1/3) + 1 + (1/4). Input The first line of the input gives the number of datasets. Then the specified number of datasets follow. A dataset has the following format. r s w 1 . . . w s r is a decimal fraction representing the width of the room, which satisfies 0 < r < 10. s is the number of the stones. You may assume 1 ≤ s ≤ 6. w i is the weight of the i -th stone, which is an integer. You may assume 1 ≤ w i ≤ 1000. You can assume that no mobiles whose widths are between r - 0.00001 and r + 0.00001 can be made of given stones. Output For each dataset in the input, one line containing a decimal fraction should be output. The decimal fraction should give the width of the widest possible mobile as defined above. An output line should not contain extra characters such as spaces. In case there is no mobile which satisfies the requirement, answer -1 instead. The answer should not have an error greater than 0.00000001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. Sample Input 5 1.3 3 1 2 1 1.4 3 1 2 1 2.0 3 1 2 1 1.59 4 2 1 1 3 1.7143 4 1 2 3 5 Output for the Sample Input -1 1.3333333333333335 1.6666666666666667 1.5833333333333335 1.7142857142857142
[ { "submission_id": "aoj_1261_4673799", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <algorithm>\n#include <iostream>\n#include <cmath>\n#include <vector>\nusing namespace std;\n\nconst int N = 7, M = 1 << N;\nint tr[M]; //-1: root, 0: no use, else:left value\nint value[M];\nint ...
aoj_1257_cpp
Problem A: Sum of Consecutive Prime Numbers Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2 + 3 + 5 + 7 + 11 + 13, 11 + 13 + 17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20. Your mission is to write a program that reports the number of representations for the given positive integer. Input The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero. Output The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted in the output. Sample Input 2 3 17 41 20 666 12 53 0 Output for the Sample Input 1 1 2 3 0 0 1 2
[ { "submission_id": "aoj_1257_10734986", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nset<int>primes;\nint main(){\n int n;\n while(true){\n cin>>n;\n primes.clear();\n if(n==0)\n break;\n for(int i=2;i<=n;++i)\n primes.insert(i);\n ...
aoj_1263_cpp
Problem G: Network Mess Gilbert is the network admin of Ginkgo company. His boss is mad about the messy network cables on the floor. He finally walked up to Gilbert and asked the lazy network admin to illustrate how computers and switches are connected. Since he is a programmer, he is very reluctant to move throughout the office and examine cables and switches with his eyes. He instead opted to get this job done by measurement and a little bit of mathematical thinking, sitting down in front of his computer all the time. Your job is to help him by writing a program to reconstruct the network topology from measurements. There are a known number of computers and an unknown number of switches. Each computer is connected to one of the switches via a cable and to nothing else. Specifically, a computer is never connected to another computer directly, or never connected to two or more switches. Switches are connected via cables to form a tree (a connected undirected graph with no cycles). No switches are ‘useless.’ In other words, each switch is on the path between at least one pair of computers. All in all, computers and switches together form a tree whose leaves are computers and whose internal nodes switches (See Figure 9). Gilbert measures the distances between all pairs of computers . The distance between two com- puters is simply the number of switches on the path between the two, plus one. Or equivalently, it is the number of cables used to connect them. You may wonder how Gilbert can actually obtain these distances solely based on measurement. Well, he can do so by a very sophisticated statistical processing technique he invented. Please do not ask the details. You are therefore given a matrix describing distances between leaves of a tree. Your job is to construct the tree from it. Input The input is a series of distance matrices, followed by a line consisting of a single ' 0 '. Each distance matrix is formatted as follows. N a 11 a 12 ... a 1 N a 21 a 22 ... a 2 N . . . . . . . . . . . . a N 1 a N 2 ... a N N N is the size, i.e. the number of rows and the number of columns, of the matrix. a ij gives the distance between the i -th leaf node (computer) and the j -th. You may assume 2 ≤ N ≤ 50 and the matrix is symmetric whose diagonal elements are all zeros. That is, a ii = 0 and a ij = a ji for each i and j . Each non-diagonal element a ij ( i ≠ j ) satisfies 2 ≤ a ij ≤ 30. You may assume there is always a solution. That is, there is a tree having the given distances between leaf nodes. Output For each distance matrix, find a tree having the given distances between leaf nodes. Then output the degree of each internal node (i.e. the number of cables adjoining each switch), all in a single line and in ascending order. Numbers in a line should be separated by a single space. A line should not contain any other characters, including trailing spaces. Sample Input 4 0 2 2 2 2 0 2 2 2 2 0 2 2 2 2 0 4 0 ...(truncated)
[ { "submission_id": "aoj_1263_1352467", "code_snippet": "#include<bits/stdc++.h>\n\n#define REP(i,s,n) for(int i=s;i<n;i++)\n#define rep(i,n) REP(i,0,n)\n\nusing namespace std;\n\nconst int MAX_V = 50 * 30;\nconst int IINF = INT_MAX;\n\nstruct Edge { int src,dst; };\nvector<Edge> G[MAX_V];\nvector<int> comp...
aoj_1262_cpp
Problem F: Atomic Car Race In the year 2020, a race of atomically energized cars will be held. Unlike today’s car races, fueling is not a concern of racing teams. Cars can run throughout the course without any refueling. Instead, the critical factor is tire (tyre). Teams should carefully plan where to change tires of their cars. The race is a road race having n checkpoints in the course. Their distances from the start are a 1 , a 2 , ... , and a n (in kilometers). The n -th checkpoint is the goal. At the i -th checkpoint ( i < n ), tires of a car can be changed. Of course, a team can choose whether to change or not to change tires at each checkpoint. It takes b seconds to change tires (including overhead for braking and accelerating). There is no time loss at a checkpoint if a team chooses not to change tires. A car cannot run fast for a while after a tire change, because the temperature of tires is lower than the designed optimum. After running long without any tire changes, on the other hand, a car cannot run fast because worn tires cannot grip the road surface well. The time to run an interval of one kilometer from x to x + 1 is given by the following expression (in seconds). Here x is a nonnegative integer denoting the distance (in kilometers) from the latest checkpoint where tires are changed (or the start). r , v , e and f are given constants. 1/( v - e × ( x - r )) (if x ≥ r ) 1/( v - f × ( r - x )) (if x < r ) Your mission is to write a program to determine the best strategy of tire changes which minimizes the total time to the goal. Input The input consists of multiple datasets each corresponding to a race situation. The format of a dataset is as follows. n a 1 a 2 . . . a n b r v e f The meaning of each of the input items is given in the problem statement. If an input line contains two or more input items, they are separated by a space. n is a positive integer not exceeding 100. Each of a 1 , a 2 , ... , and a n is a positive integer satisfying 0 < a 1 < a 2 < . . . < a n ≤ 10000. b is a positive decimal fraction not exceeding 100.0. r is a nonnegative integer satisfying 0 ≤ r ≤ a n - 1. Each of v , e and f is a positive decimal fraction. You can assume that v - e × ( a n - 1 - r ) ≥ 0.01 and v - f × r ≥ 0.01. The end of the input is indicated by a line with a single zero. Output For each dataset in the input, one line containing a decimal fraction should be output. The decimal fraction should give the elapsed time at the goal (in seconds) when the best strategy is taken. An output line should not contain extra characters such as spaces. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. Sample Input 2 2 3 1.0 1 1.0 0.1 0.3 5 5 10 15 20 25 0.15 1 1.0 0.04 0.5 10 1783 3640 3991 4623 5465 5481 6369 6533 6865 8425 4.172 72 59.4705 0.0052834 0.0611224 0 Output for the Sample Input 3.5397 31.9249 168.6682
[ { "submission_id": "aoj_1262_3167974", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int n;\n while ( cin >> n, n ) {\n vector<int> a(n+1);\n vector<double> d(10001, 100000000.0);\n d[0] = 0;\n vector<int> is(10001, 0);\n a[0] = 0;\n for ( int i = 1; i...
aoj_1265_cpp
Problem I: Shy Polygons You are given two solid polygons and their positions on the xy -plane. You can move one of the two along the x -axis (they can overlap during the move). You cannot move it in other directions. The goal is to place them as compactly as possible, subject to the following condition: the distance between any point in one polygon and any point in the other must not be smaller than a given minimum distance L . We define the width of a placement as the difference between the maximum and the minimum x -coordinates of all points in the two polygons. Your job is to write a program to calculate the minimum width of placements satisfying the above condition. Let's see an example. If the polygons in Figure 13 are placed with L = 10.0, the result will be 100. Figure 14 shows one of the optimal placements. Input The input consists of multiple datasets. Each dataset is given in the following format. L Polygon 1 Polygon 2 L is a decimal fraction, which means the required distance of two polygons. L is greater than 0.1 and less than 50.0. The format of each polygon is as follows. n x 1 y 1 x 2 y 2 . . . x n y n n is a positive integer, which represents the number of vertices of the polygon. n is greater than 2 and less than 15. Remaining lines represent the vertices of the polygon. A vertex data line has a pair of nonneg- ative integers which represent the x - and y-coordinates of a vertex. x - and y -coordinates are separated by a single space, and y -coordinate is immediately followed by a newline. x and y are less than 500. Edges of the polygon connect vertices given in two adjacent vertex data lines, and vertices given in the last and the first vertex data lines. You may assume that the vertices are given in the counterclockwise order, and the contours of polygons are simple, i.e. they do not cross nor touch themselves. Also, you may assume that the result is not sensitive to errors. In concrete terms, for a given pair of polygons, the minimum width is a function of the given minimum distance l . Let us denote the function w ( l ). Then you can assume that | w ( L ± 10 -7 ) - w ( L )| < 10 -4 . The end of the input is indicated by a line that only contains a zero. It is not a part of a dataset. Output The output should consist of a series of lines each containing a single decimal fraction. Each number should indicate the minimum width for the corresponding dataset. The answer should not have an error greater than 0.0001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. Sample Input 10.5235 3 0 0 100 100 0 100 4 0 50 20 50 20 80 0 80 10.0 4 120 45 140 35 140 65 120 55 8 0 0 100 0 100 100 0 100 0 55 80 90 80 10 0 45 10.0 3 0 0 1 0 0 1 3 0 100 1 101 0 101 10.0 3 0 0 1 0 0 100 3 0 50 100 50 0 51 0 Output for the Sample Input 114.882476 100 1 110.5005
[ { "submission_id": "aoj_1265_10848496", "code_snippet": "/*\n * Created By phyxnj@uestc\n * Last Compiler:\n * Sun, 29 Jul 2012 02:07:44 +0800\n */\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <algorithm>\n#include <cstdlib>\n#include <cmath>\n#include <set>\n#include <vector>\n#...
aoj_1267_cpp
Problem B: How I Mathematician Wonder What You Are! After counting so many stars in the sky in his childhood, Isaac, now an astronomer and a mathematician, uses a big astronomical telescope and lets his image processing program count stars. The hardest part of the program is to judge if a shining object in the sky is really a star. As a mathematician, the only way he knows is to apply a mathematical definition of stars . The mathematical defiition of a star shape is as follows: A planar shape F is star-shaped if and only if there is a point C ∈ F such that, for any point P ∈ F , the line segment CP is contained in F . Such a point C is called a center of F . To get accustomed to the definition, let's see some examples below. Figure 2: Star shapes (the first row) and non-star shapes (the second row) The firrst two are what you would normally call stars. According to the above definition, however, all shapes in the first row are star-shaped. The two in the second row are not. For each star shape, a center is indicated with a dot. Note that a star shape in general has infinitely many centers. For example, for the third quadrangular shape, all points in it are centers. Your job is to write a program that tells whether a given polygonal shape is star-shaped or not. Input The input is a sequence of datasets followed by a line containing a single zero. Each dataset specifies a polygon, and is formatted as follows. n x 1 y 1 x 2 y 2 ... x n y n The first line is the number of vertices, n , which satisfies 4 ≤ n ≤ 50. Subsequent n lines are the x - and y -coordinates of the n vertices. They are integers and satisfy 0 ≤ x i ≤ 10000 and 0 ≤ y i ≤ 10000 ( i = 1, ..., n ). Line segments ( x i , y i )-( x i +1 , y i +1 ) ( i = 1, ..., n - 1) and the line segment ( x n , y n )-( x 1 , y 1 ) form the border of the polygon in the counterclockwise order. That is, these line segments see the inside of the polygon in the left of their directions. You may assume that the polygon is simple , that is, its border never crosses or touches itself. You may also assume that no three edges of the polygon meet at a single point even when they are infinitely extended. Output For each dataset, output "1" if the polygon is star-shaped and "0" otherwise. Each number must be in a separate line and the line should not contain any other characters. Sample Input 6 66 13 96 61 76 98 13 94 4 0 45 68 8 27 21 55 14 93 12 56 95 15 48 38 46 51 65 64 31 0 Output for the Sample Input 1 0
[ { "submission_id": "aoj_1267_3894056", "code_snippet": "#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <cstring>\n\n#include <iostream>\n#include <complex>\n#include <string>\n#include <algorithm>\n#include <numeric>\n#include <vector>\n#include <queue>\n#include <stack>\n#include <map>\n...
aoj_1269_cpp
Problem D: Sum of Different Primes 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 diffrent 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 2 31 . Sample Input 24 3 24 2 2 1 1 1 4 2 18 3 17 1 17 3 17 4 100 5 1000 10 1120 14 0 0 Output for the Sample Input 2 3 1 0 0 2 1 0 1 55 200102899 2079324314
[ { "submission_id": "aoj_1269_11031582", "code_snippet": "//____ ____.__ __ _________ .__ .__ ________\n//\\ \\ / /|__| _____/ |_ ___________ \\_ ___ \\| |__ _____ _________ |__| / _____/_____ ____ ____\n// \\ Y / | |/ ___\\ __...
aoj_1266_cpp
Problem A: How I Wonder What You Are! One of the questions children often ask is "How many stars are there in the sky?" Under ideal conditions, even with the naked eye, nearly eight thousands are observable in the northern hemisphere. With a decent telescope, you may find many more, but, as the sight field will be limited, you may find much less at a time. Children may ask the same questions to their parents on a planet of some solar system billions of light-years away from the Earth. Their telescopes are similar to ours with circular sight fields, but alien kids have many eyes and can look into different directions at a time through many telescopes. Given a set of positions of stars, a set of telescopes and the directions they are looking to, your task is to count up how many stars can be seen through these telescopes. Input The input consists of one or more datasets. The number of datasets is less than 50. Each dataset describes stars and the parameters of the telescopes used. The first line of a dataset contains a positive integer n not exceeding 500, meaning the number of stars. Each of the n lines following it contains three decimal fractions, s x , s y , and s z . They give the position ( s x , s y , s z ) of the star described in Euclidean coordinates. You may assume -1000 ≤ s x ≤ 1000, -1000 ≤ s y ≤ 1000, -1000 ≤ s z ≤ 1000 and ( s x , s y , s z ) ≠ (0, 0, 0). Then comes a line containing a positive integer m not exceeding 50, meaning the number of telescopes. Each of the following m lines contains four decimal fractions, t x , t y , t z , and φ , describing a telescope. The first three numbers represent the direction of the telescope. All the telescopes are at the origin of the coordinate system (0, 0, 0) (we ignore the size of the planet). The three numbers give the point ( t x , t y , t z ) which can be seen in the center of the sight through the telescope. You may assume -1000 ≤ t x ≤ 1000, -1000 ≤ t y ≤ 1000, -1000 ≤ t z ≤ 1000 and ( t x , t y , t z ) ≠ (0, 0, 0). The fourth number φ (0 ≤ φ ≤ π /2) gives the angular radius, in radians, of the sight field of the telescope. Let us defie that θ i,j is the angle between the direction of the i -th star and the center direction of the j -th telescope and φ j is the angular radius of the sight field of the j -th telescope. The i -th star is observable through the j -th telescope if and only if θ i,j is less than . You may assume that | θ i,j - φ j | > 0.00000001 for all pairs of i and j . Figure 1: Direction and angular radius of a telescope The end of the input is indicated with a line containing a single zero. Output For each dataset, one line containing an integer meaning the number of stars observable through the telescopes should be output. No other characters should be contained in the output. Note that stars that can be seen through more than one telescope should not be counted twice or more. Sample Input 3 100 0 500 -500.243 -200.1 -300.5 0 300 200 2 1 1 1 0.65 -1 0 0 1.57 3 1 0 0 0 ...(truncated)
[ { "submission_id": "aoj_1266_4858020", "code_snippet": "#include <iostream> \n#include<vector>\n#include<algorithm>\n#include<map>\n#include<string>\n#include<iomanip>\n#include<set>\n#include<queue>\n#include<deque>\n#include<sstream>\n#include<cmath>\n#include<bitset>\nusing namespace std;\n#define rep(i,...
aoj_1268_cpp
Problem C: Cubic Eight-Puzzle Let's play a puzzle using eight cubes placed on a 3 × 3 board leaving one empty square. Faces of cubes are painted with three colors. As a puzzle step, you can roll one of the cubes to the adjacent empty square. Your goal is to make the specified color pattern visible from above by a number of such steps. The rules of this puzzle are as follows. Coloring of Cubes: All the cubes are colored in the same way as shown in Figure 3. The opposite faces have the same color. Figure 3: Coloring of a cube Initial Board State: Eight cubes are placed on the 3 × 3 board leaving one empty square. All the cubes have the same orientation as shown in Figure 4. As shown in the figure, squares on the board are given x and y coordinates, (1, 1), (1, 2), .. ., and (3, 3). The position of the initially empty square may vary. Figure 4: Initial board state Rolling Cubes: At each step, we can choose one of the cubes adjacent to the empty square and roll it into the empty square, leaving the original position empty. Figure 5 shows an example. Figure 5: Rolling a cube Goal: The goal of this puzzle is to arrange the cubes so that their top faces form the specified color pattern by a number of cube rolling steps described above. Your task is to write a program that finds the minimum number of steps required to make the specified color pattern from the given initial state. Input The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. The number of datasets is less than 16. Each dataset is formatted as follows. x y F 11 F 21 F 31 F 12 F 22 F 32 F 13 F 23 F 33 The first line contains two integers x and y separated by a space, indicating the position ( x , y ) of the initially empty square. The values of x and y are 1, 2, or 3. The following three lines specify the color pattern to make. Each line contains three characters F 1 j , F 2 j , and F 3 j , separated by a space. Character F ij indicates the top color of the cube, if any, at position ( i , j ) as follows: B: Blue W: White R: Red E: the square is Empty. There is exactly one ' E ' character in each dataset. Output For each dataset, output the minimum number of steps to achieve the goal, when the goal can be reached within 30 steps. Otherwise, output " -1 " for the dataset. Sample Input 1 2 W W W E W W W W W 2 1 R B W R W W E W W 3 3 W B W B R E R B R 3 3 B W R B W R B E R 2 1 B B B B R B B R E 1 1 R R R W W W R R E 2 1 R R R B W B R R E 3 2 R R R W E W R R R 0 0 Output for the Sample Input 0 3 13 23 29 30 -1 -1
[ { "submission_id": "aoj_1268_10852687", "code_snippet": "#include<cmath>\n#include<cstdio>\n#include<cstring>\n#include<iostream>\nusing namespace std;\nconst int n=3;\nconst int dx[]={-1,1,0,0},dy[]={0,0,-1,1};\nint fx,fy,t[4][4],ans;\nstruct node{\n\tint x,y;\n\tnode(int x=0,int y=0):x(x),y(y){}\n}a[4][4]...
aoj_1273_cpp
Problem H: The Best Name for Your Baby In the year 29XX, the government of a small country somewhere on the earth introduced a law restricting first names of the people only to traditional names in their culture, in order to preserve their cultural uniqueness. The linguists of the country specifies a set of rules once every year, and only names conforming to the rules are allowed in that year. In addition, the law also requires each person to use a name of a specific length calculated from one's birth date because otherwise too many people would use the same very popular names. Since the legislation of that law, the common task of the parents of new babies is to find the name that comes first in the alphabetical order among the legitimate names of the given length because names earlier in the alphabetical order have various benefits in their culture. Legitimate names are the strings consisting of only lowercase letters that can be obtained by repeatedly applying the rule set to the initial string "S", a string consisting only of a single uppercase S. Applying the rule set to a string is to choose one of the rules and apply it to the string. Each of the rules has the form A -> α , where A is an uppercase letter and α is a string of lowercase and/or uppercase letters. Applying such a rule to a string is to replace an occurrence of the letter A in the string to the string α . That is, when the string has the form " βAγ ", where β and γ are arbitrary (possibly empty) strings of letters, applying the rule rewrites it into the string " βαγ ". If there are two or more occurrences of A in the original string, an arbitrary one of them can be chosen for the replacement. Below is an example set of rules. S -> aAB (1) A -> (2) A -> Aa (3) B -> AbbA (4) Applying the rule (1) to "S", "aAB" is obtained. Applying (2) to it results in "aB", as A is replaced by an empty string. Then, the rule (4) can be used to make it "aAbbA". Applying (3) to the first occurrence of A makes it "aAabbA". Applying the rule (2) to the A at the end results in "aAabb". Finally, applying the rule (2) again to the remaining A results in "aabb". As no uppercase letter remains in this string, "aabb" is a legitimate name. We denote such a rewriting process as follows. (1) (2) (4) (3) (2) (2) S --> aAB --> aB --> aAbbA --> aAabbA --> aAabb --> aabb Linguists of the country may sometimes define a ridiculous rule set such as follows. S -> sA (1) A -> aS (2) B -> b (3) The only possible rewriting sequence with this rule set is: (1) (2) (1) (2) S --> sA --> saS --> sasA --> ... which will never terminate. No legitimate names exist in this case. Also, the rule (3) can never be used, as its left hand side, B, does not appear anywhere else. It may happen that no rules are supplied for some uppercase letters appearing in the rewriting steps. In its extreme case, even S might have no rules for it in the set, in which case there are no legitimate names, ...(truncated)
[ { "submission_id": "aoj_1273_10851276", "code_snippet": "#include <cctype>\n#include <cstddef>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <string>\n#include <utility>\n#include <vector>\nint n, l, tot, to[501];\nstd::string s[51], f[21][501];\...
aoj_1264_cpp
Problem H: Bingo A Bingo game is played by one gamemaster and several players. At the beginning of a game, each player is given a card with M × M numbers in a matrix (See Figure 10). As the game proceeds, the gamemaster announces a series of numbers one by one. Each player punches a hole in his card on the announced number, if any. When at least one 'Bingo' is made on the card, the player wins and leaves the game. The 'Bingo' means that all the M numbers in a line are punched vertically, horizontally or diagonally (See Figure 11). The gamemaster continues announcing numbers until all the players make a Bingo. In the ordinary Bingo games, the gamemaster chooses numbers by a random process and has no control on them. But in this problem the gamemaster knows all the cards at the beginning of the game and controls the game by choosing the number sequence to be announced at his will. Specifically, he controls the game to satisfy the following condition. Card i makes a Bingo no later than Card j , for i < j . (*) Figure 12 shows an example of how a game proceeds. The gamemaster cannot announce '5' before '16', because Card 4 makes a Bingo before Card 2 and Card 3 , violating the condition (*). Your job is to write a program which finds the minimum length of such sequence of numbers for the given cards. Input The input consists of multiple datasets. The format of each dataset is as follows. All data items are integers. P is the number of the cards, namely the number of the players. M is the number of rows and the number of columns of the matrix on each card. N k ij means the number written at the position ( i , j ) on the k -th card. If ( i , j ) ≠ ( p , q ), then N k ij ≠ N k pq . The parameters P , M , and N satisfy the conditions 2 ≤ P ≤ 4, 3 ≤ M ≤ 4, and 0 ≤ N k ij ≤ 99. The end of the input is indicated by a line containing two zeros separated by a space. It is not a dataset. Output For each dataset, output the minimum length of the sequence of numbers which satisfy the condition (*). Output a zero if there are no such sequences. Output for each dataset must be printed on a separate line. Sample Input 4 3 10 25 11 20 6 2 1 15 23 5 21 3 12 23 17 7 26 2 8 18 4 22 13 27 16 5 11 19 9 24 2 11 5 14 28 16 4 3 12 13 20 24 28 32 15 16 17 12 13 21 25 29 33 16 17 18 12 13 22 26 30 34 17 18 15 12 13 23 27 31 35 18 15 16 4 3 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 41 42 43 44 45 46 47 48 49 4 4 2 6 9 21 15 23 17 31 33 12 25 4 8 24 13 36 22 18 27 26 35 28 3 7 11 20 38 16 5 32 14 29 26 7 16 29 27 3 38 14 18 28 20 32 22 35 11 5 36 13 24 8 4 25 12 33 31 17 23 15 21 9 6 2 0 0 Output for the Sample Input 5 4 12 0 For your convenience, sequences satisfying the condition (*) for the first three datasets are shown below. There may be other sequences of the same length satisfying the condition, but no shorter. 11, 2, 23, 16, 5 15, 16, 17, 18 11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43
[ { "submission_id": "aoj_1264_10853849", "code_snippet": "#include <iostream>\n#include <string.h>\n#include <cstdio>\n#include <algorithm>\n#include <vector>\n#include <map>\nusing namespace std;\n\nconst int maxn = 7, maxv = 107, maxt = 10007, maxnum = 100000000;\n int n, m, res, total;\n int has...
aoj_1272_cpp
Problem G: Polygons on the Grid 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 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. n r 1 r 2 ... r n n is an integer which means the number of rods and satisfies 3 ≤ n ≤ 6. r i means the length of the i -th rod and satisfies 1 ≤ r i ≤ 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 3 3 4 5 5 1 2 5 5 5 6 195 221 255 260 265 290 6 130 145 169 185 195 265 3 1 1 2 6 3 3 3 3 3 3 0 Output for the Sample Input 6 19 158253 -1 -1 18
[ { "submission_id": "aoj_1272_9593544", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n int x, y;\n int cross(const Point p) const { return x * p.y - y * p.x; }\n Point operator-(const Point p) const { return {x - p.x, y - p.y}; }\n int operator*(const Point p) const {...
aoj_1275_cpp
Problem A: And Then There Was One Let’s play a stone removing game. Initially, n stones are arranged on a circle and numbered 1, ... , n clockwise (Figure 1). You are also given two numbers k and m . From this state, remove stones one by one following the rules explained below, until only one remains. In step 1, remove stone m . In step 2, locate the k -th next stone clockwise from m and remove it. In subsequent steps, start from the slot of the stone removed in the last step, make k hops clockwise on the remaining stones and remove the one you reach. In other words, skip ( k - 1) remaining stones clockwise and remove the next one. Repeat this until only one stone is left and answer its number. For example, the answer for the case n = 8, k = 5, m = 3 is 1, as shown in Figure 1. Figure 1: An example game Initial state : Eight stones are arranged on a circle. Step 1 : Stone 3 is removed since m = 3. Step 2 : You start from the slot that was occupied by stone 3. You skip four stones 4, 5, 6 and 7 (since k = 5), and remove the next one, which is 8. Step 3 : You skip stones 1, 2, 4 and 5, and thus remove 6. Note that you only count stones that are still on the circle and ignore those already removed. Stone 3 is ignored in this case. Steps 4-7 : You continue until only one stone is left. Notice that in later steps when only a few stones remain, the same stone may be skipped multiple times. For example, stones 1 and 4 are skipped twice in step 7. Final State : Finally, only one stone, 1, is on the circle. This is the final state, so the answer is 1. Input The input consists of multiple datasets each of which is formatted as follows. n k m The last dataset is followed by a line containing three zeros. Numbers in a line are separated by a single space. A dataset satisfies the following conditions. 2 ≤ n ≤ 10000, 1 ≤ k ≤ 10000, 1 ≤ m ≤ n The number of datasets is less than 100. Output For each dataset, output a line containing the stone number left in the final state. No extra characters such as spaces should appear in the output. Sample Input 8 5 3 100 9999 98 10000 10000 10000 0 0 0 Output for the Sample Input 1 93 2019
[ { "submission_id": "aoj_1275_10895099", "code_snippet": "#include<bits/stdc++.h>\n// #include<atcoder/all>\n// #include<boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\n// using namespace atcoder;\n// using bint = boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ull = unsigned long lo...
aoj_1270_cpp
Problem E: Manhattan Wiring There is a rectangular area containing n × m cells. Two cells are marked with "2", and another two with "3". Some cells are occupied by obstacles. You should connect the two "2"s and also the two "3"s with non-intersecting lines. Lines can run only vertically or horizontally connecting centers of cells without obstacles. Lines cannot run on a cell with an obstacle. Only one line can run on a cell at most once. Hence, a line cannot intersect with the other line, nor with itself. Under these constraints, the total length of the two lines should be minimized. The length of a line is defined as the number of cell borders it passes. In particular, a line connecting cells sharing their border has length 1. Fig. 6(a) shows an example setting. Fig. 6(b) shows two lines satisfying the constraints above with minimum total length 18. Figure 6: An example setting and its solution Input The input consists of multiple datasets, each in the following format. n m row 1 ... row n n is the number of rows which satisfies 2 ≤ n ≤ 9. m is the number of columns which satisfies 2 ≤ m ≤ 9. Each row i is a sequence of m digits separated by a space. The digits mean the following. 0 : Empty 1 : Occupied by an obstacle 2 : Marked with "2" 3 : Marked with "3" The end of the input is indicated with a line containing two zeros separated by a space. Output For each dataset, one line containing the minimum total length of the two lines should be output. If there is no pair of lines satisfying the requirement, answer "0" instead. No other characters should be contained in the output. Sample Input 5 5 0 0 0 0 0 0 0 0 3 0 2 0 2 0 0 1 0 1 1 1 0 0 0 0 3 2 3 2 2 0 0 3 3 6 5 2 0 0 0 0 0 3 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 2 3 0 5 9 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 2 0 0 0 0 0 2 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 9 9 3 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3 9 9 0 0 0 1 0 0 0 0 0 0 2 0 1 0 0 0 0 3 0 0 0 1 0 0 0 0 2 0 0 0 1 0 0 0 0 3 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 9 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 2 0 0 Output for the Sample Input 18 2 17 12 0 52 43
[ { "submission_id": "aoj_1270_10865943", "code_snippet": "#include <bits/stdc++.h>\ntypedef unsigned int T;\nT n, m;\nT ns[10][10];\nbool vis[10][10][70000];\nT ans[10][10][70000];\nT san[] = {\n\t1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049\n};\n\nT f(T x, T y, T S) {\n\tif (x >= n) {\n\t\tif (S) ret...
aoj_1277_cpp
Problem C: Minimal Backgammon Here is a very simple variation of the game backgammon, named “Minimal Backgammon”. The game is played by only one player, using only one of the dice and only one checker (the token used by the player). The game board is a line of ( N + 1) squares labeled as 0 (the start) to N (the goal). At the beginning, the checker is placed on the start (square 0). The aim of the game is to bring the checker to the goal (square N ). The checker proceeds as many squares as the roll of the dice. The dice generates six integers from 1 to 6 with equal probability. The checker should not go beyond the goal. If the roll of the dice would bring the checker beyond the goal, the checker retreats from the goal as many squares as the excess. For example, if the checker is placed at the square ( N - 3), the roll "5" brings the checker to the square ( N - 2), because the excess beyond the goal is 2. At the next turn, the checker proceeds toward the goal as usual. Each square, except the start and the goal, may be given one of the following two special instructions. Lose one turn (labeled " L " in Figure 2) If the checker stops here, you cannot move the checker in the next turn. Go back to the start (labeled " B " in Figure 2) If the checker stops here, the checker is brought back to the start. Figure 2: An example game Given a game board configuration (the size N , and the placement of the special instructions), you are requested to compute the probability with which the game succeeds within a given number of turns. Input The input consists of multiple datasets, each containing integers in the following format. N T L B Lose 1 ... Lose L Back 1 ... Back B N is the index of the goal, which satisfies 5 ≤ N ≤ 100. T is the number of turns. You are requested to compute the probability of success within T turns. T satisfies 1 ≤ T ≤ 100. L is the number of squares marked “Lose one turn”, which satisfies 0 ≤ L ≤ N - 1. B is the number of squares marked “Go back to the start”, which satisfies 0 ≤ B ≤ N - 1. They are separated by a space. Lose i 's are the indexes of the squares marked “Lose one turn”, which satisfy 1 ≤ Lose i ≤ N - 1. All Lose i 's are distinct, and sorted in ascending order. Back i 's are the indexes of the squares marked “Go back to the start”, which satisfy 1 ≤ Back i ≤ N - 1. All Back i 's are distinct, and sorted in ascending order. No numbers occur both in Lose i 's and Back i 's. The end of the input is indicated by a line containing four zeros separated by a space. Output For each dataset, you should answer the probability with which the game succeeds within the given number of turns. The output should not contain an error greater than 0.00001. Sample Input 6 1 0 0 7 1 0 0 7 2 0 0 6 6 1 1 2 5 7 10 0 6 1 2 3 4 5 6 0 0 0 0 Output for the Sample Input 0.166667 0.000000 0.166667 0.619642 0.000000
[ { "submission_id": "aoj_1277_3231955", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int N, T, L, B;\n cout << fixed << setprecision(6);\n while (cin >> N >> T >> L >> B, N) {\n map<int, bool> Lose;\n for (int i = 0; i < L; i++) {\n int l;\n cin >> l;\n...
aoj_1271_cpp
Problem F: Power Calculus Starting with x and repeatedly multiplying by x , we can compute x 31 with thirty multiplications: x 2 = x × x , x 3 = x 2 × x , x 4 = x 3 × x , ... , x 31 = x 30 × x . The operation of squaring can appreciably shorten the sequence of multiplications. The following is a way to compute x 31 with eight multiplications: x 2 = x × x , x 3 = x 2 × x , x 6 = x 3 × x 3 , x 7 = x 6 × x , x 14 = x 7 × x 7 , x 15 = x 14 × x , x 30 = x 15 × x 15 , x 31 = x 30 × x . This is not the shortest sequence of multiplications to compute x 31 . There are many ways with only seven multiplications. The following is one of them: x 2 = x × x , x 4 = x 2 × x 2 , x 8 = x 4 × x 4 , x 10 = x 8 × x 2 , x 20 = x 10 × x 10 , x 30 = x 20 × x 10 , x 31 = x 30 × x . There however is no way to compute x 31 with fewer multiplications. Thus this is one of the most eficient ways to compute x 31 only by multiplications. If division is also available, we can find a shorter sequence of operations. It is possible to compute x 31 with six operations (five multiplications and one division): x 2 = x × x , x 4 = x 2 × x 2 , x 8 = x 4 × x 4 , x 16 = x 8 × x 8 , x 32 = x 16 × x 16 , x 31 = x 32 ÷ x . This is one of the most eficient ways to compute x 31 if a division is as fast as a multiplication. Your mission is to write a program to find the least number of operations to compute x n by multiplication and division starting with x for the given positive integer n . Products and quotients appearing in the sequence of operations should be x to a positive integer's power. In other words, x -3 , for example, should never appear. Input The input is a sequence of one or more lines each containing a single integer n . n is positive and less than or equal to 1000. The end of the input is indicated by a zero. Output Your program should print the least total number of multiplications and divisions required to compute x n starting with x for the integer n . The numbers should be written each in a separate line without any superfluous characters such as leading or trailing spaces. Sample Input 1 31 70 91 473 512 811 953 0 Output for the Sample Input 0 6 8 9 11 9 13 12
[ { "submission_id": "aoj_1271_10852802", "code_snippet": "/*\n *Author: Zhaofa Fang\n *Created time: 2013-09-09-16.49 星期一\n */\n#include <cstdio>\n#include <cstdlib>\n#include <sstream>\n#include <iostream>\n#include <cmath>\n#include <cstring>\n#include <algorithm>\n#include <string>\n#include <utilit...
aoj_1276_cpp
Problem B: Prime Gap The sequence of n - 1 consecutive composite numbers (positive integers that are not prime and not equal to 1) lying between two successive prime numbers p and p + n is called a prime gap of length n . For example, (24, 25, 26, 27, 28) between 23 and 29 is a prime gap of length 6. Your mission is to write a program to calculate, for a given positive integer k , the length of the prime gap that contains k . For convenience, the length is considered 0 in case no prime gap contains k . Input The input is a sequence of lines each of which contains a single positive integer. Each positive integer is greater than 1 and less than or equal to the 100000th prime number, which is 1299709. The end of the input is indicated by a line containing a single zero. Output The output should be composed of lines each of which contains a single non-negative integer. It is the length of the prime gap that contains the corresponding positive integer in the input if it is a composite number, or 0 otherwise. No other characters should occur in the output. Sample Input 10 11 27 2 492170 0 Output for the Sample Input 4 0 6 0 114
[ { "submission_id": "aoj_1276_10803560", "code_snippet": "#define _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define int long long\n#define endl '\\n'\n#define print(v) for(auto& x:v)cout<<x<<' ';cout<<endl\n\nconst int N = 2e6;\nint minp[N];\nbitset<N> vi...
aoj_1279_cpp
Problem E: Geometric Map Your task in this problem is to create a program that finds the shortest path between two given locations on a given street map, which is represented as a collection of line segments on a plane. Figure 4 is an example of a street map, where some line segments represent streets and the others are signs indicating the directions in which cars cannot move. More concretely, AE , AM , MQ , EQ , CP and HJ represent the streets and the others are signs in this map. In general, an end point of a sign touches one and only one line segment representing a street and the other end point is open. Each end point of every street touches one or more streets, but no signs. The sign BF , for instance, indicates that at B cars may move left to right but may not in the reverse direction. In general, cars may not move from the obtuse angle side to the acute angle side at a point where a sign touches a street (note that the angle CBF is obtuse and the angle ABF is acute). Cars may directly move neither from P to M nor from M to P since cars moving left to right may not go through N and those moving right to left may not go through O . In a special case where the angle between a sign and a street is rectangular, cars may not move in either directions at the point. For instance, cars may directly move neither from H to J nor from J to H . You should write a program that finds the shortest path obeying these traffic rules. The length of a line segment between ( x 1 , y 1 ) and ( x 2 , y 2 ) is √{( x 2 − x 1 ) 2 + ( y 2 − y 1 ) 2 } . Input The input consists of multiple datasets, each in the following format. n x s y s x g y g x 1 1 y 1 1 x 2 1 y 2 1 . . . x 1 k y 1 k x 2 k y 2 k . . . x 1 n y 1 n x 2 n y 2 n n , representing the number of line segments, is a positive integer less than or equal to 200. ( x s , y s ) and ( x g , y g ) are the start and goal points, respectively. You can assume that ( x s , y s ) ≠ ( x g , y g ) and that each of them is located on an end point of some line segment representing a street. You can also assume that the shortest path from ( x s , y s ) to ( x g , y g ) is unique. ( x 1 k , y 1 k ) and ( x 2 k , y 2 k ) are the two end points of the kth line segment. You can assume that ( x 1 k , y 1 k ) ≠( x 2 k , y 2 k ). Two line segments never cross nor overlap. That is, if they share a point, it is always one of their end points. All the coordinates are non-negative integers less than or equal to 1000. The end of the input is indicated by a line containing a single zero. Output For each input dataset, print every street intersection point on the shortest path from the start point to the goal point, one in an output line in this order, and a zero in a line following those points. Note that a street intersection point is a point where at least two line segments representing streets meet. An output line for a street intersection point should contain its x - and y -coordinates separated by a space. Print -1 if t ...(truncated)
[ { "submission_id": "aoj_1279_4161973", "code_snippet": "#include<iostream>\n#include<string>\n#include<cstdio>\n#include<vector>\n#include<cmath>\n#include<algorithm>\n#include<functional>\n#include<iomanip>\n#include<queue>\n#include<ciso646>\n#include<random>\n#include<map>\n#include<set>\n#include<bitset...
aoj_1280_cpp
Problem F: Slim Span Given an undirected weighted graph G , you should find one of spanning trees specified as follows. The graph G is an ordered pair ( V , E ), where V is a set of vertices { v 1 , v 2 , ... , v n } and E is a set of undirected edges { e 1 , e 2 , ... , e m }. Each edge e ∈ E has its weight w ( e ). A spanning tree T is a tree (a connected subgraph without cycles) which connects all the n vertices with n - 1 edges. The slimness of a spanning tree T is defined as the difference between the largest weight and the smallest weight among the n - 1 edges of T . Figure 5: A graph G and the weights of the edges For example, a graph G in Figure 5(a) has four vertices { v 1 , v 2 , v 3 , v 4 } and five undirected edges { e 1 , e 2 , e 3 , e 4 , e 5 }. The weights of the edges are w ( e 1 ) = 3, w ( e 2 ) = 5, w ( e 3 ) = 6, w ( e 4 ) = 6, w ( e 5 ) = 7 as shown in Figure 5(b). Figure 6: Examples of the spanning trees of G There are several spanning trees for G . Four of them are depicted in Figure 6(a)-(d). The spanning tree T a in Figure 6(a) has three edges whose weights are 3, 6 and 7. The largest weight is 7 and the smallest weight is 3 so that the slimness of the tree T a is 4. The slimnesses of spanning trees T b , T c and T d shown in Figure 6(b), (c) and (d) are 3, 2 and 1, respectively. You can easily see the slimness of any other spanning tree is greater than or equal to 1, thus the spanning tree T d in Figure 6(d) is one of the slimmest spanning trees whose slimness is 1. Your job is to write a program that computes the smallest slimness. Input The input consists of multiple datasets, followed by a line containing two zeros separated by a space. Each dataset has the following format. n m a 1 b 1 w 1 . . . a m b m w m Every input item in a dataset is a non-negative integer. Items in a line are separated by a space. n is the number of the vertices and m the number of the edges. You can assume 2 ≤ n ≤ 100 and 0 ≤ m ≤ n ( n - 1)/2. a k and b k ( k = 1, ... , m ) are positive integers less than or equal to n , which represent the two vertices v a k and v b k connected by the k th edge e k . w k is a positive integer less than or equal to 10000, which indicates the weight of e k . You can assume that the graph G = ( V , E ) is simple, that is, there are no self-loops (that connect the same vertex) nor parallel edges (that are two or more edges whose both ends are the same two vertices). Output For each dataset, if the graph has spanning trees, the smallest slimness among them should be printed. Otherwise, -1 should be printed. An output should not contain extra characters. Sample Input 4 5 1 2 3 1 3 5 1 4 6 2 4 6 3 4 7 4 6 1 2 10 1 3 100 1 4 90 2 3 20 2 4 80 3 4 40 2 1 1 2 1 3 0 3 1 1 2 1 3 3 1 2 2 2 3 5 1 3 6 5 10 1 2 110 1 3 120 1 4 130 1 5 120 2 3 110 2 4 120 2 5 130 3 4 120 3 5 110 4 5 120 5 10 1 2 9384 1 3 887 1 4 2778 1 5 6916 2 3 7794 2 4 8336 2 5 5387 3 4 493 3 5 6650 4 5 1422 5 8 1 2 1 2 3 100 3 4 100 4 5 100 1 5 50 ...(truncated)
[ { "submission_id": "aoj_1280_11066219", "code_snippet": "#include <iostream>\n#include <vector>\n#include <tuple>\n#include <algorithm>\nusing namespace std;\n\nclass unionfind{\npublic:\n unionfind(int n): n_(n), m_(n) {\n parent_.resize(n);\n size_.resize(n);\n for(int i=0; i<n; i+...
aoj_1282_cpp
Problem H: Bug Hunt In this problem, we consider a simple programming language that has only declarations of one- dimensional integer arrays and assignment statements. The problem is to find a bug in the given program. The syntax of this language is given in BNF as follows: where < new line > denotes a new line character (LF). Characters used in a program are alphabetical letters, decimal digits, = , [ , ] and new line characters. No other characters appear in a program. A declaration declares an array and specifies its length. Valid indices of an array of length n are integers between 0 and n - 1, inclusive. Note that the array names are case sensitive, i.e. array a and array A are different arrays. The initial value of each element in the declared array is undefined. For example, array a of length 10 and array b of length 5 are declared respectively as follows. a[10] b[5] An expression evaluates to a non-negative integer. A < number > is interpreted as a decimal integer. An < array_name > [< expression >] evaluates to the value of the < expression > -th element of the array. An assignment assigns the value denoted by the right hand side to the array element specified by the left hand side. Examples of assignments are as follows. a[0]=3 a[1]=0 a[2]=a[a[1]] a[a[0]]=a[1] A program is executed from the first line, line by line. You can assume that an array is declared once and only once before any of its element is assigned or referred to. Given a program, you are requested to find the following bugs. An index of an array is invalid. An array element that has not been assigned before is referred to in an assignment as an index of array or as the value to be assigned. You can assume that other bugs, such as syntax errors, do not appear. You can also assume that integers represented by < number > s are between 0 and 2 31 - 1 (= 2147483647), inclusive. Input The input consists of multiple datasets followed by a line which contains only a single ' . ' (period). Each dataset consists of a program also followed by a line which contains only a single ' . ' (period). A program does not exceed 1000 lines. Any line does not exceed 80 characters excluding a new line character. Output For each program in the input, you should answer the line number of the assignment in which the first bug appears. The line numbers start with 1 for each program. If the program does not have a bug, you should answer zero. The output should not contain extra characters such as spaces. Sample Input a[3] a[0]=a[1] . x[1] x[0]=x[0] . a[0] a[0]=1 . b[2] b[0]=2 b[1]=b[b[0]] b[0]=b[1] . g[2] G[10] g[0]=0 g[1]=G[0] . a[2147483647] a[0]=1 B[2] B[a[0]]=2 a[B[a[0]]]=3 a[2147483646]=a[2] . . Output for the Sample Input 2 2 2 3 4 0
[ { "submission_id": "aoj_1282_10680131", "code_snippet": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/tag_and_trait.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n\nstruct custom_hash {\nstatic uint64_t splitmix64(u...
aoj_1278_cpp
Problem D: Lowest Pyramid 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. Figure 3: Some craft paper drawings and side views of the assembled pyramids Input The input consists of multiple datasets, each in the following format. X 0 Y 0 X 1 Y 1 X 2 Y 2 They are all integral numbers between -100 and +100 inclusive. ( X 0 , Y 0 ), ( X 1 , Y 1 ), ( X 2 , Y 2 ) 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 ( X a , Y a ), ( X b , Y b ) and ( X c , Y c ) whose coordinates are all integral values between -100 and +100 inclusive, and triangles ( X 0 , Y 0 )-( X 1 , Y 1 )-( X a , Y a ), ( X 1 , Y 1 )-( X 2 , Y 2 )-( X b , Y b ), ( X 2 , Y 2 )-( X 0 , Y 0 )-( X c , Y c ) and ( X 0 , Y 0 )-( X 1 , Y 1 )-( X 2 , Y 2 ) 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 0 0 1 0 0 1 0 0 5 0 2 5 -100 -100 100 -100 0 100 -72 -72 72 -72 0 72 0 0 0 0 0 0 Output for the Sample Input 2 1.49666 -1 8.52936
[ { "submission_id": "aoj_1278_10067849", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n#define rep(i,n) for(int i=0;i<n;i++)\n#define rep2(i,s,t) for(int i=s;i<t;i++)\n\nll sqrtz(ll x){\n if(x<0)return -201;\n ll z=sqrt(x)+2;\n while(z*z>x){\n z--;\n...
aoj_1283_cpp
Problem I: Most Distant Point from the Sea The main land of Japan called Honshu is an island surrounded by the sea. In such an island, it is natural to ask a question: "Where is the most distant point from the sea?" The answer to this question for Honshu was found in 1996. The most distant point is located in former Usuda Town, Nagano Prefecture, whose distance from the sea is 114.86 km. In this problem, you are asked to write a program which, given a map of an island, finds the most distant point from the sea in the island, and reports its distance from the sea. In order to simplify the problem, we only consider maps representable by convex polygons. Input The input consists of multiple datasets. Each dataset represents a map of an island, which is a convex polygon. The format of a dataset is as follows. n x 1 y 1 . . . x n y n Every input item in a dataset is a non-negative integer. Two input items in a line are separated by a space. n in the first line is the number of vertices of the polygon, satisfying 3 ≤ n ≤ 100. Subsequent n lines are the x - and y -coordinates of the n vertices. Line segments ( x i , y i ) - ( x i +1 , y i +1 ) (1 ≤ i ≤ n - 1) and the line segment ( x n , y n ) - ( x 1 , y 1 ) form the border of the polygon in counterclockwise order. That is, these line segments see the inside of the polygon in the left of their directions. All coordinate values are between 0 and 10000, inclusive. You can assume that the polygon is simple, that is, its border never crosses or touches itself. As stated above, the given polygon is always a convex one. The last dataset is followed by a line containing a single zero. Output For each dataset in the input, one line containing the distance of the most distant point from the sea should be output. An output line should not contain extra characters such as spaces. The answer should not have an error greater than 0.00001 (10 -5 ). You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. Sample Input 4 0 0 10000 0 10000 10000 0 10000 3 0 0 10000 0 7000 1000 6 0 40 100 20 250 40 250 70 100 90 0 70 3 0 0 10000 10000 5000 5001 0 Output for the Sample Input 5000.000000 494.233641 34.542948 0.353553
[ { "submission_id": "aoj_1283_8998626", "code_snippet": "#line 2 \"cp-library/src/cp-template.hpp\"\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\nusing i32 = int;\nusing u32 = unsigned int;\nusing...
aoj_1281_cpp
Problem G: The Morning after Halloween You are working for an amusement park as an operator of an obakeyashiki , or a haunted house, in which guests walk through narrow and dark corridors. The house is proud of their lively ghosts, which are actually robots remotely controlled by the operator, hiding here and there in the corridors. One morning, you found that the ghosts are not in the positions where they are supposed to be. Ah, yesterday was Halloween. Believe or not, paranormal spirits have moved them around the corridors in the night. You have to move them into their right positions before guests come. Your manager is eager to know how long it takes to restore the ghosts. In this problem, you are asked to write a program that, given a floor map of a house, finds the smallest number of steps to move all ghosts to the positions where they are supposed to be. A floor consists of a matrix of square cells. A cell is either a wall cell where ghosts cannot move into or a corridor cell where they can. At each step, you can move any number of ghosts simultaneously. Every ghost can either stay in the current cell, or move to one of the corridor cells in its 4-neighborhood (i.e. immediately left, right, up or down), if the ghosts satisfy the following conditions: No more than one ghost occupies one position at the end of the step. No pair of ghosts exchange their positions one another in the step. For example, suppose ghosts are located as shown in the following (partial) map, where a sharp sign (' # ) represents a wall cell and 'a', 'b', and 'c' ghosts. #### ab# #c## #### The following four maps show the only possible positions of the ghosts after one step. #### #### #### #### ab# a b# acb# ab # #c## #c## # ## #c## #### #### #### #### Input The input consists of at most 10 datasets, each of which represents a floor map of a house. The format of a dataset is as follows. w h n c 11 c 12 ... c 1 w c 21 c 22 ... c 2 w . . .. . .. . . .. . c h 1 c h 2 ... c h w w , h and n in the first line are integers, separated by a space. w and h are the floor width and height of the house, respectively. n is the number of ghosts. They satisfy the following constraints. 4 ≤ w ≤ 16 4 ≤ h ≤ 16 1 ≤ n ≤ 3 Subsequent h lines of w characters are the floor map. Each of c ij is either: a ' # ' representing a wall cell, a lowercase letter representing a corridor cell which is the initial position of a ghost, an uppercase letter representing a corridor cell which is the position where the ghost corresponding to its lowercase letter is supposed to be, or a space representing a corridor cell that is none of the above. In each map, each of the fir ...(truncated)
[ { "submission_id": "aoj_1281_10851166", "code_snippet": "#include<cstdio>\n#include<cstring>\n#include<cctype>\n#include<queue>\nusing namespace std;\n\nconst int maxs = 20;\nconst int maxn = 150;\nconst int dx[]= {1,-1,0,0,0};\nconst int dy[]= {0,0,1,-1,0};\n\ninline int ID(int a, int b, int c)\n{\n ret...
aoj_1287_cpp
Problem C: Stopped Watches 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 difficulties. 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 ha ...(truncated)
[ { "submission_id": "aoj_1287_9666489", "code_snippet": "#line 2 \"cp-library/src/cp-template.hpp\"\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\nusing i32 = int;\nusing u32 = unsigned int;\nusing...
aoj_1286_cpp
Problem B: Expected Allowance 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 1/36 + 2/36 + 3/36, 4/36, 5/36, 6/36, 5/36, 4/36, 3/36, 2/36 and 1/36, respectively. Therefore, the expected value is (1/36 + 2/36 + 3/36) × 1 + 4/36 × 2 + 5/36 × 3 + 6/36 × 4 + 5/36 × 5 + 4/36 × 6 + 3/36 × 7 + 2/36 × 8 + 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 ≤ n 2 ≤ m 0 ≤ k < nm nm × m n < 100000000 (10 8 ) 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 2 6 0 2 6 3 3 10 9 13 3 27 1 2008 3 0 0 0 Output for the Sample Input 7.00000000 4.11111111 7.71000000 1.42902599 1001.50298805
[ { "submission_id": "aoj_1286_10895025", "code_snippet": "#include<bits/stdc++.h>\n// #include<atcoder/all>\n// #include<boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\n// using namespace atcoder;\n// using bint = boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ull = unsigned long lo...
aoj_1292_cpp
Problem H: Top Spinning Spinning tops are one of the most popular and the most traditional toys. Not only spinning them, but also making one’s own is a popular enjoyment. One of the easiest way to make a top is to cut out a certain shape from a cardboard and pierce an axis stick through its center of mass. Professionally made tops usually have three dimensional shapes, but in this problem we consider only two dimensional ones. Usually, tops have rotationally symmetric shapes, such as a circle, a rectangle (with 2-fold rotational symmetry) or a regular triangle (with 3-fold symmetry). Although such symmetries are useful in determining their centers of mass, they are not definitely required; an asymmetric top also spins quite well if its axis is properly pierced at the center of mass. When a shape of a top is given as a path to cut it out from a cardboard of uniform thickness, your task is to find its center of mass to make it spin well. Also, you have to determine whether the center of mass is on the part of the cardboard cut out. If not, you cannot pierce the axis stick, of course. Input The input consists of multiple datasets, each of which describes a counterclockwise path on a cardboard to cut out a top. A path is indicated by a sequence of command lines, each of which specifies a line segment or an arc. In the description of commands below, the current position is the position to start the next cut, if any. After executing the cut specified by a command, the current position is moved to the end position of the cut made. The commands given are one of those listed below. The command name starts from the first column of a line and the command and its arguments are separated by a space. All the command arguments are integers. start x y Specifies the start position of a path. This command itself does not specify any cutting; it only sets the current position to be ( x , y ). line x y Specifies a linear cut along a straight line from the current position to the position ( x , y ), which is not identical to the current position . arc x y r Specifies a round cut along a circular arc. The arc starts from the current position and ends at ( x , y ), which is not identical to the current position . The arc has a radius of | r |. When r is negative, the center of the circle is to the left side of the direction of this round cut; when it is positive, it is to the right side (Figure 1). The absolute value of r is greater than the half distance of the two ends of the arc. Among two arcs connecting the start and the end positions with the specified radius, the arc specified is one with its central angle less than 180 degrees. close Closes a path by making a linear cut to the initial start position and terminates a dataset. If the current position is already at the start position, this command simply indicates the end of a dataset. The figure below gives an example of a command sequence and its corresponding path. N ...(truncated)
[ { "submission_id": "aoj_1292_4783909", "code_snippet": "#include<bits/stdc++.h>\ntypedef long long int ll;\ntypedef unsigned long long int ull;\n#define BIG_NUM 2000000000\n#define HUGE_NUM 1000000000000000000\n#define MOD 1000000007\n#define EPS 0.000000001\nusing namespace std;\n\n\n\n#define LOOP 50000\n...
aoj_1284_cpp
Problem J: The Teacher’s Side of Math One of the tasks students routinely carry out in their mathematics classes is to solve a polynomial equation. It is, given a polynomial, say X 2 - 4 X + 1, to find its roots (2 ± √3). If the students’ task is to find the roots of a given polynomial, the teacher’s task is then to find a polynomial that has a given root. Ms. Galsone is an enthusiastic mathematics teacher who is bored with finding solutions of quadratic equations that are as simple as a + b √ c . She wanted to make higher-degree equations whose solutions are a little more complicated. As usual in problems in mathematics classes, she wants to maintain all coefficients to be integers and keep the degree of the polynomial as small as possible (provided it has the specified root). Please help her by writing a program that carries out the task of the teacher’s side. You are given a number t of the form: t = m √ a + n √ b where a and b are distinct prime numbers, and m and n are integers greater than 1. In this problem, you are asked to find t's minimal polynomial on integers , which is the polynomial F ( X ) = a d X d + a d -1 X d -1 + ... + a 1 X + a 0 satisfying the following conditions. Coefficients a 0 , ... , a d are integers and a d > 0. F ( t ) = 0. The degree d is minimum among polynomials satisfying the above two conditions. F ( X ) is primitive. That is, coefficients a 0 , ... , a d have no common divisors greater than one. For example, the minimal polynomial of √3+ √2 on integers is F ( X ) = X 4 - 10 X 2 + 1. Verifying F ( t ) = 0 is as simple as the following ( α = 3, β = 2). F ( t ) = ( α + β ) 4 - 10( α + β ) 2 + 1 = ( α 4 + 4 α 3 β + 6 α 2 β 2 + 4 αβ 3 + β 4 ) - 10( α 2 + 2 αβ + β 2 ) + 1 = 9 + 12 αβ + 36 + 8 αβ + 4 - 10(3 + 2 αβ + 2) + 1 = (9 + 36 + 4 - 50 + 1) + (12 + 8 - 20) αβ = 0 Verifying that the degree of F ( t ) is in fact minimum is a bit more difficult. Fortunately, under the condition given in this problem, which is that a and b are distinct prime numbers and m and n greater than one, the degree of the minimal polynomial is always mn . Moreover, it is always monic . That is, the coefficient of its highest-order term ( a d ) is one. Input The input consists of multiple datasets, each in the following format. a m b n This line represents m √ a + n √ b . The last dataset is followed by a single line consisting of four zeros. Numbers in a single line are separated by a single space. Every dataset satisfies the following conditions. m √ a + n √ b ≤ 4. mn ≤ 20. The coefficients of the answer a 0 , ... , a d are between (-2 31 + 1) and (2 31 - 1), inclusive. Output For each dataset, output the coefficients of its minimal polynomial on integers F ( X ) = a d X d + a d -1 X d -1 + ... + a 1 X + a 0 , in the following format. a d a d -1 ... a 1 a 0 Non-negative integers must be printed without a sign (+ or -). Numbers in a single line must be separated by a single space and no other characters or extra spaces may appear in ...(truncated)
[ { "submission_id": "aoj_1284_10851232", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <cmath>\n#include <cctype>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <map>\n#include <iomanip>\n#include <cassert>\n\nusing namespace std...
aoj_1295_cpp
Problem A: Cubist Artwork International Center for Picassonian Cubism is a Spanish national museum of cubist artworks, dedicated to Pablo Picasso. The center held a competition for an artwork that will be displayed in front of the facade of the museum building. The artwork is a collection of cubes that are piled up on the ground and is intended to amuse visitors, who will be curious how the shape of the collection of cubes changes when it is seen from the front and the sides. The artwork is a collection of cubes with edges of one foot long and is built on a flat ground that is divided into a grid of one foot by one foot squares. Due to some technical reasons, cubes of the artwork must be either put on the ground, fitting into a unit square in the grid, or put on another cube in the way that the bottom face of the upper cube exactly meets the top face of the lower cube. No other way of putting cubes is possible. You are a member of the judging committee responsible for selecting one out of a plenty of artwork proposals submitted to the competition. The decision is made primarily based on artistic quality but the cost for installing the artwork is another important factor. Your task is to investigate the installation cost for each proposal. The cost is proportional to the number of cubes, so you have to figure out the minimum number of cubes needed for installation. Each design proposal of an artwork consists of the front view and the side view (the view seen from the right-hand side), as shown in Figure 1. Figure 1: An example of an artwork proposal The front view (resp., the side view) indicates the maximum heights of piles of cubes for each column line (resp., row line) of the grid. There are several ways to install this proposal of artwork, such as the following figures. In these figures, the dotted lines on the ground indicate the grid lines. The left figure makes use of 16 cubes, which is not optimal. That is, the artwork can be installed with a fewer number of cubes. Actually, the right one is optimal and only uses 13 cubes. Note that, a single pile of height three in the right figure plays the roles of two such piles in the left one. Notice that swapping columns of cubes does not change the side view. Similarly, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks. For example, consider the artwork proposal given in Figure 2. Figure 2: Another example of artwork proposal An optimal installation of this proposal of artwork can be achieved with 13 cubes, as shown in the following figure, which can be obtained by exchanging the rightmost two columns of the optimal installation of the artwork of Figure 1. Input The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. Each dataset is formatted as follows. w d h 1 h 2 ... h w h' 1 h' 2 ... h' d The integers w and d separated by a space are the numbers of columns and rows o ...(truncated)
[ { "submission_id": "aoj_1295_5841742", "code_snippet": "#pragma region Macros\n#include <bits/stdc++.h>\nusing namespace std;\ntemplate <class T> inline bool chmax(T &a, T b) {\n if(a < b) {\n a = b;\n return 1;\n }\n return 0;\n}\ntemplate <class T> inline bool chmin(T &a, T b) {\n ...
aoj_1289_cpp
Problem E: Spherical Mirrors 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) ∠ IQN = ∠ NQR , as shown in Figure 1. Figure 1: 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 x 1 y 1 z 1 r 1 . . . x N y N z N r N 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 ( u , v , w ) 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 ( x i , y i , z i ) and the radius r i . N , u , v , w , x i , y i , z i and r i satisfy the following conditions. 1 ≤ N ≤ 100 −100 ≤ u , v , w ≤ 100 −100 ≤ x i , y i , z i ≤ 100 5 ≤ r i ≤ 30 u 2 + v 2 + w 2 > 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. θ in Figure 1), 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 3 -20 -20 -24 100 100 100 30 10 8 3 5 -70 -70 -84 5 4 0 47 84 -23 41 42 8 45 -10 14 19 -5 28 47 12 -27 68 34 14 0 Output for the Sample Input 79.0940 79.0940 94.9128 -21.8647 54.9770 34.1761
[ { "submission_id": "aoj_1289_7221053", "code_snippet": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\nstruct Point3D {\n\tdouble px, py, pz;\n};\n\nPoint3D operator+(const Point3D &a1, const Point3D &a2) {\n\treturn Point3D{ a1.px + a2.px, a1.py + a2.py, a1.pz + a2.pz };\n}\n\nPoint3D opera...
aoj_1288_cpp
Problem D: Digits on the Floor 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 1. Since Taro may not have bars of desired lengths, Taro cannot always make forms exactly as shown in Figure 1. 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 2 as digits. On the other hand, Hanako cannot recognize the forms in Figure 3 as digits. For clarity, touching bars are slightly separated in Figures 1, 2 and 3. Actually, touching bars overlap exactly at one single point. Figure 1: Representation of digits Figure 2: 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. Figure 3: 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 x 1a y 1a x 1b y 1b x 2a y 2a x 2b y 2b . . . x na y na x nb y nb 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 x a , y a , x b , y b , delimited by single spaces, are given in each line. x a and y a are the x- and y- coordinates of one end of the bar, respectively. x b and y b are those of the other end. The coordinate system is as shown in Figure 4. You can assume 1 ≤ n ≤ 1000 and 0 ≤ x a , y a , x b , y b ≤ 1000. The end of the input is ...(truncated)
[ { "submission_id": "aoj_1288_10946400", "code_snippet": "#include <cstdio>\n#include <cstdlib>\n#include <cstring>\nusing namespace std;\nint n, xa[10010], xb[10010], ya[10010], yb[10010], v[1010][1010], xx1, xx2, q1[10010];\nint q[10010], qq[10010], r, ll, rr, in[10010], v1[10010], ans[100], c1, c2, c3;\ns...
aoj_1291_cpp
Problem G: Search of Concatenated Strings The amount of information on the World Wide Web is growing quite rapidly. In this information explosion age, we must survive by accessing only the Web pages containing information relevant to our own needs. One of the key technologies for this purpose is keyword search. By using well-known search engines, we can easily access those pages containing useful information about the topic we want to know. There are many variations in keyword search problems. If a single string is searched in a given text, the problem is quite easy. If the pattern to be searched consists of multiple strings, or is given by some powerful notation such as regular expressions, the task requires elaborate algorithms to accomplish efficiently. In our problem, a number of strings (element strings) are given, but they are not directly searched for. Concatenations of all the element strings in any order are the targets of the search here. For example, consider three element strings aa, b and ccc are given. In this case, the following six concatenated strings are the targets of the search, i.e. they should be searched in the text. aabccc aacccb baaccc bcccaa cccaab cccbaa The text may contain several occurrences of these strings. You are requested to count the number of occurrences of these strings, or speaking more precisely, the number of positions of occurrences in the text. Two or more concatenated strings may be identical. In such cases, it is necessary to consider subtle aspects of the above problem statement. For example, if two element strings are x and xx, the string xxx is an occurrence of both the concatenation of x and xx and that of xx and x. Since the number of positions of occurrences should be counted, this case is counted as one, not two. Two occurrences may overlap. For example, the string xxxx has occurrences of the concatenation xxx in two different positions. This case is counted as two. Input The input consists of a number of datasets, each giving a set of element strings and a text. The format of a dataset is as follows. n m e 1 e 2 . . . e n t 1 t 2 . . . t m The first line contains two integers separated by a space. n is the number of element strings. m is the number of lines used to represent the text. n is between 1 and 12, inclusive. Each of the following n lines gives an element string. The length (number of characters) of an element string is between 1 and 20, inclusive. The last m lines as a whole give the text. Since it is not desirable to have a very long line, the text is separated into m lines by newlines, but these newlines should be ignored. They are not parts of the text. The length of each of these lines (not including the newline) is between 1 and 100, inclusive. The length of the text is between 1 and 5000, inclusive. The element strings and the text do not contain characters other than lowercase letters. The end of the input is indicated by a line containing two zeros separated by a space. CAUTIO ...(truncated)
[ { "submission_id": "aoj_1291_10851194", "code_snippet": "#include<iostream>\n#include<cstdio>\n#include<cstring>\n#include<algorithm>\nusing namespace std;\n\nconst int N=12;\nint i,j,n,m;\nchar s[6000],ss[6000];\nchar c[20][50];\nbool f[5500][1<<N];\nint len,ll,l[N+3];\nbool b[5030][N+1];\n\nvoid check(int...
aoj_1290_cpp
Problem F: Traveling Cube 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 c 11 . . . c w 1 . . . . . . c 1 d . . . c wd v 1 v 2 v 3 v 4 v 5 v 6 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 c 11 . . . c w 1 , . . . , c 1 d . . . c wd 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 v 1 v 2 v 3 v 4 v 5 v 6 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 c ij shows the color of a square in the bed. The characters c 11 , c w 1 , c 1 d and c wd correspond to the north-west corner, the north-east corner, the south-west ...(truncated)
[ { "submission_id": "aoj_1290_10946409", "code_snippet": "#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\n#define K\t0\t// Black\n#define W\t128\t// White\n#define R\t1\t// Red\n#define G\t2\t// Green\n#define B\t3\t// Blue\n#define...
aoj_1300_cpp
Problem F: Chemist's Math You have probably learnt chemical equations (chemical reaction formulae) in your high-school days. The following are some well-known equations. 2H 2 + O 2 → 2H 2 O (1) C a (OH) 2 + CO 2 → C a CO 3 + H 2 O (2) N 2 + 3H 2 → 2NH 3 (3) While Equations (1)–(3) all have balanced left-hand sides and right-hand sides, the following ones do not. Al + O 2 → Al 2 O 3 ( wrong ) (4) C 3 H 8 + O 2 → CO 2 + H 2 O ( wrong ) (5) The equations must follow the law of conservation of mass ; the quantity of each chemical element (such as H, O, Ca, Al) should not change with chemical reactions. So we should "adjust" the numbers of molecules on the left-hand side and right-hand side: 4Al + 3O 2 → 2Al 2 O 3 ( correct ) (6) C 3 H 8 + 5O 2 → 3CO 2 + 4H 2 O (correct) (7) The coefficients of Equation (6) are (4, 3, 2) from left to right, and those of Equation (7) are (1, 5, 3, 4) from left to right. Note that the coefficient 1 may be omitted from chemical equations. The coefficients of a correct equation must satisfy the following conditions. The coefficients are all positive integers. The coefficients are relatively prime, that is, their greatest common divisor (g.c.d.) is 1. The quantities of each chemical element on the left-hand side and the right-hand side are equal. Conversely, if a chemical equation satisfies the above three conditions, we regard it as a correct equation, no matter whether the reaction or its constituent molecules can be chemically realized in the real world, and no matter whether it can be called a reaction (e.g., H 2 → H 2 is considered correct). A chemical equation satisfying Conditions 1 and 3 (but not necessarily Condition 2) is called a balanced equation. Your goal is to read in chemical equations with missing coefficients like Equation (4) and (5), line by line, and output the sequences of coefficients that make the equations correct. Note that the above three conditions do not guarantee that a correct equation is uniquely determined. For example, if we "mix" the reactions generating H 2 O and NH 3 , we would get x H 2 + y O 2 + z N 2 + u H 2 → v H 2 O + w NH 3 (8) but ( x , y , z , u , v , w ) = (2, 1, 1, 3, 2, 2) does not represent a unique correct equation; for instance, (4, 2, 1, 3, 4, 2) and (4, 2, 3, 9, 4, 6) are also "correct" according to the above definition! However, we guarantee that every chemical equation we give you will lead to a unique correct equation by adjusting their coefficients. In other words, we guarantee that (i) every chemical equation can be balanced with positive coefficients, and that (ii) all balanced equations of the original equation can be obtained by multiplying the co ...(truncated)
[ { "submission_id": "aoj_1300_1055603", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <functional>\n#include <map>\n#include <cctype>\nusing namespace std;\n#define rep(i,n) for(int i=0;i<(n);++i)\n#define rep1(i...
aoj_1294_cpp
Problem J: Zigzag Given several points on a plane, let’s try to solve a puzzle connecting them with a zigzag line. The puzzle is to find the zigzag line that passes through all the given points with the minimum number of turns. Moreover, when there are several zigzag lines with the minimum number of turns, the shortest one among them should be found. For example, consider nine points given in Figure 1. Figure 1: Given nine points A zigzag line is composed of several straight line segments. Here, the rule requests that each line segment should pass through two or more given points. A zigzag line may turn at some of the given points or anywhere else. There may be some given points passed more than once. Figure 2: Zigzag lines with three turning points. Two zigzag lines with three turning points are depicted in Figure 2 (a) and (b) for the same set of given points shown in Figure 1. The length of the zigzag line in Figure 2 (a) is shorter than that in Figure 2 (b). In fact, the length of the zigzag line in Figure 2 (a) is the shortest so that it is the solution for the nine points given in Figure 1. Another zigzag line with four turning points is depicted in Figure 3. Its length is shorter than those in Figure 2, however, the number of turning points is greater than those in Figure 2, and thus, it is not the solution. Figure 3: Zigzag line with four turning points. There are two zigzag lines that passes another set of given points depicted in Figure 4 (a) and (b). Both have the same number of turning points, and the line in (a) is longer than that in (b). However, the solution is (a), because one of the segments of the zigzag line in (b) passes only one given point, violating the rule. Figure 4: Zigzag line with two turning points (a), and not a zigzag line concerned (b). Your job is to write a program that solves this puzzle. Input The input consists of multiple datasets, followed by a line containing one zero. Each dataset has the following format. n x 1 y 1 . . . x n y n Every input item in a dataset is a non-negative integer. Items in a line are separated by a single space. n is the number of the given points. x k and y k ( k = 1, . . . , n ) indicate the position of the k -th point. The order of the points is meaningless. You can assume that 2 ≤ n ≤ 10, 0 ≤ x k ≤ 10, and 0 ≤ y k ≤ 10. Output For each dataset, the minimum number of turning points and the length of the shortest zigzag line with that number of turning points should be printed, separated by a space in a line. The length should be in a decimal fraction with an error less than 0.0001 (= 1.0 × 10 -4 ). You may assume that the minimum number of turning points is at most four, that is, the number of line segments is at most five. The example solutions for the first four datasets in the sample input are depicted in Figure 5 and 6. Sample Input 2 0 0 10 9 4 0 0 3 1 0 3 3 3 10 2 2 4 2 6 2 2 4 4 4 6 4 2 6 4 6 6 6 3 3 10 0 0 2 0 4 0 0 2 2 2 4 2 0 4 2 4 4 4 6 8 9 0 0 1 0 3 0 0 1 1 1 3 1 ...(truncated)
[ { "submission_id": "aoj_1294_10853309", "code_snippet": "#include<iostream>\n#include<cstdio>\n#include<cstdlib>\n#include<algorithm>\n#include<cstring>\n#include<cmath>\n#include<ctime>\n#include<map>\n#include<string>\n#include<vector>\n#include<set>\n\nusing namespace std;\n#define For(i,l,r) for (int i ...
aoj_1299_cpp
Problem E: Origami Through-Hole Origami is the traditional Japanese art of paper folding. One day, Professor Egami found the message board decorated with some pieces of origami works pinned on it, and became interested in the pinholes on the origami paper. Your mission is to simulate paper folding and pin punching on the folded sheet, and calculate the number of pinholes on the original sheet when unfolded. A sequence of folding instructions for a flat and square piece of paper and a single pinhole position are specified. As a folding instruction, two points P and Q are given. The paper should be folded so that P touches Q from above (Figure 4). To make a fold, we first divide the sheet into two segments by creasing the sheet along the folding line , i.e., the perpendicular bisector of the line segment PQ , and then turn over the segment containing P onto the other. You can ignore the thickness of the paper. Figure 4: Simple case of paper folding The original flat square piece of paper is folded into a structure consisting of layered paper segments, which are connected by linear hinges. For each instruction, we fold one or more paper segments along the specified folding line, dividing the original segments into new smaller ones. The folding operation turns over some of the paper segments (not only the new smaller segments but also some other segments that have no intersection with the folding line) to the reflective position against the folding line. That is, for a paper segment that intersects with the folding line, one of the two new segments made by dividing the original is turned over; for a paper segment that does not intersect with the folding line, the whole segment is simply turned over. The folding operation is carried out repeatedly applying the following rules, until we have no segment to turn over. Rule 1: The uppermost segment that contains P must be turned over. Rule 2: If a hinge of a segment is moved to the other side of the folding line by the operation, any segment that shares the same hinge must be turned over. Rule 3: If two paper segments overlap and the lower segment is turned over, the upper segment must be turned over too. In the examples shown in Figure 5, (a) and (c) show cases where only Rule 1 is applied. (b) shows a case where Rule 1 and 2 are applied to turn over two paper segments connected by a hinge, and (d) shows a case where Rule 1, 3 and 2 are applied to turn over three paper segments. Figure 5: Different cases of folding After processing all the folding instructions, the pinhole goes through all the layered segments of paper at that position. In the case of Figure 6, there are three pinholes on the unfolded sheet of paper. Figure 6: Number of pinholes on the unfolded sheet Input The input is a sequence of datasets. The end of the input is indicated by a line containing a zero. Each dataset is formatted as follows. k p x 1 p y 1 q x 1 q y 1 . . . p x k p y k q x k q y k h x h y For all datasets, the size of t ...(truncated)
[ { "submission_id": "aoj_1299_3228821", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <iomanip>\n#include <complex>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <array>\nusing namespace std;\nconst double EPS = 1e-8;\nconst double INF = 1e12;\n#define EQ(n,m) (abs(...
aoj_1296_cpp
Problem B: Repeated Substitution with Sed Do you know "sed," a tool provided with Unix? Its most popular use is to substitute every occurrence of a string contained in the input string (actually each input line) with another string β . More precisely, it proceeds as follows. Within the input string, every non-overlapping (but possibly adjacent) occurrences of α are marked. If there is more than one possibility for non-overlapping matching, the leftmost one is chosen. Each of the marked occurrences is substituted with β to obtain the output string; other parts of the input string remain intact. For example, when α is " aa " and β is " bca ", an input string " aaxaaa " will produce " bcaxbcaa ", but not " aaxbcaa " nor " bcaxabca ". Further application of the same substitution to the string " bcaxbcaa " will result in " bcaxbcbca ", but this is another substitution, which is counted as the second one. In this problem, a set of substitution pairs ( α i , β i ) ( i = 1, 2, ... , n ), an initial string γ , and a final string δ are given, and you must investigate how to produce δ from γ with a minimum number of substitutions. A single substitution ( α i , β i ) here means simultaneously substituting all the non-overlapping occurrences of α i , in the sense described above, with β i . You may use a specific substitution ( α i , β i ) multiple times, including zero times. Input The input consists of multiple datasets, each in the following format. n α 1 β 1 α 2 β 2 . . . α n β n γ δ n is a positive integer indicating the number of pairs. α i and β i are separated by a single space. You may assume that 1 ≤ | α i | < | β i | ≤ 10 for any i (| s | means the length of the string s ), α i ≠ α j for any i ≠ j , n ≤ 10 and 1 ≤ | γ | < | δ | ≤ 10. All the strings consist solely of lowercase letters. The end of the input is indicated by a line containing a single zero. Output For each dataset, output the minimum number of substitutions to obtain δ from γ . If δ cannot be produced from γ with the given set of substitutions, output -1 . Sample Input 2 a bb b aa a bbbbbbbb 1 a aa a aaaaa 3 ab aab abc aadc ad dee abc deeeeeeeec 10 a abc b bai c acf d bed e abh f fag g abe h bag i aaj j bbb a abacfaabe 0 Output for the Sample Input 3 -1 7 4
[ { "submission_id": "aoj_1296_9003254", "code_snippet": "// (⁠◕⁠ᴗ⁠◕⁠✿⁠)\n\n// #pragma GCC target(\"avx2\")\n// #pragma GCC optimize(\"O3\")\n// #pragma GCC optimize(\"unroll-loops\")\n#include <bits/stdc++.h>\n#define rep(i, n) for (ll i = 0; i < (n); i++)\n#define srep(i, s, n) for (ll i = s; i < (n); i++)\...
aoj_1297_cpp
Problem C: Swimming Jam Despite urging requests of the townspeople, the municipal office cannot afford to improve many of the apparently deficient city amenities under this recession. The city swimming pool is one of the typical examples. It has only two swimming lanes. The Municipal Fitness Agency, under this circumstances, settled usage rules so that the limited facilities can be utilized fully. Two lanes are to be used for one-way swimming of different directions. Swimmers are requested to start swimming in one of the lanes, from its one end to the other, and then change the lane to swim his/her way back. When he or she reaches the original starting end, he/she should return to his/her initial lane and starts swimming again. Each swimmer has his/her own natural constant pace. Swimmers, however, are not permitted to pass other swimmers except at the ends of the pool; as the lanes are not wide enough, that might cause accidents. If a swimmer is blocked by a slower swimmer, he/she has to follow the slower swimmer at the slower pace until the end of the lane is reached. Note that the blocking swimmer’s natural pace may be faster than the blocked swimmer; the blocking swimmer might also be blocked by another swimmer ahead, whose natural pace is slower than the blocked swimmer. Blocking would have taken place whether or not a faster swimmer was between them. Swimmers can change their order if they reach the end of the lane simultaneously. They change their order so that ones with faster natural pace swim in front. When a group of two or more swimmers formed by a congestion reaches the end of the lane, they are considered to reach there simultaneously, and thus change their order there. The number of swimmers, their natural paces in times to swim from one end to the other, and the numbers of laps they plan to swim are given. Note that here one "lap" means swimming from one end to the other and then swimming back to the original end. Your task is to calculate the time required for all the swimmers to finish their plans. All the swimmers start from the same end of the pool at the same time, the faster swimmers in front. In solving this problem, you can ignore the sizes of swimmers' bodies, and also ignore the time required to change the lanes and the order in a group of swimmers at an end of the lanes. Input The input is a sequence of datasets. Each dataset is formatted as follows. n t 1 c 1 ... t n c n n is an integer (1 ≤ n ≤ 50) that represents the number of swimmers. t i and c i are integers (1 ≤ t i ≤ 300, 1 ≤ c i ≤ 250) that represent the natural pace in times to swim from one end to the other and the number of planned laps for the i -th swimmer, respectively. ti and ci are separated by a space. The end of the input is indicated by a line containing one zero. Output For each dataset, output the time required for all the swimmers to finish their plans in a line. No extra characters should occur in the output. Sample Input 2 10 30 15 20 2 10 240 15 ...(truncated)
[ { "submission_id": "aoj_1297_10853354", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nint n, tot, tot2, ans, lamp [100], lamp2 [100], Time [100], t [100];\n\nstruct data\n{\n\tint Time, lamp;\n} a [100];\n\nbool cmpp (int x, int ...
aoj_1303_cpp
Problem I: Hobby on Rails ICPC (International Connecting Points Company) starts to sell a new railway toy. It consists of a toy tramcar and many rail units on square frames of the same size. There are four types of rail units, namely, straight (S), curve (C), left-switch (L) and right-switch (R) as shown in Figure 9. A switch has three ends, namely, branch/merge-end (B/M-end), straight-end (S-end) and curve-end (C-end). A switch is either in "through" or "branching" state. When the tramcar comes from B/M-end, and if the switch is in the through-state, the tramcar goes through to S-end and the state changes to branching; if the switch is in the branching-state, it branches toward C-end and the state changes to through. When the tramcar comes from S-end or C-end, it goes out from B/M-end regardless of the state. The state does not change in this case. Kids are given rail units of various types that fill a rectangle area of w × h , as shown in Fig- ure 10(a). Rail units meeting at an edge of adjacent two frames are automatically connected. Each rail unit may be independently rotated around the center of its frame by multiples of 90 degrees in order to change the connection of rail units, but its position cannot be changed. Kids should make "valid" layouts by rotating each rail unit, such as getting Figure 10(b) from Figure 10(a). A layout is valid when all rails at three ends of every switch are directly or indirectly connected to an end of another switch or itself. A layout in Figure 10(c) is invalid as well as Figure 10(a). Invalid layouts are frowned upon. When a tramcar runs in a valid layout, it will eventually begin to repeat the same route forever. That is, we will eventually find the tramcar periodically comes to the same running condition, which is a triple of the tramcar position in the rectangle area, its direction, and the set of the states of all the switches. A periodical route is a sequence of rail units on which the tramcar starts from a rail unit with a running condition and returns to the same rail unit with the same running condition for the first time. A periodical route through a switch or switches is called the "fun route", since kids like the rattling sound the tramcar makes when it passes through a switch. The tramcar takes the same unit time to go through a rail unit, not depending on the types of the unit or the tramcar directions. After the tramcar starts on a rail unit on a “fun route”, it will come back to the same unit with the same running condition, sooner or later. The fun time T of a fun route is the number of time units that the tramcar takes for going around the route. Of course, kids better enjoy layouts with longer fun time. Given a variety of rail units placed on a rectangular area, your job is to rotate the given rail units appropriately and to find the fun route with the longest fun time in the valid layouts. For example, there is a fun route in Figure 10(b). Its fun time is 24. Let the toy tramcar start from ...(truncated)
[ { "submission_id": "aoj_1303_4937474", "code_snippet": "#include<iostream>\n#include<cassert>\nusing namespace std;\n#define REP(i,b,n) for(int i=b;i<n;i++)\n#define rep(i,n) REP(i,0,n)\n\n#define N 0\n#define E 1\n#define S 2\n#define W 3\n\nint dx[]={0,1,0,-1};\nint dy[]={-1,0,1,0};\nint curdir[]={S,W,N...
aoj_1298_cpp
Problem D: Separate Points Numbers of black and white points are placed on a plane. Let's imagine that a straight line of infinite length is drawn on the plane. When the line does not meet any of the points, the line divides these points into two groups. If the division by such a line results in one group consisting only of black points and the other consisting only of white points, we say that the line "separates black and white points". Let's see examples in Figure 3. In the leftmost example, you can easily find that the black and white points can be perfectly separated by the dashed line according to their colors. In the remaining three examples, there exists no such straight line that gives such a separation. Figure 3: Example planes In this problem, given a set of points with their colors and positions, you are requested to decide whether there exists a straight line that separates black and white points. Input The input is a sequence of datasets, each of which is formatted as follows. n m x 1 y 1 . . . x n y n x n +1 y n +1 . . . x n + m y n + m The first line contains two positive integers separated by a single space; n is the number of black points, and m is the number of white points. They are less than or equal to 100. Then n + m lines representing the coordinates of points follow. Each line contains two integers x i and y i separated by a space, where ( x i , y i ) represents the x -coordinate and the y -coordinate of the i -th point. The color of the i -th point is black for 1 ≤ i ≤ n , and is white for n + 1 ≤ i ≤ n + m . All the points have integral x - and y -coordinate values between 0 and 10000 inclusive. You can also assume that no two points have the same position. The end of the input is indicated by a line containing two zeros separated by a space. Output For each dataset, output " YES " if there exists a line satisfying the condition. If not, output " NO ". In either case, print it in one line for each input dataset. Sample Input 3 3 100 700 200 200 600 600 500 100 500 300 800 500 3 3 100 300 400 600 400 100 600 400 500 900 300 300 3 4 300 300 500 300 400 600 100 100 200 900 500 900 800 100 1 2 300 300 100 100 500 500 1 1 100 100 200 100 2 2 0 0 500 700 1000 1400 1500 2100 2 2 0 0 1000 1000 1000 0 0 1000 3 3 0 100 4999 102 10000 103 5001 102 10000 102 0 101 3 3 100 100 200 100 100 200 0 0 400 0 0 400 3 3 2813 1640 2583 2892 2967 1916 541 3562 9298 3686 7443 7921 0 0 Output for the Sample Input YES NO NO NO YES YES NO NO NO YES
[ { "submission_id": "aoj_1298_10522105", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define all(v) (v).begin(),(v).end()\n#define pb(a) push_back(a)\n#define rep(i, n) for(int i=0;i<n;i++)\n#define foa(e, v) for(auto&& e : v)\nusing ll = long long;\nconst ll MOD7 = 1000000007, MOD998 = ...
aoj_1301_cpp
Problem G: Malfatti Circles The configuration of three circles packed inside a triangle such that each circle is tangent to the other two circles and to two of the edges of the triangle has been studied by many mathematicians for more than two centuries. Existence and uniqueness of such circles for an arbitrary triangle are easy to prove. Many methods of numerical calculation or geometric construction of such circles from an arbitrarily given triangle have been discovered. Today, such circles are called the Malfatti circles . Figure 7 illustrates an example. The Malfatti circles of the triangle with the vertices (20, 80), (-40, -20) and (120, -20) are approximately the circle with the center (24.281677, 45.219486) and the radius 21.565935, the circle with the center (3.110950, 4.409005) and the radius 24.409005, and the circle with the center (54.556724, 7.107493) and the radius 27.107493. Figure 8 illustrates another example. The Malfatti circles of the triangle with the vertices (20, -20), (120, -20) and (-40, 80) are approximately the circle with the center (25.629089, −10.057956) and the radius 9.942044, the circle with the center (53.225883, −0.849435) and the radius 19.150565, and the circle with the center (19.701191, 19.203466) and the radius 19.913790. Your mission is to write a program to calculate the radii of the Malfatti circles of the given triangles. Input The input is a sequence of datasets. A dataset is a line containing six integers x 1 , y 1 , x 2 , y 2 , x 3 and y 3 in this order, separated by a space. The coordinates of the vertices of the given triangle are ( x 1 , y 1 ), ( x 2 , y 2 ) and ( x 3 , y 3 ), respectively. You can assume that the vertices form a triangle counterclockwise. You can also assume that the following two conditions hold. All of the coordinate values are greater than −1000 and less than 1000. None of the Malfatti circles of the triangle has a radius less than 0.1. The end of the input is indicated by a line containing six zeros separated by a space. Output For each input dataset, three decimal fractions r 1 , r 2 and r 3 should be printed in a line in this order separated by a space. The radii of the Malfatti circles nearest to the vertices with the coordinates ( x 1 , y 1 ), ( x 2 , y 2 ) and ( x 3 , y 3 ) should be r 1 , r 2 and r 3 , respectively. None of the output values may have an error greater than 0.0001. No extra character should appear in the output. Sample Input 20 80 -40 -20 120 -20 20 -20 120 -20 -40 80 0 0 1 0 0 1 0 0 999 1 -999 1 897 -916 847 -972 890 -925 999 999 -999 -998 -998 -999 -999 -999 999 -999 0 731 -999 -999 999 -464 -464 999 979 -436 -955 -337 157 -439 0 0 0 0 0 0 Output for the Sample Input 21.565935 24.409005 27.107493 9.942044 19.150565 19.913790 0.148847 0.207107 0.207107 0.125125 0.499750 0.499750 0.373458 0.383897 0.100456 0.706768 0.353509 0.353509 365.638023 365.638023 365.601038 378.524085 378.605339 378.605339 21.895803 22.052921 5.895714
[ { "submission_id": "aoj_1301_10852904", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <iostream>\nusing namespace std;\nstruct Point\n{\n\tdouble x, y;\n}Tri[10];\ndouble length(Point p)\n{\n\treturn (sqrt(p.x * p.x + p.y * p.y))...
aoj_1305_cpp
Problem A: Membership Management Peter is a senior manager of Agile Change Management (ACM) Inc., where each employee is a member of one or more task groups. Since ACM is agile, task groups are often reorganized and their members frequently change, so membership management is his constant headache. Peter updates the membership information whenever any changes occur: for instance, the following line written by him means that Carol and Alice are the members of the Design Group. design:carol,alice. The name preceding the colon is the group name and the names following it specify its members. A smaller task group may be included in a larger one. So, a group name can appear as a member of another group, for instance, as follows. development:alice,bob,design,eve. Simply unfolding the design above gives the following membership specification, which is equivalent to the original. development:alice,bob,carol,alice,eve. In this case, however, alice occurs twice. After removing one of the duplicates, we have the following more concise specification. development:alice,bob,carol,eve. Your mission in this problem is to write a program that, given group specifications, identifies group members. Note that Peter's specifications can include deeply nested groups. In the following, for instance, the group one contains a single member dave. one:another. another:yetanother. yetanother:dave. Input The input is a sequence of datasets, each being in the following format. n group 1 : member 1,1 ,..., member 1, m 1 . . . . group i : member i ,1 ,..., member i , m i . . . . group n : member n ,1 ,..., member n , m n . The first line contains n, which represents the number of groups and is a positive integer no more than 100. Each of the following n lines contains the membership information of a group: group i (1 ≤ i ≤ n ) is the name of the i -th task group and is followed by a colon ( : ) and then the list of its m i member s that are delimited by a comma ( , ) and terminated by a period ( . ). Those group names are mutually different. Each m i (1 ≤ i ≤ n ) is between 1 and 10, inclusive. A member is another group name if it is one of group 1 , group 2 ,..., or groupn. Otherwise it is an employee name. There are no circular (or recursive) definitions of group(s). You may assume that m i member names of a group are mutually different. Each group or employee name is a non-empty character string of length between 1 and 15, inclusive, and consists of lowercase letters. The end of the input is indicated by a line containing a zero. Output For each dataset, output the number of employees included in the first group of the dataset, that is group 1 , in a line. No extra characters should occur in the output. Sample Input 2 development:alice,bob,design,eve. design:carol,alice. 3 one:another. another:yetanother. yetanother:dave. 3 friends:alice,bob,bestfriends,carol,fran,badcompany. bestfriends:eve,alice. badcompany:dave,carol. 5 a:b,c,d,e. b:c,d,e,f. c:d,e,f,g. d:e,f,g,h. e:f,g,h, ...(truncated)
[ { "submission_id": "aoj_1305_10739683", "code_snippet": "#include<stdio.h>\n#include<string.h>\n#include<string>\n#include<vector>\n#include<stdlib.h>\n#include<algorithm>\n#include<iostream>\nusing namespace std;\n\nvector<string> q[111];\nint n;\nchar s[300];\n\nint main()\n{\n //freopen(\"x.in\",...
aoj_1307_cpp
Problem C: Towns along a Highway There are several towns on a highway. The highway has no forks. Given the distances between the neighboring towns, we can calculate all distances from any town to others. For example, given five towns (A, B, C, D and E) and the distances between neighboring towns like in Figure C.1, we can calculate the distance matrix as an upper triangular matrix containing the distances between all pairs of the towns, as shown in Figure C.2. Figure C.1: An example of towns Figure C.2: The distance matrix for Figure C.1 In this problem, you must solve the inverse problem. You know only the distances between all pairs of the towns, that is, N ( N - 1)/2 numbers in the above matrix. Then, you should recover the order of the towns and the distances from each town to the next. Input The input is a sequence of datasets. Each dataset is formatted as follows. N d 1 d 2 ... d N ( N -1)/2 The first line contains an integer N (2 ≤ N ≤ 20), which is the number of the towns on the highway. The following lines contain N ( N -1)/2 integers separated by a single space or a newline, which are the distances between all pairs of the towns. Numbers are given in descending order without any information where they appear in the matrix. You can assume that each distance is between 1 and 400, inclusive. Notice that the longest distance is the distance from the leftmost town to the rightmost. The end of the input is indicated by a line containing a zero. Output For each dataset, output N - 1 integers in a line, each of which is the distance from a town to the next in the order of the towns. Numbers in a line must be separated by a single space. If the answer is not unique, output multiple lines ordered by the lexicographical order as a sequence of integers, each of which corresponds to an answer. For example, ' 2 10 ' should precede ' 10 2 '. If no answer exists, output nothing. At the end of the output for each dataset, a line containing five minus symbols ' ----- ' should be printed for human readability. No extra characters should occur in the output. For example, extra spaces at the end of a line are not allowed. Sample Input 2 1 3 5 3 2 3 6 3 2 5 9 8 7 6 6 4 3 2 2 1 6 9 8 8 7 6 6 5 5 3 3 3 2 2 1 1 6 11 10 9 8 7 6 6 5 5 4 3 2 2 1 1 7 72 65 55 51 48 45 40 38 34 32 27 25 24 23 21 17 14 13 11 10 7 20 190 189 188 187 186 185 184 183 182 181 180 179 178 177 176 175 174 173 172 171 170 169 168 167 166 165 164 163 162 161 160 159 158 157 156 155 154 153 152 151 150 149 148 147 146 145 144 143 142 141 140 139 138 137 136 135 134 133 132 131 130 129 128 127 126 125 124 123 122 121 120 119 118 117 116 115 114 113 112 111 110 109 108 107 106 105 104 103 102 101 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 19 60 59 58 ...(truncated)
[ { "submission_id": "aoj_1307_10850484", "code_snippet": "#include <cstdio>\n#include <cstring>\n#include <algorithm>\n#include <map>\n#include <iostream>\n#include <vector>\nusing namespace std;\nint d[500];\nint sum[100];\nint n;\nvector<int>ans[1148576];\nint cnt;\nbool vis[1148576];\nint dis[500];\nint n...
aoj_1304_cpp
Problem J: Infected Land The earth is under an attack of a deadly virus. Luckily, prompt actions of the Ministry of Health against this emergency successfully confined the spread of the infection within a square grid of areas. Recently, public health specialists found an interesting pattern with regard to the transition of infected areas. At each step in time, every area in the grid changes its infection state according to infection states of its directly (horizontally, vertically, and diagonally) adjacent areas. An infected area continues to be infected if it has two or three adjacent infected areas. An uninfected area becomes infected if it has exactly three adjacent infected areas. An area becomes free of the virus, otherwise. Your mission is to fight against the virus and disinfect all the areas. The Ministry of Health lets an anti-virus vehicle prototype under your command. The functionality of the vehicle is summarized as follows. At the beginning of each time step, you move the vehicle to one of the eight adjacent areas. The vehicle is not allowed to move to an infected area (to protect its operators from the virus). It is not allowed to stay in the same area. Following vehicle motion, all the areas, except for the area where the vehicle is in, change their infection states according to the transition rules described above. Special functionality of the vehicle protects its area from virus infection even if the area is adjacent to exactly three infected areas. Unfortunately, this virus-protection capability of the vehicle does not last. Once the vehicle leaves the area, depending on the infection states of the adjacent areas, the area can be infected. The area where the vehicle is in, which is uninfected , has the same effect to its adjacent areas as an infected area as far as the transition rules are concerned. The following series of figures illustrate a sample scenario that successfully achieves the goal. Initially, your vehicle denoted by @ is found at (1, 5) in a 5 × 5-grid of areas, and you see some infected areas which are denoted by # 's. Firstly, at the beginning of time step 1, you move your vehicle diagonally to the southwest, that is, to the area (2, 4). Note that this vehicle motion was possible because this area was not infected at the start of time step 1. Following this vehicle motion, infection state of each area changes according to the transition rules. The column "1-end" of the figure illustrates the result of such changes at the end of time step 1. Note that the area (3, 3) becomes infected because there were two adjacent infected areas and the vehicle was also in an adjacent area, three areas in total. In time step 2, you move your vehicle to the west and position it at (2, 3). Then infection states of other areas change. Note that even if your vehicle had exactly three infected adjacent areas (west, southwest, and south), the area that is being visited by the vehicle is not in ...(truncated)
[ { "submission_id": "aoj_1304_10946407", "code_snippet": "#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <cmath>\n#include <algorithm>\nusing namespace std;\n#define rep(i,n) for (int i = 0; i < (n); i++)\nconst int dx[8] = {1,1,1,-1,-1,-1,0,0};\nconst int dy[8] = {1,-1,0,1,-1,0,1,-1};\n...
aoj_1309_cpp
Problem E: The Two Men of the Japanese Alps 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 p 1 (say A ) moves to s , and the other climber (say B ) moves from p 6 to p 5 ; then A moves back to t while B moves to p 4 ; finally A arrives at p 3 and at the same time B also arrives at p 3 . 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 ( x i , y i ) ( i = 1, 2, ... , N ) of the points: the two start points are ( x 1 , y 1 ) and ( x N , y N ); the line segments of the route connect ( x i , y i ) and ( x i +1 , y i +1 ) for i = 1, 2, ... , N - 1. Here, x i is the horizontal distance along the route from the start point x 1 , and y i is the altitude relative to the start point y 1 . All the coordinates are non-negative integers smaller than 1000, and inequality x i < x i +1 holds for i = 1, 2, .. , N - 1, and 0 = y 1 = y N ≤ y i 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 ...(truncated)
[ { "submission_id": "aoj_1309_10852715", "code_snippet": "#define PII pair<int,int>\n#define PDD pair<double,double>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N=10240;\nconst double EPS=1E-7;\n\nvector<PDD> v;\nint n,cnt,x[N],y[N],f[N],h[N],nextbase[N],prvbase[N],nxt[102][N],prv[102][N];...
aoj_1306_cpp
Problem B: Balloon Collecting "Balloons should be captured efficiently", the game designer says. He is designing an oldfashioned game with two dimensional graphics. In the game, balloons fall onto the ground one after another, and the player manipulates a robot vehicle on the ground to capture the balloons. The player can control the vehicle to move left or right, or simply stay. When one of the balloons reaches the ground, the vehicle and the balloon must reside at the same position, otherwise the balloon will burst and the game ends. Figure B.1: Robot vehicle and falling balloons The goal of the game is to store all the balloons into the house at the left end on the game field. The vehicle can carry at most three balloons at a time, but its speed changes according to the number of the carrying balloons. When the vehicle carries k balloons ( k = 0, 1, 2, 3), it takes k +1 units of time to move one unit distance. The player will get higher score when the total moving distance of the vehicle is shorter. Your mission is to help the game designer check game data consisting of a set of balloons. Given a landing position (as the distance from the house) and a landing time of each balloon, you must judge whether a player can capture all the balloons, and answer the minimum moving distance needed to capture and store all the balloons. The vehicle starts from the house. If the player cannot capture all the balloons, you must identify the first balloon that the player cannot capture. Input The input is a sequence of datasets. Each dataset is formatted as follows. n p 1 t 1 . . . p n t n The first line contains an integer n, which represents the number of balloons (0 < n ≤ 40). Each of the following n lines contains two integers p i and t i (1 ≤ i ≤ n ) separated by a space. p i and t i represent the position and the time when the i -th balloon reaches the ground (0 < p i ≤ 100, 0 < t i ≤ 50000). You can assume t i < t j for i < j . The position of the house is 0, and the game starts from the time 0. The sizes of the vehicle, the house, and the balloons are small enough, and should be ignored. The vehicle needs 0 time for catching the balloons or storing them into the house. The vehicle can start moving immediately after these operations. The end of the input is indicated by a line containing a zero. Output For each dataset, output one word and one integer in a line separated by a space. No extra characters should occur in the output. If the player can capture all the balloons, output "OK" and an integer that represents the minimum moving distance of the vehicle to capture and store all the balloons. If it is impossible for the player to capture all the balloons, output "NG" and an integer k such that the k -th balloon in the dataset is the first balloon that the player cannot capture. Sample Input 2 10 100 100 270 2 10 100 100 280 3 100 150 10 360 40 450 3 100 150 10 360 40 440 2 100 10 50 200 2 100 100 50 110 1 15 10 4 1 10 2 20 3 100 90 200 0 Output for ...(truncated)
[ { "submission_id": "aoj_1306_6728978", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\narray<array<array<int,4>,101>,50501> dp;\n\nint main(){\n int n, INF = 1 << 30, r = 50500;\n while(cin >> n, n){\n int ans = -1;\n for(int t = 0; t <= r; t++){\n for(int p ...
aoj_1308_cpp
Problem D: Awkward Lights You are working as a night watchman in an office building. Your task is to check whether all the lights in the building are turned off after all the office workers in the building have left the office. If there are lights that are turned on, you must turn off those lights. This task is not as easy as it sounds to be because of the strange behavior of the lighting system of the building as described below. Although an electrical engineer checked the lighting system carefully, he could not determine the cause of this behavior. So you have no option but to continue to rely on this system for the time being. Each floor in the building consists of a grid of square rooms. Every room is equipped with one light and one toggle switch. A toggle switch has two positions but they do not mean fixed ON/OFF. When the position of the toggle switch of a room is changed to the other position, in addition to that room, the ON/OFF states of the lights of the rooms at a certain Manhattan distance from that room are reversed. The Manhattan distance between the room at ( x 1 , y 1 ) of a grid of rooms and the room at ( x 2 , y 2 ) is given by | x 1 - x 2 | + | y 1 - y 2 |. For example, if the position of the toggle switch of the room at (2, 2) of a 4 × 4 grid of rooms is changed and the given Manhattan distance is two, the ON/OFF states of the lights of the rooms at (1, 1), (1, 3), (2, 4), (3, 1), (3, 3), and (4, 2) as well as at (2, 2) are reversed as shown in Figure D.1, where black and white squares represent the ON/OFF states of the lights. Figure D.1: An example behavior of the lighting system Your mission is to write a program that answer whether all the lights on a floor can be turned off. Input The input is a sequence of datasets. Each dataset is formatted as follows. m n d S 11 S 12 S 13 ... S 1 m S 21 S 22 S 23 ... S 2 m ... S n 1 S n 2 S n 3 ... S nm The first line of a dataset contains three integers. m and n (1 ≤ m ≤ 25, 1 ≤ n ≤ 25) are the numbers of columns and rows of the grid, respectively. d (1 ≤ d ≤ m + n ) indicates the Manhattan distance. Subsequent n lines of m integers are the initial ON/OFF states. Each S ij (1 ≤ i ≤ n , 1 ≤ j ≤ m ) indicates the initial ON/OFF state of the light of the room at ( i , j ): '0' for OFF and '1' for ON. The end of the input is indicated by a line containing three zeros. Output For each dataset, output '1' if all the lights can be turned off. If not, output '0'. In either case, print it in one line for each input dataset. Sample Input 1 1 1 1 2 2 1 1 1 1 1 3 2 1 1 0 1 0 1 0 3 3 1 1 0 1 0 1 0 1 0 1 4 4 2 1 1 0 1 0 0 0 1 1 0 1 1 1 0 0 0 5 5 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 5 5 2 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 11 11 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ...(truncated)
[ { "submission_id": "aoj_1308_10853874", "code_snippet": "#include <stdio.h>\n#include <string.h>\n#include <algorithm>\n#include <iostream>\n#include <queue>\n#include <map>\n#include <set>\n#include <vector>\n#include <math.h>\n#include <string>\nusing namespace std;\n\nconst int MAXN = 1000;\nint equ,var;...
aoj_1310_cpp
Problem F: Find the Multiples You are given a sequence a 0 a 1 ... a N -1 digits and a prime number Q . For each i ≤ j with a i ≠ 0, the subsequence a i a i +1 ... a j can be read as a decimal representation of a positive integer. Subsequences with leading zeros are not considered. Your task is to count the number of pairs ( i , j ) such that the corresponding subsequence is a multiple of Q . Input The input consists of at most 50 datasets. Each dataset is represented by a line containing four integers N , S , W , and Q , separated by spaces, where 1 ≤ N ≤ 10 5 , 1 ≤ S ≤ 10 9 , 1 ≤ W ≤ 10 9 , and Q is a prime number less than 10 8 . The sequence a 0 ... a N -1 of length N is generated by the following code, in which ai is written as a[i] . int g = S; for(int i=0; i<N; i++) { a[i] = (g/7) % 10; if( g%2 == 0 ) { g = (g/2); } else { g = (g/2) ^ W; } } Note: the operators / , % , and ^ are the integer division, the modulo, and the bitwise exclusiveor, respectively. The above code is meant to be a random number generator. The intended solution does not rely on the way how the sequence is generated. The end of the input is indicated by a line containing four zeros separated by spaces. Output For each dataset, output the answer in a line. You may assume that the answer is less than 2 30 . Sample Input 3 32 64 7 4 35 89 5 5 555 442 3 5 777 465 11 100000 666 701622763 65537 0 0 0 0 Output for the Sample Input 2 4 6 3 68530 In the first dataset, the sequence is 421. We can find two multiples of Q = 7, namely, 42 and 21. In the second dataset, the sequence is 5052, from which we can find 5, 50, 505, and 5 being the multiples of Q = 5. Notice that we don't count 0 or 05 since they are not a valid representation of positive integers. Also notice that we count 5 twice, because it occurs twice in different positions. In the third and fourth datasets, the sequences are 95073 and 12221, respectively.
[ { "submission_id": "aoj_1310_10851362", "code_snippet": "#include <cstdio>\n#include <map>\n#include <iostream>\n#include <cstring>\nusing namespace std;\nusing std::map;\nint a[100010];\nmap<long long,int> mp;\nlong long pow_mod(long long a,long long b,long long p)\n{\n\tlong long ans = 1;\n\twhile(b) {\n\...
aoj_1302_cpp
Problem H: Twenty Questions Consider a closed world and a set of features that are defined for all the objects in the world. Each feature can be answered with "yes" or "no". Using those features, we can identify any object from the rest of the objects in the world. In other words, each object can be represented as a fixed-length sequence of booleans. Any object is different from other objects by at least one feature. You would like to identify an object from others. For this purpose, you can ask a series of questions to someone who knows what the object is. Every question you can ask is about one of the features. He/she immediately answers each question with "yes" or "no" correctly. You can choose the next question after you get the answer to the previous question. You kindly pay the answerer 100 yen as a tip for each question. Because you don' t have surplus money, it is necessary to minimize the number of questions in the worst case. You don’t know what is the correct answer, but fortunately know all the objects in the world. Therefore, you can plan an optimal strategy before you start questioning. The problem you have to solve is: given a set of boolean-encoded objects, minimize the maximum number of questions by which every object in the set is identifiable. Input The input is a sequence of multiple datasets. Each dataset begins with a line which consists of two integers, m and n : the number of features, and the number of objects, respectively. You can assume 0 < m ≤ 11 and 0 < n ≤ 128. It is followed by n lines, each of which corresponds to an object. Each line includes a binary string of length m which represent the value ("yes" or "no") of features. There are no two identical objects. The end of the input is indicated by a line containing two zeros. 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 8 1 11010101 11 4 00111001100 01001101011 01010000011 01100110001 11 16 01000101111 01011000000 01011111001 01101101001 01110010111 01110100111 10000001010 10010001000 10010110100 10100010100 10101010110 10110100010 11001010011 11011001001 11111000111 11111011101 11 12 10000000000 01000000000 00100000000 00010000000 00001000000 00000100000 00000010000 00000001000 00000000100 00000000010 00000000001 00000000000 9 32 001000000 000100000 000010000 000001000 000000100 000000010 000000001 000000000 011000000 010100000 010010000 010001000 010000100 010000010 010000001 010000000 101000000 100100000 100010000 100001000 100000100 100000010 100000001 100000000 111000000 110100000 110010000 110001000 110000100 110000010 110000001 110000000 0 0 Output for the Sample Input 0 2 4 11 9
[ { "submission_id": "aoj_1302_10848269", "code_snippet": "#include<iostream>\n#include<fstream>\n#include<iomanip>\n#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<cmath>\n#include<iomanip>\n#include<algorithm>\n#include<list>\n#include<map>\n#include<set>\n#include<queue>\n#include<deque>\n...
aoj_1311_cpp
Problem G: Test Case Tweaking 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. Input The input is a sequence of datasets. Each dataset is formatted as follows. n m c f 1 t 1 c 1 f 2 t 2 c 2 . . . f m t m c m Figure G.1: Example 1 of graph Figure G.2: Example 2 of graph 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 f i , t i and c i (1 ≤ i ≤ m ) 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 ≤ f i , t i ≤ n and 0 ≤ c i ≤ 10000. You can assume that f i ≠ t i and ( f i , t i ) ≠ ( f j , t j ) when i ≠ j . 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 ...(truncated)
[ { "submission_id": "aoj_1311_10848586", "code_snippet": "/* ***********************************************\nAuthor :kuangbin\nCreated Time :2013/11/15 16:30:39\nFile Name :G.cpp\n************************************************ */\n\n#include <stdio.h>\n#include <string.h>\n#include <iostream>\...
aoj_1315_cpp
Problem A: Gift from the Goddess of Programming The goddess of programming is reviewing a thick logbook, which is a yearly record of visitors to her holy altar of programming. The logbook also records her visits at the altar. The altar attracts programmers from all over the world because one visitor is chosen every year and endowed with a gift of miracle programming power by the goddess. The endowed programmer is chosen from those programmers who spent the longest time at the altar during the goddess's presence. There have been enthusiastic visitors who spent very long time at the altar but failed to receive the gift because the goddess was absent during their visits. Now, your mission is to write a program that finds how long the programmer to be endowed stayed at the altar during the goddess's presence. Input The input is a sequence of datasets. The number of datasets is less than 100. Each dataset is formatted as follows. n M 1 /D 1 h 1 : m 1 e 1 p 1 M 2 /D 2 h 2 : m 2 e 2 p 2 . . . M n /D n h n : m n e n p n The first line of a dataset contains a positive even integer, n ≤ 1000, which denotes the number of lines of the logbook. This line is followed by n lines of space-separated data, where M i /D i identifies the month and the day of the visit, h i : m i represents the time of either the entrance to or exit from the altar, e i is either I for entrance, or O for exit, and p i identifies the visitor. All the lines in the logbook are formatted in a fixed-column format. Both the month and the day in the month are represented by two digits. Therefore April 1 is represented by 04/01 and not by 4/1. The time is described in the 24-hour system, taking two digits for the hour, followed by a colon and two digits for minutes, 09:13 for instance and not like 9:13. A programmer is identified by an ID, a unique number using three digits. The same format is used to indicate entrance and exit of the goddess, whose ID is 000. All the lines in the logbook are sorted in ascending order with respect to date and time. Because the altar is closed at midnight, the altar is emptied at 00:00. You may assume that each time in the input is between 00:01 and 23:59, inclusive. A programmer may leave the altar just after entering it. In this case, the entrance and exit time are the same and the length of such a visit is considered 0 minute. You may assume for such entrance and exit records, the line that corresponds to the entrance appears earlier in the input than the line that corresponds to the exit. You may assume that at least one programmer appears in the logbook. The end of the input is indicated by a line containing a single zero. Output For each dataset, output the total sum of the blessed time of the endowed programmer. The blessed time of a programmer is the length of his/her stay at the altar during the presence of the goddess. The endowed programmer is the one whose total blessed time is the longest among all the programmers. The output should be represented ...(truncated)
[ { "submission_id": "aoj_1315_4851862", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nconst vector<int> convert={1440,60,1};\nvector<int> month={0,31,28,31,30,31,30,31,31,30,31,30};\n\nint time(string s,string t){\n int M=(s[0]-'0')*10+(s[1]-'0')-1;\n int D=(s[3]-'0')*10+(s[4]-'0')-1...
aoj_1313_cpp
Problem I: Intersection of Two Prisms Suppose that P 1 is an infinite-height prism whose axis is parallel to the z -axis, and P 2 is also an infinite-height prism whose axis is parallel to the y -axis. P 1 is defined by the polygon C 1 which is the cross section of P 1 and the xy -plane, and P 2 is also defined by the polygon C 2 which is the cross section of P 2 and the x z-plane. Figure I.1 shows two cross sections which appear as the first dataset in the sample input, and Figure I.2 shows the relationship between the prisms and their cross sections. Figure I.1: Cross sections of Prisms Figure I.2: Prisms and their cross sections Figure I.3: Intersection of two prisms Figure I.3 shows the intersection of two prisms in Figure I.2, namely, P 1 and P 2 . Write a program which calculates the volume of the intersection of two prisms. Input The input is a sequence of datasets. The number of datasets is less than 200. Each dataset is formatted as follows. m n x 11 y 11 x 12 y 12 . . . x 1 m y 1 m x 21 z 21 x 22 z 22 . . . x 2 n z 2 n m and n are integers (3 ≤ m ≤ 100, 3 ≤ n ≤ 100) which represent the numbers of the vertices of the polygons, C 1 and C 2 , respectively. x 1 i , y 1 i , x 2 j and z 2 j are integers between -100 and 100, inclusive. ( x 1 i , y 1 i ) and ( x 2 j , z 2 j ) mean the i -th and j -th vertices' positions of C 1 and C 2 respectively. The sequences of these vertex positions are given in the counterclockwise order either on the xy -plane or the xz -plane as in Figure I.1. You may assume that all the polygons are convex , that is, all the interior angles of the polygons are less than 180 degrees. You may also assume that all the polygons are simple , that is, each polygon's boundary does not cross nor touch itself. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the volume of the intersection of the two prisms, P 1 and P 2 , with a decimal representation in a line. None of the output values may have an error greater than 0.001. The output should not contain any other extra characters. Sample Input 4 3 7 2 3 3 0 2 3 1 4 2 0 1 8 1 4 4 30 2 30 12 2 12 2 2 15 2 30 8 13 14 2 8 8 5 13 5 21 7 21 9 18 15 11 15 6 10 6 8 8 5 10 12 5 9 15 6 20 10 18 12 3 3 5 5 10 3 10 10 20 8 10 15 10 8 4 4 -98 99 -99 -99 99 -98 99 97 -99 99 -98 -98 99 -99 96 99 0 0 Output for the Sample Input 4.708333333333333 1680.0000000000005 491.1500000000007 0.0 7600258.4847715655
[ { "submission_id": "aoj_1313_6066782", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define INF 2000000000 // 2e9\n#define LLINF 2000000000000000000ll // 2e18 (llmax:9e18)\n#define all(x) (x).begin(), (x).end()\n#define sq(x) ((x) * (x))\n\n#define rep(i, x) for (int i =...
aoj_1316_cpp
Problem B: The Sorcerer's Donut Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. Each square sequence does not overlap itself. (Two square sequences can share some squares.) The square sequences start from different squares, and/or go to different directions. Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions Figure B.2: The Sorcerer's Donut After Filled with Letters Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the patt ...(truncated)
[ { "submission_id": "aoj_1316_11047140", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing a2 = array<int, 2>;\nusing a3 = array<ll, 3>;\n\nbool chmin(auto& a, const auto& b) { return a > b ? a = b, 1 : 0; }\nbool chmax(auto& a, const auto& b) { return a < b ? a = ...
aoj_1314_cpp
Problem J: Matrix Calculator Dr. Jimbo, an applied mathematician, needs to calculate matrices all day for solving his own problems. In his laboratory, he uses an excellent application program for manipulating matrix expressions, however, he cannot use it outside his laboratory because the software consumes much of resources. He wants to manipulate matrices outside, so he needs a small program similar to the excellent application for his handheld computer. Your job is to provide him a program that computes expressions of matrices. Expressions of matrices are described in a simple language. Its syntax is shown in Table J.1. Note that even a space and a newline have meaningful roles in the syntax. The start symbol of this syntax is program that is defined as a sequence of assignments in Table J.1. Each assignment has a variable on the left hand side of an equal symbol (" = ") and an expression of matrices on the right hand side followed by a period and a newline ( NL ). It denotes an assignment of the value of the expression to the variable. The variable (var in Table J.1) is indicated by an uppercase Roman letter. The value of the expression ( expr ) is a matrix or a scalar, whose elements are integers. Here, a scalar integer and a 1 × 1 matrix whose only element is the same integer can be used interchangeably. An expression is one or more terms connected by " + " or " - " symbols. A term is one or more factors connected by " * " symbol. These operators (" + ", " - ", " * ") are left associative. A factor is either a primary expression (primary) or a " - " symbol followed by a factor. This unary operator " - " is right associative. The meaning of operators are the same as those in the ordinary arithmetic on matrices: Denoting matrices by A and B , A + B , A - B , A * B , and -A are defined as the matrix sum, difference, product, and negation. The sizes of A and B should be the same for addition and subtraction. The number of columns of A and the number of rows of B should be the same for multiplication. Note that all the operators +, -, * and unary - represent computations of addition, subtraction, multiplication and negation modulo M = 2 15 = 32768, respectively. Thus all the values are nonnegative integers between 0 and 32767, inclusive. For example, the result of an expression 2 - 3 should be 32767, instead of -1. inum is a non-negative decimal integer less than M . var represents the matrix that is assigned to the variable var in the most recent preceding assignment statement of the same variable. matrix represents a mathematical matrix similar to a 2-dimensional array whose elements are integers. It is denoted by a row-seq with a pair of enclosing square brackets. row-seq represents a sequence of rows, adjacent two of which are separated by a semicolon. row represents a sequence of expressions, adjacent two of which are separated by a space character. For example, [1 2 3;4 5 6] represents a matrix . The first row has three integers separated b ...(truncated)
[ { "submission_id": "aoj_1314_10908049", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 32768;\ntypedef vector<int> List;\ntypedef vector<vector<int>> Matrix;\nMatrix variables[26];\n\nMatrix parseExpr(const char*& p);\n\nvoid skip(const char *&p)\n{\n while ( p && *p...
aoj_1318_cpp
Problem D: Long Distance Taxi A taxi driver, Nakamura, was so delighted because he got a passenger who wanted to go to a city thousands of kilometers away. However, he had a problem. As you may know, most taxis in Japan run on liquefied petroleum gas (LPG) because it is cheaper than gasoline. There are more than 50,000 gas stations in the country, but less than one percent of them sell LPG. Although the LPG tank of his car was full, the tank capacity is limited and his car runs 10 kilometer per liter, so he may not be able to get to the destination without filling the tank on the way. He knew all the locations of LPG stations. Your task is to write a program that finds the best way from the current location to the destination without running out of gas. Input The input consists of several datasets, and each dataset is in the following format. N M cap src dest c 1,1 c 1,2 d 1 c 2,1 c 2,2 d 2 . . . c N,1 c N,2 d N s 1 s 2 . . . s M The first line of a dataset contains three integers ( N, M, cap ), where N is the number of roads (1 ≤ N ≤ 3000), M is the number of LPG stations (1≤ M ≤ 300), and cap is the tank capacity (1 ≤ cap ≤ 200) in liter. The next line contains the name of the current city ( src ) and the name of the destination city ( dest ). The destination city is always different from the current city. The following N lines describe roads that connect cities. The road i (1 ≤ i ≤ N) connects two different cities c i,1 and c i,2 with an integer distance d i (0 < d i ≤ 2000) in kilometer, and he can go from either city to the other. You can assume that no two different roads connect the same pair of cities. The columns are separated by a single space. The next M lines ( s 1 , s 2 ,..., s M ) indicate the names of the cities with LPG station. You can assume that a city with LPG station has at least one road. The name of a city has no more than 15 characters. Only English alphabet ('A' to 'Z' and 'a' to 'z', case sensitive) is allowed for the name. A line with three zeros terminates the input. Output For each dataset, output a line containing the length (in kilometer) of the shortest possible journey from the current city to the destination city. If Nakamura cannot reach the destination, output "-1" (without quotation marks). You must not output any other characters. The actual tank capacity is usually a little bit larger than that on the specification sheet, so you can assume that he can reach a city even when the remaining amount of the gas becomes exactly zero. In addition, you can always fill the tank at the destination so you do not have to worry about the return trip. Sample Input 6 3 34 Tokyo Kyoto Tokyo Niigata 335 Tokyo Shizuoka 174 Shizuoka Nagoya 176 Nagoya Kyoto 195 Toyama Niigata 215 Toyama Kyoto 296 Nagoya Niigata Toyama 6 3 30 Tokyo Kyoto Tokyo Niigata 335 Tokyo Shizuoka 174 Shizuoka Nagoya 176 Nagoya Kyoto 195 Toyama Niigata 215 Toyama Kyoto 296 Nagoya Niigata Toyama 0 0 0 Output for the Sample Input 846 -1
[ { "submission_id": "aoj_1318_10849725", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <queue>\n#include <map>\n#include <string>\n#include <cstring>\n#include <algorithm>\n\nusing namespace std;\n\nconst int maxn = 6000;\nconst int maxm = 6090;\ncon...
aoj_1317_cpp
Problem C: Weaker than Planned The committee members of the Kitoshima programming contest had decided to use crypto-graphic software for their secret communication. They had asked a company, Kodai Software, to develop cryptographic software that employed a cipher based on highly sophisticated mathematics. According to reports on IT projects, many projects are not delivered on time, on budget, with required features and functions. This applied to this case. Kodai Software failed to implement the cipher by the appointed date of delivery, and asked to use a simpler version that employed a type of substitution cipher for the moment. The committee members got angry and strongly requested to deliver the full specification product, but they unwillingly decided to use this inferior product for the moment. In what follows, we call the text before encryption, plaintext, and the text after encryption, ciphertext . This simple cipher substitutes letters in the plaintext, and its substitution rule is specified with a set of pairs. A pair consists of two letters and is unordered, that is, the order of the letters in the pair does not matter. A pair (A, B) and a pair (B, A) have the same meaning. In one substitution rule, one letter can appear in at most one single pair. When a letter in a pair appears in the plaintext, the letter is replaced with the other letter in the pair. Letters not specified in any pairs are left as they are. For example, by substituting the plaintext ABCDEFGHIJKLMNOPQRSTUVWXYZ with the substitution rule {(A, Z), (B, Y)} results in the following ciphertext. ZYCDEFGHIJKLMNOPQRSTUVWXBA This may be a big chance for us, because the substitution rule seems weak against cracking. We may be able to know communications between committee members. The mission here is to develop a deciphering program that finds the plaintext messages from given ciphertext messages. A ciphertext message is composed of one or more ciphertext words. A ciphertext word is generated from a plaintext word with a substitution rule. You have a list of candidate words containing the words that can appear in the plaintext; no other words may appear. Some words in the list may not actually be used in the plaintext. There always exists at least one sequence of candidate words from which the given ciphertext is obtained by some substitution rule. There may be cases where it is impossible to uniquely identify the plaintext from a given ciphertext and the list of candidate words. Input The input consists of multiple datasets, each of which contains a ciphertext message and a list of candidate words in the following format. n word 1 . . . word n sequence n in the first line is a positive integer, representing the number of candidate words. Each of the next n lines represents one of the candidate words. The last line, sequence, is a sequence of one or more ciphertext words separated by a single space and terminated with a period. You may assume the number of characters in each sequ ...(truncated)
[ { "submission_id": "aoj_1317_7228208", "code_snippet": "#ifdef LOCAL\n#define _GLIBCXX_DEBUG\n#endif\n#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vi = vector<int>;\ntemplate <class T = int>\nusing V = vector<T>;\n\n\n#define repname(a, b, c, d, ...) d\n#define rep(...) ...
aoj_1322_cpp
Problem H: ASCII Expression Mathematical expressions appearing in old papers and old technical articles are printed with typewriter in several lines, where a fixed-width or monospaced font is required to print characters (digits, symbols and spaces). Let us consider the following mathematical expression. It is printed in the following four lines: 4 2 ( 1 - ---- ) * - 5 + 6 2 3 where “- 5” indicates unary minus followed by 5. We call such an expression of lines “ASCII expression”. For helping those who want to evaluate ASCII expressions obtained through optical character recognition (OCR) from old papers, your job is to write a program that recognizes the structure of ASCII expressions and computes their values. For the sake of simplicity, you may assume that ASCII expressions are constructed by the following rules. Its syntax is shown in Table H.1. (1) Terminal symbols are ‘ 0 ’, ‘ 1 ’, ‘ 2 ’, ‘ 3 ’, ‘ 4 ’, ‘ 5 ’, ‘ 6 ’, ‘ 7 ’, ‘ 8 ’, ‘ 9 ’, ‘ + ’, ‘ - ’, ‘ * ’, ‘ ( ’, ‘ ) ’, and ‘ ’. (2) Nonterminal symbols are expr , term , factor , powexpr , primary , fraction and digit . The start symbol is expr . (3) A “cell” is a rectangular region of characters that corresponds to a terminal or nonterminal symbol (Figure H.1). In the cell, there are no redundant rows and columns that consist only of space characters. A cell corresponding to a terminal symbol consists of a single character. A cell corresponding to a nonterminal symbol contains cell(s) corresponding to its descendant(s) but never partially overlaps others. (4) Each cell has a base-line, a top-line, and a bottom-line. The base-lines of child cells of the right-hand side of rules I, II, III, and V should be aligned. Their vertical position defines the base-line position of their left-hand side cell. Table H.1: Rules for constructing ASCII expressions (similar to Backus-Naur Form) The box indicates the cell of the terminal or nonterminal symbol that corresponds to a rectan- gular region of characters. Note that each syntactically-needed space character is explicitly indicated by the period character denoted by, here. (5) powexpr consists of a primary and an optional digit . The digit is placed one line above the base-line of the primary cell. They are horizontally adjacent to each other. The base-line of a powexpr is that of the primary . (6) fraction is indicated by three or more consecutive hyphens called “vinculum”. Its dividend expr is placed just above the vinculum, and its divisor expr is placed just beneath it. The number of the hyphens of the vinculum, denoted by w h , is equal to 2 + max( w 1 , w 2 ), where w 1 and w 2 indicate the width of the cell of the dividend and that of the divisor, respectively. These cells are centered, where there are ⌈( w h − w k )/2⌉ space characters to the left and ⌊( w h − w k )/2⌋ space characters to the right, ( k = 1, 2). The base-line of a fraction is at the position of the vinculum. (7) digit consists of one character ...(truncated)
[ { "submission_id": "aoj_1322_5951862", "code_snippet": "#define MOD_TYPE 1\n\n#pragma region Macros\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n//#include <atcoder/all>\n\n\n#include <utility>\n\nnamespace atcoder {\n\nnamespace internal {\n\n// @param m `1 <= m`\n// @return x mod m\nconstexpr long...
aoj_1320_cpp
Problem F: City Merger Recent improvements in information and communication technology have made it possible to provide municipal service to a wider area more quickly and with less costs. Stimulated by this, and probably for saving their not sufficient funds, mayors of many cities started to discuss on mergers of their cities. There are, of course, many obstacles to actually put the planned mergers in practice. Each city has its own culture of which citizens are proud. One of the largest sources of friction is with the name of the new city. All citizens would insist that the name of the new city should have the original name of their own city at least as a part of it. Simply concatenating all the original names would, however, make the name too long for everyday use. You are asked by a group of mayors to write a program that finds the shortest possible name for the new city that includes all the original names of the merged cities. If two or more cities have common parts, they can be overlapped. For example, if "FUKUOKA", "OKAYAMA", and "YAMAGUCHI" cities are to be merged, "FUKUOKAYAMAGUCHI" is such a name that include all three of the original city names. Although this includes all the characters of the city name "FUKUYAMA" in this order, it does not appear as a consecutive substring, and thus "FUKUYAMA" is not considered to be included in the name. Input The input is a sequence of datasets. Each dataset begins with a line containing a positive integer n ( n ≤ 14), which denotes the number of cities to be merged. The following n lines contain the names of the cities in uppercase alphabetical letters, one in each line. You may assume that none of the original city names has more than 20 characters. Of course, no two cities have the same name. The end of the input is indicated by a line consisting of a zero. Output For each dataset, output the length of the shortest possible name of the new city in one line. The output should not contain any other characters. Sample Input 3 FUKUOKA OKAYAMA YAMAGUCHI 3 FUKUOKA FUKUYAMA OKAYAMA 2 ABCDE EDCBA 4 GA DEFG CDDE ABCD 2 ABCDE C 14 AAAAA BBBBB CCCCC DDDDD EEEEE FFFFF GGGGG HHHHH IIIII JJJJJ KKKKK LLLLL MMMMM NNNNN 0 Output for the Sample Input 16 19 9 9 5 70
[ { "submission_id": "aoj_1320_10954681", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n;\nvector<int> ls;\nvector<vector<int>> v; // v[i][j] = overlap length a[i] suffix vs a[j] prefix\nunordered_map<long long,int> cac; // memo for sediv\nunordered_map<int,int> bp; // single-bit -> ...
aoj_1312_cpp
Problem H: Where's Wally Do you know the famous series of children's books named "Where's Wally"? Each of the books contains a variety of pictures of hundreds of people. Readers are challenged to find a person called Wally in the crowd. We can consider "Where's Wally" as a kind of pattern matching of two-dimensional graphical images. Wally's figure is to be looked for in the picture. It would be interesting to write a computer program to solve "Where's Wally", but this is not an easy task since Wally in the pictures may be slightly different in his appearances. We give up the idea, and make the problem much easier to solve. You are requested to solve an easier version of the graphical pattern matching problem. An image and a pattern are given. Both are rectangular matrices of bits (in fact, the pattern is always square-shaped). 0 means white, and 1 black. The problem here is to count the number of occurrences of the pattern in the image, i.e. the number of squares in the image exactly matching the pattern. Patterns appearing rotated by any multiples of 90 degrees and/or turned over forming a mirror image should also be taken into account. Input The input is a sequence of datasets each in the following format. w h p image data pattern data The first line of a dataset consists of three positive integers w , h and p . w is the width of the image and h is the height of the image. Both are counted in numbers of bits. p is the width and height of the pattern. The pattern is always square-shaped. You may assume 1 ≤ w ≤ 1000, 1 ≤ h ≤ 1000, and 1 ≤ p ≤ 100. The following h lines give the image. Each line consists of ⌈ w /6⌉ (which is equal to &⌊( w +5)/6⌋) characters, and corresponds to a horizontal line of the image. Each of these characters represents six bits on the image line, from left to right, in a variant of the BASE64 encoding format. The encoding rule is given in the following table. The most significant bit of the value in the table corresponds to the leftmost bit in the image. The last character may also represent a few bits beyond the width of the image; these bits should be ignored. character value (six bits) A-Z 0-25 a-z 26-51 0-9 52-61 + 62 / 63 The last p lines give the pattern. Each line consists of ⌈ p /6⌉ characters, and is encoded in the same way as the image. A line containing three zeros indicates the end of the input. The total size of the input does not exceed two megabytes. Output For each dataset in the input, one line containing the number of matched squares in the image should be output. An output line should not contain extra characters. Two or more matching squares may be mutually overlapping. In such a case, they are counted separately. On the other hand, a single square is never counted twice or more, even if it matches both the original pattern and its rotation, for example. Sample Input 48 3 3 gAY4I4wA gIIgIIgg w4IAYAg4 g g w 153 3 3 kkkkkkkkkkkkkkkkkkkkkkkkkg SSSSSSSSSSSSSSSSSSSSSSSSSQ JJJJJJJJJJJJJJJJJJJJJJJJJI g Q I 1 ...(truncated)
[ { "submission_id": "aoj_1312_10849705", "code_snippet": "#include <cstdio>\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <list>\n#include <cctype>\n#include <functional>\n#include <iterator>\n#include <cstring>\n#include <cmath>\n#incl...
aoj_1323_cpp
Problem I: Encircling Circles You are given a set of circles C of a variety of radii (radiuses) placed at a variety of positions, possibly overlapping one another. Given a circle with radius r , that circle may be placed so that it encircles all of the circles in the set C if r is large enough. There may be more than one possible position of the circle of radius r to encircle all the member circles of C . We define the region U as the union of the areas of encircling circles at all such positions. In other words, for each point in U , there exists a circle of radius r that encircles that point and all the members of C . Your task is to calculate the length of the periphery of that region U . Figure I.1 shows an example of the set of circles C and the region U . In the figure, three circles contained in C are expressed by circles of solid circumference, some possible positions of the encircling circles are expressed by circles of dashed circumference, and the area U is expressed by a thick dashed closed curve. Input The input is a sequence of datasets. The number of datasets is less than 100. Each dataset is formatted as follows. n r x 1 y 1 r 1 x 2 y 2 r 2 . . . x n y n r n The first line of a dataset contains two positive integers, n and r , separated by a single space. n means the number of the circles in the set C and does not exceed 100. r means the radius of the encircling circle and does not exceed 1000. Each of the n lines following the first line contains three integers separated by a single space. ( x i , y i ) means the center position of the i -th circle of the set C and r i means its radius. You may assume −500≤ x i ≤500, −500≤ y i ≤500, and 1≤ r i ≤500. The end of the input is indicated by a line containing two zeros separated by a single space. Output For each dataset, output a line containing a decimal fraction which means the length of the periphery (circumferential length) of the region U . The output should not contain an error greater than 0.01. You can assume that, when r changes by ε (|ε| < 0.0000001), the length of the periphery of the region U will not change more than 0.001. If r is too small to cover all of the circles in C , output a line containing only 0.0. No other characters should be contained in the output. Sample Input 1 10 5 5 7 2 12 5 5 7 8 6 3 3 10 3 11 2 2 1 1 2 16 3 3 15 -5 2 5 9 2 9 5 8 6 3 38 -25 -10 8 30 5 7 -3 35 11 3 39 -25 -10 8 30 5 7 -3 35 11 3 800 -400 400 2 300 300 1 300 302 1 3 800 400 -400 2 300 300 1 307 300 3 8 147 130 80 12 130 -40 12 -110 80 12 -110 -40 12 70 140 12 70 -100 12 -50 140 12 -50 -100 12 3 493 345 154 10 291 111 75 -275 -301 46 4 55 54 0 1 40 30 5 27 36 10 0 48 7 3 30 0 3 3 -3 0 4 400 0 3 3 7 2 3 2 -5 -4 2 -4 3 2 3 10 -5 -4 5 2 3 5 -4 3 5 4 6 4 6 1 5 5 1 1 7 1 0 1 1 3 493 345 154 10 291 111 75 -275 -301 46 5 20 -9 12 5 0 15 5 3 -3 3 12 9 5 -12 9 5 0 0 Output for the Sample Input 81.68140899333463 106.81415022205297 74.11215318612639 108.92086846105579 0.0 254.85616536128433 8576.93 ...(truncated)
[ { "submission_id": "aoj_1323_6159804", "code_snippet": "#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\n#include<iostream>\n#include<string>\n#include<cstdio>\n#include<vector>\n#include<cmath>\n#include<algorithm>\n#include<functional>\n#include<iomanip>\n#include<queue>\n#include<cis...
aoj_1319_cpp
Problem E: Driving an Icosahedral Rover After decades of fruitless efforts, one of the expedition teams of ITO (Intersolar Tourism Organization) finally found a planet that would surely provide one of the best tourist attractions within a ten light-year radius from our solar system. The most attractive feature of the planet, besides its comfortable gravity and calm weather, is the area called Mare Triangularis . Despite the name, the area is not covered with water but is a great plane. Its unique feature is that it is divided into equilateral triangular sections of the same size, called trigons . The trigons provide a unique impressive landscape, a must for tourism. It is no wonder the board of ITO decided to invest a vast amount on the planet. Despite the expected secrecy of the staff, the Society of Astrogeology caught this information in no time, as always. They immediately sent their president's letter to the Institute of Science and Education of the Commonwealth Galactica claiming that authoritative academic inspections were to be completed before any commercial exploitation might damage the nature. Fortunately, astrogeologists do not plan to practice all the possible inspections on all of the trigons ; there are far too many of them. Inspections are planned only on some characteristic trigons and, for each of them, in one of twenty different scientific aspects. To accelerate building this new tourist resort, ITO's construction machinery team has already succeeded in putting their brand-new invention in practical use. It is a rover vehicle of the shape of an icosahedron , a regular polyhedron with twenty faces of equilateral triangles. The machine is customized so that each of the twenty faces exactly fits each of the trigons . Controlling the high-tech gyromotor installed inside its body, the rover can roll onto one of the three trigons neighboring the one its bottom is on. Figure E.1: The Rover on Mare Triangularis Each of the twenty faces has its own function. The set of equipments installed on the bottom face touching the ground can be applied to the trigon it is on. Of course, the rover was meant to accelerate construction of the luxury hotels to host rich interstellar travelers, but, changing the installed equipment sets, it can also be used to accelerate academic inspections. You are the driver of this rover and are asked to move the vehicle onto the trigon specified by the leader of the scientific commission with the smallest possible steps. What makes your task more difficult is that the designated face installed with the appropriate set of equipments has to be the bottom. The direction of the rover does not matter. Figure E.2:The Coordinate System Figure E.3: Face Numbering The trigons of Mare Triangularis are given two-dimensional coordinates as shown in Figure E.2. Like maps used for the Earth, the x axis is from the west to the east, and the y axis is from the south to the north. Note that all the trigons with its coordinates ...(truncated)
[ { "submission_id": "aoj_1319_10851601", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int nt[20][3]={\n{5,1,4},\n{6,2,0},\n{7,3,1},\n{8,4,2},\n{9,0,3},\n{0,10,11},\n{1,11,12},\n{2,12,13},\n{3,13,14},\n{4,14,10},\n{15,5,9},\n{16,6,5},\n{17,7,6},\n{18,8,7},\n{19,9,8},\n{10,19,16},\n{...
aoj_1321_cpp
Problem G: Captain Q′s Treasure You got an old map, which turned out to be drawn by the infamous pirate “Captain Q”. It shows the locations of a lot of treasure chests buried in an island. The map is divided into square sections, each of which has a digit on it or has no digit. The digit represents the number of chests in its 9 neighboring sections (the section itself and its 8 neighbors). You may assume that there is at most one chest in each section. Although you have the map, you can't determine the sections where the chests are buried. Even the total number of chests buried in the island is unknown. However, it is possible to calculate the minimum number of chests buried in the island. Your mission in this problem is to write a program that calculates it. Input The input is a sequence of datasets. Each dataset is formatted as follows. h w map The first line of a dataset consists of two positive integers h and w . h is the height of the map and w is the width of the map. You may assume 1≤ h ≤15 and 1≤ w ≤15. The following h lines give the map. Each line consists of w characters and corresponds to a horizontal strip of the map. Each of the characters in the line represents the state of a section as follows. ‘.’: The section is not a part of the island (water). No chest is here. ‘*’: The section is a part of the island, and the number of chests in its 9 neighbors is not known. ‘0’-‘9’: The section is a part of the island, and the digit represents the number of chests in its 9 neighbors. You may assume that the map is not self-contradicting, i.e., there is at least one arrangement of chests. You may also assume the number of sections with digits is at least one and at most 15. A line containing two zeros indicates the end of the input. Output For each dataset, output a line that contains the minimum number of chests. The output should not contain any other character. Sample Input 5 6 *2.2** ..*... ..2... ..*... *2.2** 6 5 .*2*. ..*.. ..*.. ..2.. ..*.. .*2*. 5 6 .1111. **...* 33.... **...0 .*2**. 6 9 ....1.... ...1.1... ....1.... .1..*..1. 1.1***1.1 .1..*..1. 9 9 ********* *4*4*4*4* ********* *4*4*4*4* ********* *4*4*4*4* ********* *4*4*4*** ********* 0 0 Output for the Sample Input 6 5 5 6 23
[ { "submission_id": "aoj_1321_10851230", "code_snippet": "#include <iostream>\n\n#include <cstdio>\n\n#include <string.h>\n\n#include <string>\n\n#include <algorithm>\n\n#include <map>\n\nusing namespace std;\n\n\nconst int maxn = 16;\n\nconst int inf = 100000000;\n\nstruct node\n\n{\n\n int x, y, c;\n\n}...
aoj_1324_cpp
Problem J: Round Trip Jim is planning to visit one of his best friends in a town in the mountain area. First, he leaves his hometown and goes to the destination town. This is called the go phase. Then, he comes back to his hometown. This is called the return phase. You are expected to write a program to find the minimum total cost of this trip, which is the sum of the costs of the go phase and the return phase. There is a network of towns including these two towns. Every road in this network is one-way, i.e., can only be used towards the specified direction. Each road requires a certain cost to travel. In addition to the cost of roads, it is necessary to pay a specified fee to go through each town on the way. However, since this is the visa fee for the town, it is not necessary to pay the fee on the second or later visit to the same town. The altitude (height) of each town is given. On the go phase, the use of descending roads is inhibited. That is, when going from town a to b , the altitude of a should not be greater than that of b . On the return phase, the use of ascending roads is inhibited in a similar manner. If the altitudes of a and b are equal, the road from a to b can be used on both phases. Input The input consists of multiple datasets, each in the following format. n m d 2 e 2 d 3 e 3 . . . d n-1 e n-1 a 1 b 1 c 1 a 2 b 2 c 2 . . . a m b m c m Every input item in a dataset is a non-negative integer. Input items in a line are separated by a space. n is the number of towns in the network. m is the number of (one-way) roads. You can assume the inequalities 2 ≤ n ≤ 50 and 0 ≤ m ≤ n ( n −1) hold. Towns are numbered from 1 to n , inclusive. The town 1 is Jim's hometown, and the town n is the destination town. d i is the visa fee of the town i , and e i is its altitude. You can assume 1 ≤ d i ≤ 1000 and 1≤ e i ≤ 999 for 2≤ i ≤ n −1. The towns 1 and n do not impose visa fee. The altitude of the town 1 is 0, and that of the town n is 1000. Multiple towns may have the same altitude, but you can assume that there are no more than 10 towns with the same altitude. The j -th road is from the town a j to b j with the cost c j (1 ≤ j ≤ m ). You can assume 1 ≤ a j ≤ n , 1 ≤ b j ≤ n , and 1 ≤ c j ≤ 1000. You can directly go from a j to b j , but not from b j to a j unless a road from b j to a j is separately given. There are no two roads connecting the same pair of towns towards the same direction, that is, for any i and j such that i ≠ j , a i ≠ a j or b i ≠ b j . There are no roads connecting a town to itself, that is, for any j , a j ≠ b j . The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, a line containing the minimum total cost, including the visa fees, of the trip should be output. If such a trip is not possible, output “-1”. Sample Input 3 6 3 1 1 2 1 2 3 1 3 2 1 2 1 1 1 3 4 3 1 4 3 6 5 1 1 2 1 2 3 1 3 2 1 2 1 1 1 3 4 3 1 4 4 5 3 1 3 1 1 2 5 2 3 5 3 4 5 4 2 5 3 1 5 2 1 2 1 ...(truncated)
[ { "submission_id": "aoj_1324_10858211", "code_snippet": "#include<cstdio>\n#include<cstring>\n#include<cmath>\n#include<algorithm>\n#include<iostream>\n#include<queue>\n#include<stack>\n#include<vector>\n#include<map>\n#include<set>\n#include<string>\nusing namespace std;\n#define INF 199999999\n#define eps...
aoj_1325_cpp
Problem A: Ginkgo Numbers We will define Ginkgo numbers and multiplication on Ginkgo numbers. A Ginkgo number is a pair < m , n > where m and n are integers. For example, <1, 1>, <-2, 1> and <-3,-1> are Ginkgo numbers. The multiplication on Ginkgo numbers is defined by < m , n > · < x , y > = < mx − ny , my + nx >. For example, <1, 1> · <-2, 1> = <-3,-1>. A Ginkgo number < m , n > is called a divisor of a Ginkgo number < p , q > if there exists a Ginkgo number < x , y > such that < m , n > · < x , y > = < p , q >. For any Ginkgo number < m , n >, Ginkgo numbers <1, 0>, <0, 1>, <-1, 0>, <0,-1>, < m , n >, <- n , m >, <- m ,- n > and < n ,- m > are divisors of < m , n >. If m 2 + n 2 > 1, these Ginkgo numbers are distinct. In other words, any Ginkgo number such that m 2 + n 2 > 1 has at least eight divisors. A Ginkgo number < m , n > is called a prime if m 2 + n 2 > 1 and it has exactly eight divisors. Your mission is to check whether a given Ginkgo number is a prime or not. The following two facts might be useful to check whether a Ginkgo number is a divisor of another Ginkgo number. Suppose m 2 + n 2 > 0. Then, < m , n > is a divisor of < p , q > if and only if the integer m 2 + n 2 is a common divisor of mp + nq and mq − np . If < m , n > · < x , y > = < p , q >, then ( m 2 + n 2 )( x 2 + y 2 ) = p 2 + q 2 . Input The first line of the input contains a single integer, which is the number of datasets. The rest of the input is a sequence of datasets. Each dataset is a line containing two integers m and n , separated by a space. They designate the Ginkgo number < m , n >. You can assume 1 < m 2 + n 2 < 20000. Output For each dataset, output a character ' P ' in a line if the Ginkgo number is a prime. Output a character ' C ' in a line otherwise. Sample Input 8 10 0 0 2 -3 0 4 2 0 -13 -4 1 -2 -1 3 -1 Output for the Sample Input C C P C C P P C
[ { "submission_id": "aoj_1325_10853137", "code_snippet": "#include<cstring>\n#include<string>\n#include<sstream>\n#include<fstream>\n#include<iostream>\n#include<iomanip>\n#include<cstdio>\n#include<cctype>\n#include<algorithm>\n#include<queue>\n#include<deque>\n#include<map>\n#include<set>\n#include<vector>...
aoj_1327_cpp
Problem C: One-Dimensional Cellular Automaton There is a one-dimensional cellular automaton consisting of N cells. Cells are numbered from 0 to N − 1. Each cell has a state represented as a non-negative integer less than M . The states of cells evolve through discrete time steps. We denote the state of the i-th cell at time t as S ( i , t ). The state at time t + 1 is defined by the equation S ( i , t + 1) = ( A × S ( i − 1, t ) + B × S ( i , t ) + C × S ( i + 1, t )) mod M ,         (1) where A , B and C are non-negative integer constants. For i < 0 or N ≤ i , we define S ( i , t ) = 0. Given an automaton definition and initial states of cells, your mission is to write a program that computes the states of the cells at a specified time T . Input The input is a sequence of datasets. Each dataset is formatted as follows. N M A B C T S (0, 0) S (1, 0) ... S ( N − 1, 0) The first line of a dataset consists of six integers, namely N , M , A , B , C and T . N is the number of cells. M is the modulus in the equation (1). A , B and C are coefficients in the equation (1). Finally, T is the time for which you should compute the states. You may assume that 0 < N ≤ 50, 0 < M ≤ 1000, 0 ≤ A , B , C < M and 0 ≤ T ≤ 10 9 . The second line consists of N integers, each of which is non-negative and less than M . They represent the states of the cells at time zero. A line containing six zeros indicates the end of the input. Output For each dataset, output a line that contains the states of the cells at time T . The format of the output is as follows. S (0, T ) S (1, T ) ... S ( N − 1, T ) Each state must be represented as an integer and the integers must be separated by a space. Sample Input 5 4 1 3 2 0 0 1 2 0 1 5 7 1 3 2 1 0 1 2 0 1 5 13 1 3 2 11 0 1 2 0 1 5 5 2 0 1 100 0 1 2 0 1 6 6 0 2 3 1000 0 1 2 0 1 4 20 1000 0 2 3 1000000000 0 1 2 0 1 0 1 2 0 1 0 1 2 0 1 0 1 2 0 1 30 2 1 0 1 1000000000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 30 2 1 1 1 1000000000 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30 5 2 3 1 1000000000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Output for the Sample Input 0 1 2 0 1 2 0 0 4 3 2 12 10 9 11 3 0 4 2 1 0 4 2 0 4 4 0 376 752 0 376 0 376 752 0 376 0 376 752 0 376 0 376 752 0 376 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 3 2 2 2 3 3 1 4 3 1 2 3 0 4 3 3 0 4 2 2 2 2 1 1 2 1 3 0
[ { "submission_id": "aoj_1327_11043071", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing a2 = array<ll, 2>;\nusing a3 = array<ll, 3>;\n\nbool chmin(auto& a, const auto& b) { return a > b ? a = b, 1 : 0; }\nbool chmax(auto& a, const auto& b) { return a < b ? a = b...
aoj_1328_cpp
Problem D: Find the Outlier Professor Abacus has just built a new computing engine for making numerical tables. It was designed to calculate the values of a polynomial function in one variable at several points at a time. With the polynomial function f ( x ) = x 2 + 2 x + 1, for instance, a possible expected calculation result is 1 (= f (0)), 4 (= f (1)), 9 (= f (2)), 16 (= f (3)), and 25 (= f (4)). It is a pity, however, the engine seemingly has faulty components and exactly one value among those calculated simultaneously is always wrong. With the same polynomial function as above, it can, for instance, output 1, 4, 12, 16, and 25 instead of 1, 4, 9, 16, and 25. You are requested to help the professor identify the faulty components. As the first step, you should write a program that scans calculation results of the engine and finds the wrong values. Input The input is a sequence of datasets, each representing a calculation result in the following format. d v 0 v 1 ... v d +2 Here, d in the first line is a positive integer that represents the degree of the polynomial, namely, the highest exponent of the variable. For instance, the degree of 4 x 5 + 3 x + 0.5 is five and that of 2.4 x + 3.8 is one. d is at most five. The following d + 3 lines contain the calculation result of f (0), f (1), ... , and f ( d + 2) in this order, where f is the polynomial function. Each of the lines contains a decimal fraction between -100.0 and 100.0, exclusive. You can assume that the wrong value, which is exactly one of f (0), f (1), ... , and f ( d +2), has an error greater than 1.0. Since rounding errors are inevitable, the other values may also have errors but they are small and never exceed 10 -6 . The end of the input is indicated by a line containing a zero. Output For each dataset, output i in a line when v i is wrong. Sample Input 2 1.0 4.0 12.0 16.0 25.0 1 -30.5893962764 5.76397083962 39.3853798058 74.3727663177 4 42.4715310246 79.5420238202 28.0282396675 -30.3627807522 -49.8363481393 -25.5101480106 7.58575761381 5 -21.9161699038 -48.469304271 -24.3188578417 -2.35085940324 -9.70239202086 -47.2709510623 -93.5066246072 -82.5073836498 0 Output for the Sample Input 2 1 1 6
[ { "submission_id": "aoj_1328_10496662", "code_snippet": "#include<bits/stdc++.h>\nusing namespace std;\nint d;\ndouble a[1003][1004];\ndouble k[20005];\nbool solve(){\n//\tfor(int i=1;i<=d+3;i++){\n\t////\tfor(int j=1;j<=d+2;j++){\n\t//\t\tcout<<a[i][j]<<\" \";\n\t//\t}\n\t//\tcout<<endl;\n\t//}\n\tint n=d+...
aoj_1326_cpp
Problem B: Stylish Stylish is a programming language whose syntax comprises names , that are sequences of Latin alphabet letters, three types of grouping symbols , periods ('.'), and newlines. Grouping symbols, namely round brackets ('(' and ')'), curly brackets ('{' and '}'), and square brackets ('[' and ']'), must match and be nested properly. Unlike most other programming languages, Stylish uses periods instead of whitespaces for the purpose of term separation. The following is an example of a Stylish program. 1 ( Welcome .to 2 ......... Stylish ) 3 { Stylish .is 4 .....[.( a. programming . language .fun .to. learn ) 5 .......] 6 ..... Maybe .[ 7 ....... It. will .be.an. official . ICPC . language 8 .......] 9 .....} As you see in the example, a Stylish program is indented by periods. The amount of indentation of a line is the number of leading periods of it. Your mission is to visit Stylish masters, learn their indentation styles, and become the youngest Stylish master. An indentation style for well-indented Stylish programs is defined by a triple of integers, ( R , C , S ), satisfying 1 ≤ R , C , S ≤ 20. R , C and S are amounts of indentation introduced by an open round bracket, an open curly bracket, and an open square bracket, respectively. In a well-indented program, the amount of indentation of a line is given by R ( r o − r c ) + C ( c o − c c ) + S ( s o − s c ), where r o , c o , and s o are the numbers of occurrences of open round, curly, and square brackets in all preceding lines, respectively, and r c , c c , and s c are those of close brackets. The first line has no indentation in any well-indented program. The above example is formatted in the indentation style ( R , C , S ) = (9, 5, 2). The only grouping symbol occurring in the first line of the above program is an open round bracket. Therefore the amount of indentation for the second line is 9 · (1 − 0) + 5 · (0 − 0) + 2 ·(0 − 0) = 9. The first four lines contain two open round brackets, one open curly bracket, one open square bracket, two close round brackets, but no close curly nor square bracket. Therefore the amount of indentation for the fifth line is 9 · (2 − 2) + 5 · (1 − 0) + 2 · (1 − 0) = 7. Stylish masters write only well-indented Stylish programs. Every master has his/her own indentation style. Write a program that imitates indentation styles of Stylish masters. Input The input consists of multiple datasets. The first line of a dataset contains two integers p (1 ≤ p ≤ 10) and q (1 ≤ q ≤ 10). The next p lines form a well-indented program P written by a Stylish master and the following q lines form another program Q . You may assume that every line of both programs has at least one character and at most 80 characters. Also, you may assume that no line of Q starts with a period. The last dataset is followed by a line containing two zeros. Output Apply the indentation style of P to Q and output the appropriate amount of indentation for each line of Q . The amounts must b ...(truncated)
[ { "submission_id": "aoj_1326_9614938", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)\n#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)\n#define ALL(v) (v).begin(), (v).end()\n#define UNIQUE(v) sort(ALL(v)...
aoj_1336_cpp
Problem B: The Last Ant A straight tunnel without branches is crowded with busy ants coming and going. Some ants walk left to right and others right to left. All ants walk at a constant speed of 1 cm/s. When two ants meet, they try to pass each other. However, some sections of the tunnel are narrow and two ants cannot pass each other. When two ants meet at a narrow section, they turn around and start walking in the opposite directions. When an ant reaches either end of the tunnel, it leaves the tunnel. The tunnel has an integer length in centimeters. Every narrow section of the tunnel is integer centimeters distant from the both ends. Except for these sections, the tunnel is wide enough for ants to pass each other. All ants start walking at distinct narrow sections. No ants will newly enter the tunnel. Consequently, all the ants in the tunnel will eventually leave it. Your task is to write a program that tells which is the last ant to leave the tunnel and when it will. Figure B.1 shows the movements of the ants during the first two seconds in a tunnel 6 centimeters long. Initially, three ants, numbered 1, 2, and 3, start walking at narrow sections, 1, 2, and 5 centimeters distant from the left end, respectively. After 0.5 seconds, the ants 1 and 2 meet at a wide section, and they pass each other. Two seconds after the start, the ants 1 and 3 meet at a narrow section, and they turn around. Figure B.1 corresponds to the first dataset of the sample input. Figure B.1. Movements of ants Input The input consists of one or more datasets. Each dataset is formatted as follows. n l d 1 p 1 d 2 p 2 ... d n p n The first line of a dataset contains two integers separated by a space. n (1 ≤ n ≤ 20) represents the number of ants, and l ( n + 1 ≤ l ≤ 100) represents the length of the tunnel in centimeters. The following n lines describe the initial states of ants. Each of the lines has two items, d i and p i , separated by a space. Ants are given numbers 1 through n . The ant numbered i has the initial direction d i and the initial position p i . The initial direction d i (1 ≤ i ≤ n ) is L (to the left) or R (to the right). The initial position p i (1 ≤ i ≤ n ) is an integer specifying the distance from the left end of the tunnel in centimeters. Ants are listed in the left to right order, that is, 1 ≤ p 1 < p 2 < ... < p n ≤ l - 1. The last dataset is followed by a line containing two zeros separated by a space. Output For each dataset, output how many seconds it will take before all the ants leave the tunnel, and which of the ants will be the last. The last ant is identified by its number. If two ants will leave at the same time, output the number indicating the ant that will leave through the left end of the tunnel. Sample Input 3 6 R 1 L 2 L 5 1 10 R 1 2 10 R 5 L 7 2 10 R 3 L 8 2 99 R 1 L 98 4 10 L 1 R 2 L 8 R 9 6 10 R 2 R 3 L 4 R 6 L 7 L 8 0 0 Output for the Sample Input 5 1 9 1 7 1 8 2 98 2 8 2 8 3
[ { "submission_id": "aoj_1336_10881257", "code_snippet": "#include<bits/stdc++.h>\n// #include<atcoder/all>\n// #include<boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\n// using namespace atcoder;\n// using bint = boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ull = unsigned long lo...
aoj_1331_cpp
Problem G: Let There Be Light Suppose that there are some light sources and many spherical balloons. All light sources have sizes small enough to be modeled as point light sources, and they emit light in all directions. The surfaces of the balloons absorb light and do not reflect light. Surprisingly in this world, balloons may overlap. You want the total illumination intensity at an objective point as high as possible. For this purpose, some of the balloons obstructing lights can be removed. Because of the removal costs, however, there is a certain limit on the number of balloons to be removed. Thus, you would like to remove an appropriate set of balloons so as to maximize the illumination intensity at the objective point. The following figure illustrates the configuration specified in the first dataset of the sample input given below. The figure shows the xy -plane, which is enough because, in this dataset, the z -coordinates of all the light sources, balloon centers, and the objective point are zero. In the figure, light sources are shown as stars and balloons as circles. The objective point is at the origin, and you may remove up to 4 balloons. In this case, the dashed circles in the figure correspond to the balloons to be removed. Figure G.1: First dataset of the sample input. Input The input is a sequence of datasets. Each dataset is formatted as follows. N M R S 1 x S 1 y S 1 z S 1 r ... S Nx S Ny S Nz S Nr T 1 x T 1 y T 1 z T 1 b ... T Mx T My T Mz T Mb E x E y E z The first line of a dataset contains three positive integers, N , M and R , separated by a single space. N means the number of balloons that does not exceed 2000. M means the number of light sources that does not exceed 15. R means the number of balloons that may be removed, which does not exceed N . Each of the N lines following the first line contains four integers separated by a single space. ( S ix , S iy , S iz ) means the center position of the i -th balloon and S ir means its radius. Each of the following M lines contains four integers separated by a single space. ( T jx , T jy , T jz ) means the position of the j -th light source and T jb means its brightness. The last line of a dataset contains three integers separated by a single space. ( E x , E y , E z ) means the position of the objective point. S ix , S iy , S iz , T jx , T jy , T jz , E x , E y and E z are greater than -500, and less than 500. S ir is greater than 0, and less than 500. T jb is greater than 0, and less than 80000. At the objective point, the intensity of the light from the j -th light source is in inverse proportion to the square of the distance, namely T jb / { ( T jx − E x ) 2 + ( T jy − E y ) 2 + ( T jz − E z ) 2 }, if there is no balloon interrupting the light. The total illumination intensity is the sum of the above. You may assume the following. The distance between the objective point and any light source is not less than 1. For every i and j , even if S ir changes by ε (|ε| < 0.01), whether ...(truncated)
[ { "submission_id": "aoj_1331_10958572", "code_snippet": "#include <cstdio>\n#include <set>\n#include <cmath>\nusing namespace std;\nstruct Point\n{\n double x;\n double y;\n double z;\n void read()\n {\n scanf(\"%lf %lf %lf\",&x,&y,&z);\n }\n Point(double x=0,double y=0,double z=...
aoj_1333_cpp
Problem I: Beautiful Spacing Text is a sequence of words, and a word consists of characters. Your task is to put words into a grid with W columns and sufficiently many lines. For the beauty of the layout, the following conditions have to be satisfied. The words in the text must be placed keeping their original order. The following figures show correct and incorrect layout examples for a 4 word text "This is a pen" into 11 columns. Figure I.1: A good layout. Figure I.2: BAD | Do not reorder words. Between two words adjacent in the same line, you must place at least one space character. You sometimes have to put more than one space in order to meet other conditions. Figure I.3: BAD | Words must be separated by spaces. A word must occupy the same number of consecutive columns as the number of characters in it. You cannot break a single word into two or more by breaking it into lines or by inserting spaces. Figure I.4: BAD | Characters in a single word must be contiguous. The text must be justified to the both sides. That is, the first word of a line must startfrom the first column of the line, and except the last line, the last word of a line must end at the last column. Figure I.5: BAD | Lines must be justi ed to both the left and the right sides. The text is the most beautifully laid out when there is no unnecessarily long spaces. For instance, the layout in Figure I.6 has at most 2 contiguous spaces, which is more beautiful than that in Figure I.1, having 3 contiguous spaces. Given an input text and the number of columns, please find a layout such that the length of the longest contiguous spaces between words is minimum. Figure I.6: A good and the most beautiful layout. Input The input consists of multiple datasets, each in the following format. W N x 1 x 2 ... x N W , N , and x i are all integers. W is the number of columns (3 ≤ W ≤ 80,000). N is the number of words (2 ≤ N ≤ 50,000). x i is the number of characters in the i -th word (1 ≤ x i ≤ ( W −1)/2 ). Note that the upper bound on x i assures that there always exists a layout satisfying the conditions. The last dataset is followed by a line containing two zeros. Output For each dataset, print the smallest possible number of the longest contiguous spaces between words. Sample Input 11 4 4 2 1 3 5 7 1 1 1 2 2 1 2 11 7 3 1 3 1 3 3 4 100 3 30 30 39 30 3 2 5 3 0 0 Output for the Sample Input 2 1 2 40 1
[ { "submission_id": "aoj_1333_10851267", "code_snippet": "//#include<CSpreadSheet.h>\n\n#include<iostream>\n#include<cmath>\n#include<cstdio>\n#include<sstream>\n#include<cstdlib>\n#include<string>\n#include<string.h>\n#include<cstring>\n#include<algorithm>\n#include<vector>\n#include<map>\n#include<set>\n#i...
aoj_1330_cpp
Problem F: Never Wait for Weights In a laboratory, an assistant, Nathan Wada, is measuring weight differences between sample pieces pair by pair. He is using a balance because it can more precisely measure the weight difference between two samples than a spring scale when the samples have nearly the same weight. He is occasionally asked the weight differences between pairs of samples. He can or cannot answer based on measurement results already obtained. Since he is accumulating a massive amount of measurement data, it is now not easy for him to promptly tell the weight differences. Nathan asks you to develop a program that records measurement results and automatically tells the weight differences. Input The input consists of multiple datasets. The first line of a dataset contains two integers N and M . N denotes the number of sample pieces (2 ≤ N ≤ 100,000). Each sample is assigned a unique number from 1 to N as an identifier. The rest of the dataset consists of M lines (1 ≤ M ≤ 100,000), each of which corresponds to either a measurement result or an inquiry. They are given in chronological order. A measurement result has the format, ! a b w which represents the sample piece numbered b is heavier than one numbered a by w micrograms ( a ≠ b ). That is, w = w b − w a , where w a and w b are the weights of a and b , respectively. Here, w is a non-negative integer not exceeding 1,000,000. You may assume that all measurements are exact and consistent. An inquiry has the format, ? a b which asks the weight difference between the sample pieces numbered a and b ( a ≠ b ). The last dataset is followed by a line consisting of two zeros separated by a space. Output For each inquiry, ? a b , print the weight difference in micrograms between the sample pieces numbered a and b , w b − w a , followed by a newline if the weight difference can be computed based on the measurement results prior to the inquiry. The difference can be zero, or negative as well as positive. You can assume that its absolute value is at most 1,000,000. If the difference cannot be computed based on the measurement results prior to the inquiry, print UNKNOWN followed by a newline. Sample Input 2 2 ! 1 2 1 ? 1 2 2 2 ! 1 2 1 ? 2 1 4 7 ! 1 2 100 ? 2 3 ! 2 3 100 ? 2 3 ? 1 3 ! 4 3 150 ? 4 1 0 0 Output for the Sample Input 1 -1 UNKNOWN 100 200 -50
[ { "submission_id": "aoj_1330_11066164", "code_snippet": "#include <iostream>\n#include <vector>\n#include <utility>\nusing namespace std;\n\nclass unionfind{\npublic:\n unionfind(int n): n_(n) {\n parent_.resize(n);\n size_.resize(n);\n diff_.resize(n);\n for(int i=0; i<n; i++...
aoj_1334_cpp
Problem J: Cubic Colonies In AD 3456, the earth is too small for hundreds of billions of people to live in peace. Interstellar Colonization Project with Cubes (ICPC) is a project that tries to move people on the earth to space colonies to ameliorate the problem. ICPC obtained funding from governments and manufactured space colonies very quickly and at low cost using prefabricated cubic blocks. The largest colony looks like a Rubik's cube. It consists of 3 × 3 × 3 cubic blocks (Figure J.1A). Smaller colonies miss some of the blocks in the largest colony. When we manufacture a colony with multiple cubic blocks, we begin with a single block. Then we iteratively glue a next block to existing blocks in a way that faces of them match exactly. Every pair of touched faces is glued. Figure J.1: Example of the largest colony and a smaller colony However, just before the first launch, we found a design flaw with the colonies. We need to add a cable to connect two points on the surface of each colony, but we cannot change the inside of the prefabricated blocks in a short time. Therefore we decided to attach a cable on the surface of each colony. If a part of the cable is not on the surface, it would be sheared off during the launch, so we have to put the whole cable on the surface. We would like to minimize the lengths of the cables due to budget constraints. The dashed line in Figure J.1B is such an example. Write a program that, given the shape of a colony and a pair of points on its surface, calculates the length of the shortest possible cable for that colony. Input The input contains a series of datasets. Each dataset describes a single colony and the pair of the points for the colony in the following format. x 1 y 1 z 1 x 2 y 2 z 2 b 0,0,0 b 1,0,0 b 2,0,0 b 0,1,0 b 1,1,0 b 2,1,0 b 0,2,0 b 1,2,0 b 2,2,0 b 0,0,1 b 1,0,1 b 2,0,1 b 0,1,1 b 1,1,1 b 2,1,1 b 0,2,1 b 1,2,1 b 2,2,1 b 0,0,2 b 1,0,2 b 2,0,2 b 0,1,2 b 1,1,2 b 2,1,2 b 0,2,2 b 1,2,2 b 2,2,2 ( x 1 , y 1 , z 1 ) and ( x 2 , y 2 , z 2 ) are the two distinct points on the surface of the colony, where x 1 , x 2 , y 1 , y 2 , z 1 , z 2 are integers that satisfy 0 ≤ x 1 , x 2 , y 1 , y 2 , z 1 , z 2 ≤ 3. b i,j,k is ' # ' when there is a cubic block whose two diagonal vertices are ( i , j , k ) and ( i + 1, j + 1, k + 1), and b i,j,k is ' . ' if there is no block. Figure J.1A corresponds to the first dataset in the sample input, whereas Figure J.1B corresponds to the second. A cable can pass through a zero-width gap between two blocks if they are touching only on their vertices or edges. In Figure J.2A, which is the third dataset in the sample input, the shortest cable goes from the point A (0, 0, 2) to the point B (2, 2, 2), passing through (1, 1, 2), which is shared by six blocks. Similarly, in Figure J.2B (the fourth dataset in the sample input), the shortest cable goes through the gap between two blocks not glued directly. When two blocks share only a single vertex, you can put a cable through the vertex ...(truncated)
[ { "submission_id": "aoj_1334_4876386", "code_snippet": "#include<bits/stdc++.h>\ntypedef long long int ll;\ntypedef unsigned long long int ull;\n#define BIG_NUM 2000000000\n#define HUGE_NUM 1000000000000000000\n#define MOD 1000000007\n#define EPS 0.000000001\nusing namespace std;\n\n\n#define SIZE 10005\n\n...
aoj_1335_cpp
Problem A: Equal Sum Sets Let us consider sets of positive integers less than or equal to n . Note that all elements of a set are different. Also note that the order of elements doesn't matter, that is, both {3, 5, 9} and {5, 9, 3} mean the same set. Specifying the number of set elements and their sum to be k and s , respectively, sets satisfying the conditions are limited. When n = 9, k = 3 and s = 23, {6, 8, 9} is the only such set. There may be more than one such set, in general, however. When n = 9, k = 3 and s = 22, both {5, 8, 9} and {6, 7, 9} are possible. You have to write a program that calculates the number of the sets that satisfy the given conditions. Input The input consists of multiple datasets. The number of datasets does not exceed 100. Each of the datasets has three integers n , k and s in one line, separated by a space. You may assume 1 ≤ n ≤ 20, 1 ≤ k ≤ 10 and 1 ≤ s ≤ 155. The end of the input is indicated by a line containing three zeros. Output The output for each dataset should be a line containing a single integer that gives the number of the sets that satisfy the conditions. No other characters should appear in the output. You can assume that the number of sets does not exceed 2 31 - 1. Sample Input 9 3 23 9 3 22 10 3 28 16 10 107 20 8 102 20 10 105 20 10 155 3 4 3 4 2 11 0 0 0 Output for the Sample Input 1 2 0 20 1542 5448 1 0 0
[ { "submission_id": "aoj_1335_11030135", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing a2 = array<ll, 2>;\nusing a3 = array<ll, 3>;\n\nbool chmin(auto& a, const auto& b) { return a > b ? a = b, 1 : 0; }\nbool chmax(auto& a, const auto& b) { return a < b ? a = b...
aoj_1329_cpp
Problem E: Sliding Block Puzzle In sliding block puzzles, we repeatedly slide pieces (blocks) to open spaces within a frame to establish a goal placement of pieces. A puzzle creator has designed a new puzzle by combining the ideas of sliding block puzzles and mazes. The puzzle is played in a rectangular frame segmented into unit squares. Some squares are pre-occupied by obstacles. There are a number of pieces placed in the frame, one 2 × 2 king piece and some number of 1 × 1 pawn pieces. Exactly two 1 × 1 squares are left open. If a pawn piece is adjacent to an open square, we can slide the piece there. If a whole edge of the king piece is adjacent to two open squares, we can slide the king piece. We cannot move the obstacles. Starting from a given initial placement, the objective of the puzzle is to move the king piece to the upper-left corner of the frame. The following figure illustrates the initial placement of the fourth dataset of the sample input. Figure E.1: The fourth dataset of the sample input. Your task is to write a program that computes the minimum number of moves to solve the puzzle from a given placement of pieces. Here, one move means sliding either king or pawn piece to an adjacent position. Input The input is a sequence of datasets. The first line of a dataset consists of two integers H and W separated by a space, where H and W are the height and the width of the frame. The following H lines, each consisting of W characters, denote the initial placement of pieces. In those H lines, ' X ', ' o ', ' * ', and ' . ' denote a part of the king piece, a pawn piece, an obstacle, and an open square, respectively. There are no other characters in those H lines. You may assume that 3 ≤ H ≤ 50 and 3 ≤ W ≤ 50. A line containing two zeros separated by a space indicates the end of the input. Output For each dataset, output a line containing the minimum number of moves required to move the king piece to the upper-left corner. If there is no way to do so, output -1 . Sample Input 3 3 oo. oXX .XX 3 3 XXo XX. o.o 3 5 .o*XX oooXX oooo. 7 12 oooooooooooo ooooo*****oo oooooo****oo o**ooo***ooo o***ooooo..o o**ooooooXXo ooooo****XXo 5 30 oooooooooooooooooooooooooooooo oooooooooooooooooooooooooooooo o***************************oo XX.ooooooooooooooooooooooooooo XX.ooooooooooooooooooooooooooo 0 0 Output for the Sample Input 11 0 -1 382 6807
[ { "submission_id": "aoj_1329_10853885", "code_snippet": "#include<cstdio>\n#include<cstring>\n#include<queue>\n#include<iostream>\nusing namespace std;\nconst int inf=0x3f3f3f3f;\nconst int maxn=60;\nint n,m;\nchar mp[maxn][maxn];\nconst int cx[]={-1,-1,0,1,2,2,0,1};\nconst int cy[]={0,1,2,2,0,1,-1,-1};\nst...
aoj_1338_cpp
Problem D: Clock Hands We have an analog clock whose three hands (the second hand, the minute hand and the hour hand) rotate quite smoothly. You can measure two angles between the second hand and two other hands. Write a program to find the time at which "No two hands overlap each other" and "Two angles between the second hand and two other hands are equal" for the first time on or after a given time. Figure D.1. Angles between the second hand and two other hands Clocks are not limited to 12-hour clocks. The hour hand of an H -hour clock goes around once in H hours. The minute hand still goes around once every hour, and the second hand goes around once every minute. At 0:0:0 (midnight), all the hands are at the upright position. Input The input consists of multiple datasets. Each of the dataset has four integers H , h , m and s in one line, separated by a space. H means that the clock is an H -hour clock. h , m and s mean hour, minute and second of the specified time, respectively. You may assume 2 ≤ H ≤ 100, 0 ≤ h < H , 0 ≤ m < 60, and 0 ≤ s < 60. The end of the input is indicated by a line containing four zeros. Figure D.2. Examples of H-hour clock (6-hour clock and 15-hour clock) Output Output the time T at which "No two hands overlap each other" and "Two angles between the second hand and two other hands are equal" for the first time on and after the specified time. For T being h o : m o : s o ( s o seconds past m o minutes past h o o'clock), output four non-negative integers h o , m o , n , and d in one line, separated by a space, where n / d is the irreducible fraction representing s o . For integer s o including 0, let d be 1. The time should be expressed in the remainder of H hours. In other words, one second after ( H − 1):59:59 is 0:0:0, not H :0:0. Sample Input 12 0 0 0 12 11 59 59 12 1 56 0 12 1 56 3 12 1 56 34 12 3 9 43 12 3 10 14 12 7 17 58 12 7 18 28 12 7 23 0 12 7 23 31 2 0 38 29 2 0 39 0 2 0 39 30 2 1 6 20 2 1 20 1 2 1 20 31 3 2 15 0 3 2 59 30 4 0 28 48 5 1 5 40 5 1 6 10 5 1 7 41 11 0 55 0 0 0 0 0 Output for the Sample Input 0 0 43200 1427 0 0 43200 1427 1 56 4080 1427 1 56 47280 1427 1 57 4860 1427 3 10 18600 1427 3 10 61800 1427 7 18 39240 1427 7 18 82440 1427 7 23 43140 1427 7 24 720 1427 0 38 4680 79 0 39 2340 79 0 40 0 1 1 6 3960 79 1 20 2400 79 1 21 60 79 2 15 0 1 0 0 2700 89 0 28 48 1 1 6 320 33 1 6 40 1 1 8 120 11 0 55 0 1
[ { "submission_id": "aoj_1338_9808827", "code_snippet": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i, n) for(int i = 0; i < (n); i++)\n#define srep(i, s, t) for(int i = (s); i < (t); i++)\n#define len(x) ((int)(x).size())\n#define all(x) (x).begin(), (x).end()\ntemplate < class T > bool chm...
aoj_1337_cpp
Problem C: Count the Regions There are a number of rectangles on the x-y plane. The four sides of the rectangles are parallel to either the x -axis or the y -axis, and all of the rectangles reside within a range specified later. There are no other constraints on the coordinates of the rectangles. The plane is partitioned into regions surrounded by the sides of one or more rectangles. In an example shown in Figure C.1, three rectangles overlap one another, and the plane is partitioned into eight regions. Rectangles may overlap in more complex ways. For example, two rectangles may have overlapped sides, they may share their corner points, and/or they may be nested. Figure C.2 illustrates such cases. Your job is to write a program that counts the number of the regions on the plane partitioned by the rectangles. Input The input consists of multiple datasets. Each dataset is formatted as follows. n l 1 t 1 r 1 b 1 l 2 t 2 r 2 b 2 : l n t n r n b n A dataset starts with n (1 ≤ n ≤ 50), the number of rectangles on the plane. Each of the following n lines describes a rectangle. The i -th line contains four integers, l i , t i , r i , and b i , which are the coordinates of the i -th rectangle; ( l i , t i ) gives the x-y coordinates of the top left corner, and ( r i , b i ) gives that of the bottom right corner of the rectangle (0 ≤ l i < r i ≤ 10 6 , 0 ≤ b i < t i ≤ 10 6 , for 1 ≤ i ≤ n ). The four integers are separated by a space. The input is terminated by a single zero. Output For each dataset, output a line containing the number of regions on the plane partitioned by the sides of the rectangles. Figure C.1. Three rectangles partition the plane into eight regions. This corresponds to the first dataset of the sample input. The x - and y -axes are shown for illustration purposes only, and therefore they do not partition the plane. Figure C.2. Rectangles overlapping in more complex ways. This corresponds to the second dataset. Sample Input 3 4 28 27 11 15 20 42 5 11 24 33 14 5 4 28 27 11 12 11 34 2 7 26 14 16 14 16 19 12 17 28 27 21 2 300000 1000000 600000 0 0 600000 1000000 300000 0 Output for the Sample Input 8 6 6
[ { "submission_id": "aoj_1337_10852755", "code_snippet": "#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <map>\n#include <algorithm>\nusing namespace std;\nconst int maxn = 555;\nint l[maxn],r[maxn],t[maxn],b[maxn];\nint X[maxn],Y[maxn],g[maxn][maxn];\nmap<int,int>mpx;\nmap<int,int>mpy;...
aoj_1344_cpp
Problem J: C(O|W|A*RD*|S)* CROSSWORD Puzzle The first crossword puzzle was published on December 21, 1913 by Arthur Wynne. To celebrate the centennial of his great-great-grandfather's invention, John "Coward" Wynne 1 was struggling to make crossword puzzles. He was such a coward that whenever he thought of a tricky clue for a word, he couldn’t stop worrying if people would blame him for choosing a bad clue that could never mean that word. At the end of the day, he cowardly chose boring clues, which made his puzzles less interesting. One day, he came up with a brilliant idea: puzzles in which word meanings do not matter, and yet interesting. He told his idea to his colleagues, who admitted that the idea was intriguing. They even named his puzzles "Coward's Crossword Puzzles" after his nickname. However, making a Coward's crossword puzzle was not easy. Even though he did not have to think about word meanings, it was not easy to check if a puzzle has one and only one set of answers. As the day of the centennial anniversary was approaching, John started worrying if he would not be able to make interesting ones in time. Let's help John by writing a program that solves Coward's crossword puzzles. Each puzzle consists of h × w cells along with h across clues and w down clues. The clues are regular expressions written in a pattern language whose BNF syntax is given as in the table below. clue ::= "^" pattern "$" pattern ::= simple | pattern "|" simple simple ::= basic | simple basic basic ::= elementary | elementary "*" elementary ::= "." | "A" | "B" | ... | "Z" | "(" pattern ")" Table J.1. BNF syntax of the pattern language. The clues (as denoted by p and q below) match words (as denoted by s below) according to the following rules. ^ p $ matches s if p matches s . p | q matches a string s if p and/or q matches s . pq matches a string s if there exist s 1 and s 2 such that s 1 s 2 = s , p matches s 1 , and q matches s 2 . p * matches a string s if s is empty, or there exist s 1 and s 2 such that s 1 s 2 = s , p matches s 1 , and p * matches s 2 . Each of A , B , . . . , Z matches the respective letter itself. ( p ) matches s if p matches s . . is the shorthand of (A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z) . Below is an example of a Coward’s crossword puzzle with the answers filled in the cells. Java Specific: Submitted Java programs may not use classes in the java.util.regex package. C++ Specific: Submitted C++ programs may not use the std::regex class. Input The input consists of multiple datasets, each of which represents a puzzle given in the following format. h w p 1 p 2 ... p h q 1 q 2 ... q 2 Here, h and w represent the vertical and horizontal numbers of cells, respectively, where 2 ≤ h,w ≤ 4. The p i and q j are the across and down clues for the i -th row and j -th column, respectively. Any clue has no more than 512 characters. The last dataset is followed by a line of two zeros. You may assume that there are no more ...(truncated)
[ { "submission_id": "aoj_1344_5432770", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n#include <cctype>\n#include <cassert>\n#include <array>\n#include <set>\nusing namespace std;\n\n#define ALL(v) begin(v),end(v)\n\nnamespace{\n\nstruct...
aoj_1332_cpp
Problem H: Company Organization You started a company a few years ago and fortunately it has been highly successful. As the growth of the company, you noticed that you need to manage employees in a more organized way, and decided to form several groups and assign employees to them. Now, you are planning to form n groups, each of which corresponds to a project in the company. Sometimes you have constraints on members in groups. For example, a group must be a subset of another group because the former group will consist of senior members of the latter group, the members in two groups must be the same because current activities of the two projects are closely related, the members in two groups must not be exactly the same to avoid corruption, two groups cannot have a common employee because of a security reason, and two groups must have a common employee to facilitate collaboration. In summary, by letting X i ( i = 1, ... , n ) be the set of employees assigned to the i -th group, we have five types of constraints as follows. X i ⊆ X j X i = X j X i ≠ X j X i ∩ X j = ∅ X i ∩ X j ≠ ∅ Since you have listed up constraints without considering consistency, it might be the case that you cannot satisfy all the constraints. Constraints are thus ordered according to their priorities, and you now want to know how many constraints of the highest priority can be satisfied. You do not have to take ability of employees into consideration. That is, you can assign anyone to any group. Also, you can form groups with no employee. Furthermore, you can hire or fire as many employees as you want if you can satisfy more constraints by doing so. For example, suppose that we have the following five constraints on three groups in the order of their priorities, corresponding to the first dataset in the sample input. X 2 ⊆ X 1 X 3 ⊆ X 2 X 1 ⊆ X 3 X 1 ≠ X 3 X 3 ⊆ X 1 By assigning the same set of employees to X 1 , X 2 , and X 3 , we can satisfy the first three constraints. However, no matter how we assign employees to X 1 , X 2 , and X 3 , we cannot satisfy the first four highest priority constraints at the same time. Though we can satisfy the first three constraints and the fifth constraint at the same time, the answer should be three. Input The input consists of several datasets. The first line of a dataset consists of two integers n (2 ≤ n ≤ 100) and m (1 ≤ m ≤ 10000), which indicate the number of groups and the number of constraints, respectively. Then, description of m constraints follows. The description of each constraint consists of three integers s (1 ≤ s ≤ 5), i (1 ≤ i ≤ n ), and j (1 ≤ j ≤ n , j ≠= i ), meaning a constraint of the s -th type imposed on the i -th group and the j -th group. The type number of a constraint is as listed above. The constraints are given in the descending order of priority. The input ends with a line containing two zeros. Output For each dataset, output the number of constraints of the highest priority satisfiable at the same time. Sample ...(truncated)
[ { "submission_id": "aoj_1332_10851055", "code_snippet": "#include <cstring>\n#include <cstdio>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <iostream>\n\nusing namespace std;\n\nconst int MAXN = 1e4+10;\nconst int MAXG = 110;\n\nint n,m;\nint x[MAXN],op[MAXN],y[MAXN];\n\nint f[MAXG]...
aoj_1339_cpp
Problem E: Dragon's Cruller Dragon's Cruller is a sliding puzzle on a torus. The torus surface is partitioned into nine squares as shown in its development in Figure E.1. Here, two squares with one of the sides on the development labeled with the same letter are adjacent to each other, actually sharing the side. Figure E.2 shows which squares are adjacent to which and in which way. Pieces numbered from 1 through 8 are placed on eight out of the nine squares, leaving the remaining one empty. Figure E.1. A 3 × 3 Dragon’s Cruller torus A piece can be slid to an empty square from one of its adjacent squares. The goal of the puzzle is, by sliding pieces a number of times, to reposition the pieces from the given starting arrangement into the given goal arrangement. Figure E.3 illustrates arrangements directly reached from the arrangement shown in the center after four possible slides. The cost to slide a piece depends on the direction but is independent of the position nor the piece. Your mission is to find the minimum cost required to reposition the pieces from the given starting arrangement into the given goal arrangement. Figure E.2. Adjacency Figure E.3. Examples of sliding steps Unlike some sliding puzzles on a flat square, it is known that any goal arrangement can be reached from any starting arrangements on this torus. Input The input is a sequence of at most 30 datasets. A dataset consists of seven lines. The first line contains two positive integers c h and c v , which represent the respective costs to move a piece horizontally and vertically. You can assume that both c h and c v are less than 100. The next three lines specify the starting arrangement and the last three the goal arrangement, each in the following format. d A d B d C d D d E d F d G d H d I Each line consists of three digits separated by a space. The digit d X ( X is one of A through I ) indicates the state of the square X as shown in Figure E.2. Digits 1 , . . . , 8 indicate that the piece of that number is on the square. The digit 0 indicates that the square is empty. The end of the input is indicated by two zeros separated by a space. Output For each dataset, output the minimum total cost to achieve the goal, in a line. The total cost is the sum of the costs of moves from the starting arrangement to the goal arrangement. No other characters should appear in the output. Sample Input 4 9 6 3 0 8 1 2 4 5 7 6 3 0 8 1 2 4 5 7 31 31 4 3 6 0 1 5 8 2 7 0 3 6 4 1 5 8 2 7 92 4 1 5 3 4 0 7 8 2 6 1 5 0 4 7 3 8 2 6 12 28 3 4 5 0 2 6 7 1 8 5 7 1 8 6 2 0 3 4 0 0 Output for the Sample Input 0 31 96 312
[ { "submission_id": "aoj_1339_10857961", "code_snippet": "#include<map>\n#include<set>\n#include<cmath>\n#include<queue>\n#include<cctype>\n#include<cstdio>\n#include<vector>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\ntypedef long long LL;\n#define HASH 1000003\n#define MAXN 1000010\nint fir...
aoj_1340_cpp
Problem F: Directional Resemblance Vectors have their directions and two vectors make an angle between them. Given a set of three-dimensional vectors, your task is to find the pair among them that makes the smallest angle. Input The input is a sequence of datasets. A dataset specifies a set of three-dimensional vectors, some of which are directly given in the dataset and the others are generated by the procedure described below. Each dataset is formatted as follows. m n S W x 1 y 1 z 1 x 2 y 2 z 2 : x m y m z m The first line contains four integers m , n , S , and W . The integer m is the number of vectors whose three components are directly specified in the dataset. Starting from the second line, m lines have the three components of m vectors. The i -th line of which indicates the vector v i = ( x i , y i , z i ). All the vector components are positive integers less than or equal to 100. The integer n is the number of vectors generated by the following procedure. int g = S; for(int i=m+1; i<=m+n; i++) { x[i] = (g/7) %100 + 1; y[i] = (g/700) %100 + 1; z[i] = (g/70000)%100 + 1; if( g%2 == 0 ) { g = (g/2); } else { g = (g/2) ^ W; } } For i = m + 1, . . . , m + n , the i -th vector v i of the set has three components x[i] , y[i] , and z[i] generated by this procedure. Here, values of S and W are the parameters S and W given in the first line of the dataset. You may assume 1 ≤ S ≤ 10 9 and 1 ≤ W ≤ 10 9 . The total number of vectors satisfies 2 ≤ m + n ≤ 12 × 10 4 . Note that exactly the same vector may be specified twice or more in a single dataset. A line containing four zeros indicates the end of the input. The total of m+n for all the datasets in the input never exceeds 16 × 10 5 . Output For each dataset, output the pair of vectors among the specified set with the smallest non-zero angle in between. It is assured that there are at least two vectors having different directions. Vectors should be indicated by their three components. The output for a pair of vectors v a and v b should be formatted in a line as follows. x a y a z a x b y b z b Two vectors ( x a , y a , z a ) and ( x b , y b , z b ) are ordered in the dictionary order, that is, v a < v b if x a < x b , or if x a = x b and y a < y b , or if x a = x b , y a = y b and z a < z b . When a vector pair is output, the smaller vector in this order should be output first. If more than one pair makes the equal smallest angle, the pair that is the smallest among them in the dictionary order between vector pairs should be output. The pair ( v i , v j ) is smaller than the pair ( v k , v l ) if v i < v k , or if v i = v k and v j < v l . Sample Input 4 0 2013 1124 1 1 1 2 2 2 2 1 1 1 2 1 2 100 131832453 129800231 42 40 46 42 40 46 0 100000 7004674 484521438 0 0 0 0 Output for the Sample Input 1 1 1 1 2 1 42 40 46 83 79 91 92 92 79 99 99 85
[ { "submission_id": "aoj_1340_10848362", "code_snippet": "#include <bits/stdc++.h>\n//using namespace std;\n\ntypedef long double LD;\n\nconst LD INF = 1e15;\nconst LD eps = 1e-13;\nconst int N = 155555;\n\nint n, m, S, W;\n\ninline LD norm(const LD &x) {\n\treturn x * x;\n}\n\nstruct OriP {\n\tint x, y, z;\...
aoj_1347_cpp
Problem C: Shopping Your friend will enjoy shopping. She will walk through a mall along a straight street, where $N$ individual shops (numbered from 1 to $N$) are aligned at regular intervals. Each shop has one door and is located at the one side of the street. The distances between the doors of the adjacent shops are the same length, i.e. a unit length. Starting shopping at the entrance of the mall, she visits shops in order to purchase goods. She has to go to the exit of the mall after shopping. She requires some restrictions on visiting order of shops. Each of the restrictions indicates that she shall visit a shop before visiting another shop. For example, when she wants to buy a nice dress before choosing heels, she shall visit a boutique before visiting a shoe store. When the boutique is farther than the shoe store, she must pass the shoe store before visiting the boutique, and go back to the shoe store after visiting the boutique. If only the order of the visiting shops satisfies all the restrictions, she can visit other shops in any order she likes. Write a program to determine the minimum required walking length for her to move from the entrance to the exit. Assume that the position of the door of the shop numbered $k$ is $k$ units far from the entrance, where the position of the exit is $N + 1$ units far from the entrance. Input The input consists of a single test case. $N$ $m$ $c_1$ $d_1$ . . . $c_m$ $d_m$ The first line contains two integers $N$ and $m$, where $N$ ($1 \leq N \leq 1000$) is the number of shops, and $m$ ($0 \leq m \leq 500$) is the number of restrictions. Each of the next $m$ lines contains two integers $c_i$ and $d_i$ ($1 \leq c_i < d_i \leq N$) indicating the $i$-th restriction on the visiting order, where she must visit the shop numbered $c_i$ after she visits the shop numbered $d_i$ ($i = 1, . . . , m$). There are no pair of $j$ and $k$ that satisfy $c_j = c_k$ and $d_j = d_k$. Output Output the minimum required walking length for her to move from the entrance to the exit. You should omit the length of her walk in the insides of shops. Sample Input 1 10 3 3 7 8 9 2 5 Sample Output 1 23 Sample Input 2 10 3 8 9 6 7 2 4 Sample Output 2 19 Sample Input 3 10 0 Sample Output 3 11 Sample Input 4 10 6 6 7 4 5 2 5 6 9 3 5 6 8 Sample Output 4 23 Sample Input 5 1000 8 3 4 6 1000 5 1000 7 1000 8 1000 4 1000 9 1000 1 2 Sample Output 5 2997
[ { "submission_id": "aoj_1347_2717021", "code_snippet": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <cstdio>\n#include <functional>\n#include <numeric>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <utility>\n#in...
aoj_1342_cpp
Problem H: Don't Burst the Balloon An open-top box having a square bottom is placed on the floor. You see a number of needles vertically planted on its bottom. You want to place a largest possible spheric balloon touching the box bottom, interfering with none of the side walls nor the needles. Java Specific: Submitted Java programs may not use "java.awt.geom.Area". You may use it for your debugging purposes. Figure H.1 shows an example of a box with needles and the corresponding largest spheric balloon. It corresponds to the first dataset of the sample input below. Figure H.1. The upper shows an example layout and the lower shows the largest spheric balloon that can be placed. Input The input is a sequence of datasets. Each dataset is formatted as follows. n w x 1 y 1 h 1 : x n y n h n The first line of a dataset contains two positive integers, n and w , separated by a space. n represents the number of needles, and w represents the height of the side walls. The bottom of the box is a 100 × 100 square. The corners of the bottom face are placed at positions (0, 0, 0), (0, 100, 0), (100, 100, 0), and (100, 0, 0). Each of the n lines following the first line contains three integers, x i , y i , and h i . ( x i , y i , 0) and h i represent the base position and the height of the i -th needle. No two needles stand at the same position. You can assume that 1 ≤ n ≤ 10, 10 ≤ w ≤ 200, 0 < x i < 100, 0 < y i < 100 and 1 ≤ h i ≤ 200. You can ignore the thicknesses of the needles and the walls. The end of the input is indicated by a line of two zeros. The number of datasets does not exceed 1000. Output For each dataset, output a single line containing the maximum radius of a balloon that can touch the bottom of the box without interfering with the side walls or the needles. The output should not contain an error greater than 0.0001. Sample Input 5 16 70 66 40 38 52 20 40 35 10 70 30 10 20 60 10 1 100 54 75 200 1 10 90 10 1 1 11 54 75 200 3 10 53 60 1 61 38 1 45 48 1 4 10 20 20 10 20 80 10 80 20 10 80 80 10 0 0 Output for the Sample Input 26.00000 39.00000 130.00000 49.49777 85.00000 95.00000
[ { "submission_id": "aoj_1342_9782093", "code_snippet": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define rep(i, a, b) for (ll i = (ll)(a); i < (ll)(b); i++)\n#define rrep(i, a, b) for (ll i = (ll)(b)-1; i >= (ll)(a); i--)\n#define ALL(v) (v).begin(), (v).end()\n#define UNIQUE(v) sort(ALL(v)), (v)...
aoj_1345_cpp
Problem A: Bit String Reordering You have to reorder a given bit string as specified. The only operation allowed is swapping adjacent bit pairs. Please write a program that calculates the minimum number of swaps required. The initial bit string is simply represented by a sequence of bits, while the target is specified by a run-length code . The run-length code of a bit string is a sequence of the lengths of maximal consecutive sequences of zeros or ones in the bit string. For example, the run-length code of "011100" is "1 3 2". Note that there are two different bit strings with the same run-length code, one starting with zero and the other starting with one. The target is either of these two. In Sample Input 1, bit string "100101" should be reordered so that its run-length code is "1 3 2", which means either "100011" or "011100". At least four swaps are required to obtain "011100". On the other hand, only one swap is required to make "100011". Thus, in this example, 1 is the answer. Input The input consists of a single test case. The test case is formatted as follows. $N$ $M$ $b_1$ $b_2$ . . . $b_N$ $p_1$ $p_2$ . . . $p_M$ The first line contains two integers $N$ ($1 \leq N \leq 15$) and $M$ ($1 \leq M \leq N$). The second line specifies the initial bit string by $N$ integers. Each integer $b_i$ is either 0 or 1. The third line contains the run-length code, consisting of $M$ integers. Integers $p_1$ through $p_M$ represent the lengths of consecutive sequences of zeros or ones in the bit string, from left to right. Here, $1 \leq p_j$ for $1 \leq j \leq M$ and $\sum^{M}_{j=1} p_j = N$ hold. It is guaranteed that the initial bit string can be reordered into a bit string with its run-length code $p_1, . . . , p_M$. Output Output the minimum number of swaps required Sample Input 1 6 3 1 0 0 1 0 1 1 3 2 Sample Output 1 1 Sample Input 2 7 2 1 1 1 0 0 0 0 4 3 Sample Output 2 12 Sample Input 3 15 14 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 Sample Output 3 7 Sample Input 4 1 1 0 1 Sample Output 4 0
[ { "submission_id": "aoj_1345_10500246", "code_snippet": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <ranges>\n#include <map>\nnamespace ranges = std::ranges;\nint N, M;\nstd::vector<int> rle(std::vector<int> a) {\n std::vector<int> res;\n for (int i = 0,...
aoj_1341_cpp
Problem G: Longest Chain Let us compare two triples a = (x a , y a , z a ) and b = (x b , y b , z b ) by a partial order ∠ defined as follows. a ∠ b ⇔ x a < x b and y a < y b and z a < z b Your mission is to find, in the given set of triples, the longest ascending series a 1 ∠ a 2 ∠ ... ∠ a k . Input The input is a sequence of datasets, each specifying a set of triples formatted as follows. m n A B x 1 y 1 z 1 x 2 y 2 z 2 ... x m y m z m Here, m , n , A and B in the first line, and all of x i , y i and z i ( i = 1, . . . , m ) in the following lines are non-negative integers. Each dataset specifies a set of m + n triples. The triples p 1 through p m are explicitly specified in the dataset, the i -th triple p i being ( x i , y i , z i ) . The remaining n triples are specified by parameters A and B given to the following generator routine. int a = A, b = B, C = ~(1<<31), M = (1<<16)-1; int r() { a = 36969 * (a & M) + (a >> 16); b = 18000 * (b & M) + (b >> 16); return (C & ((a << 16) + b)) % 1000000; } Repeated 3 n calls of r() defined as above yield values of x m+1 , y m+1 , z m+1 , x m+2 , y m+2 , z m+2 , ..., x m+n , y m+n , and z m+n , in this order. You can assume that 1 ≤ m + n ≤ 3 × 10 5 , 1 ≤ A,B ≤ 2 16 , and 0 ≤ x k , y k , z k < 10 6 for 1 ≤ k ≤ m + n . The input ends with a line containing four zeros. The total of m + n for all the datasets does not exceed 2 × 10 6 . Output For each dataset, output the length of the longest ascending series of triples in the specified set. If p i 1 ∠ p i 2 ∠ ... ∠ p i k is the longest, the answer should be k . Sample Input 6 0 1 1 0 0 0 0 2 2 1 1 1 2 0 2 2 2 0 2 2 2 5 0 1 1 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 10 0 1 1 3 0 0 2 1 0 2 0 1 1 2 0 1 1 1 1 0 2 0 3 0 0 2 1 0 1 2 0 0 3 0 10 1 1 0 0 0 0 Output for the Sample Input 3 5 1 3
[ { "submission_id": "aoj_1341_10853188", "code_snippet": "#include<map>\n#include<set>\n#include<queue>\n#include<cctype>\n#include<cstdio>\n#include<vector>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\ntypedef long long LL;\n#define MAXN 300010\nint A, B, C = ~(1<<31), M = (1<<16)-1;\nint myR...
aoj_1343_cpp
Problem I: Hidden Tree Consider a binary tree whose leaves are assigned integer weights. Such a tree is called balanced if, for every non-leaf node, the sum of the weights in its left subtree is equal to that in the right subtree. For instance, the tree in the following figure is balanced. Figure I.1. A balanced tree A balanced tree is said to be hidden in a sequence A , if the integers obtained by listing the weights of all leaves of the tree from left to right form a subsequence of A . Here, a subsequence is a sequence that can be derived by deleting zero or more elements from the original sequence without changing the order of the remaining elements. For instance, the balanced tree in the figure above is hidden in the sequence 3 4 1 3 1 2 4 4 6, because 4 1 1 2 4 4 is a subsequence of it. Now, your task is to find, in a given sequence of integers, the balanced tree with the largest number of leaves hidden in it. In fact, the tree shown in Figure I.1 has the largest number of leaves among the balanced trees hidden in the sequence mentioned above. Input The input consists of multiple datasets. Each dataset represents a sequence A of integers in the format N A 1 A 2 . . . A N where 1 ≤ N ≤ 1000 and 1 ≤ A i ≤ 500 for 1 ≤ i ≤ N . N is the length of the input sequence, and A i is the i -th element of the sequence. The input ends with a line consisting of a single zero. The number of datasets does not exceed 50. Output For each dataset, find the balanced tree with the largest number of leaves among those hidden in A , and output, in a line, the number of its leaves. Sample Input 9 3 4 1 3 1 2 4 4 6 4 3 12 6 3 10 10 9 8 7 6 5 4 3 2 1 11 10 9 8 7 6 5 4 3 2 1 1 8 1 1 1 1 1 1 1 1 0 Output for the Sample Input 6 2 1 5 8
[ { "submission_id": "aoj_1343_10853732", "code_snippet": "#include<map>\n#include<set>\n#include<cmath>\n#include<queue>\n#include<cctype>\n#include<cstdio>\n#include<vector>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\ntypedef long long LL;\n#define MAXN 1010\nconst int mt = 131072;\nint a[MA...
aoj_1348_cpp
Problem D: Space Golf You surely have never heard of this new planet surface exploration scheme, as it is being carried out in a project with utmost secrecy. The scheme is expected to cut costs of conventional rovertype mobile explorers considerably, using projected-type equipment nicknamed "observation bullets". Bullets do not have any active mobile abilities of their own, which is the main reason of their cost-efficiency. Each of the bullets, after being shot out on a launcher given its initial velocity, makes a parabolic trajectory until it touches down. It bounces on the surface and makes another parabolic trajectory. This will be repeated virtually infinitely. We want each of the bullets to bounce precisely at the respective spot of interest on the planet surface, adjusting its initial velocity. A variety of sensors in the bullet can gather valuable data at this instant of bounce, and send them to the observation base. Although this may sound like a conventional target shooting practice, there are several issues that make the problem more difficult. There may be some obstacles between the launcher and the target spot. The obstacles stand upright and are very thin that we can ignore their widths. Once the bullet touches any of the obstacles, we cannot be sure of its trajectory thereafter. So we have to plan launches to avoid these obstacles. Launching the bullet almost vertically in a speed high enough, we can easily make it hit the target without touching any of the obstacles, but giving a high initial speed is energyconsuming. Energy is extremely precious in space exploration, and the initial speed of the bullet should be minimized. Making the bullet bounce a number of times may make the bullet reach the target with lower initial speed. The bullet should bounce, however, no more than a given number of times. Although the body of the bullet is made strong enough, some of the sensors inside may not stand repetitive shocks. The allowed numbers of bounces vary on the type of the observation bullets. You are summoned engineering assistance to this project to author a smart program that tells the minimum required initial speed of the bullet to accomplish the mission. Figure D.1 gives a sketch of a situation, roughly corresponding to the situation of the Sample Input 4 given below. Figure D.1. A sample situation You can assume the following. The atmosphere of the planet is so thin that atmospheric resistance can be ignored. The planet is large enough so that its surface can be approximated to be a completely flat plane. The gravity acceleration can be approximated to be constant up to the highest points a bullet can reach. These mean that the bullets fly along a perfect parabolic trajectory. You can also assume the following. The surface of the planet and the bullets are made so hard that bounces can be approximated as elastic collisions. In other words, loss of kinetic energy on bounces can be ignored. As we can also ignore the atmospheric resist ...(truncated)
[ { "submission_id": "aoj_1348_4963406", "code_snippet": "#include<bits/stdc++.h> \nusing namespace std;\ntypedef long long ll;\ntemplate<typename T1,typename T2> bool chmin(T1 &a,T2 b){if(a<=b)return 0; a=b; return 1;}\ntemplate<typename T1,typename T2> bool chmax(T1 &a,T2 b){if(a>b)return 0; a=b; return 1;}...
aoj_1349_cpp
Problem E: Automotive Navigation The International Commission for Perfect Cars (ICPC) has constructed a city scale test course for advanced driver assistance systems. Your company, namely the Automotive Control Machines (ACM), is appointed by ICPC to make test runs on the course. The test course consists of streets, each running straight either east-west or north-south. No streets of the test course have dead ends, that is, at each end of a street, it meets another one. There are no grade separated streets either, and so if a pair of orthogonal streets run through the same geographical location, they always meet at a crossing or a junction, where a car can turn from one to the other. No U-turns are allowed on the test course and a car never moves outside of the streets. Oops! You have just received an error report telling that the GPS (Global Positioning System) unit of a car running on the test course was broken and the driver got lost. Fortunately, however, the odometer and the electronic compass of the car are still alive. You are requested to write a program to estimate the current location of the car from available information. You have the car's location just before its GPS unit was broken. Also, you can remotely measure the running distance and the direction of the car once every time unit. The measured direction of the car is one of north, east, south, and west. If you measure the direction of the car while it is making a turn, the measurement result can be the direction either before or after the turn. You can assume that the width of each street is zero. The car's direction when the GPS unit was broken is not known. You should consider every possible direction consistent with the street on which the car was running at that time. Input The input consists of a single test case. The first line contains four integers $n$, $x_0$, $y_0$, $t$, which are the number of streets ($4 \leq n \leq 50$), $x$- and $y$-coordinates of the car at time zero, when the GPS unit was broken, and the current time ($1 \leq t \leq 100$), respectively. $(x_0, y_0)$ is of course on some street. This is followed by $n$ lines, each containing four integers $x_s$, $y_s$, $x_e$, $y_e$ describing a street from $(x_s, y_s)$ to $(x_e, y_e)$ where $(x_s, y_s) \ne (x_e, y_e)$. Since each street runs either east-west or north-south, $x_s = x_e$ or $y_s = y_e$ is also satisfied. You can assume that no two parallel streets overlap or meet. In this coordinate system, the $x$- and $y$-axes point east and north, respectively. Each input coordinate is non-negative and at most 50. Each of the remaining $t$ lines contains an integer $d_i$ ($1 \leq d_i \leq 10$), specifying the measured running distance from time $i − 1$ to $i$, and a letter $c_i$, denoting the measured direction of the car at time $i$ and being either N for north, E for east, W for west, or S for south. Output Output all the possible current locations of the car that are consistent with the measurements. If they are ...(truncated)
[ { "submission_id": "aoj_1349_10848168", "code_snippet": "#include<map>\n#include<set>\n#include<cmath>\n#include<queue>\n#include<cctype>\n#include<cstdio>\n#include<vector>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\ntypedef long long LL;\nbool go[55][55][4];\nbool f[55][55][1010][4];\nstru...