熟悉CPPSTL库,这两道题主要是vector容器的使用。两道问题背景相似,放在一起讨论。问题抽象为学生和课程之间的映射,利用vector实现按学生(或按课程)输出这些映射关系。
以下记录做题过程中的关键点与思考
由于空间限制,无法构造一张学生×课程的二维表(40000×2500 = 100000000 = 100M)。所以需要用到动态的数组,由此用到vector。
A1047中,直接的想法是容器中存放学生姓名,但这样做导致后边对字符串类型string排序,对时间消耗太大。这里又有两种解法:
把string排序转化为字符数组char*排序。开辟一个二维字符数组,用数组下标与字符串映射
char name[40010][5];
vector<int> course[2510];
把排字符串转化为排数字。自定义一个哈希函数,将字符串映射为哈希值。(节省空间)
vector<vector<int>> v_info(2510);
int gethash(char* s) {
return (s[0] - 'A') * 26 * 26 * 10 +
(s[1] - 'A') * 26 * 10 +
(s[2] - 'A') * 10 +
(s[3] - '0');
}
string getval(int i) {
string ret;
ret.push_back('A' + i / (26 * 26 * 10));
i = i % (26 * 26 * 10);
ret.push_back('A' + i / (26 * 10));
i = i % (26 * 10);
ret.push_back('A' + i / (10));
i = i % (10);
ret.push_back('0' + i);
return ret;
}
尽量用scanf和printf代替cin和cout。因为前者省去识别数据类型的时间开销。
以下为笔者ac代码:
A1039
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int gethash(string s){
return (s.at(0) - 'A') * 26 * 26 * 10 +
(s.at(1) - 'A') * 26 * 10 +
(s.at(2) - 'A') * 10 +
(s.at(3) - '0');
}
int main(){
int n,k;
int seq,num;
string sname;
cin >> n >> k;
vector<vector<int>> v_info(175760);//n个人的数组
for (int i=0;i<k;++i){
cin >> seq >> num;
for(int j=0;j<num;++j){
cin>>sname;
v_info[gethash(sname)].push_back(seq);
}
}
for (int i=0;i<n;++i){
cin>>sname;
cout<<sname<<' '<<v_info[gethash(sname)].size();
sort(v_info[gethash(sname)].begin(),v_info[gethash(sname)].end());
for (vector<int>::iterator it=v_info[gethash(sname)].begin();it!=v_info[gethash(sname)].end();it++){
cout<<' '<<*it;
}
cout<<endl;
}
}
A1047
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> v_info(2510);
int gethash(char* s) {
return (s[0] - 'A') * 26 * 26 * 10 +
(s[1] - 'A') * 26 * 10 +
(s[2] - 'A') * 10 +
(s[3] - '0');
}
string getval(int i) {
string ret;
ret.push_back('A' + i / (26 * 26 * 10));
i = i % (26 * 26 * 10);
ret.push_back('A' + i / (26 * 10));
i = i % (26 * 10);
ret.push_back('A' + i / (10));
i = i % (10);
ret.push_back('0' + i);
return ret;
}
int main() {
int n, k;
int seq, num;
char sname[5];
scanf("%d %d", &n, &k);
for (int i = 0; i < n; ++i) {
scanf("%s %d", sname, &num);
//cin >> sname >> num;
for (int j = 0; j < num; ++j) {
scanf("%d", &seq);
//cin >> seq;
v_info[seq - 1].push_back(gethash(sname));
}
}
for (int i = 0; i < k; ++i) {
printf("%d %d\n", i + 1, v_info[i].size());
//cout << (i + 1) << ' ' << v_info[i].size() << endl;
sort(v_info[i].begin(), v_info[i].end());
for (int j = 0; j < v_info[i].size(); j++) {
printf("%s\n", getval(v_info[i].at(j)).c_str());
//cout << getval(v_info[i].at(j)) << endl;
}
}
}