题解 | 数据分类处理
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
#include <algorithm> #include <iostream> #include <string> #include <vector> #include <unordered_map> #include<set> using namespace std; int main() { int n, m; cin >> n; vector<string> I(n); string s1, s2; // 读取 I for (int i = 0; i < n; i++) { cin >> s1; I[i] = s1; } cin >> m; set<string> R1; // 读取 R for (int i = 0; i < m; i++) { cin >> s2; R1.insert(s2); } vector<string> R; for(string s : R1) { R.push_back(s); } // 为规则字符排序 sort(R.begin(), R.end(), [](const string& a, const string& b) { return stoi(a) < stoi(b); }); // 初始化 V 和 count vector<vector<bool>> V(m, vector<bool>(n, false)); unordered_map<int, int> count; // 依次取出 R 中的字符串 for (int i = 0; i < R.size(); i++) { // 依次取出 I 中字符串 for (int j = 0; j < I.size(); j++) { // 从 I[j] 中的第一个字符开始,截取长度为 R[i].length() 的字符串与 R[i] 匹配 for (int k = 0; k + R[i].length() <= I[j].size(); k++) { string part = I[j].substr(k, R[i].length()); if (part == R[i]) { //再没有加这个判定条件时,输出的p值总是偏大,原因是:I[j]中可能存在多个满足条件的子串,这就导致一个I[j]多次计数,只有当V[i][j]为false时,转变其为true才对count[stoi(R[i])]进行计数 if(!V[i][j]){ V[i][j] = true; count[stoi(R[i])]++; } } } } } int Count=0; for(pair c : count){ if(c.second>0){ Count+=2; } Count+=c.second*2; } cout<<Count; // 输出结果 for (int i = 0; i < R.size(); i++) { if (count[stoi(R[i])] > 0) { cout << " "<<stoi(R[i]); cout << " " << count[stoi(R[i])]; for (int j = 0; j < I.size(); j++) { if (V[i][j]) { cout << " " << j<<" "<<I[j]; } } } } return 0; }