题解:P17830 [CSP-J 2026] 纸牌游戏 / card(民间数据)

· · 题解

P17830 [CSP-J 2026] 纸牌游戏 / card

首先考虑暴力,对于一个位置 i,如果他的右边有等于 a_i 的,那此时操作后就一定只会剩下一个 a_i,可以跳到最后一个 a_i 的后面那个,最后统计。

接着从这个开始推正解,首先我们可以从暴力发现,如果当前的左端点的后面有相同的值,最终的序列就是 end_{a_i} + 1 位置的序列加上一个 a_i,可以直接考虑倒退。

我们接着发现,既然可以继承前面的答案,我们是不是可以直接用一个 tmp 数组指向那个位置,但现在后面其实也是一个东西拼起来的,所以其实就是对连接的一个后缀加上 a_i 的答案,可以直接打上标记。

接着直接更新前缀和数组就是当前位置会有多少局会剩余这个,直接统计答案即可。

#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;
const ll N = 5e5 + 5;
const ll M = 1e5 + 5;
const ll INF = 1e18;
const ll MOD = 1e9 + 7;
int n,m,a[N],tmp[N],cnt[N],ans[N];
vector<int> E[N];
void work(){
    cin >> n >> m;
    for(int i = 1;i <= n;i++){
        cin >> a[i];
    }
    for(int i = n;i >= 1;i--){
        if(tmp[a[i]] == 0){
            tmp[a[i]] = i;
            E[i + 1].push_back(i);
            cnt[i]++;
        }else{
            cnt[i]++;
            E[tmp[a[i]] + 1].push_back(i);
        }
    }
    for(int i = 1;i <= n;i++){
        for(auto x : E[i]){
            cnt[i] += cnt[x];
        }
    }
    for(int i = 1;i <= n;i++){
        ans[a[i]] += cnt[i];
    }
    for(int i = 1;i <= m;i++){
        cout << ans[i] << " ";
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);cout.tie(nullptr);
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    int oT_To = 1;
    //cin >> oT_To;
    while(oT_To--){ work();}
    return 0;
}

已经通过民间数据。