No.598 Overflow Fantasy
タグ : / 解いたユーザー数 206
作問者 :
koyumeishi
/ テスター :
はむこ
Problem Statement
The computer game Toaru Fantasy manages various numerical values using $N$-bit signed integers (two's complement).
An overflow bug was recently found in Toaru Fantasy, and strategies exploiting it are being studied.
Normally, you defeat an enemy by attacking it and bringing its HP down to 0 or below.
In the overflow bug strategy, on the other hand, you defeat an enemy by deliberately healing its HP, taking advantage of the fact that the enemy is also judged as defeated when its HP becomes 0 or below due to overflow.
Let $X$ be the enemy's initial HP, $A$ be the amount of HP reduced by one attack, and $B$ be the amount of HP increased by one heal.
Each attack and each heal takes 1 unit of time. Find the minimum time required to defeat the enemy.
The enemy never increases or decreases its own HP.
Information for those unfamiliar with two's complement
An integer $x (-2^{N-1} \leq x < 2^{N-1})$ can be represented as an $N$-bit signed integer using a bit sequence $a_{n-1}, a_{n-2}, \dots, a_{3}, a_{2}, a_{1}$ ($a_i$ = 0 or 1) such that
$$
x = - 2^{n-1} * a_{n-1} + \sum_{k=0}^{k < n-1} 2^k * a_k
$$
(see also: binary numeral system)
In other words, the value represented by each bit is as shown in the table below.
bit | N-1 | N-2 | ... | 3 | 2 | 1 | 0 ------|--------|-------|-----|---|---|---|--- value |-2^(N-1)|2^(N-2)| ... | 8 | 4 | 2 | 1
Addition of two integers $x,y (-2^{N-1} \leq x,y < 2^{N-1})$ works the same way as with ordinary integer types.
Any part that goes beyond the most significant bit (carry flag) is ignored.
https://en.wikipedia.org/wiki/Two%27s_complement#Addition
In pseudocode, it looks like this.
// Bit Array A + B => C
carry = 0
for i in [0, N) :
C[i] = (A[i] + B[i] + carry) % 2
carry = floor( (A[i] + B[i] + carry) / 2 )
return C
Input
$N$ $X$ $A$ $B$
The first line gives the bit length $N$ of the integer type used in the game.
The second line gives the enemy's initial HP $X$.
The third line gives the amount $A$ of HP reduced by one attack.
The fourth line gives the amount $B$ of HP increased by one heal.
All inputs are given as integers.
$2\leq N \leq 32$
$1\leq X,A,B < 2^{N-1}$
Output
Output the minimum time required to defeat the enemy.
Sample
Sample 1
Input
4 4 3 1
Output
2
All values are managed as 4-bit signed integers.
Attacking twice defeats the enemy in the minimum time.
First attack
0100 ( 敵の体力 4 ) +)1101 ( -A(=-3) を 2 の補数で表現 ) ------ 0001 ( 残り体力 1 )
Second attack
0001 ( 敵の体力 1 ) +)1101 ( -A(=-3) を 2 の補数で表現 ) ------ 1110 ( 残り体力 -2 )
Sample 2
Input
4 6 2 1
Output
2
Healing the enemy twice causes an overflow, and the enemy is judged as defeated.
0110 ( 敵の体力 6 ) +)0001 ( B(=1) ) ------ 0111 ( 残り体力 7 ) 0111 ( 敵の体力 7 ) +)0001 ( B(=1) ) ------ 1000 ( 残り体力 -8 )
Sample 3
Input
26 16777221 20 20
Output
838861
The enemy can be defeated with 838862 attacks, or with 838861 heals.
提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。