Codeforces Round #624 (Div. 3)C. Perform the Combo

题意:
给一个长度为 n 的字符串str 和一个有 m 个元素的数列p。
统计 str 的前p[i]个元素的字母出现的个数
最后再加上 str 所有字母出现的次数
输出26个字母出现的次数
思路:
原本的思路是 开一个二维数组来维护26个字母的个数,累加求和即可。但是TLE

/*****************************
*author:ccf
*source:cf_round_624_C
*topic:
*******************************/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#define ll long long
using namespace std;

const int N = 2e5+7;
int cas,n,m;
int cnt[200],p[N];
char str[N];
int ans[N][200];
int main(){
	//freopen("data.in","r",stdin);
	scanf("%d",&cas);
	while(cas--){
		memset(cnt,0,sizeof cnt);
		memset(ans,0,sizeof ans);
		scanf("%d %d",&n,&m);
		scanf("%s",str+1);
		
		for(int i = 1 ; i <= n; ++i){
			cnt[str[i]]++;
			for(char j = 'a'; j <= 'z';++j){
 				ans[i][j] = ans[i-1][j];
 				if(j == str[i]) ans[i][str[i]]++;
			}
		}
		for(int i = 1; i <= m; ++i){
			scanf("%d",p+i);
			for(char j = 'a'; j<= 'z';++j )
				cnt[j] += ans[p[i]][j];
		}
		for(char i = 'a'; i <= 'z'; ++i){
			printf("%d",cnt[i]);
			if(i == 'z') printf("\n");
			else printf(" ");
		}
	}
	return 0;
}

赛后学到一个十分巧妙类似于"后缀和"的思路:
先将每个停止的位置出现的次数,用一个数组 cnt[p[i]]记录下来。
tmp表示扫描到第 i 个位置时,出现的停止的次数
然后从后向前依次扫描, 如果第 i 个位置停止过(cnt[i] > 0),就将出现的次数累加,tmp += cnt[p[i]],最后统计字母出现的次数即可,ans[str[i]] += tmp。
拿第一个样例来举例:

4 2
abca
1 3
先将str所有的字母出现的次数先统计一遍:
ans[a] = 2,ans[b] = 1,ans[c] = 1
1,3号位置出现过一次cnt[1] = 1,cnt[3] = 1;

从后向前扫描:
扫到‘a’时,tmp = 0
扫到‘ac’时,tmp += cnt[3],tmp = 1,ans[c] += 1,ans[c] = 2;
扫到‘acb’时,tmp = 1,ans[b] += 1,ans[b] = 2;
扫到‘acb’时,tmp += 1,tmp = 2,ans[a] += 1,ans[a] = 4;
得出答案
/*****************************
*author:ccf
*source:cf_round_624_C
*topic:
*******************************/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#define ll long long
using namespace std;

const int N = 2e5+7;
int n,m,cas;
char str[N];
int p[N];
int cnt[N],ans[N],tmp = 0;
void solve(){
	for(int i = n; i >= 1; --i){
		ans[str[i]]++;
		if(cnt[i]){
			tmp += cnt[i];
		}
		ans[str[i]] += tmp;
	}
	for(char i = 'a'; i <= 'z'; ++i){
		printf("%d ",ans[i]);
	}
	printf("\n");
}
int main(){
	//freopen("data.in","r",stdin);
	scanf("%d",&cas);
	while(cas--){
		tmp = 0;
		memset(ans,0,sizeof ans);
		memset(cnt,0,sizeof cnt);
		scanf("%d %d",&n,&m);
		scanf("%s",str+1);
		for(int i = 1; i <= m; ++i) scanf("%d",p+i),cnt[p[i]]++;
		solve();
	}
	return 0;
}

发布了141 篇原创文章 · 获赞 71 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/sinat_40872274/article/details/104890149