题解 | #01串的价值#

01串的价值

http://www.nowcoder.com/questionTerminal/16976852ad2f4e26a1ff9f555234cab2

/** 解题思路:
 * 计算1和0各自数目,假设1更多有sum次,找出1的最左和最右,求和公式1+到sum,然后左边右边都是0,按规则加上。
 */
#include <bits/stdc++.h>

using namespace std;

int val_of_len(int len)
{
    return (len * (1 + len)) / 2;
}
int main()
{
    int t, max_val;
    string str;
    int count[2] = {0, 0};

    cin >> t >> str;
    // cout << str << endl;

    for (int i = 0; i < str.length(); ++i)
    {
        if (str[i] == '0')
        {
            count[0]++;
        }
        else if (str[i] == '1')
        {
            count[1]++;
        }
    }
    // if (count[0] > count[1])
    // {
    //     max_val = val_of_len(count[0]) + val_of_len(str.find_first_of('0')) + val_of_len(str.length() - 1 - str.find_last_of('0'));
    // }
    // else if (count[1] > count[0])
    //     max_val = val_of_len(count[1]) + val_of_len(str.find_first_of('1')) + val_of_len(str.length() - 1 - str.find_last_of('1'));
    // else
    // {
    //     // cout << str.find_first_of('0') << endl;
    //     // cout << str.find_last_of('0') << endl;
    //     // cout << str.find_first_of('1') << endl;
    //     // cout << str.find_last_of('1') << endl;
    //     max_val = max(val_of_len(count[0]) + val_of_len(str.find_first_of('0')) + val_of_len(str.length() - 1 - str.find_last_of('0')),
    //                   val_of_len(count[1]) + val_of_len(str.find_first_of('1')) + val_of_len(str.length() - 1 - str.find_last_of('1')));
    // }
    max_val = max(val_of_len(count[0]) + val_of_len(str.find_first_of('0')) + val_of_len(str.length() - 1 - str.find_last_of('0')), val_of_len(count[1]) + val_of_len(str.find_first_of('1')) + val_of_len(str.length() - 1 - str.find_last_of('1')));
    cout << max_val << endl;
    return 0;
}

/* 根据牛友指出的错误进行了修正的版本 */
全部评论
5 11001 答案应该是7啊 1+2+1+2+1 = 7 但这么做是6
2 回复 分享
发布于 2022-08-23 06:30 陕西
嗯嗯,确实。这样的话,应该去掉if和else的判断,直接用max_val = max(val_of_len(count[0]) + val_of_len(str.find_first_of('0')) + val_of_len(str.length() - 1 - str.find_last_of('0')),val_of_len(count[1]) + val_of_len(str.find_first_of('1')) + val_of_len(str.length() - 1 - str.find_last_of('1')));来计算最优解。
点赞 回复 分享
发布于 2022-08-25 10:27 北京

相关推荐

不愿透露姓名的神秘牛友
07-08 13:05
点赞 评论 收藏
分享
06-20 17:42
东华大学 Java
凉风落木楚山秋:要是在2015,你这简历还可以月入十万,可惜现在是2025,已经跟不上版本了
我的简历长这样
点赞 评论 收藏
分享
机械打工仔:我来告诉你原因,是因为sobb有在线简历,有些HR为了快会直接先看在线简历,初步感觉不合适就不会找你要详细的了
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务