7-2 Number Game (35分)
A number game is to start from a given number A, and to reach the destination number B by a sequence of operations.
For the current number X, there are 3 types of operations:
- X=X+1
- X=X−1
- X=X×N
Your job is to find the minimum number of steps required to reach B from A.
Input Specification:
Each input file contains several test cases. The first line gives a positive integer K (≤10) which is the total number of cases. For each case, three integers are given: A, B and N, where − and 1. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in a line the minimum number of steps required to reach B from A.
Sample Input:
3
3 11 2
-5 -12 3
-2 1000 7
Sample Output:
3 2 13
AC代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int maxn=200005; 5 bool vis[maxn]; 6 queue<int> que,q; 7 int handle(int a,int b,int n) 8 { 9 if(a==b) return 0; 10 memset(vis,0,sizeof(vis)); 11 vis[a]=true; 12 while(!que.empty()) que.pop(); 13 while(!q.empty()) q.pop(); 14 que.push(a); 15 q.push(0); 16 while(!que.empty()) 17 { 18 int x=que.front(),y=q.front(); 19 que.pop();q.pop(); 20 int z=x+1; 21 if(z<200000 && vis[z]==false){ 22 if(z==b) return y+1; 23 vis[z]=true; 24 que.push(z); 25 q.push(y+1); 26 } 27 z=x-1; 28 if(z>0 && vis[z]==false){ 29 if(z==b) return y+1; 30 vis[z]=true; 31 que.push(z); 32 q.push(y+1); 33 } 34 z=x*n; 35 if(z<200000 && vis[z]==false){ 36 if(z==b) return y+1; 37 vis[z]=true; 38 que.push(z); 39 q.push(y+1); 40 } 41 } 42 } 43 int main() 44 { 45 int t; 46 for(scanf("%d",&t);t;--t){ 47 int a,b,n,ans=0; 48 scanf("%d %d %d",&a,&b,&n); 49 if(a==b) ans=0; 50 else if(a<b){ 51 if(a>0) ans=handle(a,b,n); 52 else if(a<=0 && b>0) ans=handle(1,b,n)+1-a; 53 else ans=b-a; 54 } 55 else{ 56 if(a<0) ans=handle(-a,-b,n); 57 else if(a>=0 && b<0) ans=handle(1,-b,n)+a+1; 58 else ans=a-b; 59 } 60 printf("%d ",ans); 61 } 62 return 0; 63 }