北大2907题

来源:互联网 发布:网络理财骗局 编辑:程序博客网 时间:2024/05/18 08:43

题目连接:http://acm.pku.edu.cn/JudgeOnline/problem?id=2907

 

走点的先后次序会影响走的最短路径,点的个数最多10,因此用排列树穷举所有情况找到最短的找到各个点的距离。

 

#include <iostream>
#include <cmath>

using namespace std;

#define MAX 10

struct Position
{
 int row;
 int col;
};

struct Prob
{
 int num;
 int x[MAX];
 Position pos[MAX];
 Position org;

 int len;
 int res;

 void Init()
 {
  len = 0;
  res = 100000;

  int i;
  for(i = 0;i < MAX;++i)
   x[i] = i;
 }

 int Distance(Position& p1,Position& p2)
 {
  return abs(p1.col - p2.col) + abs(p1.row - p2.row);
 }

 void Work(int cur)
 {
  if(cur == num)
  {
   if(len + Distance(pos[x[cur-1]],org) < res)
    res = len + Distance(pos[x[cur-1]],org);
  }
  else
  {
   int i,back;
   for(i = cur;i < num;++i)
   {
    back = len;
    swap(x[cur],x[i]);
    
    if(cur == 0)
     len = Distance(pos[x[cur]],org);
    else
     len += Distance(pos[x[cur-1]],pos[x[cur]]);
    if(len < res)
     Work(cur+1);

    len = back;
    swap(x[cur],x[i]);
   }
  }
 }
};

int main()
{
 freopen("in.txt","r",stdin);

 Prob pb;
 int i,t;
 cin >> t;
 while(t--)
 {
  cin >> pb.len >> pb.len;
  cin >> pb.org.row >> pb.org.col;
  cin >> pb.num;

  for(i = 0;i < pb.num;++i)
   cin >> pb.pos[i].row >> pb.pos[i].col;

  pb.Init();
  pb.Work(0);

  printf("The shortest path has length %d/n",pb.res);
 }
 return 0;
}