您的位置:首页 > 其它

hdu 4960 Another OCD Patient(dp)

2014-08-20 21:05 495 查看

Another OCD Patient

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 645 Accepted Submission(s): 238
Problem Description Xiaoji is an OCD (obsessive-compulsive disorder) patient. This morning, his children played with plasticene. They broke the plasticene into N pieces, and put them in a line. Each piece has a volume Vi. Since Xiaoji is an OCD patient, he can't stand with the disorder of the volume of the N pieces of plasticene. Now he wants to merge some successive pieces so that the volume in line is symmetrical! For example, (10, 20, 20, 10), (4,1,4) and (2) are symmetrical but (3,1,2), (3, 1, 1) and (1, 2, 1, 2) are not.
However, because Xiaoji's OCD is more and more serious, now he has a strange opinion that merging i successive pieces into one will cost ai. And he wants to achieve his goal with minimum cost. Can you help him?
By the way, if one piece is merged by Xiaoji, he would not use it to merge again. Don't ask why. You should know Xiaoji has an OCD. Input The input contains multiple test cases.
The first line of each case is an integer N (0 < N <= 5000), indicating the number of pieces in a line. The second line contains N integers Vi, volume of each piece (0 < Vi <=10^9). The third line contains N integers ai (0 < ai <=10000), and a1 is always 0.
The input is terminated by N = 0. Output Output one line containing the minimum cost of all operations Xiaoji needs. Sample Input
5
6 2 8 7 1
0 5 2 10 20
0

Sample Output
10

Hint

In the sample, there is two ways to achieve Xiaoji's goal.
[6 2 8 7 1] -> [8 8 7 1] -> [8 8 8] will cost 5 + 5 = 10.
[6 2 8 7 1] -> [24] will cost 20. 

Author
SYSU
Source
2014 Multi-University Training Contest 9
今天比赛的时候想到记忆化搜索,时间复杂度n^2logn,不过想想实际,也就n^2的复杂度,因为这个复杂度,怕被卡时间,所以
也没什么信心打,结果跟队友码别的题,码到最后才发现思路错了,囧
view code#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 5010;
int  L
, R
, cnt;
ll dp
, sum
, a
, v
, n;
bool vis
;

int find(int l, int r, ll x)
{
int n = r;
while(l<=r)
{
int m = (l+r)>>1;
if(sum
-sum[m-1]==x) return m;
if(sum
-sum[m-1]>x) l=m+1;
else r = m-1;
}
return 0;
}

void init()
{
cnt = 0;
for(int l=1; l<=n; l++)
{
int r = find(l+1, n, sum[l]);
if(!r) continue;
L[cnt] = l;
R[cnt++] = r;
}
}

ll dfs(int pos, int l, int r)
{
if(l>=r) return 0;
if(dp[l]!=-1) return dp[l];
ll& ans=dp[l];
ans = v[r-l+1];
for(int i=pos; i<cnt; i++)
{
ans = min(dfs(i+1, L[i]+1,R[i]-1)+v[L[i]-l+1]+v[r-R[i]+1], ans);
}
return ans;
}

void solve()
{
for(int i=1; i<=n; i++){
scanf("%I64d", &a[i]);
sum[i] = sum[i-1]+a[i];
}
for(int i=1; i<=n; i++) scanf("%I64d", v+i);
init();
memset(dp, -1, sizeof(dp));
printf("%I64d\n",dfs(0, 1, n));
}

int main()
{
//    freopen("in.txt", "r", stdin);
while(scanf("%I64d", &n)>0 && n) solve();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: