Vasya and Book

本文介绍了一种算法,用于计算从当前页面跳转到目标页面所需的最小按钮点击次数。适用于电子书阅读器,屏幕显示固定数量页面的情况下,通过前后翻页按钮实现高效页面跳转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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≤103) — the number of testcases.

Each testcase is denoted by a line containing four integers n, x, y, d (1≤n,d≤109, 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.


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.

 

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cmath>
 6 using namespace std;
 7 int main(){
 8     int t,n,x,y,d,tmp,min_page;
 9     scanf("%d",&t);
10     while (t--){
11         tmp = 0;
12         min_page = 1e+9;
13         scanf("%d%d%d%d",&n,&x,&y,&d);
14         //第一种情况:可直接翻过
15         if (abs(x - y) % d == 0)
16             min_page = min(min_page,abs(x - y) / d);
17         //第二种情况:先往前翻页,再往后翻页
18         if ((y - 1) % d == 0){
19             tmp += (x - 1) / d + (y - 1) / d;
20             if((x - 1) * 1.0 / d != 0)
21                 tmp++;
22             min_page = min(min_page,tmp);
23         }
24         //第三种情况:先往后翻页,再往前翻页
25         tmp = 0;
26         if ((n - y) % d == 0){
27             tmp += (n - y) / d + (n - x) / d;
28             if((n - x) * 1.0 / d != 0)
29                 tmp++;
30             min_page = min(min_page,tmp);
31         }
32         if (min_page == 1e+9)
33             printf("-1\n");
34         else
35             printf("%d\n",min_page);
36     }
37     return 0;
38 }
View Code

 

 

转载于:https://www.cnblogs.com/Luckykid/p/10054948.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值