[USACO2008 MAR]土地购买 Bzoj1597

将所有矩形按照长度l[i]从小到大排序,用f[i]表示买下前i个矩形的最小花费,那么容易得到方程f[i]=min(j=0->i-1,{max(k=i->n, {w[k]})*l[j+1]+f[j]}),复杂度为O(n^2)。

考虑把所有矩形看成直角坐标系中的点Pi(l[i],w[i]),那么显然如果对于点Pi存在某个点Pk使得l[k]>=l[i]&&w[k]>=w[i],那么矩形i将没有意义,只要买下了矩形k就必然买下了矩形i,因此可以将矩形i删去。删掉多余点后,会发现各个点的纵坐标是单调递减的!

按各点x坐标排序,这样一来动规方程就变为了f[i]=min(f[j]+x[i]*y[j+1])。可以证明,f[i]是单调递增的(例如用四边形不等式)。这样就转化成了1D1D动态规划的最简单模型了。

使用一个队列保存每一个决策控制的下标范围,用二分查找来更新范围,总的复杂度降至O(nlogn)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <deque>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

struct Point
{
  int x, y;
  Point(const int _x = 0, const int _y = 0): x(_x), y(_y) { }
  bool operator<(const Point &rhs) const
  { return (x > rhs.x || (x == rhs.x && y > rhs.y)); }
  bool operator==(const Point &rhs) const
  { return (x >= rhs.x && y > rhs.y); }
};
struct Decision
{
  int left, right, index;
  Decision(const int _left = 0, const int _right = 0, const int _index = 0):
    left(_left), right(_right), index(_index) { }
};
vector<Point> a;
deque<Decision> Q;
int n;
long long f[50001];
inline long long W(const int j, const int i)
{ return f[j]+static_cast<long long>(a[i-1].x)*a[j].y; }
int Find(const Decision &d, const int i)
{
  int left = d.left, right = d.right+1;
  while (right-left > 1)
  {
    int mid = (left+right)>>1;
    if (W(i, mid) < W(d.index, mid))
      right = mid;
    else
      left = mid;
  }
  return left;
}
int main()
{
  ios::sync_with_stdio(false);
  cin >> n;
  for (int i = 0, x, y; i != n; ++i)
  {
    cin >> x >> y;
    a.push_back(Point(x, y));
  }
  sort(a.begin(), a.end());
  n = unique(a.begin(), a.end())-a.begin();
  a = vector<Point>(a.rbegin()+a.size()-n, a.rend());

  f[0] = 0;
  Q.push_back(Decision(1, n, 0));
  for (int i = 1; i <= n; ++i)
  {
    f[i] = W(Q.front().index, i);
    if (Q.front().left == Q.front().right)
      Q.pop_front();
    else
      ++Q.front().left;
    while (!Q.empty())
    {
      if (W(i, Q.back().left) < W(Q.back().index, Q.back().left))
        Q.pop_back();
      else
      {
        Q.back().right = Find(Q.back(), i);
        break;
      }
    }
    if (Q.empty() || Q.back().right != n)
      Q.push_back(Decision((Q.empty() ? i : Q.back().right)+1, n, i));
  }
  cout << f[n] << endl;
}

Comments