《挑战程序设计竞赛》2.4.1 数据结构-优先队列 POJ2431 3253 3614 2010(3)

POJ2431

POJ3253

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

题意

有一块长木板,要经过n-1次切割将其切成n块FJ想要的木板,对于每块木板,没切割一次,将会消耗和这条木板长度值相等的金钱,问最少需要多少钱,可将木板切成自己想要的n块。

思路

这个题前面用贪心法已经解过了,贪心法朴素实现时间复杂度是O(N2)。
而如果用优先队列实现,复杂度将是O(N)次O(logN)。

代码

Source Code

Problem: 3253       User: liangrx06
Memory: 348K        Time: 16MS
Language: C++       Result: Accepted
Source Code
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;

int main()
{
    long long sum;
    int i, n, t, a, b;
    while (~scanf("%d", &n)) {
        priority_queue<int, vector<int>, greater<int> >q;
        for (i = 0; i < n; i++) {
            scanf("%d", &t);
            q.push(t);
        }
        sum = 0;
        if (q.size() == 1) {
            a = q.top();
            sum += a;
            q.pop();
        }
        while (q.size() > 1)
        {
            a = q.top();
            q.pop();
            b = q.top();
            q.pop();
            t = a + b;
            sum += t;
            q.push(t);
        }
        printf("%lld\n", sum);
    }
    return 0;
}

POJ3614

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

题意

有C个奶牛去晒太阳 (1 <=C <= 2500),每个奶牛各自能够忍受的阳光强度有一个最小值和一个最大值,太大就晒伤了,太小奶牛没感觉。
而刚开始的阳光的强度非常大,奶牛都承受不住,然后奶牛就得涂抹防晒霜,防晒霜的作用是让阳光照在身上的阳光强度固定为某个值。
那么为了不让奶牛烫伤,又不会没有效果。
给出了L种防晒霜。每种的数量和固定的阳光强度也给出来了
每个奶牛只能抹一瓶防晒霜,最后问能够享受晒太阳的奶牛有几个。

思路

那么将奶牛按照阳光强度的最小值从小到大排序,将防晒霜也按照能固定的阳光强度从小到大排序。
从最小的防晒霜枚举,将所有符合 最小值小于等于该防晒霜的 奶牛的 最大值 放入优先队列之中。
然后优先队列是小值先出,所以就可以将这些最大值中的最小的取出来。更新答案。

代码

#include <iostream> 
#include <algorithm> 
#include <cstring> 
#include <cstdio> 
#include <map> 
#include <vector> 
#include <queue> 
#define MAXN 2555 
#define INF 1000000007 
using namespace std;  
int C, L;  
typedef pair<int, int> P;  
priority_queue<int, vector<int>, greater<int> > q;  
P cow[MAXN], bot[MAXN];  
int main()  
{  
    scanf("%d%d", &C, &L);  
    for(int i = 0; i < C; i++) scanf("%d%d", &cow[i].first, &cow[i].second);  
    for(int i = 0; i < L; i++) scanf("%d%d", &bot[i].first, &bot[i].second);  
    sort(cow, cow + C);  
    sort(bot, bot + L);  
    int j = 0, ans = 0;  
    for(int i = 0; i < L; i++)  
    {  
        while(j < C && cow[j].first <= bot[i].first)  
        {  
            q.push(cow[j].second);  
            j++;  
        }  
        while(!q.empty() && bot[i].second)  
        {  
            int x = q.top();  
            q.pop();  
            if(x < bot[i].first) continue;  
            ans++;  
            bot[i].second--;  
        }  
    }  
    printf("%d\n", ans);  
    return 0;  

你可能感兴趣的:(数据结构,poj,挑战程序设计竞赛)