动态规划(pta例题)

本文介绍了动态规划在解决算法问题中的应用,包括求解最长单调递增子序列的O(n^2)算法和解决游船租借问题的策略,提供输入输出样例及个人理解,旨在帮助读者理解动态规划的运用。

可恶的动态规划篇(DP篇)

正如你们所见,大二老狗开始接触算法了,今天就来讲讲动态规划,废话不多说。
贴题
7-1
设计一个O(n2)时间的算法,找出由n个数组成的序列的最长单调递增子序列。

输入格式:
输入有两行: 第一行:n,代表要输入的数列的个数 第二行:n个数,数字之间用空格格开

输出格式:
最长单调递增子序列的长度

输入样例:
在这里给出一组输入。例如:

5
1 3 5 2 9
输出样例:
4

#include<bits/stdc++.h>
using namespace std;
#define num 100
int a[num];
int LMax(int n){
   
   
    int b[num]={
   
   0};
    b[1]=1;//数组只有一个数时,最长为1
    int max=0;
    for(int i=2;i<=n;i++){
   
   
       
        for(int j=1;j
### C语言编程例题及解答 #### 使用PTA平台进行C语言编程练习 PTA程序设计类实验辅助教学平台是一个在线编程平台,旨在为学生提供良好的编程实践环境,帮助学生掌握编程语言和编程思想,提高程序设计能力。该平台提供了丰富的编程练习题目和实验题目,学生可以在线编辑代码并提交解答,平台会自动判断答案的正确性并给出反馈[^1]。 下面展示几个常见的C语言编程实例及其解决方案: #### 实现投票统计功能 ```c #include <stdio.h> #include <string.h> int main() { char votes[] = "ABCAACBB"; int count[256] = {0}; for (int i = 0; i < strlen(votes); ++i) { count[votes[i]]++; } printf("Vote statistics:\n"); for (char ch = 'A'; ch <= 'Z'; ++ch) { if (count[ch]) { printf("%c : %d\n", ch, count[ch]); } } return 0; } ``` 这段代码实现了简单的投票统计功能,通过遍历字符数组`votes`来计算每个字母出现次数,并输出结果[^2]。 #### 判断某一年是否为闰年 ```c #include <stdbool.h> #include <stdio.h> bool isLeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } int main() { int year; scanf("%d", &year); if (isLeapYear(year)) { printf("%d 是闰年。\n", year); } else { printf("%d 不是闰年。\n", year); } return 0; } ``` 此段代码定义了一个名为`isLeapYear()`的函数用来判定给定的一年是不是闰年,并在主函数中调用了这个函数来进行具体测试。 #### 打印杨辉三角形 ```c #include <stdio.h> void printPascalTriangle(int nRows) { long pascalValue = 1; for (int line = 0; line < nRows; ++line) { for (int space = 0; space < nRows - line - 1; ++space) { printf(" "); } for (int col = 0; col <= line; ++col) { printf("%ld ", pascalValue); pascalValue = pascalValue * (line - col) / (col + 1); } printf("\n"); pascalValue = 1; } } int main() { int rows; scanf("%d", &rows); printPascalTriangle(rows); return 0; } ``` 上述代码展示了如何构建以及打印指定行数的杨辉三角形,其中利用了组合数学中的性质简化了计算过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值