跳到正文

题解

题解【补充】:P2786 英语1(eng1)- 英语作文 之 cin 分隔符

Cpp__5417__约 6 分钟
原文
文章信息与版本

文章信息

发布
2026年11月14日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 6 分钟
题目
P2786

版本

  1. v1当前

P2786 之 题解补充

各位大佬做法好多啊。这里只讲一个能够让分隔符变得“简单”的东西。(但是有点复杂)

先看核心代码:

C++
#define ORIG_TABLE ctype<char>::classic_table()
void ModifySpliter(string s){
    auto orig=ORIG_TABLE;
    vector<ctype<char>::mask>table(orig,orig+ctype<char>::table_size);
    for(auto &i:s)table[i]|=ctype_base::space;
    cin.imbue(locale(cin.getloc(),new ctype<char>(table.data())));
}
void SetDefault(){ModifySpliter("");}

了解这个东东,首先要知道一个东西叫做「字符属性表」。这个东西控制 C++ 标准库(通常是输入输出)对待字符的行为。比如默认情况下 cin 对待除了空格、Tab、换行以外的字符基本都不视为空白符,就是靠这个东西控制的。

ModifySpliter 函数通过 ctype<char> 获取标准字符属性表,对参数字符串(所有分隔符)的属性添加一个 ctype_base::space,就是空白符属性,再将改完后的字符属性表放回 cin。

逐行解析
  1. 定义一个宏 ORIG_TABLE,通过 ctype<char> 获取初始的字符属性表。
  2. 定义函数 ModifySpliter。
  3. 获取初始属性表。
  4. 定义一个 vector,名字叫 table,用于存储修改后的属性表。
  5. 依次遍历参数的每一个字符,使用「或」运算向这些字符添加空白符属性。
  6. 将修改后的属性表放进 cin 中。此时 cin 就会在标准属性表(而不是原有属性表)上将参数中的所有字符视为空白符。
    • new ctype<char>(table.data())):动态分配一个属性表,返回一个 ctype<char>* 指针。
    • cin.getloc():获取 cin 当前 locale。
    • locale(cin.getloc(),new ctype<char>(table.data())):用动态分配的属性表修改 cin.getloc()(只修改 ctype,即字符属性表),返回修改后的 locale,并且接管分配的属性表,在内部自动 delete,不用担心内存泄漏。
    • cin.imbue(locale(cin.getloc(),new ctype<char>(table.data())));:将新修改的 locale 放入 cin 中。
  7. 结束 ModifySpliter 函数。
  8. 定义还原函数 SetDefault,将 cin 的属性表设为标准属性表。

瞎扯了那么多,直接上本题代码:

AC of C++
C++
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f3f3f3f3f
#define int LL
#define i64 __int128
#define cauto const auto
#define uint uLL
#define gcd(a,b) __gcd(a,b)
#define lcm(a,b) ((a)*(b)/__gcd(a,b))
#define lowbit(x) ((x)&-(x))
#define debugf(format,argu...) fprintf(stderr,format,##argu)
#define input(type) ({type a;cin>>a;a;})
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
typedef pair<int,int> pii;
template<size_t N,typename T>using graph=vector<T>[N];
template<size_t N,typename T=int>using wgraph=graph<N,pair<int,T>>;
template<size_t N>using uwgraph=graph<N,int>;
template<typename T=int>
struct edge{int u,v;T w;bool operator<(const edge &x)const{return w<x.w;}};
template<>struct edge<void>{int x,y;};
const int N=1e5+38;
int n,p,r;
map<string,int>Mp;
#define ORIG_TABLE ctype<char>::classic_table()
void ModifySpliter(string s){
    auto orig=ORIG_TABLE;
    vector<ctype<char>::mask>table(orig,orig+ctype<char>::table_size);
    for(cauto &i:s)table[i]|=ctype_base::space;
    cin.imbue(locale(cin.getloc(),new ctype<char>(table.data())));
    cin.clear();
}
void SetDefault(){ModifySpliter("");}
void Cpp(){
    cin>>n>>p;
    for(int i=1;i<=n;i++){string s;int b;cin>>s>>b;Mp[s]=b;}
    ModifySpliter(",.!?");
    string s;
    while(cin>>s)r=(r+Mp[s])%p;
    printf("%lld\n",r);
}
signed main(){
	cin.tie(nullptr)->sync_with_stdio(false);
	int q=1;
//	cin>>q;
	while(q--){Cpp();}
	return 38&17;
}

由于讲的是 C++ 的技巧,其他代码就不挂了。

原文