P2786

· · 题解

我看其他题解都没有介绍怎么将输入的文章变成单词我就介绍一下吧。

首先我们按照空格分割读入:

while (std::cin >> word)

但是这样就会读入到一些奇怪的单词"jvruo!but",因此对于每一个单词我们再对其split就是按照标点符号划分并存入vector,注意不要在循环里定义vector否则会因为反复的调用析构函数(clear)而损失效率,split函数的定义如下:

const std::string special = ",.!?";

std::vector <std::string> split(std::string s){

    std::string str = "";
    std::vector <std::string> ans;

    for (char c : s){

        if (special.find(c) != -1) ans.push_back(str),str = "";
        else str.push_back(c);

    }
    ans.push_back(str);

    return ans;
}

到这就可以去写代码了,顺便既然很多题解都提到了map,我就说一下unordered_map,用法和map差不多,区别:

1.需要将头文件改为unordered_map
2.无法映射除std::string以外的所有STL容器包括但不限于std::pair,std::tuple,std::vector
3.内部使用hash实现,所以复杂度为O(1)更快

完整代码:

#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>

const std::string special = ",.!?";

std::vector <std::string> split(std::string s){

    std::string str = "";
    std::vector <std::string> ans;

    for (char c : s){

        if (special.find(c) != -1) ans.push_back(str),str = "";
        else str.push_back(c);

    }
    ans.push_back(str);

    return ans;
}

int main(){

    std::ios::sync_with_stdio(0);
    std::cin.tie(0),std::cout.tie(0);

    char c;
    int n,p,b;
    long ans = 0;
    std::string word;
    std::vector <std::string> words;
    std::unordered_map <std::string,int> ds;

    std::cin >> n >> p;
    for (int i = 1;i <= n;i++) std::cin >> word >> b,ds[word] = b;
    while (std::cin >> word){

        words = split(word);
        for (auto s : words) ans += ds[s];

    }
    std::cout << ans % p << '\n';

    return 0;
}