1. 硬币找零
题目描述:假设有几种硬币,如1、3、5,并且数量无限。请找出能够组成某个数目的找零所使用最少的硬币数。
分析: dp [0] = 0
dp [1] = 1 + dp [1-1]
dp [2] = 1 + dp [2-1]
dp [3] = min (dp [3 - 1] + 1, dp [3 - 3] + 1)
#include<iostream>
#include<algorithm>
#define INF 32767
using namespace std; int dp[];
int coin[] = { , , }; int main()
{
int sum;
cin >> sum;
dp[] = ;
for (int i = ; i <= ; ++i)
dp[i] = INF;
for (int i = ; i <= sum; ++i)
for (int j = ; j <= ; ++j)
if (coin[j] <= i)
dp[i] = min(dp[i], dp[i - coin[j]] + );
cout << dp[sum] << endl;
return ;
}
2. 最长递增子序列
• 题目描述:最长递增子序列(Longest Increasing Subsequence)是指找到一个给定序列的最长子序列的长度,使得子序列中的所有元素单调递增。
给定一个序列,求解它的最长 递增 子序列 的长度。比如: arr[] = {3,1,4,1,5,9,2,6,5} 的最长递增子序列长度为4。即为:1,4,5,9
#include<iostream>
#include<algorithm>
using namespace std; int arr[] = { , , , , , , , , };
int dp[]; int main()
{
for (int i = ; i < ; ++i)
dp[i] = ;
for (int i = ; i < ; ++i)
for (int j = ; j < i; ++j)
if (arr[i] > arr[j])
dp[i] = max(dp[i], dp[j] + );
int mi = ;
for (int i = ; i < ; ++i)
mi = max(mi, dp[i]);
cout << mi << endl;
return ;
}
3. 数字三角形
Problem description | |
|
|
Input | |
Your program is to read from standard input. The first line contains one integer T, the number of test cases, for each test case: the first line contain a integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99. | |
Output | |
Your program is to write to standard output. The highest sum is written as an integer for each test case one line. | |
Sample Input | |
1 5 |
|
Sample Output | |
30 |
|
Problem Source | |
IOI 1994 |
代码:
#include<iostream>
#include<algorithm>
using namespace std; int dp[][];
int arr[][]; int main()
{
int N;
cin >> N;
if (N == )
cout << N;
for (int i = ; i < N; ++i)
for (int j = ; j <= i; ++j)
cin >> arr[i][j];
for (int i = ; i < N; ++i)
dp[N - ][i] = arr[N - ][i];
for (int i = N - ; i >= ; --i)
for (int j = ; j <= i; ++j)
dp[i][j] = max(arr[i][j] + dp[i + ][j], arr[i][j] + dp[i + ][j + ]);
cout << dp[][] << endl;
return ;
}
4. 最大最大连续子序列和/积
• 求取数组中最大连续子序列和,例如给定数组为A={1, 3, -2, 4, -5}, 则最大连续子序列和为6,即1+3+(-2)+ 4 = 6。
• 求取数组中最大连续子序列积。