uva 10025 The ? 1 ? 2 ? ... ? n = k problem
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=966 题意:?1?2?3?4...?n=k,把每个?替换成+或者-,找到最小的n使得式子成立。 题意:这道题最关键的一点是。如果s1=1+2+3+.,x+..+n>=k (所有数取正数),那么一定有s2=1+2+3+..-x+..+n=k
非严格证明如下:
s1-s2 = 2x,s1-k=2x
一个数减去偶数,奇偶性不变。x是从1到n中的一个,2*x则包含了s1和s2相差的数所有可能性。
具体做法就是找到一个大于等于k的s1,且s1-k是偶数。
/* ***********************************************
Author :111qqz
Created Time :2016年01月28日 星期四 13时58分24秒
File Name :code/uva/10025.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 k;
7int main()
8{
9 #ifndef ONLINE_JUDGE
10 freopen("code/in.txt","r",stdin);
11 #endif
12 int T;
13 cin>>T;
14 while (T--)
15 {
16 scanf("%d",&k);
17 if (k<0) k = -k;
int sum = 0 ;
int p = int(sqrt(2*k));
1// cout<<"p:"<<p<<endl;
2 for ( int i = p ; ;i++)
3 {
4 sum = (1+i)*i/2;
1 if (sum>=k&&(sum-k)%2==0&&sum>0)
2 {
3 cout<<i<<endl;
4 break;
5 }
6 }
7 if (T)
8 {
9 puts("");
10 }
11 }
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}