zoukankan      html  css  js  c++  java
  • POJ 1738:An old Stone Game 石子归并 (GarsiaWachs算法)

    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
     1 #include <stdio.h>
     2 #include <iostream>
     3 #include <cstring>
     4 #include <algorithm>
     5 #define MAX 55555
     6 using namespace std;
     7 int a[MAX],n,num,result;
     8 void combine(int k)
     9 {
    10     int i,j;
    11     int temp=a[k]+a[k-1];
    12     result+=temp;
    13     for(i=k;i<num-1;i++)
    14         a[i]=a[i+1];
    15     num--;
    16     for(j=k-1;j>0&&a[j-1]<temp;j--)
    17         a[j]=a[j-1];
    18     a[j]=temp;
    19     while(j>=2&&a[j]>=a[j-2])
    20     {
    21         int d=num-j;
    22         combine(j-1);
    23         j=num-d;
    24     }
    25 }
    26 int main()
    27 {
    28     int i;
    29     while(scanf("%d",&n)&&n){
    30         if(n==0) return 0;
    31         for(i=0;i<n;i++)
    32             scanf("%d",&a[i]);
    33         num=1;
    34         result=0;
    35         for(i=1;i<n;i++){
    36             a[num++]=a[i];
    37             while(num>=3&&a[num-3]<=a[num-1])
    38                 combine(num-2);
    39         }
    40         while(num>1) combine(num-1);
    41         printf("%d
    ",result);
    42     }
    43     return 0;
    44 }
  • 相关阅读:
    esp32(M5STACK)在线体验(Ubuntu)
    esp32(M5STACK)程序烧写(Ubuntu)
    在Ubuntu环境下搭建esp32开发环境
    markdown让文字居中和带颜色
    Doxyfile中插入图片
    System.load 与 System.loadLibrary 的使用
    常见mysql的数据迁移
    mysql中有关树的函数
    spring整合quartz实现动态定时器
    javaweb项目中发布webservices服务
  • 原文地址:https://www.cnblogs.com/wydxry/p/7243286.html
Copyright © 2011-2022 走看看