CodeChef CDMU02(数组辅助查询)

来源:互联网 发布:autodesk主要软件 编辑:程序博客网 时间:2024/05/16 07:26

题目大意:给你一个字符串p,然后给你q次的查询,每次查询一个单词以及对应区间[L,R]内的相应的字母,出现的次数。
解析:可以用一个数组dp[27][N]表示在当前位置该位置上的字符出现了几次。查询时就dp[ch-‘a’][R] - dp[ch-‘a’][L-1]进行询问。
总结:我最早的时候想成了用线段树来做,不过马上被我给否决了。因为这里只有查询没有修改。

#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <cstdlib>#include <iostream>using namespace std;typedef long long ll;const int INF = 0x3f3f3f3f;const int N = 1000010;char str[N];int dp[27][N];int readstr(char s[]) {    char ch;    int len = 0;    while((ch = getchar()) != EOF) {        if(ch == '\t' || ch == ' ' || ch == '\n') break;        s[len] = ch;        len++;    }    s[len] = '\0';    return len;}int main() {    int q, L, R;    char buf[5], ch;    while(readstr(str+1)) {        int len = strlen(str+1);        for(int i = 0; i < 26; i++)            for(int j = 0; j <= len; j++) {                dp[i][j] = 0;            }        for(int i = 0; i < 26; i++)            for(int j = 1; str[j]; j++) {                dp[i][j] = dp[i][j-1] + ((str[j]-'a') == i);            }        scanf("%d", &q);        while(q--) {            scanf("%s%d%d", buf, &L, &R);            ch = buf[0];            printf("%d\n", dp[ch-'a'][R] - dp[ch-'a'][L-1]);        }    }    return 0;}
0 0
原创粉丝点击