poj 1738 取石子游戏 区间dpgarsiawachs算法

17 篇文章 0 订阅

http://poj.org/problem?id=1738

Description

There is an old stone game.At the beginning of the game the player picks n(1<=n<=50000) piles of stones in a line. The goal is to merge the stones in one pile observing the following rules: 
At each step of the game,the player can merge two adjoining piles to a new pile.The score is the number of stones in the new pile. 
You are to write a program to determine the minimum of the total score. 

Input

The input contains several test cases. The first line of each test case contains an integer n, denoting the number of piles. The following n integers describe the number of stones in each pile at the beginning of the game. 
The last test case is followed by one zero. 

Output

For each test case output the answer on a single line.You may assume the answer will not exceed 1000000000.

Sample Input

1
100
3
3 4 3
4
1 1 1 1
0

Sample Output

0
17
8
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<queue>
using namespace std;
const int N=50005;
int stone[N],ans,j;
void add(int k)
{
    int tem=stone[k]+stone[k-1];
    ans+=tem;
    for(int i=k ; i<j-1; i++)
    {
        stone[i]=stone[i+1];
    }
    j--;
    int m;
    for(m=k-1 ; m>0 && stone[m-1]<tem ; m--)
    {
        stone[m]=stone[m-1];
    }
    stone[m]=tem;
    while(m>=2 && stone[m-2]<=stone[m])
    {
        int d=j-m;
        add(m-1);
        m=j-d;
    }
}
int main()
{
    int n;
    while(cin>>n && n)
    {
        for(int i=0; i<n; i++)
            cin>>stone[i];
        j=1;ans=0;
        for(int i=1; i<n; i++)
        {
            stone[j++]=stone[i];
            while(j>=3 && stone[j-3]<=stone[j-1])
                      add(j-2);
        }
        while(j>1) add(j-1);
        cout<<ans<<endl;
    }
    return 0;
}

算法解释: http://fanhq666.blog.163.com/blog/static/81943426201062865551410/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值