2025天梯赛 L2专项训练
L2-049 鱼与熊掌 - 团体程序设计天梯赛-练习集
思路就是模拟,正常写就完事
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
vector<vector<int>>arr(a, vector<int>(0));
for (int i = 0; i < a; i++)
{
int ok;
cin >> ok;
for (int j = 0; j < ok; j++)
{
int op;
cin >> op;
arr[i].push_back(op);
}
}
int q;
cin >> q;
for (int i = 0; i < q; i++)
{
int A, B;
cin >> A >> B;
int cnt = 0;
for (int i = 0; i < a; i++)
{
int flag = 0;
for (int j = 0; j < arr[i].size(); j++)
{
if (arr[i][j] == A)
{
flag++;
}
if (arr[i][j] == B)
{
flag++;
}
if (flag == 2)
{
cnt++;
break;
}
}
}
cout << cnt << endl;
}
}
L2-050 懂蛇语 - 团体程序设计天梯赛-练习集
这个题目,写出来几个问题,来看第一版代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<string>arr(n);
vector<string>brr(n);
getchar();
for (int i = 0; i < n; i++)
{
getline(cin, arr[i]);
brr[i] = arr[i][0];
for (int j = 1; j < arr[i].size(); j++)
{
if (arr[i][j] == ' ')
{
while (1)
{
j++;
if (arr[i][j] != ' ')
{
brr[i] += arr[i][j];
break;
}
}
}
}
}
int q;
cin >> q;
getchar();
for (int i = 0; i < q; i++)
{
string man;
getline(cin, man);
string ok;
ok += man[0];
for (int j = 1; j < man.size(); j++)
{
if (man[j] == ' ')
{
while (1)
{
j++;
if (man[j] != ' ')
{
ok += man[j];
break;
}
}
}
}
int cnt = 0;
vector<string>ans(0);
for (int i = 0; i < n; i++)
{
if (ok == brr[i])
{
ans.push_back(arr[i]);
cnt++;
}
}
if (cnt == 0)
{
cout << man;
}
if (cnt == 1)
{
cout << ans[0];
}
if (cnt > 1)
{
sort(ans.begin(), ans.end());
cout << ans[0];
for (int i = 1; i < ans.size(); i++)
{
cout << '|' << ans[i];
}
}
cout << endl;
}
}
有以下错误:
遍历查询会爆,应该用键值对
分词的时候不要手动分用自动的;
来看修改代码:
#include<bits/stdc++.h>
#include<unordered_map>
using namespace std;
int main()
{
int n;
cin >> n;
unordered_map<string, vector<string>>dip;
getchar();
for (int i = 0; i < n; i++)
{
string A;
getline(cin, A);
string B; // 存储缩写
stringstream ss(A); // 将字符串 A 转为流
string word; // 临时存储每个单词
while (ss >> word) { // 自动按空格分词
B += word[0]; // 取每个单词的首字母
}
dip[B].push_back(A);
}
//预处理答案:
for (auto it : dip)
{
if (it.second.size() > 1)
{
sort(dip[it.first].begin(), dip[it.first].end());
}
}
int q;
cin >> q;
getchar();
for (int i = 0; i < q; i++)
{
string man;
getline(cin, man);
string ok;
stringstream ss(man);
string word;
while (ss >> word)
{
ok += word[0];
}
int flag = 0;
if (dip[ok].size() > 0)
{
cout << dip[ok][0];
if (dip[ok].size() > 1)
{
for (int ooo = 1; ooo < dip[ok].size(); ooo++)
{
cout << '|' << dip[ok][ooo];
}
}
}
else
cout << man;
cout << endl;
}
}