想吃冰卻又敏感保護不足?直擊★美車模手癢不小心...正妹的東京自助旅行學生退場 NHK:馬面...
2012-03-18 17:49:47 人氣(441) | 回應(0) | 推薦(0) | 收藏(0) 上一篇 | 下一篇

[UVA] 846 - Steps

0
收藏
0
推薦


  Steps 

One steps through integer points of the straight line. The length of a step must be nonnegative and can be by one bigger than, equal to, or by one smaller than the length of the previous step.

What is the minimum number of steps in order to get from x to y? The length of the first and the last step must be 1.

Input and Output 

Input consists of a line containing n, the number of test cases. For each test case, a line follows with two integers: 0$ le$x$ le$y < 231. For each test case, print a line giving the minimum number of steps to get from x to y.

Sample Input 

3
45 48
45 49
45 50

Sample Output 

3
3
4

做法 : Greedy
例如
L = 3 => 1+1+1
L = 4 => 1+2+1
L = 5 => 1+2+1+1 ...
#include <stdio.h>
#include <math.h>
int main() {
int t, x, y, L;
scanf("%d", &t);
while(t--) {
scanf("%d %d", &x, &y);
L = y-x;
int steps = 0, n = (int)sqrt(L);
steps = n;
L -= n*(n+1)/2;
while(L > 0) {
while(n*(n+1)/2 > L)
n--;
if(n*(n+1)/2 == L)
L = 0, steps += n;
else
L -= n, steps ++;
}
printf("%d\n", steps);
}
return 0;
}
 

846Steps
台長:Morris
人氣(441) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 694 - The Collatz Sequence
此分類上一篇:[UVA] 1260 - Sales

我要回應
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入以下數字 (ex:123)

(有*為必填)
詳全文