跳到正文

题解

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

FishDeity约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年11月1日
收录
2026年11月2日
更新
2026年11月9日
篇幅
约 3 分钟
题目
P17830

版本

  1. v1当前

关键性质

对于一局从第 ss 张开始的游戏,最终桌面上留下的点数,就是从 asa_s 沿父亲边一路跳到 ana_n 的那条链。

我们记 lxl_x 为 xx 最后一次出现的位置,则 xx 的父亲就是 alx+1a_{l_x+1},记其为 fxf_x。

由于 lfx>lxl_{f_{x}}>l_x,一直跳最后一定跳到 ana_n,所以这是一棵以 ana_n 为根的树。

性质证明

lxl_x 是 xx 最后一次出现的位置。之后如果还有牌,紧跟着的就是 alx+1a_{l_x+1}。这时 xx 还没被消掉(后面已经没有 xx 了),这张牌会一直把 xx 顶在桌面上,直到它自己被消掉。所以 xx 的“上级”就是 alx+1a_{l_x+1}。

于是从 asa_s 开始打,asa_s 会一层层把它的所有祖先都带上,一直到根 ana_n。

答案统计

每个点的权值是相应的数字在数组中出现的次数,数 ii 的答案为根节点为 ii 的子树的权值和。

ACcode

C++
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define N 500005
#define M 300005

inline LL read(){
	char ch=getchar();
	int w=1;
	LL s=0;
	while(ch<'0'||ch>'9'){
		if(ch=='-')w*=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		s=(s<<3)+(s<<1)+(ch^48);
		ch=getchar();
	}
	return w*s;
}
inline void write(LL n){
	if(n<0)putchar('-'),n=-n;
	if(n>9)write(n/10);
	putchar(n%10+'0');
	return ;
}

LL a[N],cnt[M],ans[M],lst[M];
struct node{
	LL num,lst;
}pos[M];
bool cmp(node x,node y){
	return x.lst<y.lst;
}
int main(){
	LL n=read(),m=read();
	for(LL i=1;i<=n;i++){
		a[i]=read();
		cnt[a[i]]++;
		lst[a[i]]=i;
	}
	for(LL i=1;i<=m;i++){
		pos[i]={i,lst[i]};
		ans[i]=cnt[i];
	}
	sort(pos+1,pos+m+1,cmp);
	for(LL i=1;i<m;i++){
		LL x=pos[i].num;
		LL p=a[lst[x]+1];
		ans[p]+=ans[x];
	}
	for(LL i=1;i<=m;i++){
		write(ans[i]);
		putchar(' ');
	}
	return 0;
}
原文
存档评论1 条抓取于