【PAT甲级】1045 Favorite Color Stripe (30 分)(DP)

题意:

输入一个正整数N(<=200),代表颜色总数,接下来输入一个正整数M(<=200),代表喜爱的颜色数量,接着输入M个正整数表示喜爱颜色的编号(同一颜色不会出现两次),接下来输入一个正整数L(<=10000),代表条带的长度,接着输入L个正整数表示条带上的颜色的编号。输出以喜爱颜色顺序排列的最长子串长度(不必每种颜色都有,只保证相对位置相同,同种颜色可连续)。

AAAAAccepted code:

 1 #define HAVE_STRUCT_TIMESPEC
 2 #include<bits/stdc++.h>
 3 using namespace std;
 4 int a[10007],pos[207];
 5 int dp[10007];
 6 int main(){
 7     ios::sync_with_stdio(false);
 8     cin.tie(NULL);
 9     cout.tie(NULL);
10     int n,m;
11     cin>>n>>m;
12     int color;
13     for(int i=1;i<=m;++i){
14         cin>>color;
15         pos[color]=i;//记录颜色的相对位置
16     }
17     int cnt=0;
18     int stripe;
19     int l;
20     cin>>l;
21     for(int i=1;i<=l;++i){
22         cin>>stripe;
23         if(pos[stripe])
24             a[++cnt]=pos[stripe],dp[cnt]=1;//记录条带上颜色在喜爱条带上的位置
25     }
26     int mx=0;
27     for(int i=1;i<=cnt;++i){
28         for(int j=1;j<i;++j)//以相对位置j结尾的都可以在后面加上以相对位置i结尾的颜色
29             if(a[j]<=a[i])
30                 dp[i]=max(dp[i],dp[j]+1);//更新以相对位置i结尾的子串的长度
31         mx=max(mx,dp[i]);//选取最长长度作为答案
32     }
33     cout<<mx;
34     return 0;
35 }

 

 

 

posted @ 2019-09-29 08:49  sewage  阅读(138)  评论(0编辑  收藏  举报