天天看點

問題 B: 【例4-1】最短路徑問題

問題 B: 【例4-1】最短路徑問題

時間限制: 1 Sec  記憶體限制: 128 MB

送出: 43  解決: 27

[送出][狀态][讨論版][命題人:quanxing][Edit] [TestData]

題目連結:http://acm.ocrosoft.com/problem.php?cid=1712&pid=1

題目描述

平面上有n個點(n≤100),每個點的坐标均在-10000~10000之間。其中的一些點之間有連線。

若有連線,則表示可從一個點到達另一個點,即兩點間有通路,通路的距離為兩點間的直線距離。現在的任務是找出從一點到另一點之間的最短路徑。

輸入

共n+m+3行,其中:

第一行為整數n。

第2行到第n+1行(共n行) ,每行兩個整數x和y,描述了一個點的坐标。

第n+2行為一個整數m,表示圖中連線的個數。

此後的m 行,每行描述一條連線,由兩個整數i和j組成,表示第i個點和第j個點之間有連線。

最後一行:兩個整數s和t,分别表示源點和目标點。

輸出

一行,一個實數(保留兩位小數),表示從s到t的最短路徑長度。

樣例輸入

5

0 0

2 0

2 2

0 2

3 1

5

1 2

1 3

1 4

2 5

3 5

1 5
           

樣例輸出

3.41

           

思路:先把點與點的距離算出來,然後類似dijstra算法套就行了,難度主要在化點為線

代碼:

#include<bits/stdc++.h>

using namespace std;

int n, m, pos;

#define inf 0x3f3f3f3f

#define maxn 105

int visit[maxn];

double dis[maxn], length[maxn][maxn];

int Start, End;

struct Point

{

    double x, y;//結構體存點

}p[105];

double dijstra()

{

    for (int i = 1; i <= n; i++)

    {

         dis[i] = length[Start][i];

         //cout << dis[i] << " ";

    }

    dis[Start] = 0;

    visit[Start] = 1;

    for (int i = 1; i < n; i++)

    {

         double minn = inf;

         for (int j = 1; j <= n; j++)

         {

             if (visit[j] == 0 && minn > dis[j])

             {



                  minn = dis[j];//cout << "minn   " << minn << "   j   "<<j<<endl;

                  pos = j;

             }

         }

         visit[pos] = 1;

         for (int j = 1; j <= n; j++)

         {

             if (visit[j] == 0 && dis[j] > dis[pos] + length[pos][j])

             {

                  dis[j] = dis[pos] + length[pos][j];

             }

         }

    }

    return dis[End];

}

int  main()

{

    cin >> n;

    for (int i = 1; i <= n; i++)

    {

         cin >> p[i].x >> p[i].y;

    }

    cin >> m;

    for (int i = 0; i <= 100; i++)

    {

         for (int j = 0; j <= 100; j++)

         {

             length[i][j] = 99999999;

         }

    }

    for (int i = 1; i <= m; i++)

    {

         int start, end;

         cin >> start >> end;



         length[start][end] = sqrt((p[start].x - p[end].x)*(p[start].x - p[end].x) + (p[start].y - p[end].y)*(p[start].y - p[end].y));//算出每個點之間的額距離

         //cout << "length[start][end]" << length[start][end] << endl;

         length[end][start] = length[start][end];

    }

    cin >> Start >> End;

    cout << fixed << setprecision(2);

    cout << dijstra();//套dijstra

    int z;

    cin >> z;

}