Codeforces Round #159 (Div. 2) D sum

 
 
D. Sum
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).

Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.

Input

The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an(0 ≤ ai ≤ 109) — the original array.

It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).

Output

In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.

Sample test(s)
input
4
1 2 3 5
output
+++-
input
3
3 3 5
output
++-
 
 題意:給出一組遞增的數a1,a2,a3.....an(a(i - 1) <= a(i) <= 2 * a (i - 1)),在數之間加上‘+’或‘-’運算符算出一個sum,要求0 <=
 
 sum <= a1;(sum開始爲0;)輸出其中一組符合的運算符串(答案有可能不唯一,輸出其中一組可以了且一定有解);
 
 
 
這題一開始不會做。。。想得太複雜了。。。。看別人代碼才知道純數學推導出來
 
~~~~~經驗不足,慚愧慚愧。。。。。
 
 
 
推導:
設數據a1,a2,a3......a(n - 2),a(n - 1),a(n);
 
因爲數據間滿足a(i - 1) <= a(i) <= 2 * a (i - 1);
 
所以a(n) 是最大的;
 
所以從a(n)開始減;
 
因爲a(n - 1) <= a(n) <= 2 * a (n - 1);
 
所以設k = a(n) - a (n - 1);
 
0 <= k <= a(n - 1);
 
因爲 a(n - 2) <= a(n - 1) <= 2 * a (n - 2);且k > 0
 
 0 <= k <= 2 * a(n - 2);
 
所以 k = k - a(n - 2);
 
所以 -a(n - 2) <= k <= a(n - 2);
 
所以 0 <= abs (k) <= a(n - 2);
 
所以當n > 2 時 abs(k)一定在0到 a(n - 2)之間;
 
當K < 0 時, -k就大於0了;
 
在判斷n == 2,1也符合;
 
所以做法很簡單;
 
代碼:
 
 
#include <stdio.h>
__int64 num[100100];
char ch[100100];
int main ()
{
	int n,i,j,k;
	scanf ("%d",&n);
	for (i = 0 ; i < n ; i ++)
		scanf ("%I64d",&num[i]);
	k = num[n - 1];//k 就是 sum; 
	ch[n - 1] = '+';
	for (i = n - 2 ; i >= 0 ; i --)
	{
		if (k >= 0)
		{
			ch[i] = '-';
			k -= num[i];
		}
		else
		{
			ch[i] = '+';
			k += num[i];
		}
	}
	if (k < 0) //當K 小於0 所有符合都要相反,k就邊正了 
	{
		for (i = 0 ; i < n ; i ++)
			printf ("%c",ch[i] == '+' ? '-' : '+');
		printf ("\n");	
	}	
	else
		printf ("%s\n",ch);
}

 
 
 
 
 
 
 
 
 
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章