题解 | #[C++]数据分类处理#
数据分类处理
http://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
这是道应用题,重在理解题意。
- 首先输入输出,我采用了vector<unsigned>, 因为string更便于查找,查找能直接返回索引,所以在搜索过程中全部把int转为string。</unsigned>
- R的排序和去重
- 按序搜寻,采用了一个vector<vector<tuple<int, unsigned int>>>来记录,第一层vector里存放的是R中对应元素的查找结果,如果没找到也有对象,只不过size为空;第二层vector内的是一个个的查找记录,每个记录是tuple格式,分别是其索引和I中对应的数。在搜索的过程中统计下总共会输出的整数个数。
这是个细节题,重点在于认真审题,读懂题意,细节挺多的。
#include<iostream> #include<sstream> #include<vector> #include<tuple> #include<algorithm> using namespace std; int main() { int I_n, R_n; string I_line, R_line; while(getline(cin, I_line) && getline(cin, R_line)){ istringstream is_I(I_line), is_R(R_line); vector<unsigned int> I, R; is_I >> I_n; unsigned tmp; for (int i = 0; i < I_n; ++i){ is_I>> tmp; I.push_back(tmp); } is_R>> R_n; for (int i = 0; i < R_n; ++i){ is_R >> tmp; R.push_back(tmp); } sort(R.begin(), R.end()); R.erase(unique(R.begin(), R.end()), R.end()); int total = 0; vector<vector<tuple<int, unsigned int>>> vvp; for (int i = 0; i < R.size(); ++i){ vector<tuple<int, unsigned int >> vp; for(int j = 0; j < I.size(); ++j){ if (to_string(I[j]).find(to_string(R[i])) != string::npos){ vp.emplace_back(j, I[j]); } } if (!vp.empty()) total += 2 + vp.size() * 2; vvp.push_back(vp); } cout << total; for (int i = 0; i< R.size(); ++i){ if (!vvp[i].empty()){ cout << " "<< R[i]<< " " << vvp[i].size() ; for (int j = 0; j < vvp[i].size(); ++j){ cout << " "<< get<0>(vvp[i][j])<< " "<< get<1>(vvp[i][j]) ; } } } cout << endl; } return 0; }