暑假练习:uva11400(最长上升子序列)

题目链接:uva11400

解析:这题的题意比较难理解,题目给出每种灯泡的电压v,电源费用k,灯泡的费用c,灯泡数量l。那么其中一种灯泡需要花的钱d[i] = l[i] * c[i] + k[i]。现在要求求出最少费用,那问题就变成了:是前i种灯泡全用灯泡i省钱,还是前i种灯泡中选不同种灯泡省钱。状态d[i]就代表了前i种灯泡中最小费用,转移方程就是min{ d[j] + (s[i] - s[j]) * c[i] + k[i] },其中s[i]是前i种灯泡的总数量。

代码实例:出自算法竞赛入门经典-刘汝佳

// UVa11400 Lighting System Design
// Rujia Liu
#include<iostream>
#include<algorithm>
using namespace std;

const int maxn = 1000 + 5;

struct Lamp {
  int v, k, c, l;
  bool operator < (const Lamp& rhs) const {
    return v < rhs.v;
  }
} lamp[maxn];

int n, s[maxn], d[maxn];

int main() {
  while(cin >> n && n) {
    for(int i = 1; i <= n; i++)
      cin >> lamp[i].v >> lamp[i].k >> lamp[i].c >> lamp[i].l;
    sort(lamp+1, lamp+n+1);
    s[0] = 0;
    for(int i = 1; i <= n; i++) s[i] = s[i-1] + lamp[i].l;
    d[0] = 0;
    for(int i = 1; i <= n; i++) {
      d[i] = s[i] * lamp[i].c + lamp[i].k; // 前i个灯泡全买类型i
      for(int j = 1; j <= i; j++)
        d[i] = min(d[i], d[j] + (s[i] - s[j]) * lamp[i].c + lamp[i].k);
    }
    cout << d[n] << "
";
  }
  return 0;
}
原文地址:https://www.cnblogs.com/long98/p/10352223.html