数据结构六——动规与贪心
作者:互联网
动态规划
例1:和最大的连续子序列
例2:最长递增子序列
code
#include<stdio.h>
const int MAXN = 12000;
int n, a[MAXN + 1], dp[MAXN + 1];
int longestNum(){
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = 1;
for (int j = 1; j < i; j++)
if (a[j] < a[i] && dp[j] + 1 > dp[i]) dp[i] = dp[j] + 1;
}
int max = 0;
for (int i = 1; i <= n; i++)
if (dp[i] > max) max = dp[i];
return max;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
printf("%d", longestNum());
return 0;
}
#include<stdio.h> //nlogn解法
const int MAXN = 12000;
int n, a[MAXN + 1], b[MAXN + 1];
void binSearch(int x, int l, int r) {
//找到b[l]...b[r]中比x大的最小的数,替换成x。 保证b[r]>x.
if (r > l) {
int mid = (r + l) / 2;
if (b[mid] == x) return;
else if (b[mid] > x) binSearch(x, l, mid);
else if (b[mid] < x) binSearch(x, mid + 1, r);
}
else b[r] = x;
}
int longestNum() {
int max = 1;
b[1] = a[1];
for (int i = 2; i <= n; i++) {
if (a[i] < b[max]) binSearch(a[i], 1, max);
else if (a[i] > b[max]) b[++max] = a[i];
}
return max;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
printf("%d", longestNum());
return 0;
}
最优矩阵乘法
贪心算法
例1:最大订单问题
例2:任务安排问题
code
#include<stdio.h>
const int Maxn = 100;
const int MaxConsume = 200;
int n, r[Maxn + 1], p[Maxn + 1];
int taskProcess() {
int cnt = 0, t = 0, tasknum = n;
while (tasknum) {
int min = MaxConsume + 1, minIndex;
for (int i = 1; i <= n; i++)
if (t >= r[i] && p[i] > 0 && p[i] < min) {
min = p[i]; minIndex = i;
}
p[minIndex]--; t++;
if (!p[minIndex]){
cnt += t; tasknum--;
}
}
return cnt;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &r[i]);
for (int i = 1; i <= n; i++) scanf("%d", &p[i]);
printf("%d", taskProcess());
return 0;
}
排序不等式
更多例子
摔鸡蛋
标签:int,max,mid,binSearch,MAXN,动规,数据结构,dp,贪心 来源: https://blog.csdn.net/m0_53100741/article/details/117301175