zoukankan      html  css  js  c++  java
  • FZU1327 优先队列

    Problem 1327 Blocks of Stones II

    Accept: 318    Submit: 881
    Time Limit: 1000 mSec    Memory Limit : 32768 KB

    Problem Description

    There are n blocks of stones in a line laying on the ground. Now you are to merge these blocks of stones together with the restriction that you can only merge the neighbouring blocks each time. The score you get for each merging is the number of stones the new blocks has.

    Before each merging, you are allowed to swap any neighbouring blocks for any times. You are to calculate the minimal score you will get during the whole process.

    Input

    There are multiple test cases. For each case, the first line contains a integer n(n<=10000), representing the number of blocks. The second line contains n integers, representing number of stones in each blocks.

    Output

    For each case, output one line containing a single integer, representing the minimal score. The results are within 32bit integers.

    Sample Input

    3
    2 5 1

    Sample Output

    11
    题目大意:给你很多堆石头,让你合并这些石头,每次只能合并两堆,且你会得到相当于两堆石头总量的分数,让你将石头合并为一堆,求在这个过程中你得到的最小的分数。
    思路分析:典型贪心题目,每次合并两堆最小的石头,得到的分数是最少的,思路很简单,但是在实现的时候如果是合并一次排序一次,那么时间复杂度将是n^2log2n,会TLE,
    对于本题,我们要充分运用优先队列的性质,内部有序,建立一个最小堆,然后用这个最小堆来模拟石头的合并,效率将大大提高,做这道题的过程也就相当于我优先队列的学习
    过程了,新知识get.
    代码:#include<iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <queue>
    #include <stack>
    #include <map>
    using namespace std;
    priority_queue<int,vector<int>,greater<int> >q;//建立最小堆
    const int maxn=10000+5;
    int a[maxn];
    int main()
    {
        int n,i;
        while(cin>>n)
        {
            int sum=0;
            for(i=0;i<n;i++) cin>>a[i];
            for(i=0;i<n;i++)
                q.push(a[i]);
            int s,k;
            while(q.size()!=1)
            {
                s=q.top();
                q.pop();
                s+=q.top();
                q.pop();
                sum+=s;
                q.push(s);
            }
            cout<<sum<<endl;
                q.pop();
        }
        return 0;
    }
  • 相关阅读:
    C#(99):Queue<T>队列与Stack<T>堆栈
    C#(99):字典Dictionary<Tkey.TValue>与SortedList
    C#(99):列表:List<T>与HashSet和只读集合
    C#(99):C#数组Array
    C#(99):枚举类型与位域枚举Enum
    C#(99):结构类型:Struct
    C#(99):定义类成员(属性、方法、索引、运算符、事件)、接口实现
    C#(99):定义类、System.Object对象、构造函数与析构函数、抽象类与静态类
    SuperSocket.ClientEngine介绍
    C#(99):五、并行编程
  • 原文地址:https://www.cnblogs.com/xuejianye/p/5321475.html
Copyright © 2011-2022 走看看