题解 | #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 北京

相关推荐

点赞 评论 收藏
分享
ResourceUtilization:四六级不愧是大学最有用的证之一
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务