一、题目
Suppose you are a baker planning to bake some hand-made cream breads.
To bake a cream bread, we need to use one slice of bread and one kind of cream. Each hand-made cream bread has a taste score to describe how delicious it is, which is obtained by multiplying the taste score for bread and the taste score for cream. (The taste scores could be negative, howerver, two negative tast scores can still produce delicious cream bread.)
The bread and cream are stored separately.
The constraint is that you need to examine the breads in a given order, and for each piece of bread, you have to decide immediately (without looking at the remaining breads) whether you would like to take it.
After you are finished with breads, you will take the same amount of cream in the same manner. The breads and creams you take will be paired in the same order as you take them.
Given N taste scores for bread and M taste scores for cream, you are supposed to calculate the maximum total taste scores for all hand-made cream bread.
Input Specification: Each input file contains one test case. For each case, the first line contains two integers N and M (1≤N,M≤1e3 ), which are the numbers of bread and cream, respectively. The second line gives N taste scores for bread. The third line gives M taste scores for cream. The taste scores are integers in [?1e3 ,1e3 ].
All the numbers in a line are separated by a space.
Output Specification: Print in a line the maximum total taste score.
Sample Input: 3 4 -1 10 8 10 8 11 9
Sample Output: 188
Hint: The maximum total taste score for the sample case is 10×10+8×11=188.
二、思路
动态规划。考察从第一个面包breadscore[1]选到第i块面包breadscore[i],从第一个奶油creamscore[1]选到第j个奶油creamscore[j],乘积最大的搭配finalscore[i][j]。
如果第 i 块面包和第j个奶油搭配,则 finalscore[i][j] = finalscore[i-1][j-1]+ breadscore[i] * creamscore[j],如果不搭配,那么就回到上一个面包 finalscore[i - 1][j],或上一个奶油 finalscore[i][j - 1] 的结论。
三、代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
using namespace std;
#define maxsize 1001
int Max(int n1, int n2, int n3)
{
int max;
if (n1 >= n2 && n1 >= n3)
max = n1;
else if (n2 >= n1 && n2 >= n3)
max = n2;
else
max = n3;
return max;
}
int max(int x, int y)
{
if (x > y) return x;
else return y;
}
int n,m,ans;
int breadscore[maxsize], creamscore[maxsize];
int finalscore[maxsize][maxsize];
int main() {
scanf_s("%d %d",&n,&m);
for (int i = 1; i <= n; i++) {
scanf_s("%d",&breadscore[i]);
}
for (int i = 1; i <= m; i++) {
scanf_s("%d", &creamscore[i]);
}
for (int i = 1; i <= n;i++) {
for (int j = 1; j <= m; j++) {
finalscore[i][j] = Max(finalscore[i-1][j-1]+ breadscore[i]* creamscore[j], finalscore[i - 1][j], finalscore[i][j - 1]);
ans = max(ans, finalscore[i][j]);
}
}
printf("%d",ans);
return 0;
}
|