1029. Ministry
Time limit: 1.0 second
Memory limit: 64 MB
Mr. F. wants to get a document be signed by a minister. A minister signs a document only if it is approved by his ministry. The ministry is an
M-floor building with floors numbered from 1 to
M, 1 ≤
M ≤ 100. Each floor has
N rooms (1 ≤
N ≤ 500) also numbered from 1 to
N. In each room there is one (and only one) official.
A document is approved by the ministry only if it is signed by at least one official from the
M-th floor. An official signs a document only if at least one of the following conditions is satisfied:
Each official collects a fee for signing a document. The fee is a positive integer not exceeding 10
9.
You should find the cheapest way to approve the document.
Input
The first line of an input contains two integers, separated by space. The first integer
M represents the number of floors in the building, and the second integer
N represents the number of rooms per floor. Each of the next
M lines contains
N integers separated with spaces that describe fees (the
k-th integer at
l-th line is the fee required by the official working in the
k-th room at the
l-th floor).
Output
You should print the numbers of rooms in the order they should be visited to approve the document in the cheapest way. If there are more than one way leading to the cheapest cost you may print an any of them.
Sample
|
/**
以楼层划分阶段,而楼层中的每个房间则为状态
设dp[i][j]表示经过点 (i-1,j) 向上到达 点 (i,j) 所花费的路径,对于每一层,可以从左至右扫描一次,再从右到左扫描一次
dp[i][j]=min{f[i-1][k]+cost[i-1,k,j]}+c[i,j];
**/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxn 666
int n,m;
int mini=1;
long f[maxn][maxn]={0};
struct DpStruct
{
long long w;
int c;
int from;
}dp[maxn][maxn];
void read()
{
scanf("%d%d",&n,&m);
for(int j=1;j<=n;j++)
for(int k=1;k<=m;k++)
scanf("%d",&f[j][k]);
memset(dp,0,sizeof(dp));
for(int i=1;i<=m;i++)
{
dp[n][i].w=f[n][i];
}
}
void DP()
{
for(int i=n-1;i>=1;i--)
{
for(int j=1;j<=m;j++)//从上来
{
dp[i][j].w=dp[i+1][j].w+f[i][j];
dp[i][j].c=i+1;
dp[i][j].from=j;
}
for(int j=2;j<=m;j++)//从左来
{
if(dp[i][j].w>dp[i][j-1].w+f[i][j])
{
dp[i][j].w=dp[i][j-1].w+f[i][j];
dp[i][j].c=i;
dp[i][j].from=j-1;
}
}
for(int j=m-1;j>=1;j--)//从右来
{
if(dp[i][j].w>dp[i][j+1].w+f[i][j])
{
dp[i][j].w=dp[i][j+1].w+f[i][j];
dp[i][j].c=i;
dp[i][j].from=j+1;
}
}
}
for(int i=2;i<=m;i++)
if(dp[1][i].w<dp[1][mini].w)
mini=i;
}
void print()
{
int c1=1;
while(dp[c1][mini].c!=0)
{
cout<<mini<<" ";
int temp=mini;
mini=dp[c1][mini].from;
c1=dp[c1][temp].c;
}
cout<<mini;
}
int main()
{
read();
DP();
print();
return 0;
}