CSDN 编程竞赛十二期题解

竞赛总览

CSDN编程竞赛十二期:比赛详情 (csdn.net)

竞赛题解

题目1、豚鼠排名榜

已知字符A.B,C。每个字符都有自己的权值q。现不知道权值q,只知道A,B,C的三次比较结果。

#include 
#include 
#include 

int data [][3] = {
    {1, 2, 3},
    {1, 3, 2},
    {2, 1, 3},
    {2, 3, 1},
    {3, 1, 2},
    {3, 2, 1}
};

std::string resize (std::string exp, int m) {
    std::string str = "";
    for (int i = 0; i < exp.length (); i++) {
        if (exp [i] >= 'A' && exp [i] <= 'C') {
            str += data [m][exp [i] - 'A'] + '0';
        } else {
            str += exp [i];
        }
    }
    return str;
}

std::string solution (std::string exp1, std::string exp2, std::string exp3) {
    std::string result = "Impossible";
    std::string exp1t, exp2t, exp3t;
    for (int m = 0; m < 6; m++) {
        exp1t = resize (exp1, m);
        exp2t = resize (exp2, m);
        exp3t = resize (exp3, m);
        if (check (exp1t) && check (exp2t) && check (exp3t)) {
            result = "";
            for (int i = 1; i <= 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if (data [m][j] == i) {
                        result += 'A' + j;
                    }
                }
           }
           break;
        }
    }
    return result;
}

int main () {
    std::string exp1, exp2, exp3;
    getline (std::cin, exp1);
    getline (std::cin, exp2);
    getline (std::cin, exp3);
    printf ("%d", solution (exp1, exp2, exp3));
    return 0;
}

可以使用模拟法。

给三种字符分别赋予一个权值,再对比较结果进行校验。

如果能通过校验,说明假设的权值相对大小是正确的;

否则,继续换另一组权值,再次对比较结果进行校验,直到找到正确答案为止。

题目2、字符串转换

已知一个字符串a,b。字符串b中包含数量不等的特殊符号“.”,“*”(字符串存在没有特殊符号或者全由特殊符号组成的情况)。“.”表示该字符可以变成任意字符,“* ”表示该字符的前一个字符可以变成任意多个。现在我们想知道b可否通过特殊符号变成a。a*可以转化为a,aa,aaa,aaaa…

其实可以直接用正则表达式秒杀此题。

#include 

std::string solution (std::string a, std::string b) {
    std::regex reg (b);
    std::smatch match;
    std::string result = std::regex_match (a, match, reg) ? "yes" : "no";
    return result;
}

不过,博主对平台的在线测评系统不太熟悉,C++的正则表达式库总是报错(赛后本地调试就没有这个问题,怀疑是环境版本问题),因此最后还是放弃了这个想法。

正则表达式本质上是一个状态推理自动机,所以可以改用动态规划算法实现。

题目3、蚂蚁家族

小蚂蚁群是一个庞大的群体,在这个蚂蚁群中有n只小蚂蚁,为了保证所有蚂蚁在消息传送的时候都能接收到消息,需要在他们之间建立通信关系。就是要求小蚂蚁都可以通过多只或者直接联系到其他人。已知几条小蚂蚁之间有通信关系,请问还需要再新建至少多少条关系?

并查集算法。求出小蚂蚁群体的数目(互相之间能访问到的,算一个群体),再用总数减去这个数量,即可得到需要新建的关系数量。

题目4、小股炒股

已知n天后的股票行情,现在已有的本金是m,规定只能入手一次股票和抛售一次股票。最大收益(含本金)是?

先计算出来交易能获得的最大收益(不含本金),再加上本金即可得到最终答案。

你可能感兴趣的:(CSDN,竞赛题解,算法,c++)