uva 846 Steps
题意:从x增加到y,第一步和最后一步步长只能是1,其他步一定可以是上一步减一,和上一步相等,或者上一步步长加一,三种情况,且步长恒为正。问从x到y最少需要的步数。
思路:首先可以知道,走的最快的方法是1+2+3+...+k+...+3+2+1.这个式子的结果是一个完全平方数,为k^2,式子的长度为2*k-1.即为答案。 我们可以知道k肯定不超过 ceil(sqrt(y-x)).但是中间的k是不一定要加的。再判断k^2减去k是否已经达到结果,如果是,就将答案减一。 注意对于这种做法x=y是特殊情况。。需要特判。。。。
/* ***********************************************
Author :111qqz
Created Time :2016年01月28日 星期四 19时57分44秒
File Name :code/uva/846.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6int x,y;
7int main()
8{
9 #ifndef ONLINE_JUDGE
10 freopen("code/in.txt","r",stdin);
11 #endif
1 int T;
2 cin>>T;
3 while (T--)
4 {
5 scanf("%d %d",&x,&y);
6 if (x==y) {cout<<0<<endl;continue;}
7 int k = ceil(sqrt(y-x));
1 int sum = k*(k-1);
2 int ans = 2*k-1;
3 if (y-x<=sum) ans--;
cout<<ans<<endl; //x,y相等的情况要特判
}
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}
还有一种做法是比较好想的非数学方法。 由于对第一步和最后一步的步长有要求,都是1. 很容易想到从两边往中间走。 然后每走两步(两个方向各一步),后增加一次步长。
/* ***********************************************
Author :111qqz
Created Time :2016年01月28日 星期四 19时57分44秒
File Name :code/uva/846.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6int x,y;
7int main()
8{
9 #ifndef ONLINE_JUDGE
10 freopen("code/in.txt","r",stdin);
11 #endif
1 int T;
2 cin>>T;
3 while (T--)
4 {
5 scanf("%d %d",&x,&y);
6 int step = 1;
7 int len = y-x;
8 int x = 0;
9 int ans = 0 ;
10 while (len>0) //思路关键:从两边往中间走。
11 {
12 len-=step;
13 ans++;
14 if (x) step++;
15 x ^=1;
16 }
17 cout<<ans<<endl;
}
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}