最长递增子序列系列的两种写法

来源:互联网 发布:拼音输入法的编程语言 编辑:程序博客网 时间:2024/06/05 17:04

第一个案例:  code(vs) 1576 最长严格上升子序列

第一种写法:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int main(){    int n, a[5005], dp[5005], ans = 0;    scanf("%d", &n);    for(int i = 0; i < n; i++)    {        scanf("%d", a+i);        dp[i] = 1;    }    for(int i = 0; i < n; i++)        for(int j = i+1;  j < n; j++)    {        if(a[j] > a[i] && dp[j] < dp[i]+1)            dp[j] = dp[i]+1;        ans = max(ans, dp[j]);    }    printf("%d\n", ans);}
第二种写法:

#include<stdio.h>#include<algorithm>#include<string.h>using namespace std;int main(){    int n, a[5005], ans = 0, dp[5005];    scanf("%d", &n);    for(int i = 0; i < n; i++)    {        dp[i] = 1;        scanf("%d", a+i);        int max1 = 0;        if(i > 0)        {            for(int j = 0; j < i; j++)            {                if(a[i] > a[j] && max1 < dp[j])                    max1 = dp[j];            }            dp[i] = max1+1;            ans = max(ans, dp[i]);        }    }    printf("%d\n", ans);}
第二个案例:code(vs) 3027 线段覆盖2

第一种写法:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;struct Node{    int l, r, v;}node[1005];bool cmp(Node a, Node b){    return a.r < b.r;}int main(){    int n, dp[1005], ans = 0;    scanf("%d", &n);    for(int i = 0; i < n; i++)    {        scanf("%d%d%d", &node[i].l, &node[i].r, &node[i].v);    }    sort(node, node+n, cmp);    for(int i = 0; i < n; i++)    {        dp[i] = node[i].v;    }    for(int i = 0; i < n; i++)    {        for(int j = i+1; j < n; j++)        {            if(node[i].r <= node[j].l && dp[j] < dp[i]+node[j].v)                {                    dp[j] = dp[i]+node[j].v;                }              ans = max(ans, dp[j]);        }    }    printf("%d\n", ans);}

第二种写法:

#include <algorithm>#include <stdio.h>#include <string.h>using namespace std;int n;struct  Node{    int l, r, v;} node[1001];int cmp(const Node x, const Node y){    return x.r < y.r;}int main(void){    scanf("%d", &n);    int ans = 0;    for(int i = 0; i < n; i ++)    {        scanf("%d%d%d", &node[i].l, &node[i].r, &node[i].v);    }    sort(node, node+n, cmp);    for(int i = 1; i < n; i ++)    {        int temp = 0;        for(int j = 0; j < i; j ++)        {            if(node[i].l >= node[j].r)            {                if(temp < node[j].v)                    temp = node[j].v;            }        }        node[i].v = node[i].v + temp;        if(ans < node[i].v)        {            ans = node[i].v;        }    }    printf("%d\n", ans);    return 0;}

个人认为第二种写法比较好。


1 0
原创粉丝点击