Codeforces 493C Convert to Ones

题意:给了一串只含0和1的字符串,有两种操作,分别有对应的价值,第一种可以交换相邻的连续的1子串和0子串,第二种可以将连续的0子串变成1子串,最后得到全1的字符串,问得到的最小价值是多少。

分析:贪心,如果第一种操作价值小,那么尽可能利用第一种操作,就是把所有的0通过交换放到一起,再整体变成1,通过分析每一种情况发现,交换的次数正好等于连续的0子串的个数减去1。如果第二种操作价值小,那么就尽可能用第二种操作,找到所有的0子串变成1即可。

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 3e5 + 10;
char s[maxn];
int main()
{
    int n;
    ll x,y;
    cin>>n>>x>>y;
    scanf("%s",s);
    int len = strlen(s);
    ll cnt = 0;
    for(int i = 0; i < len; i++)
    {
        int flag = i;
        if(s[flag] == '0')
        {
            cnt++;
            while(s[flag] == '0' && flag < len)
                flag++;
            i = flag;
        }
    }
    if(cnt == 0)cout<<0<<endl;
    else
    {
        cnt--;
        cout<<min(cnt * x + y,y * (cnt + 1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhlbjtu2016/article/details/81065939