CF 812B Sagheer, the Hausmeister

来源:互联网 发布:java人才培训班 编辑:程序博客网 时间:2024/06/10 17:44

The way I get this done is dynamic programming . Unlike the greedy method I do a little preliminary stuff to finished it.
the equation is pretty easy , just three way of get next floor.but we have to find the topmost floor that need to go .

#include <bits/stdc++.h>#include <cstring>using namespace std;const int maxn = 1005;const int INF  = 1<<29;int n = 0,m;int dp[maxn][2];int lmost[maxn],rmost[maxn];int go(int from,int to,int i){    if(from == 1 && to == 1)    {        return lmost[i]*2 + 1;    }    if(from == 0 && to == 0)    {        return rmost[i]*2 + 1;    }    if( from != to)    {        return m +2;    }}int main(){    cin>>n>>m;    string str[20];    int ceilling = 0;    for(int i=n; i>=1; i--)    {        cin>>str[i];    }    int flag = 0;    for(int i=n;i>=1;i--)    {        for(int j=1;j<=m;j++)        {            if(str[i][j] == '1')            {                flag = 1;                break;            }        }        if(flag == 0) n--;        if(flag) break;    }//    cout<<n<<endl;    for(int i = 1;i<=n;i++)    {        int f = 0;        for(int j=1;j<=m;j++)        {            if(str[i][j] == '1')            {                f = 1;                lmost[i] = m-j+1;                break;            }        }        for(int j = m;j>=1;j--)        {            if(str[i][j] == '1')            {                rmost[i] = j;                break;            }        }        if(!f)        {            lmost[i] = rmost[i] = 0;        }    }    //cout<<n<<endl;    if(n == 1)    {        cout<<rmost[1]<<endl;        return 0;    }   //cout<<n<<endl;//    for(int i=n;i>=1;i--)//    {//        cout<<lmost[i]<<" "<<rmost[i]<<endl;//    }    dp[1][0] = 0;    dp[1][1] = m;    for(int i=2; i<=n; i++)    {        dp[i][0] = min(dp[i-1][0] + go(0,0,i-1),dp[i-1][1]+go(1,0,i-1));        dp[i][1] = min(dp[i-1][1] + go(1,1,i-1),dp[i-1][0]+go(0,1,i-1));    }//    cout<<endl;//    for(int i=n;i>=1;i--)//    {//        for(int j =0 ;j<2;j++)//        {//            cout<<dp[i][j]<<" ";//        }//        cout<<endl;//    }    cout<<min(dp[n][0] + rmost[n],dp[n][1] + lmost[n])<<endl;    return 0;}
原创粉丝点击