题解:P10486 [入门赛 #25] sql
洛谷 P10486
题目传送门
题目概述
题目要求我们处理一个模拟数据库查询的问题,通过输入的命令来查询表格中的数据。我们需要实现一个程序,能够根据输入的查询命令,从表格中检索并输出相应的结果。
输入格式
- 标题输入:首先输入表格的标题。
- 维度输入:接着输入表格的行数
n和列数m。 - 表格数据输入:输入表格的列名,然后输入表格的数据行。
解题思路
定义数据结构
我们定义了一个结构体 Node 来存储表格的相关信息:
n和m分别表示表格的行数和列数。name存储表格的标题。table是一个二维字符串向量,用来存储表格的数据。
struct Node {
LL n, m;
string name;
vector<vector<string>> table;
void init() {
table.resize(n, vector<string>(m));
}
};
初始化表格
在输入标题和维度后,调用 init() 方法初始化表格,为表格分配足够的空间。
命令解析
查询命令由几个部分组成:
select:指定要查询的列名。from:指定要查询的表格。where:指定查询条件。
我们可以通过以下步骤解析命令:
- 读取命令的各个部分。
- 根据
select部分确定要查询的列。 - 根据
where部分确定查询条件。
具体实现
分割字符串
使用 split() 函数将字符串按指定分隔符分割成多个子字符串。
vector<string> split(string str, const char* pattern) {
vector<string> result;
istringstream stream(str);
string token;
while (getline(stream, token, *pattern)) {
result.push_back(token);
}
return result;
}
查找列索引
使用 find() 函数在表格的第一行中查找列名对应的索引。
LL find(vector<string> line, string str) {
for (LL i = 0; i < line.size(); ++i) {
if (line[i] == str) {
return i;
}
}
return -1;
}
执行查询
根据查询命令,执行查询操作:
- 如果
select部分只有一个列名,直接查询并输出结果。 - 如果
select部分有多个列名,使用split()函数分割列名,然后查询并输出所有指定列的数据。
代码实现
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <sstream>
using namespace std;
typedef long long LL;
const LL N = 1e1 + 5;
const LL M = 1e3 + 5;
struct Node {
LL n, m;
string name;
vector<vector<string>> table;
void init() {
table.resize(n, vector<string>(m));
}
} a[N];
LL n, m;
map<string, int> map_;
vector<string> split(string str, const char* pattern) {
vector<string> result;
istringstream stream(str);
string token;
while (getline(stream, token, *pattern)) {
result.push_back(token);
}
return result;
}
LL find(vector<string> line, string str) {
for (LL i = 0; i < line.size(); ++i) {
if (line[i] == str) {
return i;
}
}
return -1;
}
int main() {
cin >> n;
for (LL i = 0; i < n; ++i) {
cin >> a[i].name;
map_.insert(make_pair(a[i].name, i));
cin >> a[i].n >> a[i].m;
a[i].init();
for (LL j = 0; j < a[i].n; ++j) {
for (LL k = 0; k < a[i].m; ++k) {
cin >> a[i].table[j][k];
}
}
}
cin >> m;
for (LL i = 0; i < m; ++i) {
string cmd[6];
cin >> cmd[0] >> cmd[1] >> cmd[2] >> cmd[3] >> cmd[4] >> cmd[5];
bool fnd = cmd[1].find(",") == string::npos;
if (fnd) {
vector<string> obj = split(cmd[5], "=");
LL x = find(a[map_[cmd[3]]].table[0], cmd[1]), y = find(a[map_[cmd[3]]].table[0], obj[0]);
for (LL j = 1; j < a[map_[cmd[3]]].n; ++j) {
if (a[map_[cmd[3]]].table[j][y] == obj[1]) {
cout << a[map_[cmd[3]]].table[j][x] << endl;
}
}
} else {
vector<string> obj = split(cmd[5], "=");
LL y = find(a[map_[cmd[3]]].table[0], obj[0]);
vector<string> sssss = split(cmd[1], ",");
vector<LL> x(sssss.size());
LL ii = 0;
for (auto& s : sssss) {
x[ii] = find(a[map_[cmd[3]]].table[0], s);
++ii;
}
for (LL j = 1; j < a[map_[cmd[3]]].n; ++j) {
if (a[map_[cmd[3]]].table[j][y] == obj[1]) {
for (LL k = 0; k < ii; ++k) {
cout << a[map_[cmd[3]]].table[j][x[k]] << " ";
}
cout << endl;
}
}
}
}
return 0;
}
本人蒟蒻,第一次发题解,望审核大人通过!