1. 程式人生 > >CodeForces 859C Pie Rules(dp逆推)

CodeForces 859C Pie Rules(dp逆推)

任重而道遠

You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person.

The way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the "decider" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left.

All of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive?

Input

Input will begin with an integer N (1 ≤ N ≤ 50), the number of slices of pie.

Following this is a line with N integers indicating the sizes of the slices (each between 1 and 100000, inclusive), in the order in which they must be handed out.

Output

Print two integers. First, the sum of the sizes of slices eaten by Alice, then the sum of the sizes of the slices eaten by Bob, assuming both players make their decisions optimally.

Examples

input

3
141 592 653

output

653 733

input

5
10 21 10 21 10

output

31 41

Note

In the first example, Bob takes the size 141 slice for himself and gives the decider token to Alice. Then Alice gives the size 592 slice to Bob and keeps the decider token for herself, so that she can then give the size 653 slice to herself.

 

Solution:

dp[i]表示分到從後往前的第i塊時, 當前拿令牌的人能獲得的最大收益。

需要明確的一點是:dp[i]只與持有令牌有關,與誰持有無關。因為無論是誰,都會採取最優策略去分配。

於是可以得出轉移方程:dp[i] = max (dp[i + 1], sum[i + 1] - dp[i + 1] + a[i]), 其中a[i]為第i塊pie的大小,sum[i]為a[i]字尾和

但由於我們只知道最初持有令牌的是Bob,所以必須逆推。這樣的話,dp[1]就表示Bob最終的收益;

 

AC程式碼:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

int a[55], sum[55], dp[55];

int read () {
	int x = 0, f = 0; char c = getchar ();
	while (!isdigit (c)) f |= (c == '-'), c = getchar ();
	while (isdigit (c)) x = x * 10 + c - '0', c = getchar ();
	return f ? -x : x;
}

int main () {
	int n = read ();
	for (int i = 1; i <= n; i++) a[i] = read ();
	for (int i = n; i >= 1; i--) sum[i] = sum[i + 1] + a[i];
	dp[n] = a[n];
	for (int i = n - 1; i >= 1; i--)
		dp[i] = max (dp[i + 1], sum[i + 1] - dp[i + 1] + a[i]);
	printf ("%d %d", sum[1] - dp[1], dp[1]);
	return 0;
}