<C语言;售货员问题

休言女子非英物,夜夜龙泉壁上鸣。这篇文章主要讲述< C语言; 售货员问题相关的知识,希望能为你提供帮助。
Background


For years, computer scientists have been trying to find efficient solutions to different computing problems. For some of them efficient algorithms are already available, these are the "easy" problems like sorting, evaluating a polynomial or finding the shortest path in a graph. For the "hard" ones only exponential-time algorithms are known. The traveling-salesman problem belongs to this latter group. 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.
Problem


The president of Gridland has hired you to design a program that calculates the length of the shortest traveling-salesman tour for the towns in the country. In Gridland, there is one town at each of the points of a rectangular grid. Roads run from every town in the directions North, Northwest, West, Southwest, South, Southeast, East, and Northeast, provided that there is a neighbouring town in that direction. The distance between neighbouring towns in directions North-South or East-West is 1 unit. The length of the roads is measured by the Euclidean distance. For example, Figure 7 shows 2 * 3-Gridland, i.e., a rectangular grid of dimensions 2 by 3. In 2 * 3-Gridland, the shortest tour has length 6.

&lt;C语言;售货员问题

文章图片

Figure 7: A traveling-salesman tour in 2 * 3-Gridland.
Input


The first line contains the number of scenarios.


For each scenario, the grid dimensions m and n will be given as two integer numbers in a single line, separated by a single blank, satisfying 1 < m < 50 and 1 < n < 50.
Output

The output for each scenario begins with a line containing "Scenario #i:", where i is the number of the scenario starting at 1. In the next line, print the length of the shortest traveling-salesman tour rounded to two decimal digits. The output for every scenario ends with a blank line.
Sample Input


2
2 2
2 3
Sample Output


Scenario #1:
4.00


Scenario #2:
6.00


中文版:
&lt;C语言;售货员问题

文章图片



简单地说,就是从出发点出去遍历所有的点然后回到原点。重点有两个:
1.回到原点
2.全部遍历
其实更重要的是这四个字:矩形网格。这四个字大大降低了本题的难度,如果你没看到这四个字然后拼命在那画三角形,那就厉害了。


这题其实很简单,我们不可能一看到题目就敲代码,先画几个图。


&lt;C语言;售货员问题

文章图片

好像字和图都有点丑?没关系,看得懂就好了。
显然,我们使用归纳法已经得出答案。可以看到,当行X列中两个都是偶数的时候,答案是(m*n-1)+根号2,其余情况答案都是m*n。


接下来编程即可。
由于根号2是1.41,我们可以把它拆成m*n+.41,这样方便我们输出。


#include< stdio.h>
int main()

int number;
printf("请问您想输入多少个案例:");
scanf_s("%d", & number);
for (int i = 1; i < = number; i++)

int n, m;
scanf_s("%d %d", & n, & m);
printf("其所需要的最短路径是:%d", n*m);
if (n % 2 & & m % 2)
printf(".%d\\n", 41);
else
printf(".00\\n");

printf("\\n");
return 0;



运行结果如下:
&lt;C语言;售货员问题

文章图片



当然,还是要按照题目要求输出的,我只是任性。




欢迎关注微信公众号:幻象客

&lt;C语言;售货员问题

文章图片

【< C语言; 售货员问题】


    推荐阅读