<?php
fscanf(STDIN,"%d %d",$N,$X);
$input=explode(' ',trim(fgets(STDIN))); //inputの数は$N

$count = 0;
$out = 0;
for ($i = 0; $i <= $N; $i++) {
  $out = $out + intval($input[$i]);
  if($out <= $X) {
    $count++;
  }
}
echo $count+1;


Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


<?php
fscanf(STDIN, "%d %d", $n, $x);
$c = 1; $d = 0;
$l = array_map('intval', explode(' ', trim(fgets(STDIN))));
for ($i=0; $i < $n; $i++) {
  $d += $l[$i];
  if ($d > $x) {
    $c = $i + 1;
    break;
  }
}
echo $c;
?>


<?php
//error_reporting(0);
//$N = trim(fgets(STDIN));
list($W,$H,$x,$y) =  explode(" ",trim(fgets(STDIN)));
//$L =  explode(" ",trim(fgets(STDIN)));
$pat = 0;
if ($x*2==$W && $y*2==$H) {
  $pat=1;
}
printf("%f %d\n",$W*$H/2,$pat);

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


<?php
list($n,$k)=explode(" ",trim(fgets(STDIN)));
if($k==1){
  echo 0;
}else{
  echo $n-$k;
}

Score : 100 points

Problem Statement

Takahashi is distributing N balls to K persons.

If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls?

Constraints

1 \leq K \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the maximum possible difference in the number of balls received.

Sample Input 1

3 2

Sample Output 1

1

The only way to distribute three balls to two persons so that each of them receives at least one ball is to give one ball to one person and give two balls to the other person.

Thus, the maximum possible difference in the number of balls received is 1.

Sample Input 2

3 1

Sample Output 2

0

We have no choice but to give three balls to the only person, in which case the difference in the number of balls received is 0.

Sample Input 3

8 5

Sample Output 3

3

For example, if we give 1, 4, 1, 1, 1 balls to the five persons, the number of balls received between the person with the most balls and the person with the fewest balls would be 3, which is the maximum result.


<?php

fscanf(STDIN, "%d %d", $n, $k);

if($k != 1){
    echo $n - $k;
}else{
    echo 0;
}


Score : 300 points

Problem Statement

There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).

We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:

Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.

Find the minimum total cost required to collect all the balls when we optimally choose p and q.

Constraints

1 \leq N \leq 50

|x_i|, |y_i| \leq 10^9

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum total cost required to collect all the balls.

Sample Input 1

2
1 1
2 2

Sample Output 1

1

If we choose p = 1, q = 1, we can collect all the balls at a cost of 1 by collecting them in the order (1, 1), (2, 2).

Sample Input 2

3
1 4
4 6
7 8

Sample Output 2

1

If we choose p = -3, q = -2, we can collect all the balls at a cost of 1 by collecting them in the order (7, 8), (4, 6), (1, 4).

Sample Input 3

4
1 1
1 2
2 1
2 2

Sample Output 3

2


<?php
fscanf(STDIN, "%d", $N);
  $numArray = explode(" ", trim(fgets(STDIN)));
$str= array();
rsort($numArray);

for($i=1;isset($numArray[1])&&$i<$N&&$numArray[1]>0;$i++){
    $str[]=$numArray[$N-$i]." ".$numArray[1];
    $numArray[$N-$i]=$numArray[$N-$i]-$numArray[1];
    array_splice($numArray, 1, 1);
}

sort($numArray);
$M=count($numArray);
for($j=1;$j<$M;$j++){
  $str[]= $numArray[$j]." ".$numArray[0];
  $numArray[0]=$numArray[$j]-$numArray[0];
}

  echo ($numArray[0])."\n";
foreach($str as $s){
  echo ($s)."\n";
}

?>

Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0


<?php
$n = (int)trim(fgets(STDIN));

$input = explode(' ', trim(fgets(STDIN)));
$as = [];
foreach ($input as $v) {
	$as[] = (int)$v;
}
sort($as);

if ($n === 2) {
	echo ($as[1] - $as[0]) . PHP_EOL;
	echo $as[1] . ' ' . $as[0];
	exit();
}
$tmp = $as[0] - $as[1];
$result = [];
$result[] = $as[0] . ' ' . $as[1];
for ($i=2; $i < $n; $i++) {
	if ($i === $n-1) {
		$result[] = $as[$i] . ' ' . $tmp;
		$tmp = $as[$i] - $tmp;
	}else{
		$tmp = $tmp - $as[$i];
		$result[] = $tmp . ' ' . $as[$i];
	}
}
echo $tmp . PHP_EOL;
echo implode(PHP_EOL, $result);


<?php
$stdin = fscanf(STDIN, "%d %d %d\n");

sort($stdin);

print($stdin[0] + $stdin[1]);

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


<?php
$arr = explode(" ", trim(fgets(STDIN)));
sort($arr);
echo $arr[0]+$arr[1];
?>


<?php
  $int = explode(" ",fgets(STDIN));
	sort($int);
	echo $int[0] + $int[1];
?>


<?php
  define("N", intval(trim(fgets(STDIN))));
	$weightList = explode(' ',trim(fgets(STDIN)));
	$preDif = null;
	$curDif = 0;
	for($t=1; $t<N; $t++){

    $s1 = array_sum(array_slice($weightList,0,$t));
    $s2 = array_sum(array_slice($weightList,$t));
		$curDif = abs($s1 - $s2);
    if($curDif > $preDif && is_numeric($preDif)){
      break;
    }
      $preDif = $curDif;
    }

    echo $preDif;

?>

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


<?php

function fibonacci($n) {
  $f0 = $f1 = 1;
  for ($i = 2; $i <= $n; $i++) {
    $tmp = $f1;
    $f1 = $f0 + $f1;
    $f0 = $tmp;
  }

  return $f1;
}

$stdin = fscanf(STDIN, "%d %d\n");
for ($i = 0; $i < $stdin[1]; $i++) {
  $array[] = trim(fgets(STDIN)) * 1;
  if ($i != 0 && $array[$i] - $array[$i - 1] == 1) {
    print(0);
    return;
  }
}
$array[] = $stdin[0] + 1;
for ($i = 0; $i < count($array); $i++) {
  if ($i == 0) {
    $f = $array[$i] - 1;
    $sum = fibonacci($f);
    continue;
  }

  $f = $array[$i] - $array[$i - 1] - 2;
  $sum *= fibonacci($f);
  $sum %= 1000000007;
}

print($sum);

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

S is a string of length N consisting of . and #.

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes


<?php

fscanf(STDIN, "%d", $n);

$tree =[];
$counttree = [];

init($n);
$k = $n -1;
while($k--){
    fscanf(STDIN, "%s %s", $x, $y);
    $hen[] = [$x,$y];
    set($x, $y);
}
$str = trim(fgets(STDIN));
$str_array = explode(" ", $str);
$newcounttree =$counttree;
foreach($counttree as $n => $value){
    foreach($tree[$n] as $valuen => $hoge){
        $newcounttree[$n] += $counttree[$valuen]/ 20000;
    }
}

sort($str_array);
asort($newcounttree);
$i=0;
$goalstr = "";
foreach($newcounttree as $num => $value){
    $goaltree[$num] = $str_array[$i];
    $i++;
}
$sum = 0;
foreach($hen as $array){
    $sum += min($goaltree[$array[0]],$goaltree[$array[1]]);
}
ksort($goaltree);
echo $sum.PHP_EOL.implode(" ",$goaltree);

function init($n){
    global $tree;
    global $counttree;
    for($i=1;$i<=$n;$i++){
        $tree[$i] = [];
        $counttree[$i] = 0;
    }
}

function set($x, $y){
    global $tree;
    global $counttree;
    if(!isset($tree[$x][$y])) {
        $tree[$x][$y] = 1;
        $counttree[$x]++;
    }
    if(!isset($tree[$y][$x])) {
        $tree[$y][$x] = 1;
        $counttree[$y]++;
    }
}

Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.


<?php
fscanf(STDIN, '%d %d', $all, $piece);
$piece += $all * 3;
echo floor($piece / 2)."\n";

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


<?php
list($n) = explode(" ", trim(fgets(STDIN)));
$ranks = [];
$names_pts = [];
while ($line = fgets(STDIN)) {
	list($name, $pt) = explode(" ", trim($line));
	$ranks["{$name}_{$pt}"] = 1;
	$names_pts[$name][] = $pt;
}
$names = array_keys($names_pts);

sort($names);
foreach ($names_pts as &$name_pts){
	rsort($name_pts);
}
unset($name_pts);

$rank = 0;
foreach ($names as $name){
	foreach ((array)$names_pts[$name] as $pt){
		$rank++;
		$ranks["{$name}_{$pt}"] = $rank;
	}
}

echo implode("\n", $ranks);

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


<?php
fscanf(STDIN,"%d %d",$N,$K);
$V = fgets(STDIN);
$arrayV = explode(" ",$V);
$max = 0;
if($K === 1){
  echo max($arrayV[0],$arrayV[$N-1]);
}else{
  for($i=0;$i<=$K;$i++){
    for($j=0;$j<=$K-$i;$j++){
      for($m=0;$m<=$K-$i-$j && $m<$i+$j;$m++){
        $value = calculate($i,$j,$m,$arrayV,$N);
        if($value > $max){
          $max = $value;
        }
      }
    }
  }
  echo $max;
}

function calculate($left,$right,$delete,$array,$N){
  $arrayResult = array();
  for($i=0;$i<$left;$i++){
    $arrayResult[] = $array[$i];
  }
  for($i=0;$i<$right;$i++){
    $arrayResult[] = $array[$N-1-$i];
  }
  for($i=0;$i<$delete;$i++){
    $mins = array_keys($arrayResult, min($arrayResult));
    unset($arrayResult[$mins[0]]);
  }
  return array_sum($arrayResult);
}


<?php
fscanf(STDIN,"%d %d",$N,$K);
$V = fgets(STDIN);
$arrayV = explode(" ",$V);
$max = 0;
if($K === 1){
  echo max($arrayV[0],$arrayV[$N-1]);
}else{
  for($i=0;$i<$K;$i++){
    for($j=0;$j<$K;$j++){
      if($i+$j > $K){
        break;
      }
      for($m=0;$m<$K;$m++){
        if($i+$j+$m > $K || $i+$j <= $m){
          break;
        }
        $value = calculate($i,$j,$m,$arrayV,$N);
        if($value > $max){
          $max = $value;
        }
      }
    }
  }
  echo $max;
}

function calculate($left,$right,$delete,$array,$N){
  $arrayResult = array();
  for($i=0;$i<$left;$i++){
    $arrayResult[] = $array[$i];
  }
  for($i=0;$i<$right;$i++){
    $arrayResult[] = $array[$N-1-$i];
  }
  for($i=0;$i<$delete;$i++){
    $mins = array_keys($arrayResult, min($arrayResult));
    unset($arrayResult[$mins[0]]);
  }
  return array_sum($arrayResult);
}


<?php

fscanf(STDIN,"%d %d",$n, $k);
$values = explode(" ", trim(fgets(STDIN)));

$max =0;
for($i=0;$i<=$k;$i++){
    $left=[];
    for($ii=0;$ii<$i;$ii++){
        $left[]=$values[$ii] ?? 0;
    }

    for($j=0;$j<=($k-$i);$j++){
        $right = [];

        for($jj=0;$jj<$j;$jj++){

            $right[]=$values[$n - 1 - $jj] ?? 0;
        }
        $gomi = $k - $i -$j;
        $array = [];
        $array = array_merge($left,$right);
        sort($array);
        for($l=0;$l<$gomi;$l++){
            if(!isset($array[$l])){
                break;
            }
            if($array[$l] < 0){
                $array[$l] =0;
            }else{
                break;
            }
        }
        $max = max($max, array_sum($array));
    }
}

echo $max;


<?php
/**
 * ABC128
 * D - equeue
 */

// $s = trim(fgets(STDIN));
// fscanf(STDIN, "%d %d", $a, $b);
// $n = array_map('intval', explode(' ', trim(fgets(STDIN))));

fscanf(STDIN, "%d %d", $n, $k);
$v = array_map('intval', explode(' ', trim(fgets(STDIN))));

$r = min($n, $k);
$point_max = 0;
for ($a = 0; $a <= $r; $a++) { // Aの数
    for ($b = 0; $b <= $r - $a; $b++) { // Bの数
        $hands = [];
        // Aの操作
        for ($i = 0; $i < $a; $i++) {
            $hands[] = $v[$i];
        }
        // Bの操作
        for ($i = 0; $i < $b; $i++) {
            $hands[] = $v[$n - 1 - $i];
        }
        // C・Dの操作
        sort($hands);
        for ($i = 0; $i < $k - $a - $b; $i++) {
            unset($hands[$i]);
        }
        $point = array_sum($hands);
        if ($point > $point_max) {
            $point_max = $point;
        }
    }
}

echo $point_max, PHP_EOL;


Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


<?php
	list($n,$m) =  explode(" ",trim(fgets(STDIN)));
	$left = array();
	$right = array();

	for($i=0; $i<$m; $i++) {
		fscanf(STDIN,"%d %d",$x,$y);
		$left[$i] = $x;
		$right[$i] = $y;
	}

	$ans = min($right) - max($left) + 1;

	if ($ans < 0) {
		echo 0;
	else {
		echo $ans;
	}
?>

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


<?php
  	fscanf(STDIN, '%d %d', $card_num, $gate_num);
	$bottom = 1;
	$top = $card_num;
	for($i = 0; $i < $gate_num; $i++){
      	fscanf(STDIN, '%d %d', $min, $max);
      	$bottom = max($bottom, $min);
      	$top = min($top, $max);
    }
	if($top < $bottom){
      	echo 0;
      	exit;
    }
	echo $top - $bottom + 1;


<?php

#C - Prison

fscanf(STDIN, "%d %d", $N, $M);

# 最初のゲートを取得
fscanf(STDIN, "%d %d", $begin, $end);
$back_gate = range($begin, $end);

for ( $i = 1 ; $i < $M ; $i++ ) {
    fscanf(STDIN, "%d %d", $begin, $end);
    $next_gate = range($begin, $end);
    $back_gate = array_intersect($back_gate, $next_gate);
    if (count($back_gate) == 0) {
        break;
    }
}

echo count($back_gate);


<?php
list($n,$m)=explode(" ",trim(fgets(STDIN)));
$l=1;
$r=$n;
$i=0;
while($i<$m){
  list($a,$b)=explode(" ",trim(fgets(STDIN)));
  $l=min($l,$a);
  $r=min($r,$b);
  ++$i;
}
echo max($r-$l+1,0);


<?php

#C - Prison

fscanf(STDIN, "%d %d", $N, $M);

# 最初のゲートを取得
fscanf($STDIN, "%d %d", $begin, $end);
$back_gate = range($begin, $end);

for ( $i = 1 ; $i < $M ; $i++ ) {
    fscanf($STDIN, "%d %d", $begin, $end);
    $next_gate = range($begin, $end);
    $back_gate = array_intersect($back_gate, $next_gate);
}

echo count($back_gate);


<?php
fscanf(STDIN, "%d %d", $n, $k);
fscanf(STDIN, "%s", $s);
$char = strtolower(substr($s, $k-1, 1));
$s = substr_replace($s, $char, $k-1, 1);
echo $s;

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


<?php

$int = explode(" ",trim(fgets(STDIN)));
$char = str_split(trim(fgets(STDIN)));
$result;
for($i=0;$i<$int[0];$i++){
  if($i == $int[1]){
    $result .= mb_strtolower($char[$i]);
  }else{
  	$result = $result.$char[$i];
  }
}

echo $result;

?>


<?php
$int = explode(" ",trim(fgets(STDIN)));
$char = str_split(trim(fgets(STDIN)));
$result;
for($i=0;$i<$int[0];$i++){
  if($i === $int[1]){
    $result += $char[i];
  }
  $resulr += $char[i];
}

echo $result;

?>


<?php
class MyTest {

    private function getInput() {
        while (!empty($input = fgets(STDIN))) {
            $ret[] = trim($input);
        }
        return $ret;
    }

    private function main($input) {
        $line1 = explode(' ', $input[0]);
        $n = $line1[0];
        $k = $line1[1];
        $str = $input[1];
        $ret = '';
        for($i = 0; $i < $n;  $i++){
            if ($i == $k - 1) {
                $txt = strtolower($str[$i]);
            } else {
                $txt = $str[$i];
            }
            $ret .= $txt;
        }
        echo $ret;
    }

    public function run() {
        $input = self::getInput();
        self::main($input);
    }

}

MyTest::run();


Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


<?php
$string = trim(fgets(STDIN));
$firstHalf = ltrim(substr($string, 0, 2), '0');
$secondHalf = ltrim(substr($string, 2), '0');

if (0 < $firstHalf && $firstHalf <= 12 && 0 < $secondHalf && $secondHalf <= 12) {
	echo 'AMBIGUOUS', PHP_EOL;
} elseif (0 < $firstHalf && $firstHalf <= 12 && 0 < $secondHalf && $secondHalf <= 99) {
    echo 'MMYY', PHP_EOL;
} elseif (0 < $firstHalf && $firstHalf <= 99 && 0 < $secondHalf && $secondHalf <= 12) {
	echo 'YYMM', PHP_EOL;
} else {
	echo 'NA', PHP_EOL;
}


<?php
class Scanner {
    private $arr = [];
    private $count = 0;
    private $pointer = 0;
    public function next() {
        if($this->pointer >= $this->count) {
            $str = trim(fgets(STDIN));
            $this->arr = explode(' ', $str);
            $this->count = count($this->arr);
            $this->pointer = 0;
        }
        $result = $this->arr[$this->pointer];
        $this->pointer++;
        return $result;
    }
    public function hasNext() {
        return $this->pointer < $this->count;
    }
    public function nextInt() {
        return (int)$this->next();
    }
    public function nextDouble() {
        return (double)$this->next();
    }
}

class out {
    public static function println($str = "") {
        echo $str . PHP_EOL;
    }
}

$sc = new Scanner();
$s = $sc->next();

$A = $s[0] . $s[1];
$B = $s[2] . $s[3];
$isYYMM = $B >= '01' && $B <= '12';
$isMMYY = $A >= '01' && $A <= '12';
switch (true) {
    case $isYYMM && $isMMYY:
        $result = 'AMBIGUOUS';
        break;
    case $isYYMM && !$isMMYY:
        $result = 'YYMM';
        break;
    case !$isYYMM && $isMMYY:
        $result = 'MMYY';
        break;
    default:
        $result = 'NA';
        break;
}

out::println($result);


Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


<?php
#C - Dice and Coin

fscanf(STDIN, "%d %d", $N, $K);

$P = [];

#サイコロの目が$iの時、得点が$K以上になるためには、$coin_count連続で表が出る必要がある。
for ( $i = 1; $i <= $N; $i++ ) {

    #scoreが$K以上になるためのコイントス回数
    $score = $i;
    $coin_count = 0;
    while ( $K > $score) {
        $score *= 2;
        $coin_count++;
    }

    #コイントス回数からサイコロが$iの時の分母を計算
    $denominator = 1;
    for ( $j = 1; $j <= $coin_count; $j++ ) {
        $denominator *= 2;
    }

    $score = $i;
    $coin_count = 0;

    $P[] = $N * $denominator;
}

$numerator = 0;
foreach ($P as $el) {
    $numerator += ($P[0] / $el);
}

$probability = ($numerator / $P[0]);

echo $probability;


<?php
class MyTest {

    private function main() {
        fscanf(STDIN, "%d %d", $n, $k);
        $ret = 0;
        for($i = $n; $i > 0; $i--){
            if ($i >= $k) {
                $ret += 1/$n;
            } else {
                $tmp = 1/$n;
                $j = $i;
                while($j < $k) {
                    $j *= 2;
                    $tmp*=0.5;
                }
                $ret += $tmp;
            }
        }
        echo $ret."\n";
    }

    public function run() {
        self::main();
    }

}

MyTest::run();


<?php
//error_reporting(0);
//$N = trim(fgets(STDIN));
list($R,$G,$B,$N) =  explode(" ",trim(fgets(STDIN)));

$ret=0;
for($i=0;$i<=$N;$i++) {
  for($j=0;$j<=$N;$j++) {
    //この時点でわかりそう
    $left = $N - ($i*$R+$j*$G);
    if ($left < 0) continue;
    if (($left % $B)==0) {
      $ret++;
    }
  }
}
printf("%d\n",$ret);

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


<?php
$n = fgets(STDIN);
$row = explode(" ", $n);
$result = floor($row[2]/$row[0])*$row[1];
echo $result;


<?php
fscanf(STDIN, "%d %d %d", $a, $b, $t);

$biscuit = 0;

for ($i = $a; $i <= $t; $i+= $a) {
    $biscuit += $b;
}

echo $biscuit, "\n";


<?php

$parts = explode(" ",trim(fgets(STDIN)));
$A = $parts[0];
$B = $parts[1];
$T = $parts[2];

echo floor( ($T+0.5)/$A)*$B;


<?php
fscanf(STDIN, "%d", $n);
$v = explode(' ', trim(fgets(STDIN)));
$c = explode(' ', trim(fgets(STDIN)));
$x = 0;
for ($i = 0; $i < $n; $i++) {
	$d = $v[$i] - $c[$i];
	if ($d > 0) $x += $d;
}
echo $x;

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


<?php

while ($stdin = fgets(STDIN)) {
    $line[] = trim($stdin);
}
foreach ($line as $key => $value) {
    $data[] = explode(' ', $value);
}

//foreach ($data as &$line) {
//    $line = array_map(function($val) { return (int)$val; }, $line);
//}

$N = $data[0][0];
$A = $data[1];

$min = null;
$sum = 0;
$minusCnt = 0;
for ($i = 0; $i < $N; $i++) {
    $abs = abs($A[$i]);
    if (is_null($min) || $min > $abs) {
        $min = $abs;
    }
    $sum += $abs;
    if ($A[$i] < 0) {
        $minusCnt++;
    }
}

if ($minusCnt % 2 === 1) {
    $sum -= $min * 2;
}
$ans = $sum;

printf('%d', $ans);

?>

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

The output may not fit into a 32-bit integer type.


<?php
$n = trim(fgets(STDIN));
$chars = str_split(trim(fgets(STDIN)));
$k = trim(fgets(STDIN));

$kth = $chars[$k - 1];
foreach ($chars as $char) {
	if ($char === $kth) {
    	echo $char;
    } else {
    	echo '*';
    }
}
echo PHP_EOL;

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


<?php
  $N = trim(fgets(STDIN));
  $S = trim(fgets(STDIN));
  $white = 0;
  $black = 0;

  for($i = 0; $i < $N; $i++){
    if($S[$i] == "."){
      $white++;
    }else{
      $black++;
    }
  }

  if($white > $black){
    echo $black."\n";
  }else{
    echo $white."\n";
  }

?>

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

1 \leq N \leq 2\times 10^5

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


<?php
/**
 * ABC124
 * A - Buttons
 */

fscanf(STDIN, "%d %d", $a, $b);

if ($a - $b >= 2) {
    $result = $a * 2 - 1;
} elseif ($b - $a >= 2) {
    $result = $b * 2 - 1;
} else {
    $result = $a + $b;
}

echo $result, PHP_EOL;

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


<?php
list($a, $b) = explode(' ', trim(fgets(STDIN)));

if ($a === $b) {
	echo $a + $b, PHP_EOL;
    exit();
}

echo (max($a, $b) + max($a, $b) - 1), PHP_EOL;


<?php
  list($n) = explode(" ", trim(fgets(STDIN)));

  $a = explode(" ", trim(fgets(STDIN)));

  $ans = 1;

  $max = $a[0];
  for ($i=1; $i<$n; $i++) {
    if($max <= $a[$i]){
      $ans++;
      $max = $a[$i];
    }
  }
  echo $ans;

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


<?php
fscanf(STDIN,'%s',$s);
// echo gettype($s);
$s_number = strlen($s);
$s_array = str_split($s);

// 黒白黒
$count1 = 0;
for($i=1;$i<$s_number;$i++){
    if($i % 2 === 0){
        if($s_array[$i] != 1){
            $count1++;
        }else {
            if($s_array[$i] != 0){
                $count1++;
            }
        }
    }
}

$count2 = 0;
for ($i = 0; $i < $s_number; ++$i) {
    if ($i % 2 === 0) {
        // $S[$i] === 1である必要がある
        if ($s_array[$i] != 0){
          $count2++;
        }
    } else {
        if ($s_array[$i] != 1){
         $count2++;
        }
    }
}
echo min($count1,$count2);
?>

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


<?php
//error_reporting(0);
$S = trim(fgets(STDIN));
//list($A,$B) =  explode(" ",trim(fgets(STDIN)));
//$H=explode(" ",trim(fgets(STDIN)));
$len = strlen($S);
$bs=0;
$ws=1;
$bcnt=0;
$wcnt=0;
for($i=0;$i<$len;$i++) {
  if ($bs == $S[$i]) {
    $bcnt++;
  }
  if ($ws == $S[$i]) {
    $wcnt++;
  }
  $bs = rev($bs);
  $ws = rev($ws);
}
printf("%d\n",min($wcnt,$bcnt));
function rev($i)
{
  if ($i==0) return 1;
  else return 0;
}


<?php
fscanf(STDIN,"%d %d",$N,$K);
$S=strval(trim(fgets(STDIN)));
$length = strlen($S);
$array1 = [];
$array0 = [];

while(substr($S,0,1) !== false){
  if(substr($S,0,1) === "1"){
    if(strpos($S,"0") === false){
      $array1[] = strlen($S);
      $array0[] = 0;
      break;
    }else{
      $S = substr($S,strpos($S,"0"),strlen($S)-1);
      $array1[] = $length-strlen($S);
      $length = strlen($S);
    }
  }else{
    $array1[] = 0;
  }
  if(substr($S,0,1) === "0"){
    if(strpos($S,"1") === false){
      $array0[] = strlen($S);
      break;
    }else{
      $S = substr($S,strpos($S,"1"),strlen($S)-1);
      $array0[] = $length-strlen($S);
      $length = strlen($S);
    }
  }else{
    $array0[] = 0;
  }
}

$size = count($array1);
if($K>=$size){
  $max = array_sum($array1)+array_sum($array0);
}else{
  $value = 0;
  $max = $array1[0]+$array0[0];
  for($i=0;$i<$size-$K+1;$i++){
    if($i===$size-$K && $i===0){
      for($j=0;$j<$K;$j++){
        $value += $array1[$i+$j];
      }
    }elseif($i===0){
      for($j=0;$j<$K+1;$j++){
        $value += $array1[$i+$j];
      }
    }elseif($i===$size-$K){
      //何もしない
    }else{
      $value += $array1[($K-1)+$i+1];
    }
    if($i===0){
      for($j=0;$j<$K;$j++){
        $value += $array0[$i+$j];
      }
    }else{
      $value += $array0[($K-1)+$i];
    }
    if($value > $max){
      $max = $value;
    }
    $value -= $array1[$i];
    $value -= $array0[$i];
  }
}
echo $max;

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


<?php
/**
 * ABC124
 * D - Handstand
 */

fscanf(STDIN, "%d %d", $n, $k);
$s = trim(fgets(STDIN));

$number_list = [];
$length = strlen($s);

if ($s[0] === '0') {
    $number_list[] = 0;
}
$j = 0;
for ($i = 0; $i < $length;) {
    while ($j < $length and $s[$i] === $s[$j]) {
        $j++;
    }
    $number_list[] = $j - $i;
    $i = $j;
}
if ($s[$length - 1] === '0') {
    $number_list[] = 0;
}

// 累積和
$cumulative_sum_list = [0];
foreach ($number_list as $key => $number) {
    $cumulative_sum_list[$key + 1] = $cumulative_sum_list[$key] + $number;
}

$cumulative_sum_list_length = count($cumulative_sum_list);

$result = 0;

for ($left = 0; $left < $cumulative_sum_list_length; $left += 2) {
    $right = min($left + $k * 2 + 1, $cumulative_sum_list_length - 1);
    $total = $cumulative_sum_list[$right] - $cumulative_sum_list[$left];
    if ($result < $total) {
        $result = $total;
    }
}

echo $result, PHP_EOL;


<?php
fscanf(STDIN, "%d", $a);
fscanf(STDIN, "%d", $e);
fscanf(STDIN, "%d", $k);
echo ($e - $a <= $k) ? 'Yay' : ':(';

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


<?php
$a = (int)trim(fgets(STDIN));
$b = (int)trim(fgets(STDIN));
$c = (int)trim(fgets(STDIN));
$d = (int)trim(fgets(STDIN));
$e = (int)trim(fgets(STDIN));
$k = (int)trim(fgets(STDIN));

if ($e-$a > $k) {
	echo ':(';
}else{
	echo 'Yay!';
}


<?php

// 入力
fscanf(STDIN, "%d", $a);
fscanf(STDIN, "%d", $b);
fscanf(STDIN, "%d", $c);
fscanf(STDIN, "%d", $d);
fscanf(STDIN, "%d", $e);
fscanf(STDIN, "%d", $k);

// ソート
$cities = [$a, $b, $c, $d, $e];
asort($cities);
if (($cities[4] - $cities[0]) > $k) {
    // 出力
    echo ":(\n";
} else {
    // 出力
    echo "Yay!\n";
}


<?php

fscanf(STDIN, '%d', $x['a']);
fscanf(STDIN, '%d', $x['b']);
fscanf(STDIN, '%d', $x['c']);
fscanf(STDIN, '%d', $x['d']);
fscanf(STDIN, '%d', $x['e']);

$min_x = 0;
$min_mod = 10;
foreach ($x as $v) {
    if (0 <  $v % 10 && $min_mod > $v % 10) {
        $min_x = $v;
        $min_mod = $v % 10;
    }
}

$sum = 0;
$cnt = 0;
foreach ($x as $v) {
    if ($cnt == 0 && $min_x == $v) {
        $cnt = 1;
        continue;
    }

    $sum += ceil($v / 10) * 10;
}

$sum += $min_x;

echo $sum . PHP_EOL;

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


<?php
$n = (int) trim(fgets(STDIN));

$count = [0,0,0,0,0];
$count[0] = (int) trim(fgets(STDIN));
$count[1] = (int) trim(fgets(STDIN));
$count[2] = (int) trim(fgets(STDIN));
$count[3] = (int) trim(fgets(STDIN));
$count[4] = (int) trim(fgets(STDIN));

$person = [
    $n , 0 , 0 , 0 , 0 , 0
];

$ans = 0;

while ($person[5] != $n) {
    ++$ans;
    for($i = 4; $i >= 0; $i--){
        $move = min($person[$i] , $count[$i]);
        $person[$i + 1] += $move;
        $person[$i] -= $move;
    }
}

echo $ans . "\n";

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


<?php
$a = array();
fscanf(STDIN, "%d", $n);
for($i = 0;$i < 5;$i ++) {
	fscanf(STDIN, "%d", $a[$i]);
}

$min = min($a);
$div = intval($n / $min);
$ret = $div + 5;
print($ret."\n");

?>


<?php

fscanf(STDIN, "%d", $N);
fscanf(STDIN, "%d", $min);
    for ($i=0; $i < 4; $i++) {
        fscanf(STDIN, "%d", $now);
        if ($min > $now) {
            $min = $now;
        }
    }
    $result = 4 + floor($N / $min);
    if ($N % $min >= 1) {
        $result++;
    }
    echo $result;


<?php
/**
 * ABC123
 * D - Cake 123
 */

// $s = trim(fgets(STDIN));
// fscanf(STDIN, "%d %d", $a, $b);
// $n = array_map('intval', explode(' ', trim(fgets(STDIN))));

fscanf(STDIN, "%d %d %d %d", $x, $y, $z, $k);
$a_list = array_map('intval', explode(' ', trim(fgets(STDIN))));
$b_list = array_map('intval', explode(' ', trim(fgets(STDIN))));
$c_list = array_map('intval', explode(' ', trim(fgets(STDIN))));
$ab_list = [];
foreach ($a_list as $a) {
    foreach ($b_list as $b) {
        $ab_list[$a . ',' . $b] = $a + $b;
    }
}

arsort($ab_list);
$ab_list = array_slice($ab_list, 0, $k, true);

$abc_list = [];
foreach ($ab_list as $key => $ab) {
    foreach ($c_list as $c) {
        $abc_list[$key . ',' . $c] = $ab + $c;
    }
}

arsort($abc_list);
$abc_list = array_slice($abc_list, 0, $k, true);

foreach ($abc_list as $abc) {
    echo $abc, PHP_EOL;
}

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.


<?php

$counts = [];
fscanf(STDIN, "%d %d %d %d", $counts[0], $counts[1], $counts[2], $k);

$cakes = [];
for ($i = 0; $i < 3; $i++) {
    $input = trim(fgets(STDIN));
    $cakes[$i] = explode(' ', $input);
    rsort($cakes[$i]);
}

$calc = function($p) use ($cakes) {
    $sum = 0;
    for ($i = 0; $i < 3; $i++) {
        $j = $p[$i];
        $n = $cakes[$i][$j];
        $sum += $n;
    }
    return $sum;
};

$points = [];
for ($ix = 0; $ix < $counts[0]; $ix++) {
    for ($iy = 0; $iy < $counts[1]; $iy++) {
        for ($iz = 0; $iz < $counts[2]; $iz++) {
            $points[] = $calc([$ix, $iy, $iz]);
        }
    }
}
rsort($points);
for ($i = 0; $i < $k; $i++) {
    echo $points[$i].PHP_EOL;
}


<?php
$a = ints();
echo max($a) < array_sum($a) - max($a) ? 'Yes' : 'No';
function ints()
{
    return array_map('intval', explode(' ', trim(fgets(STDIN))));
}

Score : 100 points

Problem Statement

You are given three integers A, B and C.

Determine if there exists an equilateral triangle whose sides have lengths A, B and C.

Constraints

All values in input are integers.

1 \leq A,B,C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

If there exists an equilateral triangle whose sides have lengths A, B and C, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

There exists an equilateral triangle whose sides have lengths 2, 2 and 2.

Sample Input 2

3 4 5

Sample Output 2

No

There is no equilateral triangle whose sides have lengths 3, 4 and 5.


Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


<?php
$b = trim(fgets(STDIN));

if ($b == 'A' || $b == 'T')　{

} else {

}

?>


<?php

$s = trim(fgets(STDIN));
$match = [];

$result = preg_match_all('/[ACGT]+/',$s,$match);
$maxLength = 0;

if ($result > 0) {
    foreach ($match as $m) {
        $maxLength = max([strlen($m[0]) , $maxLength]);
    }
}

print($maxLength . "\n");

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

S is a string of length between 1 and 10 (inclusive).

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


<?php
$n = trim(fgets(STDIN));
$s = trim(fgets(STDIN));
$max = pow(2, $n) - 1;
for ($i = 0; $i < $n; $i++) {
    if ($i == 0) {
        $count = 1;
        continue;
    }
    $a = '/' . substr($s, $i, 1) . '/';
    $before = substr($s, 0, $i);
    if (preg_match($a, $before) === 1) {
        $count += ($count-1)/2 + 1;
    } else {
        $count = $count * 2 + 1;
    }
}
echo $count % (pow(10, 9) + 7);

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


<?php
fscanf(STDIN, "%d %d", $H, $W);
fscanf(STDIN, "%d %d", $h, $w);
$ans_w = $W - $w;
$ans_h = $H - $h;
echo $ans_w + $ans_h+1;

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


<?php
fscanf(STDIN, '%d %d', $H, $W);
fscanf(STDIN, '%d %d', $h, $w);
$ans = $H * $W - $h * $W - $w * $H + $h * $w;
echo $ans . PHP_EOL;


<?php
fscanf(STDIN,'%d%d',$H,$W);
fscanf(STDIN,'%d%d',$h,$w);
echo ($H-$h)*($W-$w);

 ?>


<?php
  fscanf(STDIN,"%d %d %d",$n,$m,$c);
  $b = explode(" ",trim(fgets(STDIN)));
  for($i=0; $i<$n; $i++){
    $a = explode(" ",trim(fgets(STDIN)));
    $ans = 0;
    for($j=0; $j<$m; $j++){
      $ans += $a[$j]*$b[$j];
    }
    if($ans+$c > 0){
      echo $i."\n";
      exit;
    }
  }
  echo "0\n";

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a 32-bit integer type.


<?php

list($n, $m) = explode(" ", trim(fgets(STDIN)));
for($i = 0; $i < $n; $i++){
    list($p, $c) = explode(" ", trim(fgets(STDIN)));
    @$amount[$p] += $c;
}
ksort($amount);

$total = 0;
foreach($amount as $price => $a){
    $buyCount = min($m, $a);
    $m = $m - $buyCount;
    $total += $price * $buyCount;
}
echo $total;


<?php
    $NM = explode(" ",trim(fgets(STDIN)));
    $N = $NM[0];
    $M = $NM[1];

    for ($i = 0; $i < $N; $i++) {
        $AB = explode(" ",trim(fgets(STDIN)));
        $price[] = $AB[0];
        $stock[$price[$i]] = $AB[1];
    }

    ksort($stock);
    $buy = 0;
    $ans = 0;
    foreach ($stock as $key => $val)
    {
        //この店で買う数
        $buy = min($M, $val);

        //金額をたす
        $ans += $buy * $key;

        //必要な個数を減らす
        $M -= $buy;
    }

    echo $ans;

?>


<?php
fscanf(STDIN, "%d %d %d",$a,$b,$k);
$a_divisor = array();
$b_divisor = array();
$com_divisor = array();
//aの約数を取得
for($i=1;$i<=$a;$i++){

	if($a % $i == 0){
			$a_divisor[] = $i;
	}
}
//ｂの約数を取得
for($i=1;$i<=$b;$i++){

	if($b % $i == 0){
		$b_divisor[] = $i;
	}
}
//aとbの公約数
for($i=0;$i<count($a_divisor);$i++){

	for($n=0;$n<count($b_divisor);$n++){

		if ($a_divisor[$i]==$b_divisor[$n]){

			$com_divisor[]=$a_divisor[$i];
			break;
		}
	}
}
//k番目に大きいもの
echo $com_divisor[count($com_divisor) - $k];
?>

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


<?php

fscanf(STDIN, '%d %d %d', $A, $B, $K);

// A, Bの約数を全て挙げる
// 共通のものにしぼる
// そのうちK番目のものをとってくる

$aArray = [];
for($i = 1; $i <= $A; $i++){
    if($A % $i === 0){
        $aArray[] = $i;
    }
}

$bArray = [];
for($i = 1; $i <= $B; $i++){
    if($B % $i === 0){
        $bArray[] = $i;
    }
}

$array = array_intersect($aArray, $bArray);
rsort($array);

var_dump($array);

$ans = $array[$K - 1];

echo $ans.PHP_EOL;


<?php
$data = trim(fgets(STDIN));
$data = str_split( $data );

$a = 0;
$b = 0;
foreach( $data as $val )
{
  if( $val == 0 ) { $a++; }
  else			  { $b++; }
}

$result = min( $a, $b )*2;
echo $result;

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


<?php
list($n, $m) = explode(" ", trim(fgets(STDIN)));
$sum = $n*($n-1)/2;
for($i = 0; $i < $m; $i++){
    $data[] =  explode(" ", trim(fgets(STDIN)));
}
$data = array_reverse($data);

$uft = new UFT($n);
$sum = ($n * ($n-1)) / 2;
foreach($data as $row){
    $history[] = $sum;
    $s1 = $uft->size($row[0]);
    $s2 = $uft->size($row[1]);
    $uft->unite($row[0], $row[1]);
    $s3 = $uft->size($row[0]);
    if($s1 != $s3){
        $sum -= $s1 * $s2;
    }
}
echo implode("\n", array_reverse($history));

class UFT{
    public $parent;
    public $size;
    public $rank;
    public function __construct($size){
        for($i = 1; $i <= $size; $i++){
            $this->size[$i] = 1;
            $this->rank[$i] = 1;
            $this->parent[$i] = 0;
        }
    }
    public function dump(){
        o("--------------");
        o($this->parent);
        o($this->size);
        o($this->rank);
    }
    public function getRoot($i){
        if($this->parent[$i] == 0){
            return $i;
        }else{
            return $this->getRoot($this->parent[$i]);
        }
    }
    public function unite($i, $j){
        $rootI = $this->getRoot($j);
        $rootJ = $this->getRoot($i);
        if($rootJ == $rootI)return false;//元から同じグループ
        if($this->rank[$rootI] > $this->rank[$rootJ])list($rootI, $rootJ) = [$rootJ, $rootI];//Rank(J)>Rank(I)に揃えておく
        $this->parent[$rootI] = $rootJ;
        if($this->rank[$rootI] == $this->rank[$rootJ]){
            $this->rank[$rootJ]++;
        }
        $this->size[$rootJ]+=$this->size[$rootI];
        $this->size[$rootI] = '*';//不要な情報となるので潰す/デバッグ出力向けに*を入れている
        $this->rank[$rootI] = '*';//同上
    }
    public function size($i){return $this->size[$this->getRoot($i)];}
    public function isUnion($i, $j){return $this->getRoot($i) == $this->getRoot($j);}
}

//デバッグ用
function o($val){
    $trace = debug_backtrace();
    echo $trace[0]['line'].")";
    if(is_array($val)){
        if(count($val) == 0){
            echo "empty array";
        }elseif(!is_array(current($val))){
            echo "array:";
            echo implode(" ", $val)."\n";
        }else{
            echo "array:array\n";
            foreach($val as $row){
                echo implode(" ", $row)."\n";
            }
        }
    }else{
        echo $val."\n";
    }
}

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

6 5
2 3
1 2
5 6
3 4
4 5

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


<?php
list($n, $m) = explode(" ", trim(fgets(STDIN)));

$sum = $n*($n-1)/2;

for($i = 0; $i < $m; $i++){
    $data[] =  explode(" ", trim(fgets(STDIN)));
}
$data = array_reverse($data);
$tree = new UnionFindTree($n);
foreach($data as $row){
    $hist[] = $sum;
    $s1 = $tree->findRootNode($row[0]-1)->size;
    $s2 = $tree->findRootNode($row[1]-1)->size;
    $tree->unite($row[0]-1, $row[1]-1);
    $s3 = $tree->findRootNode($row[0]-1)->size;
    $s4 = $tree->findRootNode($row[1]-1)->size;
    if($s1!=$s3){
        $sum -= $s1 * $s2;
    }
    o([$s1,$s2, $s3, $s4]);
}
foreach(array_reverse($hist) as $num){
    echo $num."\n";
}

class Node
{
    public $parentIndex;
    public $rank;
    public $size = 1;
    function __construct($parentIndex, $rank)
    {
        $this->parentIndex = $parentIndex;
        $this->rank = $rank;
    }
}
class UnionFindTree
{
    private $nodes = [];
    public function  __construct($nodeCount)
    {
        for ($i = 0; $i < $nodeCount; $i++) {
            $this->nodes[$i] = new Node($i, 0);
        }
    }
    public function findRootNode($target){
        return $this->nodes[$this->findRoot($target)];
    }
    public function findRoot($target)
    {
        $parentIndex = $this->nodes[$target]->parentIndex;
        if($parentIndex === $target){
            return $target;
        } else {
            $rootIndex = $this->findRoot($parentIndex);
            $this->nodes[$target]->parentIndex = $rootIndex;
            return $rootIndex;
        }
    }
    public function unite($x, $y)
    {
        $xRootIndex = $this->findRoot($x);
        $yRootIndex = $this->findRoot($y);
        if ($xRootIndex === $yRootIndex) {
            return;
        }
        $xRootNode = $this->nodes[$xRootIndex];
        $yRootNode = $this->nodes[$yRootIndex];
        if ($xRootNode->rank < $yRootNode->rank) {
            $this->nodes[$x]->parentIndex = $y;
            $yRootNode->size+=$xRootNode->size;
        } else {
            $this->nodes[$y]->parentIndex = $x;
            $xRootNode->size+=$yRootNode->size;
            if ($xRootNode->rank === $yRootNode->rank) {
                $xRootNode->rank++;
            }
        }
    }
    public function isSameGroup($x, $y)
    {
        return $this->findRoot($x) === $this->findRoot($y);
    }
}


Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


<?php

$s = explode('/', trim(fgets(STDIN)));
if ($s[0]<=2018){
  echo "Heisei";
} else if ($s[0]==2019 && $s[1]<=4){
  echo "Heisei";
} else {
  echo "TBD";
}

?>


Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


<?php
list($A, $B, $Q) = explode(" ", trim(fgets(STDIN)));
$A = intval($A);
$B = intval($B);
$Q = intval($Q);
for($i = 0; $i < $A; $i++){
    $aArray[] = intval(fgets(STDIN));
}
array_unshift($aArray, -10**18);
$aArray[] = 10**18;
for($i = 0; $i < $B; $i++){
    $bArray[] = intval(fgets(STDIN));
}
array_unshift($bArray, -10**18);
$bArray[] = 10**18;

for($i = 0; $i < $Q; $i++){
    $qArray[] = intval(fgets(STDIN));
}

foreach($qArray as $q){
    $min = 10**18;
    $a = bsl($aArray, $q);
    $b = bsl($bArray, $q);
    foreach([$aArray[$a], $aArray[$a+1]] as $a1){
        $p3 = $bArray[$b];
        $p4 = $bArray[$b+1];
        $min = min($min, abs($q - $a1) + abs($a1 - $p3));
        $min = min($min, abs($q - $a1) + abs($a1 - $p4));
    }
    foreach([$bArray[$b], $bArray[$b+1]] as $b1){
        $p3 = $aArray[$a];
        $p4 = $aArray[$a+1];
        $min = min($min, abs($q - $b1) + abs($b1 - $p3));
        $min = min($min, abs($q - $b1) + abs($b1 - $p4));
    }
    printf("%d\n", $min);
}

//二分探索　target以下で最大の値の場所を返す
function bsl($nums, $target) {
    $size = count($nums);
    $min = 0;
    $max = $size - 1;
    while(true){
        $center = floor(($min + $max) / 2);
        $centerValue = $nums[$center];
        if($target == $centerValue){
            return $center;
        }elseif($target > $centerValue){
            $min = $center + 1;
        }else{
            $max = $center;
        }
        if($min == $max){
            $center = floor(($min + $max) / 2);
            $centerValue = $nums[$center];
            if($centerValue == $target){
                return $center;
            }elseif($centerValue < $target){
                return $center;
            }else{
                return $center-1;
            }
        }
    }
}

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


<?php
$input = fgets(STDIN);
$ab=explode(" ",$input);
$A=$ab[0];
$B=$ab[1];
$ans=$B%$A==0?$A+$B:$B-$A;
echo $ans;
?>

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


<?php
  fscanf(STDIN,"%d %d",$n,$m);
  $k = [];
  for($i=0; $i<$n; $i++){
    $k[] = explode(" ",trim(fgets(STDIN)));
  }
  for($x=0; $x<$n; $x++){
    unset($k[$x][0]);
  }
  $result = array_intersect($k[0],$k[1]);
  echo count(array_intersect($result,$k[2]))."\n";
  ?>

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

3 4
2 1 3
3 1 2 3
2 3 2

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3