【JZOJ5341】【NOIP2017模拟9.2A组】密州盛宴

Description

这里写图片描述

Data Constraint

这里写图片描述

Solution

我们发现要想让序列合法,苏东坡必须每个时刻都有菜吃。 要想满足这个条件,我们从后往前数的时候,任意时刻1的数量-0的数量必须大于等于-1。意味着0每出现1个,1就必须出现1个,然后0可以多出现一个,意味着村民再吃1盘。若1的数量-0的数量为-2,意味着苏东坡有一个时刻吃不了菜。我们发现每次遇到一个不合法的,该位上的数一定是0,我们只用将0丢到最前方即可。那么中间的数的往右移动数+1,并且这些数的后缀和都+1。由此想法,我们只用找到后缀和最小的值,答案即最小值-1。

Code

#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
const ll maxn=1e5+5;
ll a[maxn],b[maxn];
ll n,m,i,t,j,k,l,x,y,z,num,r,mid,mi,ans;
char s[maxn*10];
int main(){
    freopen("meal.in","r",stdin);freopen("meal.out","w",stdout);
    while (1){
        scanf("%lld%lld\n",&n,&m);
        if (!n) return 0;n=1;mi=0;
        for (i=1;i<=m;i++)scanf("%s%lld",s+n,&a[i]),n+=strlen(s+n),b[i]=n-1;
        x=0;ans=1e9;
        for (i=m;i>=1;i--){
            t=0;k=1e9;
            for (j=b[i];j>b[i-1];j--){
                if (s[j]==48) t--;
                else t++;
                k=min(k,t);
            }
            if (t<0) k=k+t*(a[i]-1);
            ans=min(ans,k+x);
            x+=t*a[i];
        }
        if (x<0) printf("-1\n");
        else{
            if (ans>=-1) printf("0\n");
            else printf("%lld\n",-1-ans);
        }
    }
}
发布了257 篇原创文章 · 获赞 451 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/crybymyself/article/details/77803227