题目描述:

Vasya is reading a e-book. The file of the book consists of 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 1≤t≤103) — the number of testcases.

Each testcase is denoted by a line containing four integers 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 −1.

INPUT:

3
10 4 5 2
5 1 3 4
20 4 19 3

OUTPUT:

4
-1
5

记得fmax和fmin要开G++编译器!

#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int main(){
	int t,p,a,b,x;
	cin>>t;
	while(t--){
		long long sum=0;
		cin>>p>>a>>b>>x;
		if(a==b){
			cout<<0<<endl;
		}else{
			int k=abs(a-b);
			
			if(k%x==0){
				sum=k/x;
				cout<<sum<<endl;
			}else{
				/*两种情况,a->1->b,a->p->b*/
				int m1,m2;
				if((a-1)%x==0){
					sum+=(a-1)/x;
				}else{
					sum+=(a-1)/x+1;
				}
				if((b-1)%x==0){
					sum+=(b-1)/x;
				}else{
					sum=-1;
				}
				m1=sum;
				sum=0;
				if((p-a)%x==0){
					sum+=(p-a)/x;
				}else{
					sum+=(p-a)/x+1;
				}
				if((p-b)%x==0){
					sum+=(p-b)/x;
				}else{
					sum=-1;
				}
				m2=sum;
				//cout<<m1<<endl<<m2<<endl<<endl;
				if(m1!=-1&&m2!=-1){
					if(m1<m2){
						cout<<m1<<endl;
					}else{
						cout<<m2<<endl; 
					}
					//cout<<fmin(m1,m2)<<endl;
				}if(m1!=-1&&m2==-1){
					cout<<m1<<endl;
				}if(m1==-1&&m2!=-1){
					cout<<m2<<endl;
				}if(m1==-1&&m2==-1){
					cout<<-1<<endl;
				}
			}
		}
	}
	return 0;
} 

  

相关文章: