uva116(代码写挫了)

思路很明确的一个题目,

但是却在uva上wa了好多次,但是在hdu上过了,问题在于,hdu数据不全

当列数为1 的时候,我原来的代码是会崩的,并且会错,幸好一开始错在RE才让我想到1的问题,要是一直wa,可能真的要找更久的bug了,这个细节,真的该好好反思一下

错误代码 :  如何m==1的话,当j==m-1时,后面j==0是无法进入的,被continue掉了;

样例:

/*
4 1
3
2
1
5

answer:
3
1
*/

正确代码如下:

#include <iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>

using namespace std;

const int maxn=1000;
const int inf=0x3f3f3f3f;
int a[maxn][maxn];
int dp[maxn][maxn];
int nextt[maxn][maxn];
int n,m;

void solve()
{
    int ans=inf;
    int first=0;
    for(int j=m-1; j>=0; j--)
    {
        for(int i=0; i<n; i++)
        {
            if(j==m-1)
            {
                dp[i][j]=a[i][j];

            }
            else
            {
                dp[i][j]=inf;
                int row[]= {i,i+1,i-1};
                if(i==0) row[2]=n-1;
                if(i==n-1) row[1]=0;
                sort(row,row+3);
                for(int k=0; k<3; k++)
                {
                    if(dp[i][j]>dp[row[k]][j+1]+a[i][j])
                    {
                        dp[i][j]=dp[row[k]][j+1]+a[i][j];
                        nextt[i][j]=row[k];
                    }
                }
            }

            if(j==0&&ans>dp[i][j])
            {
                ans=dp[i][j];
                first=i;
            }
        }
    }
    cout<<first+1;
    for(int i=nextt[first][0],j=0; j<m-1; j++,i=nextt[i][j])
        cout<<" "<<i+1;
    cout<<endl;
    cout<<ans<<endl;
}
int main()
{
    while(cin>>n>>m)
    {
        for(int i=0; i<n; i++)
            for(int j=0; j<m; j++)
                cin>>a[i][j];
        solve();
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/sinat_36215255/article/details/79198298
116