码迷,mamicode.com
首页 > 其他好文 > 详细

51nod1022 石子归并 V2

时间:2016-09-17 14:46:04      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

证明w满足四边形不等式,这里w是m的附属量,形如m[i,j]=opt{m[i,k]+m[k,j]+w[i,j]},此时大多要先证明w满足条件才能进一步证明m满足条件
证明m满足四边形不等式
证明s[i,j-1]≤s[i,j]≤s[i+1,j]

#include<cstdio>
#include<cstring>
#include<cctype>
#include<algorithm>
using namespace std;
#define rep(i,s,t) for(int i=s;i<=t;i++)
#define dwn(i,s,t) for(int i=s;i>=t;i--)
#define clr(x,c) memset(x,c,sizeof(x))
#define ll long long
int read(){
	int x=0;char c=getchar();
	while(!isdigit(c)) c=getchar();
	while(isdigit(c)) x=x*10+c-‘0‘,c=getchar();
	return x;
}
const int nmax=2e3+5;
const ll inf=1e17;
ll a[nmax],dp[nmax][nmax],s[nmax][nmax];
void mins(ll &a,ll b){
	if(a>b) a=b;
}
int main(){
	int n=read();rep(i,1,n*2) rep(j,1,n*2) dp[i][j]=inf;
	rep(i,1,n) a[i]=read();
	rep(i,1,n) a[i+n]=a[i];
	rep(i,1,2*n) a[i]+=a[i-1],dp[i][i]=0,s[i][i]=i;
	int t,tp;
	rep(i,1,n-1) rep(j,1,2*n-i) {
		t=j+i;
		rep(k,s[j][t-1],s[j+1][t]) {
			tp=dp[j][k]+dp[k+1][t]+a[t]-a[j-1];
			if(tp<dp[j][t]) dp[j][t]=tp,s[j][t]=k;
		}
	}
	ll ans=inf;
	rep(i,1,n) mins(ans,dp[i][i+n-1]);
	printf("%lld\n",ans);
	return 0;
}

  

基准时间限制:1 秒 空间限制:131072 KB 分值: 160 难度:6级算法题
技术分享 收藏
技术分享 关注
N堆石子摆成一个环。现要将石子有次序地合并成一堆。规定每次只能选相邻的2堆石子合并成新的一堆,并将新的一堆石子数记为该次合并的代价。计算将N堆石子合并成一堆的最小代价。
 
例如: 1 2 3 4,有不少合并方法
1 2 3 4 => 3 3 4(3) => 6 4(9) => 10(19)
1 2 3 4 => 1 5 4(5) => 1 9(14) => 10(24)
1 2 3 4 => 1 2 7(7) => 3 7(10) => 10(20)
 
括号里面为总代价可以看出,第一种方法的代价最低,现在给出n堆石子的数量,计算最小合并代价。
 
Input
第1行:N(2 <= N <= 1000)
第2 - N + 1:N堆石子的数量(1 <= A[i] <= 10000)
Output
输出最小合并代价
Input示例
4
1
2
3
4
Output示例
19

51nod1022 石子归并 V2

标签:

原文地址:http://www.cnblogs.com/fighting-to-the-end/p/5878360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!