1443B - Saving the City - CodeForces Solution


dp greedy math sortings *1300

Please click on ads to support us..

Python Code:

for i in range(int(input())):
    a ,b = map(int , input().split())
    s = (input())
    ind = []
    for j in range(len(s)):
        if s[j]=="1":
            ind.append(j+1)
    var = []
    for j in range(len(ind)-1):
        if ind[j+1]-ind[j]!=1:
            var.append(ind[j+1]-ind[j]-1)
    answer = []
    ans = 0
    for j in range(len(var)):
        if var[j]*b <= a:
            ans += var[j]*b
        else:
            answer.append(ans+a)
            ans = 0
        if j==len(var)-1:
            answer.append(ans+a)
        if s.count("1")==0:
        print(0)
    elif len(answer)==0:
        print(a)
    else:
        print(sum(answer))

C++ Code:

#include <bits/stdc++.h>
using namespace std;
int dp[100005],z[100005];
char c[10005];
int main()
{
	int t;
	cin>>t;
	while(t--){
		//TODO
		int a,b;
		memset(dp,0,sizeof(dp));
		cin>>a>>b>>c;
		int n=strlen(c);
		if(c[0]=='1'){
			//TODO
			dp[0]=a;
		}
		for(int i=0; i<n; i++){
			//TODO
			if(c[i]=='0'){
				//TODO
				dp[i]=dp[i-1];
			}
			else{
				int j;
				for(j=i-1; j>=0; j--){
					//TODO
					if(c[j]=='1'){
						//TODO
						break;
					}
				}
				if(j<0){
					//TODO
					dp[i]=a;
					continue;
				}
				if(c[i-1]=='1'){
					//TODO
					dp[i]=dp[i-1];
					continue;
				}
				dp[i]=min(dp[i-1]+a,dp[j]+(i-j-1)*b);
			}
		}
		cout<<dp[n-1]<<endl;
	}
	return 0;
}
   					   	 	 	    		   		  		


Comments

Submit
0 Comments
More Questions

1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game
1187A - Stickers and Toys
313B - Ilya and Queries
579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK
1635A - Min Or Sum
474A - Keyboard