poj1450 Gridland

这个题是NP旅行商问题的简化版,求的是一个矩阵上的最短的路径。

NP旅行商问题是Given a set of N towns and roads between these towns, the problem is to compute the shortest path allowing a salesman to visit each of the towns once and only once and return to the starting point.只不过这道题是将这N towns 放在了一个矩阵上,这样可以找到规律,如下:

设矩阵为M*N,如果M和N都是奇数,那么最短的路径中有且仅有一条斜边,即√2的单位长度,答案是M*N-1+√2

其他情况 答案是M*N

下面是代码,注意sqrt()的参数是double型,即sqrt(2.0);

View Code
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;

int main()
{
    int num;
    cin>>num;
    int m,n,i;
    double res;
    for(i=1;i<=num;i++)
    {
        cin>>m>>n;
        if(m%2==1 && n%2==1)
            res=m*n-1+sqrt(2.0);
        else
            res=m*n;
        printf("Scenario #%d:\n",i);
        printf("%0.2lf\n",res);
        printf("\n");
    }
    return 0;
}


这个题在tju oj1015也出现过。

转载于:https://www.cnblogs.com/pushing-my-way/archive/2012/07/11/2586364.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值