I guess most of you played cards on the trip to Harbin, but I’m sure you have never played the
following card game. This card game has N rounds and 100000 types of cards numbered from 1 to
100000. A new card will be opened when each round begins. You can “bing” this new card. And if the
card you last “bing” is the same with this new one, you will get 1 point. You can ”bing” only one card,
but you can change it into a new one. For example, the order of the 4 cards is 1 3 4 3. You can “bing”
1 in the first round and change it into 3 in the second round. You get no point in the third round, but
get 1 point in the last round. Additionally, there is a special card 999. If you “bing” it and it is opened
again, you will get 3 point.
Given the order of N cards, tell me the maximum points you can get.
Input
The input file will contain multiple test cases. Each test case will consist of two lines. The first line of
each test case contains one integer N (2 N 100000). The second line of each test case contains a
sequence of n integers, indicating the order of cards. A single line with the number ‘0’ marks the end
of input; do not process this case.
Output
For each input test case, print the maximum points you can get.
Sample Input
2
1 1
5
1 999 3 3 999
0
Sample Output
1
3
给你一张牌 遇到相同的你可以得一分,每次你可以选择是否换掉手上的牌。
基础dp 当前牌的分数 可以由 上一张相同的位置+1,或者上一张牌的最大值中得到。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int n;
int dp[101010];
int pre[101010];
int main()
{
while(cin>>n&&n)
{
memset(dp,0,sizeof(dp));
memset(pre,-1,sizeof(pre));
int maxx=0;
for(int i=0;i<n;i++)
{
int d;
scanf("%d",&d);
if(d!=999)
{
if(pre[d]!=-1)
{
dp[i]=max(maxx,dp[pre[d]]+1);
}
else dp[i]=maxx;
}
else
{
if(pre[d]!=-1)
{
dp[i]=max(maxx,dp[pre[d]]+3);
}
else dp[i]=maxx;
}
maxx=max(dp[i],maxx);
pre[d]=i;
}
printf("%d\n",maxx );
}
}