Timus 1119. Metro 动态规划

Many of SKB Kontur programmers like to get to work by Metro because the main office is situated quite close the station Uralmash. So, since a sedentary life requires active exercises off-duty, many of the staff — Nikifor among them — walk from their homes to Metro stations on foot.
Problem illustration
Nikifor lives in a part of our city where streets form a grid of residential quarters. All the quarters are squares with side 100 meters. A Metro entrance is situated at one of the crossroads. Nikifor starts his way from another crossroad which is south and west of the Metro entrance. Naturally, Nikifor, starting from his home, walks along the streets leading either to the north or to the east. On his way he may cross some quarters diagonally from their south-western corners to the north-eastern ones. Thus, some of the routes are shorter than others. Nikifor wonders, how long is the shortest route.
You are to write a program that will calculate the length of the shortest route from the south-western corner of the grid to the north-eastern one.

Input

There are two integers in the first line:  N and  M (0 <  N, M ≤ 1000) — west-east and south-north sizes of the grid. Nikifor starts his way from a crossroad which is situated south-west of the quarter with coordinates (1, 1). A Metro station is situated north-east of the quarter with coordinates ( NM). The second input line contains a number  K (0 ≤  K ≤ 100) which is a number of quarters that can be crossed diagonally. Then  K lines with pairs of numbers separated with a space follow — these are the coordinates of those quarters.

Output

Your program is to output a length of the shortest route from Nikifor's home to the Metro station in meters, rounded to the integer amount of meters.

Sample

input output
3 2
3
1 1
3 2
1 2
383


很好的一道动态规划法题目。

注意:

1 行列别搞错了,要很细心一点一点对起来

2 要以边线思考,不要以方块来计算, N*M个方块就成了(N+1)*(M+1)条交叉线了,最下面和最左边的线就方便初始化了

3 注意C++的四舍五入的方法

动态规划的状态转移方程:

if (A[y][x]) B[x] = t + 1.414213562;
else 	B[x] = min(B[x-1], B[x]) + 1 ;
A[y][x]表示是否有对角线,有对角线必定是走对角线的。


void Metro1119_Vec()
{
	int N, M, K, x, y;
	cin>>N>>M;//小心什么是行什么是列
	vector<vector<bool> > A(M+1, vector<bool>(N+1));
	cin>>K;
	for (int i = 0; i < K; i++)
	{
		cin>>x>>y;//列和行别搞错了
		A[y][x] = 1;
	}
	vector<double> B(N+1);
	for (int i = 0; i <= N; i++)
	{
		B[i] = (double)i;
	}
	for (y = 1; y <= M; y++)
	{
		double t = B[0];
		B[0] += 1.0;
		for (x = 1; x <= N; x++)
		{
			double a = B[x];
			if (A[y][x]) B[x] = t + 1.414213562;
			else 	B[x] = min(B[x-1], B[x]) + 1 ;
			t = a;
		}
	}
	cout<<(int)(B[N] * 100.0 + 0.5);//修改要全面
}


逛了下网上,发现本题还可以利用LIS的思想去做的。

还可以使用一下bitset的容器进一步省内存。

有空继续优化一下。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值