Codeforces Round #417 B. Sagheer, the Hausmeister
题目链接:http://codeforces.com/contest/812/problem/B
题意:
给你一个建筑物n层,每层m个房间。1的房间为亮灯的,0为灭顶的房间。左边有一条楼梯,右边有一条楼梯。你从房子的左下放的楼梯进入,当你走上一层的时候,一定要关完这一层的全部灯。问你怎么走步数最少。
题解:
简单dp题目。dpl[i] 和 dpr[i] 。dpl[i] 为走完第i层,在走到左边的楼梯的步数, dpr[i] 为走到右边的步数。
转移方程:
回到左边:
dpl[i] = min(楼下在左边上来+2*最右边灯的位置(要回到左边), 楼下从右边上来+m+1) + 1(上楼)
dpl[i] = min(dpl[i+1] +2*r[i] , dpr[i+1] + m + 1) + 1;
同理到右边也是一样。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cmath> 6 #include <string> 7 #include <vector> 8 #include <map> 9 #include <set> 10 #include <stack> 11 #include <queue> 12 #include <sstream> 13 #include <algorithm> 14 using namespace std; 15 #define pb push_back 16 #define mp make_pair 17 #define ms(a, b) memset((a), (b), sizeof(a)) 18 #define eps 1e-3 19 typedef long long LL; 20 typedef unsigned long long ULL; 21 const int inf = 0x3f3f3f3f; 22 const LL INF = 0x7fffffff; 23 const int maxn = 100+10; 24 const int mod = 1e9+7; 25 char s[maxn][maxn]; 26 int dpl[maxn], dpr[maxn]; 27 int l[maxn], r[maxn]; 28 void init() { 29 ms(dpl, 0); 30 ms(dpr, 0); 31 } 32 void solve() { 33 int n, m; 34 scanf("%d%d", &n, &m); 35 for(int i = 1;i<=n;i++) 36 scanf("%s",s[i]); 37 for(int i = 1;i<=n;i++){ 38 for(int j = 1;j<=m;j++){ 39 if(s[i][j] == '1'){ 40 l[i] = m + 1 - j;break; 41 } 42 } 43 for(int j = m;j>=1;j--){ 44 if(s[i][j] == '1'){ 45 r[i] = j;break; 46 } 47 } 48 } 49 // for(int i = 1;i<=n;i++){ 50 // cout << l[i] << " " << r[i] << endl; 51 // } 52 bool allzero = true; 53 for(int i = 1;i<=n;i++) 54 for(int j = 1;j<=m;j++) 55 if(s[i][j]=='1') allzero = false; 56 if(allzero){ 57 printf("0\n");return; 58 } 59 int high; 60 for(int i = 1;i<=n;i++){ 61 bool haveone = false; 62 for(int j = 1;j<=m;j++) 63 if(s[i][j] == '1') haveone = true; 64 if(haveone) {high = i;break;} 65 } 66 // cout << high <<endl; 67 if(high == n){ 68 printf("%d\n", r[n]); 69 return; 70 } 71 dpl[n] = 2*r[n]; 72 dpr[n] = m+1; 73 for(int i = n-1;i>high;i--){ 74 dpl[i] = min(dpl[i+1]+2*r[i], dpr[i+1]+m+1)+1; 75 dpr[i] = min(dpr[i+1]+2*l[i], dpl[i+1]+m+1)+1; 76 } 77 dpl[high] = min(dpl[high+1]+r[high], dpr[high+1]+l[high])+1; 78 dpr[high] = min(dpr[high+1]+l[high], dpl[high+1]+r[high])+1; 79 printf("%d\n", dpl[high], dpr[high]); 80 return; 81 } 82 int main() { 83 #ifdef LOCAL 84 freopen("input.txt", "r", stdin); 85 freopen("output.txt", "w", stdout); 86 #endif // LOCAL 87 init(); 88 solve(); 89 return 0; 90 }
你努力的时候,比你厉害的人也在努力。