题解:P13986 [PO Final 2023] 降重 / Synonyms
sen_lin114514 · · 题解
P13986 [PO Final 2023] 降重 / Synonyms 题解
题目大意
给定一些单词直接的翻译关系,将一个单词从一种语言翻译为另一种语言并尽量保证和原来的不相同。
思路
阅读题目可知,一个单词会有多种翻译,因此,我们可以将一个单词的翻译存进一个集合中,然后每次遍历该集合,查询该单词对于的翻译,对于每个翻译同样也有一个集合,遍历该集合,查询该单词翻译回去是否相同,不相同则直接输出,若为找到不相同的则直接输出原单词即可。
实现并不是很难,可以通过标准库中的 map 将字符串映射为数字并当作下标存储其翻译。建议使用 unordered_map 来减小常数。
代码
#include <unordered_map>
#include <iostream>
#include <vector>
using std :: unordered_map;
using std :: string;
using std :: vector;
const int N = 6000;
int n,m;
unordered_map<string,int> x;
unordered_map<string,int> y;
vector<string> word1[N];
vector<string> word2[N];
int cnt1 = 0;
int cnt2 = 0;
int main()
{
std :: cin >> n;
for (int i = 1; i <= n; i++)
{
string a, b;
std :: cin >> a >> b;
if (!x[a])
{
cnt1 ++;
x[a] = cnt1;
}
word1[x[a]].push_back(b);
if (!y[b])
{
cnt2 ++;
y[b] = cnt2;
}
word2[y[b]].push_back(a);
}
std :: cin >> m;
for (int i = 1; i <= m; i++)
{
string a;
std :: cin >> a;
string ans = a;
bool found = false;
for (auto &t : word1[x[a]])
{
for (auto &s : word2[y[t]])
{
if (s != a)
{
ans = s;
found = true;
break;
}
}
if (found) break;
}
std :: cout << ans << " ";
}
}