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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章