Bing it UVALive

来源:互联网 发布:java图形用户界面 编辑:程序博客网 时间:2024/05/29 23:23

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

大致题意:给你n个牌,然后你可以选择某个位置i上的牌“bing”,然后从该位置开始按顺序翻牌,每次你可以将你手中的牌改变成翻开的牌值,如果翻开的牌的值和你手上的牌的值一样,则获得一个点数,而且如果牌的值是999,则获得3个点数,问你所能获得的最大的点数。

思路:简单dp,dp[i]表示到达i位置时所能获得的最大点数,pre[a[i]]记录前一个值为a[i]的坐标,那么状态转移方程为dp[i]=max(dp[i-1],dp[pre[a[i]]+1or3).

代码如下

#include <cstdio>  #include <cstring>  #include <algorithm> #include <iostream> using namespace std;  #define LL long longint pre[100005];int dp[100005];  int a[100005]; int main(){    int n;    while(1)    {        scanf("%d",&n);        if(!n)        break;        memset(pre,0,sizeof(pre));        memset(dp,0,sizeof(dp));        for(int i=1;i<=n;i++)        scanf("%d",&a[i]);        for(int i=1;i<=n;i++)        {            if(pre[a[i]]!=0)//如果前面有与a[i]相同的值             {                if(a[i]==999)                dp[i]=max(dp[i-1],dp[pre[a[i]]]+3);                else                 dp[i]=max(dp[i-1],dp[pre[a[i]]]+1);             }             else                 dp[i]=dp[i-1];            pre[a[i]]=i;//注意更新        }        printf("%d\n",dp[n]);    }     return 0;}
原创粉丝点击