STL的妙用(二)——洛谷 P2073 送花

题目描述

小明准备给小红送一束花,以表达他对小红的爱意。他在花店看中了一些花,准备用它们包成花束。

这些花都很漂亮,每朵花有一个美丽值W,价格为C。

小明一开始有一个空的花束,他不断地向里面添加花。他有以下几种操作:

操作 含义

1 W C 添加一朵美丽值为W,价格为C的花。

3 小明觉得当前花束中最便宜的一朵花太廉价,不适合送给小红,所以删除最便宜的一朵花。

2 小明觉得当前花束中最贵的一朵花太贵,他心疼自己的钱,所以删除最贵的一朵花。

-1 完成添加与删除,开始包装花束

若删除操作时没有花,则跳过删除操作。

如果加入的花朵价格已经与花束中已有花朵价格重复,则这一朵花不能加入花束。

请你帮小明写一个程序,计算出开始包装花束时,花束中所有花的美丽值的总和,以及小明需要为花束付出的总价格。

正常做法

平衡树模板。略。

STL做法

注意到“加入的花朵价格”不能“与花束中已有花朵价格重复”。也就是说这是一个集合!

那么我们考虑用set来维护。

所用到的数据储存结构如下:

struct node
{
  int w, c;
  node(int w = 0, int c = 0) : w(w), c(c) { }
  friend bool operator< (node a, node b)
  {
    return a.c < b.c;
  }
};
set<node> s;

set的用法

  1. 插入: s.insert((node)xxx)
  2. 删除: s.erase((node)xxx) / s.erase((iterator)it)
  3. 遍历: for(set ::iterator i=s.begin();i!=s.end();++i) (*i).xxx=xxx; / (C++11:) for (auto i : s) i.xxx=xxx;

代码

#include <bits/stdc++.h>
using namespace std;
struct node
{
  int w, c;
  node(int w = 0, int c = 0) : w(w), c(c) { }
  friend bool operator< (node a, node b)
  {
    return a.c < b.c;
  }
};
set<node> s;
int main()
{
  int op;
  cin >> op;
  while (op != -1)
  {
    if (op == 1)
    {
      int w, c;
      cin >> w >> c;
      s.insert(node(w, c));
    }
    if (op == 2)
    {
      if (s.size()) s.erase(--s.end());
    }
    if (op == 3)
    {
      if (s.size()) s.erase(s.begin());
    }
    cin >> op;
  }
  int a1 = 0, a2 = 0;
  for (auto i : s) a1 += i.w, a2 += i.c;
  printf("%d %d\n", a1, a2);
}

猜你喜欢

转载自www.cnblogs.com/water-lift/p/12818234.html