24h購物| | PChome| 登入
2012-03-18 17:49:47| 人氣1,774| 回應0 | 上一篇 | 下一篇

[UVA] 846 - Steps

推薦 0 收藏 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;
}
 

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

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文