1. 程式人生 > >CodeForces-812B Sagheer, the Hausmeister

CodeForces-812B Sagheer, the Hausmeister

小dp

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int N=20;
const int M=100+10;
char g[N][M];
int l[N],r[N];
int d[N][2];
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=n-1;i>=0;i--)
		scanf("%s",g[i]);
	int top=0;
	for(int i=0;i<n;i++)
		r[i]=0,l[i]=m+1;
	for(int i=0;i<n;i++)
	{
		bool flag=false;
		for(int j=0;j<=m+1;j++)
			if(g[i][j]=='1')
			{
				flag=true;
				l[i]=min(l[i],j);
				r[i]=max(r[i],j);
			}
		if(flag) top=i;
	}
	d[0][0]=2*r[0];
	d[0][1]=m+1;
	for(int i=1;i<top;i++)
	{
		d[i][0]=min(d[i-1][0]+2*r[i],d[i-1][1]+m+1);
		d[i][1]=min(d[i-1][1]+2*(m-l[i]+1),d[i-1][0]+m+1);
	}
	int ans=0;
	if(top>0)
		ans=min(d[top-1][0]+r[top],d[top-1][1]+(m-l[top]+1));
	else
		ans=r[top];
	ans+=top;
	printf("%d\n",ans);
	return 0;
}