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

· · 题解

关键性质

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

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

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

性质证明

于是从 $a_s$ 开始打,$a_s$ 会一层层把它的所有祖先都带上,一直到根 $a_n$。 ## 答案统计 每个点的权值是相应的数字在数组中出现的次数,数 $i$ 的答案为根节点为 $i$ 的子树的权值和。 ## ACcode ```cpp #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; } ```