DANCING
We restate the problem:
Given a sequence a1, a2, ..., an (ai > 0) and the following operation: choose any three consecutive numbers (ai-1, ai, ai+1), change them into (ai-1 + ai, -ai, ai + ai+1). After some operations, we obtain the sequence (b1, b2, ..., bn). Given (b1, b2, ..., bn), find the initial sequence.
Solution:
Let Si=a1+a2+...+ai
To change (ai-1, ai, ai+1) into (ai-1 + ai, -ai, ai + ai+1) in a is equivalent to change (Si-1, Si) into (Si, Si-1) in S, that is exchange the ith and (i+1)th element. Sn's position is never changed.
So we have the following algorithm:
• Calculate Si = b1 + b2 + ... + bi for 1 <= i <= n-1
•Then we sort Si increasingly. Suppose the new order of S is S1, S2, ..., Sn-1.
• Let S0 = 0 and Sn = b1 + b2 + ... + bn, we have ai = Si - Si-1 for all 1 <= i <= n.
This is the initial sequence a1, a2, ..., an.
Ta thu được dãy ban đầu a1, a2, ..., an
• If the initial sequence does not satisfy ai > 0 for all i (because Si is sorted increasingly, we already have ai >= 0 for all 2 <= i <= n-1), print -1. Otherwise sequence a is exactly the solution of the problem.
Algorithm complexity: O(nlogn)
KINGDOM
This problem can be solved by using dynamic programming in a tree. Let f[u, t] be the maximum value obtained from the subtree root u when we have a budget of t.
Suppose u have k child nodes v1, v2, ..., vk. So:
f[u, t] = V(u) + max{ f[v1, t1] + f[v2, t2] + ... + f[vk, tk] | t1 + t2 + ... + tk = t - C(u) }
To computemax{ f[v1, t1] + f[v2, t2] + ... + f[vk, tk] | t1 + t2 + ... + tk = t - C(u) }, we use dynamic programming once again in the child nodes of u. That is:g[i, t] = max{ f[v1, t1] + f[v2, t2] + ... f[vi, ti] | t1 + t2 + ... + ti = t}
Analysis:
Let N(u) be the number of child nodes of u.
To compute g, at each node we need about N(u)*t^2 steps. To compute f we need n*t steps.
So the algorithm complexity is about:
n*t + t^2sum(N[u]|u=1..n) = O((t^2).n)
Solution for WIFI and BINLADEN will be posted later.
