[英]What is a faster way to sort these string inputs based on their position in the sentence?
Practicing for the national Olympiad of Informatics stumbled a problem that goes as follows: The user inputs the amount of words (n) in the sentence and the proceeds on entering the words along with their positions separated by a space. 参加国家信息奥林匹克竞赛的练习发现了一个问题,如下所示:用户输入句子中单词的数量(n),然后输入单词的过程以及单词之间的位置(用空格隔开)。 You are asked to input the sentence with the correct order of words.
要求您输入正确词序的句子。
For example: 例如:
Input: 输入:
4
this 1
sentence 4
is 2
a 3
Output: 输出:
this is a sentence
Restrictions: 限制:
1 <= N <= 3 * 10^5
1 <= Size of a word <= 50
I have tried to solve this problem using an unordered_map and it turns out is solves this pretty fast taking only 0.588 seconds going over all the test cases which made my solution the 5th fastest out of 45. However the fastest solution only takes 0.14 seconds to compute and I can't figure out how he/she did it. 我尝试使用unordered_map解决此问题,结果是在所有测试用例上仅花费0.588秒即可解决此问题,这使我的解决方案在45个测试中排名第五,但是最快的解决方案仅需0.14秒即可计算我不知道他/她是怎么做到的。 What is a faster way to solve this problem than using unordered_map?
与使用unordered_map相比,解决此问题的最快方法是什么?
unordered_map < int, string > words;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string word;
int position;
cin >> word >> position;
words[position] = word;
}
for (int i = 1; i <= n; i++) {
cout << words[i] << "\n";
}
std::unordered_map
is a little overboard for this problem. std::unordered_map
对于此问题有点过分。 Since you are provided the order that the elements will be in you can get away with a std::vector<std::string>
, and you just put the elements in the vector where the input tells you. 由于提供了元素的顺序,因此可以使用
std::vector<std::string>
摆脱掉,只需将元素放在输入告诉您的矢量中即可。 That simplifies the program code to 简化了程序代码
int main()
{
int records;
std::cin >> records;
std::vector<std::string> sentence(records);
std::string word;
int place;
while (std::cin >> word >> place)
sentence[place - 1] = std::move(word); // subtract one as input is 1 based index, use move to save an allocation and copy
for (auto const& e : sentence)
std::cout << e << " ";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.