Sample Input 1
6 2 4
Sample Output 1
2
Sample Input 2
7 4 3
Sample Output 2
1
Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:
Move from coordinate 7 to 4
Move from coordinate 4 to 7
Move from coordinate 7 to 4
Move from coordinate 4 to 1
Here, the absolute value of the coordinate of the destination is 1
, and we cannot make it smaller.
Sample Input 3
10 1 2
Sample Output 3
8
Sample Input 4
1000000000000000 1000000000000000 1000000000000000
Sample Output 4
1000000000000000
The answer can be enormous.
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<time.h>
#include<vector>
using namespace std;
long long x,k,d;
int main()
{
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
scanf("%lld%lld%lld",&x,&k,&d);
x = abs(x);
long long t1 = x/d;
//long long t2 = k - t1;
if(t1<=k){//先移动t1次
x -= t1 * d;
k -= t1;
}
else if(t1>k){ //不够t1移动k次
x -= k * d;
k = 0;
}
if(k==0) //k为0先输出了
printf("%lld\n",abs(x));
else{ //因为已经移动到了最近处
k = k % 2; //如果k是偶数,可以循环移动使位置不变,则答案就是x
x -= k * d; //是奇数的话,x还要再移动d
printf("%lld\n",abs(x));
}
return 0;
}
官方题解也是这个思路:
#include <iostream>
#include <algorithm>
using namespace std;
using ll = long long;
int main() {
ll X, K, D;
cin >> X >> K >> D;
X = abs(X);
ll straight = min(K, X / D);
K -= straight;
X -= straight * D;
if (K % 2 == 0) {
cout << X << endl;
} else {
cout << D - X << endl;
}
return 0;
}