题目链接
Codeforces Round 99(Rated for Div. 2) – B Jumps
Description
- You are standing on the OX-axis at point 0 and you want to move to an
integer point x>0. You can make several jumps. Suppose you’re
currently at point y (y may be negative) and jump for the k-th time.
You can: either jump to the point y+k or jump to the point y−1. What
is the minimum number of jumps you need to reach the point x?
Input
- The first line contains a single integer t (1≤t≤1000) — the number of
test cases.
The first and only line of each test case contains the single integer x (1≤x≤106) — the destination point.
Output
- For each test case, print the single integer — the minimum number of
jumps to reach x. It can be proved that we can reach any integer
point x.
输入
5
1
2
3
4
5
输出
1
3
2
3
4
思路
- 先用+k跳,直到pos=1+2+3+…+k=steps(1+k)/2>=x为止
- 如果pos=x 结束
- 如果pos>x 则把之前的每步逐一换成-1跳,则pos=pos-(step+1)
step∈[1,k],不难发现第k步时pos∈[pos−k−1,pos−2],而pos-k<x 所以当x≠pos-1时必然在第k步时pos范围内可达到,而x=pos-1时只能加一次-1步。
AC代码
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int step=0;
while(step*(step+1)/2<n)
step++;
if(step*(step+1)==2*n) cout<<step<<endl;
else{
while(!(n>=step*(step+1)/2-step-1&&n<=step*(step+1)/2-2))
step++;
cout<<step<<endl;
}
}
}