1082A--Vasya and Book

题目

Vasya is reading a e-book. The file of the book consists of n pages, numbered from 1 to n. The screen is currently displaying the contents of page x, and Vasya wants to read the page y. There are two buttons on the book which allow Vasya to scroll d pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of 10 pages, and d=3, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.

Help Vasya to calculate the minimum number of times he needs to press a button to move to page y.

Input

The first line contains one integer t (1≤t≤10^3) — the number of testcases.
Each testcase is denoted by a line containing four integers n, x, y, d (1≤n,d≤10^9, 1≤x,y≤n) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.

Output

Print one line for each test.

If Vasya can move from page x to page y, print the minimum number of times he needs to press a button to do it. Otherwise print −1.

Example
input
3
10 4 5 2
5 1 3 4
20 4 19 3
output
4
-1
5
NOTE

In the first test case the optimal sequence is: 4→2→1→3→5

In the second test case it is possible to get to pages 1 and 5.

In the third test case the optimal sequence is: 4→7→10→13→16→19.

题意:Vasya看一本n页的书,打算x页翻到y页,每次只能翻d页(当能翻到第一页或者最后一页时,翻的页数可以小于d);Vasya可以往前或者后翻,求Vasya翻到指定页数的最小次数,如果不能翻到则输出-1.
解题思路:有三种情况,当(x-y)%d == 0时,则直接求出翻的次数count =(x-y)/d;如果无法直接翻到指定页,则有两种情况,其一,翻到第一页后,再向指定页翻,此时需保证(y-1)%d == 0;其二,翻到第n页,然后再翻到第y页,此时需保证(n-y)%d == 0;最后算出最小值,否则无法翻到指定页
AC–Code
import java.util.Scanner;

public class CF1082A {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t-->0)
		{
			int n = sc.nextInt();
			int x = sc.nextInt();
			int y = sc.nextInt();
			int d = sc.nextInt();
			int count = Integer.MAX_VALUE;
			if(Math.abs(y-x)%d==0)
			{
				count = Math.abs(y-x)/d;
			}
			else{
				if((y-1)%d==0)
				{
					int cun = (x-1+d-1)/d;
					cun += (y-1)/d;
					count = cun;
				}
				if((n-y)%d==0)
				{
					int cun = (n-x+d-1)/d;
					cun += (n-y)/d;
					count = Math.min(cun, count);
				}
			}
			if(count==Integer.MAX_VALUE){
				System.out.println(-1);
			}
			else{
				System.out.println(count);
			}
		}
		sc.close();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值