Bing it UVALive - 4764 (简单dp)

本文介绍了一个简单的动态规划问题,通过一个卡片游戏的例子来说明如何计算最大得分。游戏规则包括选择卡片、更换卡片以及根据特定条件获取分数等。文章提供了一段C++代码实现,展示了如何利用动态规划解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 long
int 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值