题目来源:http://poj.org/problem?id=1260
问题描述
Pearls
Description In Pearlania everybody is fond of pearls. One company, called The Royal Pearl, produces a lot of jewelry with pearls in it. The Royal Pearl has its name because it delivers to the royal family of Pearlania. But it also produces bracelets and necklaces for ordinary people. Of course the quality of the pearls for these people is much lower then the quality of pearls for the royal family.In Pearlania pearls are separated into 100 different quality classes. A quality class is identified by the price for one single pearl in that quality class. This price is unique for that quality class and the price is always higher then the price for a pearl in a lower quality class. Input The first line of the input contains the number of test cases. Each test case starts with a line containing the number of categories c (1<=c<=100). Then, c lines follow, each with two numbers ai and pi. The first of these numbers is the number of pearls ai needed in a class (1 <= ai <= 1000). Output For each test case a single line containing a single number: the lowest possible price needed to buy everything on the list. Sample Input 2
2
100 1
100 2
3
1 10
1 11
100 12 Sample Output 330
1344 Source |
------------------------------------------------------------
题意
给定一系列等级的物品数和价钱,可以用更高系列的价格买低系列物品,问最少多少钱可以买下所有物品。
------------------------------------------------------------
思路
动态规划。
dp[i][j] = dp[i][j]: 等级[i,c]的珍珠以最低等级为j的价格买入所花的钱
三重循环最小化每个dp[i][j]
------------------------------------------------------------
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
const int INF = 0x3f3f3f3f;
int c;
int a[105], p[105], dp[105][105]; // dp[i][j]: 等级[i,c]的珍珠以最低等级为j的价格买入
int main()
{
#ifndef ONLINE_JUDGE
freopen("1260.txt", "r", stdin);
#endif
int t, i, j, k, ans = INF;
scanf("%d", &t);
while (t--)
{
scanf("%d", &c);
for (i=1; i<=c; i++)
{
scanf("%d%d", a+i, p+i);
}
memset(dp, 0x3f, sizeof(dp));
dp[c][c] = (a[c]+10)*p[c];
for (i = c-1; i > 0; i--)
{
for (j = i; j <= c; j++)
{
if (i+1 <= j)
{
dp[i][j] = dp[i+1][j] + a[i]*p[j];
}
for (k = j + 1; k <= c; k++)
{
dp[i][j] = std::min(dp[i][j], dp[i+1][k] + (a[i]+10)*p[j]);
}
}
}
ans = INF;
for (i=1; i<=c; i++)
{
ans = std::min(ans, dp[1][i]);
}
printf("%d\n", ans);
}
return 0;
}