大佬说这道题肯定dp,dp两个端点,好像挺有道理,
然而w了,搜题解都是深搜,(深搜动不动就T, 还是算了吧),自古深搜dp是一家啊,还是dp
有坑就是如果某层上面的搜索的灯都关掉了,就不用再向上走了,
1 # include <cstdio> 2 # include <algorithm> 3 # include <iostream> 4 # include <cstring> 5 using namespace std; 6 7 const int maxn=100+5; 8 int n,m; 9 char s[maxn]; 10 int ls[20],rs[20]; 11 int dp[3][20]; 12 13 int main(){ 14 while(scanf("%d%d",&m,&n)==2&&m&&n){ 15 for(int i=1;i<=m;i++){ 16 ls[i]=n+1; 17 rs[i]=0; 18 scanf("%s",s); 19 for(int j=0;j<=n+1;j++){ 20 if(s[j]=='1') { 21 ls[i]=min(ls[i],j); 22 rs[i]=max(rs[i],j); 23 } 24 } 25 } 26 int en=0; 27 for(int i=1;i<=m;i++){ 28 if(ls[i]==n+1&&rs[i]==0) en=i; 29 else break; 30 } 31 en+=1; 32 for(int i=m;i>en;i--){ 33 if(i==m){ 34 dp[1][i]=rs[i]*2;dp[2][i]=n+1; 35 } 36 else { 37 dp[1][i]=min(dp[1][i+1]+rs[i]*2,dp[2][i+1]+n+1)+1; 38 dp[2][i]=min(dp[2][i+1]+(n-ls[i]+1)*2,dp[1][i+1]+n+1)+1; 39 } 40 } 41 if(en==m+1) printf("0 "); 42 else if(en==m) printf("%d ",rs[m]); 43 else { 44 int ans=min(dp[1][en+1]+rs[en],dp[2][en+1]+(n-ls[en]+1))+1; 45 printf("%d ",ans); 46 } 47 } 48 return 0; 49 }