Shortest path counting
阿新 • • 發佈:2018-11-03
Shortest path counting
1000(ms)
65535(kb)
1008 / 1840
Tags: 動態規劃
@淺夏沫若.code: #include<iostream>
#include<string>
using namespace std;
struct node
{
int value=1;
int path = 1;
}map[20][20];
int main()
{
int n = 0;
cin >> n;
for(int i=1;i<=n;i++)
for (int j = 1; j <= n; j++)
{
if (i == 1 || j == 1)
map[i][j].value = i * j;
else
{
if (map[i - 1][j].value > map[i][j - 1].value)
{
map[i][j].value = map[i][j - 1].value+1;
map[i][j].path = map[i][j - 1].path;
}
else if (map[i - 1][j].value == map[i][j - 1].value)
{
map[i][j].value = map[i][j - 1].value + 1;
map[i][j].path = map[i][j - 1].path+ map[i - 1][j].path;
}
else
{
map[i][j].value = map[i-1][j].value + 1;
map[i][j].path = map[i-1][j].path;
}
}
}
cout << map[n][n].path<<endl;
return 0;
}
A chess rook can move horizontally o r vertically to any square in the same row o r in the same column of a chessboard. Find the number of shortest paths by which a rook can move from one corner of a chessboard to the diagonally opposite corner。
輸入
a interger number n is row and column of chessboard. 0 < n <=16
輸出
the number of shortest paths.
樣例輸入
4
樣例輸出
20
@淺夏沫若.code: #include<iostream>
#include<string>
using namespace std;
struct node
{
int value=1;
int path = 1;
}map[20][20];
int main()
{
int n = 0;
cin >> n;
for(int i=1;i<=n;i++)
for (int j = 1; j <= n; j++)
{
if (i == 1 || j == 1)
map[i][j].value = i * j;
else
{
if (map[i - 1][j].value > map[i][j - 1].value)
{
map[i][j].value = map[i][j - 1].value+1;
map[i][j].path = map[i][j - 1].path;
}
else if (map[i - 1][j].value == map[i][j - 1].value)
{
map[i][j].value = map[i][j - 1].value + 1;
map[i][j].path = map[i][j - 1].path+ map[i - 1][j].path;
}
else
{
map[i][j].value = map[i-1][j].value + 1;
map[i][j].path = map[i-1][j].path;
}
}
}
cout << map[n][n].path<<endl;
return 0;
}