E. K-periodic Garland

E. K-periodic Garland

#include
using namespace std;
typedef long long ll;
typedef pairP;
const int inf = 0x7f7f7f7f;
const int N = 1e6+10;
const ll mod = 1e9+7;
const double PI = 3.14;

int read(){
    char ch=getchar();int x=0,f=1;
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while('0'<=ch&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int random(int n){return(ll)rand()*rand()%n;}


char s[N];
int dp[N][2],pre[N];
//dp[i][0]表示第i个为0最少的操作
//dp[i][1]表示第i个为1最少的操作
void solve(){
    int n = read(),k = read();
    scanf("%s",s+1);
    for(int i = 1;i <= n;i++){
        pre[i] = dp[i][0] = dp[i][1] = 0;
        pre[i] = pre[i-1]+s[i]-48;
    }
    for(int i = 1;i <= n;i++){
        int p = max(0,i-k);
        dp[i][0] = min(dp[i-1][0],dp[i-1][1])+(s[i]=='1');//找到前面最小的
        dp[i][1] = min(pre[i-1],dp[p][1]+pre[i-1]-pre[p])+(s[i]=='0');
        //有两种情况,一种是将前pre[i-1]个1都化成0,
        //还一种就是将第p个变成1,但是再p~i-1的1应该去掉
    }
    printf("%d\n",min(dp[n][0],dp[n][1]));
}
int main(){
    //srand((unsigned)time(0));
    //freopen("out.txt","w",stdout);
    //freopen("in.txt","r",stdin);
    //cout<<50*(50/2500)<

你可能感兴趣的:(DP,Codeforces)