洛谷刷题6: 数字排列输出以及接收题目输入的思路问题(洛谷P1603)

这个题其实挺容易的,但是自己写的代码就是没往容易的地方去想,不管是用字符串去接收输入,还是最后的数字排列以达到最小值,自己都想的无比复杂,相比之下,题解的代码真是无比优美:

#include<iostream>
#include<algorithm>
#include<iomanip>
#include<math.h>
#include<string>
using namespace std;
int word[6], c;
int wordbank(string s,int &c)
{
    if (s == "one" || s == "a" || s == "first" || s == "another") { word[c] = 1; c++; return 0; }
    if (s == "two" || s == "both" || s == "second") { word[c] = 4; c++; return 0; }
    if (s == "three" || s == "third") { word[c] = 9; c++; return 0; }
    if (s == "four") { word[c] = 16; c++; return 0; }
    if (s == "five") { word[c] = 25; c++; return 0; }
    if (s == "six") { word[c] = 36; c++; return 0; }
    if (s == "seven") { word[c] = 49; c++; return 0; }
    if (s == "eight") { word[c] = 64; c++; return 0; }
    if (s == "nine") { word[c] = 81; c++; return 0; }
    if (s == "eleven") { word[c] = 21; c++; return 0; }
    if (s == "twelve") { word[c] = 44; c++; return 0; }
    if (s == "thirteen") { word[c] = 69; c++; return 0; }
    if (s == "fourteen") { word[c] = 96; c++; return 0; }
    if (s == "fifteen") { word[c] = 25; c++; return 0; }
    if (s == "sixteen") { word[c] = 56; c++; return 0; }
    if (s == "seventeen") { word[c] = 89; c++; return 0; }
    if (s == "eighteen") { word[c] = 24; c++; return 0; }
    if (s == "nineteen") { word[c] = 61; c++; return 0; }
}
int main()
{
    string str[6];
    for (int i = 0; i < 6; i++)
    {
        cin >> str[i];
        if (str[i][str[i].size() - 1] == '.') str[i].erase(str[i].size() - 1, 1);
        wordbank(str[i], c);
    }
    sort(word, word + c);
    long long result = 0;//注意这个地方,自己刚开始用了int,结果有个测试点过不去,原因就是int的范围太小,以后做字符串的题应当注意
    for (int i = 0; i < c; i++)
    {
        result = result * 100 + word[i];
    }
    cout << result;
    return 0;

}

这里题目说了总共有六个单词,自己想的是直接用一个字符串接收这一行文本,再去用find函数去识别有没有表示数字的单词,这样写效率不高而且麻烦,不如分六次输入每个单词

还有result = result * 100 + word[i];这句,自己真的没想到把这些二位数排序还可以这样干。

posted @ 2021-01-26 09:36  _翩若惊鸿  阅读(136)  评论(0)    收藏  举报