Official

B - Hammer Editorial by en_translator


This problem can be solved with a proper case division.

In general, when a problem requires dividing into cases, it is important to reduce the branches as much as possible.

For example, in this problem, we can assume that the coordinate of the wall is always positive, and the branches are reduced.

By multiplying by \(-1\) to all if necessary, we can assume that the coordinate \(Y\) of the wall is positive, and we can solve the problem with the following conditional branches:

  • If \(X<Y\), he can directly head to the goal.
  • If \(X>Y\), he need to pick the hammer up to reach the goal.
    • If \(Z>Y\), he cannot pick the hammer up.
    • If \(Z<Y\), he first goes to \(Z\) to pick the hammer up, and then head to the goal \(X\).

Sample Code (C)

#include<stdio.h>
#include<stdlib.h>

int main(){
	int x,y,z;
	scanf("%d%d%d",&x,&y,&z);
	
	if(y<0){
		x=-x;
		y=-y;
		z=-z;
	}
	
	if(x<y){
		printf("%d\n",abs(x));
	}else{
		if(z>y){
			puts("-1");
		}else{
			printf("%d\n",abs(z)+abs(x-z));
		}
	}
}

posted:
last update: