| Time Limit: 1000MS | Memory Limit: 65536K | |||
| Total Submissions: 4808 | Accepted: 1549 | Special Judge | ||
Description
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:
a. the official works on the 1st floor;
b. the document is signed by the official working in the room with the same number but situated one floor below;
c. the document is signed by an official working in a neighbouring room (rooms are neighbouring if they are situated on the same floor and their numbers differ by one).
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
Output
Sample Input
3 4 10 10 1 10 2 2 2 10 1 10 10 10
Sample Output
3 3 2 1 1
Hint
This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed.
题意:n*m的矩阵,输出从第一行走到最后一行的最短路径。可以往下、往左、往右走。
解题思路:由于这题不可能来回走,即到达(i,j)位置,必定直接下来,或者从左边过来,或者从右边过来,不可能先左走一会儿,再右走过来。所以dp[i][j]表示到达(i,j)位置的最小值,分别按照往下走,往左走,往右走扫描一遍即可,注意记录一下路径。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 505;
int n,m,map[maxn][maxn];
int dp[maxn][maxn],dir[maxn][maxn];
void print(int x,int y)
{
if(dir[x][y] == 0)
print(x-1,y);
else if(dir[x][y] == 1)
print(x,y-1);
else if(dir[x][y] == 2)
print(x,y+1);
printf("%d\n",y);
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
scanf("%d",&map[i][j]);
for(int i = 1; i <= m; i++)
{
dp[1][i] = map[1][i];
dir[1][i] = -1;
}
for(int i = 2; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
dp[i][j] = dp[i-1][j] + map[i][j];
dir[i][j] = 0;
}
for(int j = 2; j <= m; j++)
if(dp[i][j] > dp[i][j-1] + map[i][j])
{
dp[i][j] = dp[i][j-1] + map[i][j];
dir[i][j] = 1;
}
for(int j = m - 1; j >= 1; j--)
if(dp[i][j] > dp[i][j+1] + map[i][j])
{
dp[i][j] = dp[i][j+1] + map[i][j];
dir[i][j] = 2;
}
}
int pos = 1;
for(int i = 2; i <= m; i++)
if(dp[n][i] < dp[n][pos])
pos = i;
print(n,pos);
}
return 0;
}
1082


&spm=1001.2101.3001.11974&articleId=51510247&d=1&t=3&u=c9dc1209682a4de7ab07e0516af059e1)

被折叠的 条评论
为什么被折叠?



