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);
}

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