可以先將k取絕對值,只考慮正數k,然後假設?都是+,也就是sum = +1+2+3+....+n,然後當sum > k時,將某些'+'變成'-'湊成k,可以發現把'+'變成'-'時,sum都是減掉偶數,例如Example,sum = +1+2+..+5 = 15,要湊成12,這時候把任一個數變號都是減掉偶數,因此奇數(15)減掉偶數不可能變成偶數(12),所以要把sum往上加,直到sum為偶數為止(因為偶數-偶數=偶數)。
總結:sum = 1+2+3+..+n,如果k為偶數,sum為>=k的最小偶數(偶=偶-偶);如果k為奇數,sum為>=k的最小奇數(奇=奇-偶)。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cmath> | |
using namespace std; | |
int main() | |
{ | |
int Case, k; | |
scanf("%d",&Case); | |
while (Case--){ | |
scanf("%d",&k); | |
k = abs(k); | |
int n = 0; | |
int sum = 0; | |
while (sum < k) sum += (++n); | |
if (k % 2) | |
while (sum % 2 != 1) sum += (++n); | |
else | |
while (sum % 2 != 0) sum += (++n); | |
if (k == 0) printf("3\n"); | |
else printf("%d\n",n); | |
if (Case) printf("\n"); | |
} | |
return 0; | |
} |
沒有留言:
張貼留言