<?php

$s=new Scanner();

$n=$s->nextInt();

$score=0;
$exclus=0;

for($i=0;$i<$n;$i++){
  $scoring[$i]=$s->nextInt();
  $score+=$scoring[$i];
}

sort($scoring);

if($score%10==0){
  for($i=0;$i<$n;$i++){

    if($scoring[$i]%10!=0){
      $score-=$scoring[$i];
      break;
    }
    if($i==$n-1){
      $score=0;

    }
  }
}

echo $score.PHP_EOL;

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();
  }
}

#$B2~9T$"$j$NI8=`=PNO%/%i%9(B
class out{
  public static function println($str = ""){
    echo ($str . PHP_EOL);
  }

  #$BH>3Q6h@Z$j$G$NJQ?t$N=PNO(B
  public static function print_v(){
    $params = func_get_args();
    foreach ($params as $param) {
      echo ($param." ");
    }
    echo PHP_EOL;
  }
}


<?php
$num = fscanf(STDIN, "%d", $a);
$sum = 0;
$min = 0;
for($i=0;$i<$num;$i++){
  $point = fscanf(STDIN, "%d", $p);
  $sum += $point;
  if($point % 10 != 0) {
    if($min == 0 || $point < $min) {
      $min = $point;
    }
  }
}
if(($sum % 10) != 0){
  echo $sum . "\n";
} else {
  echo $sum - $min . "\n";
}
?>

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

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.

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
list($h, $w) = ints();
echo str_repeat('#', $w + 2) . PHP_EOL;
for ($i = 0; $i < $h; ++$i) {
    $a = strs();
    echo '#' . implode('', $a) . '#' . PHP_EOL;
}
echo str_repeat('#', $w + 2) . PHP_EOL;
function strs()
{
    return explode(' ', trim(fgets(STDIN)));
}
function ints()
{
    return array_map('intval', explode(' ', trim(fgets(STDIN))));
}

Score : 200 points

Problem Statement

You are given a image with a height of H pixels and a width of W pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the i-th row from the top and j-th column from the left is a_{ij}.

Put a box around this image and output the result. The box should consist of # and have a thickness of 1.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}

Output

Print the image surrounded by a box that consists of # and has a thickness of 1.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


<?php
error_reporting(0);
$stdin = file_get_contents('php://stdin');
$line = explode("\n",$stdin);
$fi = 0;
$cnt = 0;
$list = array();
$key = new stdclass();
foreach($line as $l) {
  if (strlen($l)==0) continue;
  if ($fi == 0) {
    $a = explode(" ",$l);
    $key->A = $a;
    $fi++;
    continue;
  }
  if ($fi > 0) {
    $a = explode(" ",$l);
    $key->X[] = $a;
  }
}
$A = $key->A[0];
$B = $key->A[1];
$C = $key->A[2];

if (($C >= $A) && ($C <= $B)) {
  printf("Yes\n");
}
else {
  printf("No\n");
}

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

8 8
1 2
3 4
1 5
2 8
3 7
5 2
4 1
6 8

Sample Output 3

3
3
2
2
2
1
1
2


<?php
fscanf(STDIN, "%d %d", $n, $m);
$ret = array_pad([], $n, 0);
for($i = 0; $i < $m; $i++) {
    fscanf(STDIN, "%d %d", $a, $b);
    if(array_key_exists($a - 1, $ret)) $ret[$a - 1]++;
    if(array_key_exists($b - 1, $ret)) $ret[$b - 1]++;
}
foreach($ret as $key => $v) echo $v. "\n";


<?php

class In {

	private $buf = [];
	private $count = 0;
	private $pointer = 0;

	public function nextLine() {
		$ret = '';
		if($this->hasNext()){
			while($this->hasNext()){
				$ret .= $this->next();
			}
		}else{
			$ret = trim(fgets(STDIN));
		}

		return $ret;
	}

	public function next() {
		if(!$this->hasNext()) {
			$str = trim(fgets(STDIN));
			$this->buf = explode(' ',$str);
			$this->count = count($this->buf);
			$this->pointer = 0;
		}

		return $this->buf[$this->pointer++];
	}

	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 function println($str = '') {
		echo $str . PHP_EOL;
	}
}

$in = new In();
$out = new Out();

$N = $in->nextInt();
$M = $in->nextInt();

$A = [];
for($i = 0;$i < $N;$i++) {
	$A[] = 0;
}

for ($i = 0;$i < $M;$i++) {
	$a = $in->nextInt()-1;
	$b = $in->nextInt()-1;

	$A[$a]++;
	$A[$b]++;
}

for ($i = 0;$i < $N;$i++) {
	$out->println($A[$i]);
}

?>


Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


<?php
$input = explode(" ",trim(fgets(STDIN)));
$K = $input[1];
$num = array();
$name = array();
$i = 0;
while($i < $input[0]){
    $array = explode(" ",trim(fgets(STDIN)));
    if(empty($num[$array[0]])){
        $num[$array[0]] = $array[1];
    }else{
        $num[$array[0]] += $array[1];
    }
    if(!(in_array($array[0],$name))){
        $name[] = $array[0];
    }
    ++$i;
}
sort($name);
$i = 0;
while($i < count($name)){
    $K -= $num[$name[$i]];
    if($K <= 0){
        echo $name[$i];
        break;
    }
    ++$i;
}


<?php
/*
    Problem URL : http://abc060.contest.atcoder.jp/tasks/abc060_d

    Score  :
    Result :
    Time   : ms
    Memory : KB
 */

ini_set('memory_limit', '256M');

// define('DEBUG', true);
define('DEBUG', false);

$ans = 0;
$mem = array();

fscanf(STDIN, "%d %d %d", $A, $B, $C);

while ($A % 2 != 1 && $B %2 != 1 && $C %2 != 1) {
    $str = "{$A}_{$B}_{$C}";
    if (isset($mem[$str])) {
        echo "-1\n";
        exit;
    } else {
        $mem[$str] = 1;
    }

    $ans ++;

    $A2 = $A / 2;
    $B2 = $B / 2;
    $C2 = $C / 2;

    $A = $B2 + $C2;
    $B = $A2 + $C2;
    $C = $A2 + $B2;

    // echo "{$A} {$B} {$C}\n";
}

echo $ans . PHP_EOL;

Score : 300 points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.

After the second action, they have 10, 12 and 14.

After the third action, they have 13, 12 and 11.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1


<?php
fscanf(STDIN,'%s%s%s',$A,$B,$C);
$Alen=strlen($A);
$Blen=strlen($B);
$Clen=strlen($C);
if($A[$Alen-1]==$B[0]&&$B[$Blen-1]==$C[0]){
  echo 'YES';
}else{
  echo "NO";
}

 ?>

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


<?php
error_reporting(0);
$stdin = file_get_contents('php://stdin');
$line = explode("\n",$stdin);
$fi = 0;
$cnt = 0;
$list = array();
$key = new stdclass();
foreach($line as $l) {
  if (strlen($l)==0) continue;
  if ($fi == 0) {
    $a = explode(" ",$l);
    $key->A = $a;
    $fi++;
    continue;
  }
  if ($fi > 0) {
    $a = explode(" ",$l);
    $key->X[] = $a;
  }
}
$A = $key->A[0];
$B = $key->A[1];
$C = $key->A[2];

//X%B=CでX=Aの倍数
if ($A==1) {
  printf("YES\n");
  exit;
}
//わからん
if ($A%2 == $C%2) {
  printf("YES\n");
}
else {
  printf("NO\n");
}


<?php
 fscanf(STDIN,"%s",$o);
 fscanf(STDIN,"%s",$e);

 for($i=0;$i<strlen($o);$i++){
   echo $o[$i];
   echo $e[$i];
 }

echo "\n";

Score : 200 points

Problem Statement

Snuke signed up for a new website which holds programming competitions.
He worried that he might forget his password, and he took notes of it.
Since directly recording his password would cause him trouble if stolen,
he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order.
Restore the original password.

Constraints

O and E consists of lowercase English letters (a - z).

1 \leq |O|,|E| \leq 50

|O| - |E| is either 0 or 1.

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


Score : 100 points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".

The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

The input is given from Standard Input in the following format:

A B

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at 1 o'clock the next day.


<?php
error_reporting(0);
$stdin = file_get_contents('php://stdin');
$line = explode("\n",$stdin);
$fi = 0;
$cnt = 0;
$list = array();
$key = new stdclass();
foreach($line as $l) {
  if (strlen($l)==0) continue;
  if ($fi == 0) {
    $a = explode(" ",$l);
    $key->A = $a;
    $fi++;
    continue;
  }
  if ($fi > 0) {
    $a = explode(" ",$l);
    $key->X[] = $a;
  }
}
$N = $key->A[0];
//$N=$A*$BのA,Bをどうやって求める？
$res=$N;
$m=9999999999;
for($i=1;$i<sqrt($N);$i++) {
  $r = (int)($N / $i);
  if (($r * $i) == $N) {
    $m = max(strlen($r),strlen($i));
    if ($m < $res) {
      $res = $m;
    }
  }
}
printf("%d\n",$res);

Score : 300 points

Problem Statement

You are given an integer N.

For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.

For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.

Find the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Constraints

1 \leq N \leq 10^{10}

N is an integer.

Input

The input is given from Standard Input in the following format:

N

Output

Print the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Sample Input 1

10000

Sample Output 1

3

F(A,B) has a minimum value of 3 at (A,B)=(100,100).

Sample Input 2

1000003

Sample Output 2

7

There are two pairs (A,B) that satisfy the condition: (1,1000003) and (1000003,1). For these pairs, F(1,1000003)=F(1000003,1)=7.

Sample Input 3

9876543210

Sample Output 3

6


<?php
list($W,$a,$b) = explode(" ",fgets(STDIN));
if($a<=$b && $a+$W>=$b) $ans=0;
elseif($a<$b) $ans = $b-($a+$W);
else $ans = $a-($b+$W);
printf("%d\n",$ans);

Score : 200 points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

1≤W≤10^5

1≤a,b≤10^5

Input

The input is given from Standard Input in the following format:

W a b

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 1.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4


<?php
list($n, $c, $k) = ints();
for ($i = 0; $i < $n; ++$i) list($t[]) = ints();
sort($t);
$cnt = $nbus = $num = 0;
foreach ($t as $tt) {
    if ($tt <= $nbus && $num < $c) {
        ++$num;
        continue;
    }
    $nbus = $tt + $k;
    $num = 1;
    ++$cnt;
}
echo $cnt;
function ints()
{
    return array_map('intval', explode(' ', trim(fgets(STDIN))));
}

Score : 300 points

Problem Statement

Every day, N passengers arrive at Takahashi Airport.
The i-th passenger arrives at time T_i.

Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers.
Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport.
Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane.
For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).

When setting the departure times for buses under this condition, find the minimum required number of buses.
Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.

Constraints

2 \leq N \leq 100000

1 \leq C \leq 10^9

1 \leq K \leq 10^9

1 \leq T_i \leq 10^9

C, K and T_i are integers.

Input

The input is given from Standard Input in the following format:

N C K
T_1
T_2
:
T_N

Output

Print the minimum required number of buses.

Sample Input 1

5 3 5
1
2
3
6
12

Sample Output 1

3

For example, the following three buses are enough:

A bus departing at time 4.5, that carries the passengers arriving at time 2 and 3.

A bus departing at time 6, that carries the passengers arriving at time 1 and 6.

A bus departing at time 12, that carries the passenger arriving at time 12.

Sample Input 2

6 3 3
7
6
2
8
10
6

Sample Output 2

3


<?php
$n = trim(fgets(STDIN));
$k = explode(" ",trim(fgets(STDIN)));
$s = array_sum($k);
rsort($k);

$i = 1;
$p =$k[0];
$s -= $p;
while($i < $n){
$q = $k[$i];
if($p > $s * 2){
break;
}
$s -= $q;
$p = $q;
++$i;
}
echo $i;
?>

Score : 400 points

Problem Statement

Snuke found N strange creatures.
Each creature has a fixed color and size. The color and size of the i-th creature are represented by i and A_i, respectively.

Every creature can absorb another creature whose size is at most twice the size of itself.
When a creature of size A and color B absorbs another creature of size C and color D (C \leq 2 \times A), they will merge into one creature of size A+C and color B.
Here, depending on the sizes of two creatures, it is possible that both of them can absorb the other.

Snuke has been watching these creatures merge over and over and ultimately become one creature.
Find the number of the possible colors of this creature.

Constraints

2 \leq N \leq 100000

1 \leq A_i \leq 10^9

A_i is an integer.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

Print the number of the possible colors of the last remaining creature after the N creatures repeatedly merge and ultimately become one creature.

Sample Input 1

3
3 1 4

Sample Output 1

2

The possible colors of the last remaining creature are colors 1 and 3.
For example, when the creature of color 3 absorbs the creature of color 2, then the creature of color 1 absorbs the creature of color 3, the color of the last remaining creature will be color 1.

Sample Input 2

5
1 1 1 1 1

Sample Output 2

5

There may be multiple creatures of the same size.

Sample Input 3

6
40 1 30 2 7 20

Sample Output 3

4


Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

The input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

The input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897


<?php
  list($n, $m) = explode(" ", trim(fgets(STDIN)));
  if($n > $m){
    echo "Alice";
  }else if($n == $m){
    echo "Draw";
  }else{
    echo "Bob";
  }

Score : 100 points

Problem Statement

Alice and Bob are playing One Card Poker.

One Card Poker is a two-player game using playing cards.

Each card in this game shows an integer between 1 and 13, inclusive.

The strength of a card is determined by the number written on it, as follows:

Weak 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < 11 < 12 < 13 < 1 Strong

One Card Poker is played as follows:

Each player picks one card from the deck. The chosen card becomes the player's hand.

The players reveal their hands to each other. The player with the stronger card wins the game.

If their cards are equally strong, the game is drawn.

You are watching Alice and Bob playing the game, and can see their hands.

The number written on Alice's card is A, and the number written on Bob's card is B.

Write a program to determine the outcome of the game.

Constraints

1≦A≦13

1≦B≦13

A and B are integers.

Input

The input is given from Standard Input in the following format:

A B

Output

Print Alice if Alice will win. Print Bob if Bob will win. Print Draw if the game will be drawn.

Sample Input 1

8 6

Sample Output 1

Alice

8 is written on Alice's card, and 6 is written on Bob's card.
Alice has the stronger card, and thus the output should be Alice.

Sample Input 2

1 1

Sample Output 2

Draw

Since their cards have the same number, the game will be drawn.

Sample Input 3

13 1

Sample Output 3

Bob


<?php
	fscanf(STDIN, "%d %d", $A, $B);

	if($A === $B){
		echo 'Draw';
	}else if($A > $B && $B !== 1){
		echo 'Alice';
	}else{
		echo 'Bob';
	}
?>


<?php
/*
    Problem URL : http://abc054.contest.atcoder.jp/tasks/abc054_c

    Score  :
    Result :
    Time   : ms
    Memory : KB
 */

ini_set('error_reporting', E_ALL & ~E_NOTICE);
ini_set('memory_limit', '-1');

$v = array();
$ans = 0;

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

for ($i = 0; $i < $M; $i++) {
    fscanf(STDIN, "%d %d", $a, $b);
    $v[$a][$b] = 1;
    $v[$b][$a] = 1;
}

// var_dump($v);
// exit;

$arr = array("1");
$base = "1";

for ($i = 0; $i < $N-1; $i++) {
    $newArr = array();
    foreach ($arr as $tmp) {
        $last = substr($tmp, strlen($tmp) - 1);
        // echo "last:{$last}\n";
        // var_dump($v[$last]);
        foreach ($v[$last] as $nex => $dummy) {
            if (!in_array($nex, str_split($tmp))) {
                $newArr[] = $tmp . $nex;
            }
        }
    }
    $arr = $newArr;
}
// var_dump($arr);

foreach ($arr as $x) {
    $arrx = str_split($x);
    $sum = array();
    for ($i = 0; $i < $N; $i++) {
        $sum[$arrx[$i]]++;
    }
    // echo max($sum) . PHP_EOL;
    if (max($sum) == 1) {
        $ans++;
    }
}
echo $ans . PHP_EOL;

Score : 300 points

Problem Statement

You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

The given graph contains neither self-loops nor double edges.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

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

Sample Output 2

1

This test case is the same as the one described in the problem statement.


<?php
  declare(strict_types=1);

  class M
  {
      public $a, $b, $c;
      public function __construct($a, $b, $c)
      {
          $this->a = $a;
          $this->b = $b;
          $this->c = $c;
      }

      public function add($x)
      {
          $a = $this->a + $x->a;
          $b = $this->b + $x->b;
          $c = $this->c + $x->c;
          return new M($a, $b, $c);
      }

      public function getRatio()
      {
          return $this->a - $this->b;
      }
  }

  fscanf(STDIN, "%i %i %i", $n, $ma, $mb); if ($n >= 20) $undefined[$bomb]->hoge();
  for ($i = 0; $i < $n; ++$i)
  {
      fscanf(STDIN, "%i %i %i", $a, $b, $c);
      $store[$i] = new M($a * $mb, $b * $ma, $c);
  }

  $minimize = function (&$value, $candidate)
  {
      $value = min([$value, $candidate]) ?? $candidate;
  };

  $p = (int)ceil($n / 2);
  $limit = 1 << $p;
  $dp[0] = new M(0, 0, 0);
  for ($combination = (int)0; $combination < $limit; ++$combination)
  {
      for ($i = 0; $i < $p; ++$i)
      {
          $modified = $combination | (1 << $i);
          if (!isset($dp[$modified]))
          {
              $dp[$modified] = $dp[$combination]->add($store[$i]);
              if ($dp[$modified]->getRatio() !== 0)
              {
                  $minimize($dp_cost[$dp[$modified]->a], $dp[$modified]->c);
              }
              else
              {
                  $minimize($dp_cost[0], $dp[$modified]->c);
              }
          }
      }
  }
  $limit = 1 << $n;
  for ($combination = (int)0; $combination < $limit; $combination += $p)
  {
      for (; $i < $n; ++$i)
      {
          $modified = $combination | (1 << $i);
          if (!isset($dp[$modified]))
          {
              $dp[$modified] = $dp[$combination]->add($store[$i]);
              if ($dp[$modified]->getRatio() !== 0)
              {
                  if (isset($dp_cost[$dp[$modified]->b]))
                  {
                      $minimize($dp_cost[0], $dp_cost[$dp[$modified]->b] + $dp[$modified]->c);
                  }
              }
              else
              {
                  $minimize($dp_cost[0], $dp[$modified]->c);
              }
          }
      }
  }

  echo ($dp_cost[0] ?? -1).PHP_EOL;

Score : 400 points

Problem Statement

Dolphin is planning to generate a small amount of a certain chemical substance C.

In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.

He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy.

The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock.

The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan).

Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C.

Find the minimum amount of money required to generate the substance C.

If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.

Constraints

1≦N≦40

1≦a_i,b_i≦10

1≦c_i≦100

1≦M_a,M_b≦10

gcd(M_a,M_b)=1

a_i, b_i, c_i, M_a and M_b are integers.

Input

The input is given from Standard Input in the following format:

N M_a M_b
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.

Sample Input 1

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

Sample Output 1

3

The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2.

In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1.

The total price of these packages is 3 yen.

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1.


<?php

list($boxCount) = getSingleLine();
$boxes = getSingleLine();

$sumStones = array_sum($boxes);
$k = $sumStones/(($boxCount + 1) * $boxCount / 2);
$diffList = [];

for ($i = 0; $i < $boxCount; $i++) {
    $nextBoxIndex = ($i + 1) % $boxCount;
    $diffList[] = $boxes[$nextBoxIndex] - $boxes[$i];
}

$validated = [];

for ($i = 0; $i < $boxCount; $i++) {
    $diffSum = array_sum($diffList);
    if ($diffList[$i] < $k && $k % $boxCount === 0) {
        $validated[] = true;
    }else{
        $validatedp[] = false;
        }
}

if (in_array(false,$validated,true)) {
    echo 'YES';
} else {
    echo 'NO';
}

/**
 * @return array
 */
function getSingleLine():array
{
    return array_map('intval', explode(' ', trim(fgets(STDIN))));
}

Score : 500 points

Problem Statement

There are N boxes arranged in a circle. The i-th box contains A_i stones.

Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:

Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-th box. Here, the (N+k)-th box is identified with the k-th box.

Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

If it is possible to remove all the stones from the boxes, print YES. Otherwise, print NO.

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

All the stones can be removed in one operation by selecting the second box.

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO


<?php
  declare(strict_types=1);

  fscanf(STDIN, "%i", $n);
  $xs = explode(" ", trim(fgets(STDIN)));

  $solve = function () use ($n, $xs)
  {
      $s = (int)(($n * $n + $n) / 2);
      $k = (int)(array_sum($xs) / $s);
      $xs[$n] = $xs[0];

      for ($i = 1; $i < ($n + 1); $i++)
      {
          if ((($xs[$i] - $xs[$i - 1] - $k) % $n) !== 0)
              return FALSE;
      }

      return TRUE;
  };

  echo ($solve() ? "YES" : "NO").PHP_EOL;


<?php
class main {
var $adv = array();
var $p = array();
function run() {
    fscanf(STDIN, "%d", $n);
    $line = trim(fgets(STDIN));
    $this->p = explode(" ", $line);
    for ($i = count($this->p);$i > 0;$i--) {
        $this->p[$i] = $this->p[$i - 1];
        unset($this->p[$i - 1]);
    }
    $this->adv = array();
    for ($i = 0; $i < $n - 1; $i++) {
        $line = trim(fgets(STDIN));
        $arr = explode(" ", $line);
        $this->adv[$arr[0]][$arr[1]] = null;
        $this->adv[$arr[1]][$arr[0]] = null;
    }
    $flag = 0;
    $sum_c = 0;
    foreach ($this->adv[1] as $c => $t) {
        if (is_null($t)) {
            $sum_c += $this->t(1, $c);
        } else {
            $sum_c += $t;
        }
    }

    if (count($this->adv[1]) == 1) {
        $d = $this->p[1];
    } else {
        $d = 2 * $this->p[1];
    }

    if ($d != $sum_c) {
        $flag = 1;
    }

    if ($flag) {
        echo "NO";
    } else {
        echo "YES";
    }
}

function t($root, $cur) {
    if (!is_null($this->adv[$cur][$root])) {
        return $this->adv[$cur][$root];
    } elseif (count($this->adv[$cur]) == 1) {
        $this->adv[$root][$cur] = $this->p[$cur];
        unset($this->adv[$cur]);
        return $this->p[$cur];
    }
    $sum_c = 0;
    $max = 0;
    foreach ($this->adv[$cur] as $c => $t) {
        if ($root != $c) {
            $c_t = $this->t($cur, $c);
            $sum_c += $c_t;
            if ($c_t > $max) {
                $max = $c_t;
            }
        }
    }

    $cur_t = 2 * $this->p[$cur] - $sum_c;
    $l = ($sum_c - $cur_t) / 2;
    if ($l > min($max, ($sum_c / 2))) {
        echo "NO";
        exit;
    }
    if ($this->p[$cur] < max($max, ($sum_c / 2))) {
        echo "NO";
        exit;
    }
    $this->adv[$root][$cur] = $cur_t;
    unset($this->adv[$cur]);
    return $cur_t;
}

}

$object = new main();
$object->run();

Score : 700 points

Problem Statement

There is a tree with N vertices, numbered 1 through N.
The i-th of the N-1 edges connects vertices a_i and b_i.

Currently, there are A_i stones placed on vertex i.
Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation:

Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices.
Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them.

Note that the operation cannot be performed if there is a vertex with no stone on the path.

Constraints

2 ≦ N ≦ 10^5

1 ≦ a_i,b_i ≦ N

0 ≦ A_i ≦ 10^9

The given graph is a tree.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

If it is possible to remove all the stones from the vertices, print YES. Otherwise, print NO.

Sample Input 1

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

Sample Output 1

YES

All the stones can be removed, as follows:

Select vertices 4 and 5. Then, there is one stone remaining on each vertex except 4.

Select vertices 1 and 5. Then, there is no stone on any vertex.

Sample Input 2

3
1 2 1
1 2
2 3

Sample Output 2

NO

Sample Input 3

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

Sample Output 3

YES


<?php
class main {
var $adv = array();
var $p = array();
function run() {
    fscanf(STDIN, "%d", $n);
    $line = trim(fgets(STDIN));
    $this->p = explode(" ", $line);
    for ($i = count($this->p);$i > 0;$i--) {
        $this->p[$i] = $this->p[$i - 1];
        unset($this->p[$i - 1]);
    }
    $this->adv = array();
    for ($i = 0; $i < $n - 1; $i++) {
        $line = trim(fgets(STDIN));
        $arr = explode(" ", $line);
        $this->adv[$arr[0]][$arr[1]] = null;
        $this->adv[$arr[1]][$arr[0]] = null;
    }
    $flag = 0;
    $sum_c = 0;
    foreach ($this->adv[1] as $c => $t) {
        if (is_null($t)) {
            $sum_c += $this->t(1, $c);
        } else {
            $sum_c += $t;
        }
    }

    if (count($this->adv[1]) == 1) {
        $d = $this->p[1];
    } else {
        $d = 2 * $this->p[1];
    }

    if ($d != $sum_c) {
        $flag = 1;
    }

    if ($flag) {
        echo "NO";
    } else {
        echo "YES";
    }
}

function t($root, $cur) {
    if (!is_null($this->adv[$cur][$root])) {
        return $this->adv[$cur][$root];
    } elseif (count($this->adv[$cur]) == 1) {
        $this->adv[$root][$cur] = $this->p[$cur];
        unset($this->adv[$cur]);
        return $this->p[$cur];
    }
    $sum_c = 0;
    $max = 0;
    foreach ($this->adv[$cur] as $c => $t) {
        if ($root != $c) {
            $c_t = $this->t($cur, $c);
            $sum_c += $c_t;
            if ($c_t > $max) {
                $max = $c_t;
            }
        }
    }

    $cur_t = 2 * $this->p[$cur] - $sum_c;
    $l = ($sum_c - $cur_t) / 2;
    if ($l > min($max, ($sum_c / 2))) {
        echo "NO";
        exit;
    }
    if ($cur_t < 0) {
        echo "NO";
        exit;
    } elseif (count($this->adv[$cur]) == 2 && $cur_t != $sum_c && $cur_t != 0) {
        echo "NO";
        exit;
    } elseif (($cur_t + $sum_c - $max) < ($max)) {
        echo "NO";
        exit;
    }
    $this->adv[$root][$cur] = $cur_t;
    unset($this->adv[$cur]);
    return $cur_t;
}

}

$object = new main();
$object->run();


Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


<?php
$n = int();
$A = ints();
echo count(array_unique($A)) - (count(array_unique($A)) % 2 == 0);

function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}

Score : 400 points

Problem Statement

Snuke has decided to play a game using cards.
He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written.

He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept.

Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck.

Constraints

3 ≦ N ≦ 10^{5}

N is odd.

1 ≦ A_i ≦ 10^{5}

A_i is an integer.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_{N}

Output

Print the answer.

Sample Input 1

5
1 2 1 3 7

Sample Output 1

3

One optimal solution is to perform the operation once, taking out two cards with 1 and one card with 2. One card with 1 and another with 2 will be eaten, and the remaining card with 1 will be returned to deck. Then, the values written on the remaining cards in the deck will be pairwise distinct: 1, 3 and 7.

Sample Input 2

15
1 3 5 2 1 3 2 8 8 6 2 6 11 1 1

Sample Output 2

7


<?php
    $input = explode(" ",fgets(STDIN));
    $sumA = $input[0] * $input[1];
    $sumB = $input[2] * $input[3];

    if ($sumA >= $sumB) {
        echo $sumA;
    } else {
        echo $sumB;
    }
?>

Score : 100 points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B.
The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

1≤A≤10^4

1≤B≤10^4

1≤C≤10^4

1≤D≤10^4

Input

The input is given from Standard Input in the following format:

A B C D

Output

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of 3×5=15, and the second rectangle has an area of 2×7=14.
Thus, the output should be 15, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000


<?php
  fscanf(STDIN, "%d %d %d", $N, $A, $B);

	$towns = array_map("intval", explode(" ", trim(fgets(STDIN))));

	$min = 0;
	for($j=1; $j < $N;$j++){
      $gap = $towns[$j] - $towns[$j - 1];
      $min += min(($gap * $A), $B);
    }

	echo $min;
  ?>

Score : 500 points

Problem Statement

There are N towns on a line running east-west.
The towns are numbered 1 through N, in order from west to east.
Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value.
The coordinate of town i is X_i.

You are now at town 1, and you want to visit all the other towns.
You have two ways to travel:

Walk on the line.
Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.

Teleport to any location of your choice.
Your fatigue level increases by B, regardless of the distance covered.

Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

Constraints

All input values are integers.

2≤N≤10^5

1≤X_i≤10^9

For all i(1≤i≤N-1), X_i<X_{i+1}.

1≤A≤10^9

1≤B≤10^9

Input

The input is given from Standard Input in the following format:

N A B
X_1 X_2 ... X_N

Output

Print the minimum possible total increase of your fatigue level when you visit all the towns.

Sample Input 1

4 2 5
1 2 5 7

Sample Output 1

11

From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4.
The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.

Sample Input 2

7 1 100
40 43 45 105 108 115 124

Sample Output 2

84

From town 1, walk all the way to town 7.
The total increase of your fatigue level in this case is 84, which is the minimum possible value.

Sample Input 3

7 1 2
24 35 40 68 72 99 103

Sample Output 3

12

Visit all the towns in any order by teleporting six times.
The total increase of your fatigue level in this case is 12, which is the minimum possible value.


Score : 300 points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.

Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.

Here, both the x- and y-coordinates before and after each movement must be integers.

He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

The input is given from Standard Input in the following format:

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.

The i-th character in S should correspond to his i-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)

Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)

Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (-1,0) → (-1,1) → (-1,2) → (-1,3) → (0,3) → (1,3) → (1,2)

Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,-1) → (1,-1) → (0,-1) → (0,0)

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


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

for($i=1;$i<=$M;$i++){
  ${"array".$i} = explode(" ",fgets(STDIN));
}

if($N-1 === $M){
  echo 0;
}else{
  $arrayResult = array();
  $arrayNumber = array();
  $arrayResult[1] = 0;
//  $arrayNumber[1] = 1;
  $result = 0;
  for($i=1;$i<=$M;$i++){
    $x = ${"array".$i}[0];
    $y = ${"array".$i}[1];
    $z = ${"array".$i}[2];
    if(array_key_exists($y,$arrayResult)){
      $value = 0;
      if($z >= $arrayResult[$x]+$arrayResult[$y]){
//        $arrayResult[$y] = $arrayResult[$x]+$arrayResult[$y];
        $result++;
      }elseif(${"array".$arrayNumber[$y]}[2] >= ${"array".$arrayNumber[$y]}[0]+$arrayResult[$x]+$z){
        $result++;
      }else{
//        $arrayResult[$y] = $arrayResult[$x]+$z;
      }
      //☆　>=対応
      if(${"array".$arrayNumber[$y]}[0]+${"array".$arrayNumber[$y]}[2] > $arrayResult[$x]+$z){
        $arrayResult[$y] = $arrayResult[$x]+$z;
        $arrayNumber[$y] = $i;
      }
    }else{
      $arrayResult[$y] = $arrayResult[$x]+$z;
      $arrayNumber[$y] = $i;
    }
  }
  echo $result;
}

Score : 400 points

Problem Statement

You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


Score : 600 points

Problem Statement

A tetromino is a figure formed by joining four squares edge to edge.
We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:

Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession are a_I, a_O, a_T, a_J, a_L, a_S and a_Z, respectively.
Snuke will join K of his tetrominos to form a rectangle that is two squares tall and 2K squares wide.
Here, the following rules must be followed:

When placing each tetromino, rotation is allowed, but reflection is not.

Each square in the rectangle must be covered by exactly one tetromino.

No part of each tetromino may be outside the rectangle.

Snuke wants to form as large a rectangle as possible.
Find the maximum possible value of K.

Constraints

0≤a_I,a_O,a_T,a_J,a_L,a_S,a_Z≤10^9

a_I+a_O+a_T+a_J+a_L+a_S+a_Z≥1

Input

The input is given from Standard Input in the following format:

a_I a_O a_T a_J a_L a_S a_Z

Output

Print the maximum possible value of K. If no rectangle can be formed, print 0.

Sample Input 1

2 1 1 0 0 0 0

Sample Output 1

3

One possible way to form the largest rectangle is shown in the following figure:

Sample Input 2

0 0 10 0 0 0 0

Sample Output 2

0

No rectangle can be formed.


Score : 800 points

Problem Statement

You are given an integer sequence x of length N.
Determine if there exists an integer sequence a that satisfies all of the following conditions, and if it exists, construct an instance of a.

a is N^2 in length, containing N copies of each of the integers 1, 2, ..., N.

For each 1 ≤ i ≤ N, the i-th occurrence of the integer i from the left in a is the x_i-th element of a from the left.

Constraints

1 ≤ N ≤ 500

1 ≤ x_i ≤ N^2

All x_i are distinct.

Input

The input is given from Standard Input in the following format:

N
x_1 x_2 ... x_N

Output

If there does not exist an integer sequence a that satisfies all the conditions, print No.
If there does exist such an sequence a, print Yes in the first line, then print an instance of a in the second line, with spaces inbetween.

Sample Input 1

3
1 5 9

Sample Output 1

Yes
1 1 1 2 2 2 3 3 3

For example, the second occurrence of the integer 2 from the left in a in the output is the fifth element of a from the left.
Similarly, the condition is satisfied for the integers 1 and 3.

Sample Input 2

2
4 1

Sample Output 2

No


<?php
fscanf(STDIN, "%d %s %d", $a, $op, $b);
echo ($op == '+') ? $a + $b : $a - $b, PHP_EOL;

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

The input is given from Standard Input in the following format:

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


<?php
error_reporting(0);
$stdin = file_get_contents('php://stdin');
$line = explode("\n",$stdin);
$fi = 0;
$cnt = 0;
$list = array();
$key = new stdclass();
foreach($line as $l) {
  if (strlen($l)==0) continue;
  if ($fi == 0) {
    $a = explode(" ",$l);
    $key->A = $a;
    $fi++;
    continue;
  }
  if ($fi > 0) {
    $a = explode(" ",$l);
    $key->X[] = $a;
  }
}
if ($key->A[1]=='+') {
  printf("%d\n",$key->A[0]+$key->A[2]);
}
else {
  printf("%d\n",$key->A[0]-$key->A[2]);
}


<?php

$n = (int) fgets(STDIN);
$t = explode(' ', rtrim(fgets(STDIN)));
$m = (int) fgets(STDIN);
$px = [];
for ($index=0; $index < $m; $index++) {
    $px[$index] = explode(' ', rtrim(fgets(STDIN)));
}

for ($index=0; $index < $m; $index++) {
    $result = 0;
    foreach ($t as $key => $value) {
        if ($px[$index][0] == $key + 1) {
            $result += (int) $px[$index][1];
        } else {
            $result += (int) $value;
        }
    }
    echo $result."\n";
}

Score : 200 points

Problem Statement

Joisino is about to compete in the final round of a certain programming competition.
In this contest, there are N problems, numbered 1 through N.
Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).

Also, there are M kinds of drinks offered to the contestants, numbered 1 through M.
If Joisino takes drink i(1≦i≦M), her brain will be stimulated and the time it takes for her to solve problem P_i will become X_i seconds.
It does not affect the time to solve the other problems.

A contestant is allowed to take exactly one of the drinks before the start of the contest.
For each drink, Joisino wants to know how many seconds it takes her to solve all the problems if she takes that drink.
Here, assume that the time it takes her to solve all the problems is equal to the sum of the time it takes for her to solve individual problems.
Your task is to write a program to calculate it instead of her.

Constraints

All input values are integers.

1≦N≦100

1≦T_i≦10^5

1≦M≦100

1≦P_i≦N

1≦X_i≦10^5

Input

The input is given from Standard Input in the following format:

N
T_1 T_2 ... T_N
M
P_1 X_1
P_2 X_2
:
P_M X_M

Output

For each drink, calculate how many seconds it takes Joisino to solve all the problems if she takes that drink, and print the results, one per line.

Sample Input 1

3
2 1 4
2
1 1
2 3

Sample Output 1

6
9

If Joisino takes drink 1, the time it takes her to solve each problem will be 1, 1 and 4 seconds, respectively, totaling 6 seconds.

If Joisino takes drink 2, the time it takes her to solve each problem will be 2, 3 and 4 seconds, respectively, totaling 9 seconds.

Sample Input 2

5
7 2 3 8 5
3
4 2
1 7
4 13

Sample Output 2

19
25
30


<?php

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

$count = 0;

for($i = $a ; $i <= $b ; $i++) {
	if($i % $x == 0) $count++;
}

echo $count;

Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


<?php
	fscanf(STDIN,"%d%d%d",$a,$b,$c);
	$a_count = (int)(($a-1)/$c);
	$b_count = (int)(($b)/$c);
	echo ($b_count-$a_count)."\n";

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

The input is given from Standard Input in the following format:

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


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

if($a%$x==0){
  $result = 1;
}

if($b%$x==0){
  $result = 1;
}

$result += intdiv(($b-$a),$x);

echo $result;


<?php
/*
    Problem URL : http://abc048.contest.atcoder.jp/tasks/abc048_b

    Score  :
    Result :
    Time   : ms
    Memory : KB
 */

ini_set('error_reporting', E_ALL & ~E_NOTICE);

fscanf(STDIN, "%s %s %s", $a, $b, $x);
// echo implode(" ", array($a, $b, $x)) . PHP_EOL;

$mmin = bigDiv($a, $x, true);
$mmax = bigDiv($b, $x);
$ans = bigSub($mmax, $mmin);
if ($ans === false) {
    echo "0\n";
    exit;
}
$ans = bigAdd($ans, "1");
// echo $mmin , " " , $mmax , PHP_EOL;
echo $ans . PHP_EOL;
exit;

$x = bigAdd("999999999999999", "2");
$x = bigSub("10000000000000000000", "2");
// $x = bigDiv("10000000000000000000", "3", true);
$x = bigDiv("99999999999999999999", "10000000000000000000");
$x = bigDiv("9", "4");
// $x = bigDiv("10000000000000000000", "7");
// $x = bigDiv("100", "49", true);
// var_dump($x);
echo $x . PHP_EOL;

function bigDiv($a, $b, $ceilFlag = false) {
    if (gettype($a) != "string") {
        exit("arg1 not string\n");
    }
    if (gettype($b) != "string") {
        exit("arg2 not string\n");
    }
    $ans = array();
    $a = bigGetArray($a);
    // $b = bigGetArray($b);
    $aa = array();
    while (true) {
        if (array_sum($a) == 0 && $ans) {
            while($a) {
                array_unshift($ans, array_pop($a));
            }
            break;
        }
        $ret = bigSub(bigKeta($aa), $b);
        // print_r($ret);
        // echo PHP_EOL;
        if ($ret === false) {
            if (!$a) break;
            array_unshift($aa, array_pop($a));
            if ($ans) {
                array_unshift($ans, 0);
            }
        } else {
            if (!$ans) {
                array_unshift($ans, 0);
            }
            $ans[0]++;
            $aa = bigGetArray($ret);
        }
    }
    // var_dump($ans);
    $ret = implode("", array_reverse($ans));
    // echo "amari: " . implode("", array_reverse($aa)) . PHP_EOL;
    $amari = implode("", array_reverse($aa));
    if ($amari != 0 && $ceilFlag === true) {
        $ret = bigAdd($ret, "1");
    }
    if ($ret == null) {
        $ret = "0";
    }
    // echo  $ret . PHP_EOL;
    return $ret;
}

function bigAdd($a, $b) {
    if (gettype($a) != "string") {
        exit("arg1 not string\n");
    }
    if (gettype($b) != "string") {
        exit("arg2 not string\n");
    }
    $a = bigGetArray($a);
    $b = bigGetArray($b);
    $keta = max(count($a), count($b));
    for ($i = 0; $i < $keta; $i++) {
        $a_ex = isset($a[$i]) ? $a[$i] : 0;
        $b_ex = isset($b[$i]) ? $b[$i] : 0;
        $a[$i] = $a_ex + $b_ex;
    }
    $a = bigKeta($a);

    return $a;
}

/*
    param : string
    return: string
*/
function bigSub($a, $b) {
    // echo "sub1: {$a} {$b}\n";
    if (gettype($a) != "string") {
        exit("arg1 not string\n");
    }
    if (gettype($b) != "string") {
        exit("arg2 not string\n");
    }
    if (strlen($b) > strlen($a)) {
        // exit("arg2 is larger than ard1\n");
        return false;
    }
    if ((strlen($b) == strlen($a)) && $b > $a) {
        // exit("arg2 is larger than ard1\n");
        return false;
    }

    $a = bigGetArray($a);
    $b = bigGetArray($b);
    $keta = max(count($a), count($b));
    for ($i = 0; $i < $keta; $i++) {
        $a_ex = isset($a[$i]) ? $a[$i] : 0;
        $b_ex = isset($b[$i]) ? $b[$i] : 0;
        $a[$i] = $a_ex - $b_ex;
    }
    $a = bigKeta($a);

    // echo "sub2: {$a}\n";
    return $a;
}

/*
    param : string
    return: array
*/
function bigGetArray($a) {
    if (gettype($a) != "string") {
        exit("arg1 not string\n");
    }
    return array_reverse(str_split($a));
}

function bigGetString($a) {
    if (gettype($a) != "array") {
        exit("arg1 not array\n");
    }
    return implode("", array_reverse($a));
}

/*
    param : array
    return: string
*/
function bigKeta($a) {
    if (gettype($a) != "array") {
        exit("arg1 not array\n");
    }
    $cnt = count($a);

    $flag = true;

    while($flag) {
        $flag = false;
        foreach ($a as $key => $val) {
            if ($val < 0) {
                $a[$key+1]--;
                $a[$key] += 10;
                $flag = true;
            }
            if ($val > 9) {
                $a[$key+1]++;
                $a[$key] -= 10;
                $flag = true;
            }
        }
    }

    if ($a[$cnt-1] == "0") {
        unset($a[$cnt-1]);
    }
    return implode("", array_reverse($a));
}


<?php
/*
    Problem URL : http://abc048.contest.atcoder.jp/tasks/abc048_b

    Score  :
    Result :
    Time   : ms
    Memory : KB
 */

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

$mmin = ceil($a / $x);
$mmax = floor($b / $x);

echo ($mmax - $mmin + 1) . PHP_EOL;


<?php

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

$count = 0;

for($i = $a ; ; $i++) {
	if($i % $x == 0) {
		$count++;
		break;
	}
}

$count += floor(($b - $i)/$x);

echo $count;


Score : 500 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

There are N computers and N sockets in a one-dimensional world.
The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i.
It is guaranteed that these 2N coordinates are pairwise distinct.

Snuke wants to connect each computer to a socket using a cable.
Each socket can be connected to only one computer.

In how many ways can he minimize the total length of the cables?
Compute the answer modulo 10^9+7.

Constraints

1 ≤ N ≤ 10^5

0 ≤ a_i, b_i ≤ 10^9

The coordinates are integers.

The coordinates are pairwise distinct.

Input

The input is given from Standard Input in the following format:

N
a_1
:
a_N
b_1
:
b_N

Output

Print the number of ways to minimize the total length of the cables, modulo 10^9+7.

Sample Input 1

2
0
10
20
30

Sample Output 1

2

There are two optimal connections: 0-20, 10-30 and 0-30, 10-20.
In both connections the total length of the cables is 40.

Sample Input 2

3
3
10
8
7
12
5

Sample Output 2

1


Score : 400 points

Problem Statement

We have a pyramid with N steps, built with blocks.
The steps are numbered 1 through N from top to bottom.
For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally.
The pyramid is built so that the blocks at the centers of the steps are aligned vertically.

A pyramid with N=4 steps

Snuke wrote a permutation of (1, 2, ..., 2N-1) into the blocks of step N.
Then, he wrote integers into all remaining blocks, under the following rule:

The integer written into a block b must be equal to the median of the three integers written into the three blocks directly under b, or to the lower left or lower right of b.

Writing integers into the blocks

Afterwards, he erased all integers written into the blocks.
Now, he only remembers that the integer written into the block of step 1 was x.

Construct a permutation of (1, 2, ..., 2N-1) that could have been written into the blocks of step N, or declare that Snuke's memory is incorrect and such a permutation does not exist.

Constraints

2≤N≤10^5

1≤x≤2N-1

Input

The input is given from Standard Input in the following format:

N x

Output

If no permutation of (1, 2, ..., 2N-1) could have been written into the blocks of step N, print No.

Otherwise, print Yes in the first line, then print 2N-1 lines in addition.

The i-th of these 2N-1 lines should contain the i-th element of a possible permutation.

Sample Input 1

4 4

Sample Output 1

Yes
1
6
3
7
4
5
2

This case corresponds to the figure in the problem statement.

Sample Input 2

2 1

Sample Output 2

No

No matter what permutation was written into the blocks of step N, the integer written into the block of step 1 would be 2.


<?php
/*
    http://agc006.contest.atcoder.jp/tasks/agc006_b

    Score  :
    Result :
    Time   : ms
    Memory : KB
 */

// define('DEBUG', true);
define('DEBUG', false);

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

// echo "{$N} {$x}\n";
// exit;

$len = $N * 2 - 1;

if ($x == 1 || $x == $len) {
	echo "NO" . PHP_EOL;
	exit;
}

$stock = array();
for ($i = 1; $i < $x - 1; $i++) {
	$stock[] = $i;
}
for ($i = $x + 2; $i <= $len; $i++) {
	$stock[] = $i;
}
// var_dump($stock);

$ans = array();
$ans[$N - 1] = $x;
$ans[$N - 2] = $x-1;
$ans[$N] = $x+1;
// var_dump($ans);

for ($i = 0; $i < $N - 2; $i++) {
	// echo "count1 = " . count($stock) . PHP_EOL;
	$ans[$i] = array_pop($stock);
	// var_dump($ans);
}
for ($i = 0; $i < $N - 2; $i++) {
	// echo "count2 = " . count($stock) . PHP_EOL;
	$ans[$i + $N + 1] = array_pop($stock);
	// var_dump($ans);
}
ksort($ans);
echo "Yes\n";
echo implode(" ", $ans) . PHP_EOL;
// echo kenzan($ans) . PHP_EOL;
exit;

for ($i = 1; $i <= 9; $i++) {
	$arr[$i] = $i;
}

$mmin = PHP_INT_MAX;
$mmax = 0;

for ($loop = 0; $loop < 10000; $loop++) {

	$arr2 = $arr;
	shuffle($arr2);
	$orig = $arr2;
	// echo implode(" ", $arr2) . " -> ";
	while (count($arr2) > 1) {
		$arr3 = array();
		for ($i = 0; $i < count($arr2) - 2; $i++) {
			$arr3[$i] = med($arr2[$i], $arr2[$i+1], $arr2[$i+2]);
		}
		// echo implode(" ", $arr3) . PHP_EOL;
		$arr2 = $arr3;
	}
if ($arr2[0] == 2) echo "[2] " . implode(" ", $orig) . PHP_EOL;
if ($arr2[0] == 8) echo "[8] " . implode(" ", $orig) . PHP_EOL;
// echo $arr2[0] . PHP_EOL;
	$mmin = min($mmin, $arr2[0]);
	$mmax = max($mmax, $arr2[0]);
}

// echo "{$mmin} {$mmax}\n";

function med($a, $b, $c) {
	return ($a + $b + $c) - max($a, $b, $c) - min($a, $b, $c);

	if ($a >= $b && $b >= $c) {
		return $b;
	} elseif ($a >= $c && $c >= $b ) {
		return $c;
	} else {
		return $a;
	}
}

function kenzan($a) {
	var_dump($a);
	$arr2 = $a;
	while (count($arr2) > 1) {
		// echo "count:" . count($arr2). PHP_EOL;
		$arr3 = array();
		for ($i = 0; $i < count($arr2) - 2; $i++) {
			$arr3[$i] = med($arr2[$i], $arr2[$i+1], $arr2[$i+2]);
		}
		// echo implode(" ", $arr3) . PHP_EOL;
		$arr2 = $arr3;
	}
	// echo "kenzan: " . $arr2[0] . PHP_EOL;
}


<?php
$bunsetus = trim(fgets(STDIN));
$bunsetu = explode(" ", $bunsetus);
$check = 0;
$number = 0;
foreach($bunsetu as $value){
  if($value == $check){
    $number += 1;
  }else{
    $check = $value;
  }
}
echo $number;
?>

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

The input is given from Standard Input in the following format:

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


<?php

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

$array = [$a,$b,$c];
$uniq = array_unique($array);

echo count($uniq);


Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

The input is given from Standard Input in the following format:

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


<?php
    $input_lines = trim(fgets(STDIN));
    $iNum = (int)$input_lines;
    $iPossibleA = 0;
    $iPossibleB = 0;

    $in;

    for($i = 0; $i < $iNum; $i++){
        $in = explode(" ", trim(fgets(STDIN)));
        $a = $in[0];
        $b = $in[1];
        if($iPossibleA <= $a && $iPossibleB <= $b){
            $iPossibleA = $a;
            $iPossibleB = $b;
        } else {
            $iMag = ceil(round(max( (double)$iPossibleA/$a, (double)$iPossibleB/$b),5));
            $iPossibleA = $a * $iMag;
            $iPossibleB = $b * $iMag;
        }
    }

    echo $iPossibleA+$iPossibleB;
?>


<?php
$n = trim(fgets(STDIN));
fscanf(STDIN,"%d %d",$takahashi,$aoki);
if($n>1){
    for($i=2;$i<=$n;++$i){
        fscanf(STDIN,"%d %d",$t,$a);
        if($takahashi<=$t && $aoki<=$a){
            $takahashi=$t;
            $aoki=$a;
        }else{
            if($takahashi>$t && $aoki>$a){
                if($takahashi>$aoki){
                    $takahashi=$t*ceil($takahashi/$t);
                    $aoki=$takahashi/$t*$a;
                }else{
                    $aoki=$a*ceil($aoki/$a);
                    $takahashi=$aoki/$a*$t;
                }
            }elseif($takahashi>$t){
                $takahashi=$t*ceil($takahashi/$t);
                $aoki=$takahashi/$t*$a;
            }elseif($aoki>$a){
                $aoki=$a*ceil($aoki/$a);
                $takahashi=$aoki/$a*$t;
            }
        }
    }
}
echo $takahashi+$aoki;
?>


<?php
/*
    http://arc062.contest.atcoder.jp/tasks/arc062_a

    Score  :
    Result :
    Time   : ms
    Memory : KB
 */

// define('DEBUG', true);
define('DEBUG', false);

fscanf(STDIN, "%d", $N);
for ($i = 0; $i < $N; $i++) {
	fscanf(STDIN, "%d %d", $T, $A);
	if ($i == 0) {
		$TT = $T;
		$AA = $A;
	} else {
		$fTT = ceil($TT / $T);
		$fAA = ceil($AA / $A);
		$ratio = max($fTT, $fAA);
		$TT = $T * $ratio;
		$AA = $A * $ratio;
	}
	// echo "Q {$TT} {$AA}\n";
}
printf("%d\n", $TT + $AA);


<?php
// Your code here!
$inp = fgets(STDIN);
$inp = explode(" ",$inp);
list($n,$a,$b) = array_map(function($a){return (int)$a;},$inp);
$s = fgets(STDIN);
$ca = 0;
$co = 0;
$ss = str_split($s) ;
foreach ($ss as $c)
{

    if($c == "a")
    {
        $ca += 1;
        if($ca <= $a + $b)
        {
            echo("Yes\n");
        }
        else
        {
            echo("No\n");
        }
    }
    else if($c == "b")
    {

        $co += 1;
        if($co <= $b and $ca <= $a + $b)
        {
            echo("Yes\n");
            $ca += 1;
        }
        else
        {
            echo("No\n");
        }

    }
    else
    {
        echo("No\n");
    }
}
?>

Score : 200 points

Problem Statement

There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.

Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.

A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B.

An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B and the student ranks B-th or above among all overseas students.

A string S is assigned indicating attributes of all participants. If the i-th character of string S is a, this means the participant ranked i-th in the Qualification contests is a Japanese student; b means the participant ranked i-th is an overseas student; and c means the participant ranked i-th is neither of these.

Write a program that outputs for all the participants in descending rank either Yes if they passed the Qualification contests or No if they did not pass.

Constraints

1≦N,A,B≦100000

A+B≦N

S is N characters long.

S consists only of the letters a, b and c.

Input

Inputs are provided from Standard Input in the following form.

N A B
S

Output

Output N lines. On the i-th line, output Yes if the i-th participant passed the Qualification contests or No if that participant did not pass.

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

The first, second, fifth, sixth, and seventh participants pass the Qualification contests.

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

No
Yes
Yes
Yes
Yes
No
Yes
Yes
No
Yes
No
No

The sixth participant is third among overseas students and thus does not pass the Qualification contests.

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No


<?php
  fscanf(STDIN,"%d %d %d", $n,$a,$b);
  $s = trim(fgets(STDIN));
  $tag = "tag";
  $foreign = 0;
  $tuka = 0;
  for($i=0; $i<$n; $i++){
    if($tuka < $a+$b){
      if($s[$i] == "a" ){
        $tag = "Yes";
        $tuka++;
      }else if($s[$i] == "b"){
        if($foreign < $b){
          $tag = "Yes";
          $foreign++;
          $tuka++;
        }else{
          $tag = "No";
        }
      }else{
        $tag = "No";
      }
    }else{
      $tag = "No";
    }
    echo $tag."\n";
  }


<?php
fscanf(STDIN, '%d %d %d', $N, $A, $B);
fscanf(STDIN, "%s", $str);

$passed = $A + $B;
$countPassed = 0;
$countB = 0;

for ($i = 0; $i < $N; $i++) {
	if ($str[$i] === 'a' && $countPassed < $passed) {
		$countPassed++;
		echo 'YES'. PHP_EOL;;
	} else if ($str[$i] === 'b' && $countPassed < $passed && $countB < $B) {
		$countPassed++;
		$countB++;
		echo 'YES'. PHP_EOL;;
	} else {
		echo 'NO'. PHP_EOL;;
	}
}


<?php

$arr = array();
fscanf(STDIN, "%d %d", $W, $H);
$ans = 0;

$WW = $W + 1;
$HH = $H + 1;

for ($i = 0; $i < $W; $i++) {
	$key = "W_" . strval($i);
	fscanf(STDIN, "%d", $arr[$key]);
}

for ($i = 0; $i < $H; $i++) {
	$key = "H_" . strval($i);
	fscanf(STDIN, "%d", $arr[$key]);
}
asort($arr);
foreach ($arr as $key => $val) {
	list($WH, $num) = explode("_", $key);
	if ($WH == "W") {
		$kazu = $HH;
		$WW--;
	} else {
		$kazu = $WW;
		$HH--;
	}
	$ans += $val * $kazu;
}
echo $ans . PHP_EOL;

Score : 500 points

Problem Statement

On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers.

There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and the difference between the x coordinates is 1.

The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is p_i for any value of j, while the cost of paving a road between houses on coordinates (i,j) and (i,j+1) is q_j for any value of i.

Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.

Constraints

1 ≦ W,H ≦ 10^5

1 ≦ p_i ≦ 10^8(0 ≦ i ≦ W-1)

1 ≦ q_j ≦ 10^8(0 ≦ j ≦ H-1)

p_i (0 ≦ i ≦ W−1) is an integer.

q_j (0 ≦ j ≦ H−1) is an integer.

Input

Inputs are provided from Standard Input in the following form.

W H
p_0
:
p_{W-1}
q_0
:
q_{H-1}

Output

Output an integer representing the minimum total cost.

Sample Input 1

2 2
3
5
2
7

Sample Output 1

29

It is enough to pave the following eight roads.

Road connecting houses at (0,0) and (0,1)

Road connecting houses at (0,1) and (1,1)

Road connecting houses at (0,2) and (1,2)

Road connecting houses at (1,0) and (1,1)

Road connecting houses at (1,0) and (2,0)

Road connecting houses at (1,1) and (1,2)

Road connecting houses at (1,2) and (2,2)

Road connecting houses at (2,0) and (2,1)

Sample Input 2

4 3
2
4
8
1
2
9
3

Sample Output 2

60


Score : 100 points

Problem Statement

A professor invented Cookie Breeding Machine for his students who like cookies very much.

When one cookie with the taste of x is put into the machine and a non-negative integer y less than or equal to 127 is input on the machine,
it consumes the cookie and generates two cookies with the taste of y and (x XOR y).

Here, XOR represents Bitwise Exclusive OR.

At first, there is only one cookie and the taste of it is D .

Find the maximum value of the sum of the taste of the exactly N cookies generated after the following operation is conducted N-1 times.

Put one of the cookies into the machine.

Input a non-negative integer less than or equal to 127 on the machine.

Constraints

1 \leq T \leq 1000

1 \leq N_t \leq 1000 (1 \leq t \leq T)

1 \leq D_t \leq 127 (1 \leq t \leq T)

Input

The input is given from Standard Input in the following format:

T
N_1 D_1
:
N_T D_T

The input consists of multiple test cases. An Integer T that represents the number of test cases is given on line 1.

Each test case is given on the next T lines.

In the t-th test case ( 1 \leq t \leq T ),
N_t that represents the number of cookies generated through the operations and D_t that represents the taste of the initial cookie are given separated by space.

Output

For each test case, print the maximum value of the sum of the taste of the N cookies generated through the operations on one line.

Sample Input 1

3
3 1
4 108
1 10

Sample Output 1

255
400
10

On the 1st test case, if the machine is used as follows, three cookies with the taste of 61, 95 and 99 are generated.
Since the sum of these values is maximum among all possible ways, the answer is 255.

Put the cookie with the taste of 1 and input an integer 60 on the machine, lose the cookie and get two cookies with the taste of 60 and 61.

Put the cookie with the taste of 60 and input an integer 99 on the machine, lose the cookie and get two cookies with the taste of 99 and 95.

On the 3rd test case, the machine may not be used.


<?php
/*
    URL    : http://agc005.contest.atcoder.jp/tasks/agc005_a

    Score  :
    Result :
    Time   : ms
    Memory : KB
 */

ini_set('error_reporting', E_ALL & ~E_NOTICE);

fscanf(STDIN, "%s", $X);
$lenX = strlen($X);
// echo $X . PHP_EOL;
$W = "";

for ($i = 0; $i < $lenX; $i++) {
	if ($X[0] === "T" && $W[strlen($W)-1] === "S") {
		$W = substr($W, 0, strlen($W) - 1);
	} else {
		$W .= $X[0];
	}
	$X = substr($X, 1);
	// echo "{$W} {$X}\n";
}

// echo $W . PHP_EOL;
echo strlen($W) . PHP_EOL;

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

Note that the answer may not fit into a 32-bit integer.

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


<?php
list($s) = strs();
list($k) = ints();
for ($i = 0; $i < 26; ++$i) $a2n[chr(97 + $i)] = $i;
$n = strlen($s);
// 先頭から順番にaに出来るものをaにする
for ($i = 0; $i < $n; ++$i) {
    $x = $a2n[$s[$i]];
    if ($x === 0) continue;
    if ($k >= 26 - $x) {
        $s[$i] = 'a';
        $k -= 26 - $x;
    }
}
// 残ったkは全部最後の文字に使う
if ($k > 0) $s[$n - 1] = chr(97 + ($a2n[$s[$n - 1]] + $k) % 26);
echo $s . PHP_EOL;
function ints()
{
    return array_map('intval', explode(' ', trim(fgets(STDIN))));
}
function strs()
{
    return explode(' ', trim(fgets(STDIN)));
}

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


<?php
$str = trim(fgets(STDIN));
$k = intval(fgets(STDIN));
$abc = "";
for($a = "a"; $a != "aa"; $a++){
    $abc.=$a;
}
for($i = 0; $i < strlen($str); $i++){
    $left = 26-strpos($abc,$str[$i]);
    if($left <= $k){
        $k-=$left;
        $str[$i] = "a";
    }
}
for($i = 0; $i < $k % 26; $i++){
    $aa = $str[strlen($str)-1];
    $aa++;
    $str[strlen($str)-1] = $aa;
}
echo $str,"\n";


<?php
    $a = str_split(trim(fgets(STDIN)));
    $b = str_split(trim(fgets(STDIN)));
    $c = str_split(trim(fgets(STDIN)));
    $p = "a";
    while(true){
        if(count($$p)==0){
            echo strtoupper($p),"\n";
            exit;
        }
        $p = array_shift($$p);
    }

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

The input is given from Standard Input in the following format:

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


<?php
$s = str();
$n = strlen($s);
$sum = 0;
for($i = 0; $i < 2**($n-1);$i++){
    $flags = sprintf("%0".($n-1)."b", $i);
    $num = 0;
    for($j = 0; $j < $n; $j++){
        $num = $num*10+$s[$j];
        if($j == $n-1 || $flags[$j]==1){
            $sum+=$num;
            $num = 0;
        }
    }
    $sum+=$num;
}
echo $sum;

function str(){return trim(fgets(STDIN));}
function ints(){return array_map('intval',explode(' ',trim(fgets(STDIN))));}
function int(){return intval(trim(fgets(STDIN)));}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}
function popcount($x){$c=0;while($x){$x&=$x-1;++$c;}return$c;}
function o(...$val){
    if(count($val)==1)$val=array_shift($val);
    echo debug_backtrace()[0]['line'].")";
    if(is_array($val)){
        if(count($val) == 0)echo "empty array";
        elseif(!is_array(current($val)))echo "array: ",implode(" ", addIndex($val)),"\n";
        else{
            echo "array:array\n";
            if(isCleanArray($val))foreach($val as $row)echo implode(" ", addIndex($row)),"\n";
            else foreach($val as $i => $row)echo "[".$i."] ".implode(" ", addIndex($row)),"\n";
        }
    }else echo $val."\n";
}
function addIndex($val){if(!isCleanArray($val)){$val = array_map(function($k, $v){return $k.":".$v;}, array_keys($val), $val);}return $val;}
function isCleanArray($array){$clean=true;$i = 0;foreach($array as $k=>$v){if($k != $i++)$clean = false;}return $clean;}
// 座圧対象の配列 -> [圧縮された配列,復元用のMap,圧縮用のMap]
function atsu($array){$a = array_flip($array);$fuku=array_flip($a);sort($fuku);$atsu = array_flip($fuku);foreach($array as $i=>$val)$array[$i]=$atsu[$val];return [$array, $fuku, $atsu];}
function gcdAll($array){$gcd=$array[0];for($i=1,$I=count($array);$i<$I;++$i){$gcd=gcd($gcd,$array[$i]);}return $gcd;}
function gcd($m, $n){if(!$n)return $m;return gcd($n, $m % $n);}
function lcmAll($array){$lcm=$array[0];for($i=1,$I=count($array);$i<$I;++$i){$lcm=lcm($lcm,$array[$i]);}return $lcm;}
function lcm($a, $b) {return $a / gcd($a, $b) * $b;}

function dfs($current, $from = -1, $d = 0){
  global $G, $distance;
  $distance[$current] = $d;
  foreach($G[$current] as $to){
    if($from != $to){
      dfs($to, $current, $d + 1);
    }
  }
}

function loadTree($N = false){
  if($N === false)$N = $GLOBALS['N'];
  return loadGraph($N, $N-1);
}
function loadGraph($N = false, $M = false, $both = true){
  if($N === false)$N = $GLOBALS['N'];
  if($M === false)$N = $GLOBALS['M'];
  $G = array_fill(1, $N, []);
  for($i = 0; $i < $M; $i++){
    $values = ints();
    if(count($values) == 2){
      list($a, $b) = $values;
      $G[$a][] = $b;
      if($both)$G[$b][] = $a;
    }else{
      list($a, $b, $d) = $values;
      $G[$a][] = [$b, $d];
      if($both)$G[$b][] = [$a, $d];
    }
  }
  return $G;
}

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

The input is given from Standard Input in the following format:

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


<?php
  fscanf(STDIN, "%d", $n);
  fscanf(STDIN, "%d", $k);
  fscanf(STDIN, "%d", $x);
  fscanf(STDIN, "%d", $y);

  $sum = 0;

  for($i = 0; $i < $n; $i++){
    if($i < $k){
      $sum += $x;
    }else{
      $sum += $y;
    }
  }

  echo $sum;

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

The input is given from Standard Input in the following format:

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


<?php

$input = file_get_contents('php://stdin');
$counts = count_chars($input, 1);
echo count(array_unique($counts)) === 1 ? 'Yes' : 'No';

Score : 200 points

Problem Statement

Let w be a string consisting of lowercase letters.
We will call w beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in w.

You are given the string w. Determine if w is beautiful.

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

The input is given from Standard Input in the following format:

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No


<?php

$data = $argv[1];
$l = strlen($data);

for($i = 0; $i < $l; $i++) {
	$char = substr($data, $i, 1);
	if (substr_count($data, $char) % 2 == 0 ){
		$result = "Yes";
	}
	else{
		$result = "No";
	}
}

echo $result . "\n";
?>


<?php
$w = str_split(trim(fgets(STDIN)));
$count = array_count_values($w);

foreach ($count as $cnt) {
    if ($cnt % 2 != 0) {
        echo 'No';
        die;
    } else {

    }
}
echo 'Yes';


Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

The input is given from Standard Input in the following format:

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

The input is given from Standard Input in the following format:

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


Score : 200 points

Problem Statement

Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip.
At the beginning of Day 1, he is at home. His plan is described in a string S of length N.
On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction:

North if the i-th letter of S is N

West if the i-th letter of S is W

South if the i-th letter of S is S

East if the i-th letter of S is E

He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day N.

Constraints

1 ≦ | S | ≦ 1000

S consists of the letters N, W, S, E.

Input

The input is given from Standard Input in the following format:

S

Output

Print Yes if it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Otherwise, print No.

Sample Input 1

SENW

Sample Output 1

Yes

If Snuke travels a distance of 1 on each day, he will be back at home at the end of day 4.

Sample Input 2

NSNNSNSN

Sample Output 2

Yes

Sample Input 3

NNEW

Sample Output 3

No

Sample Input 4

W

Sample Output 4

No