天天看點

最短路-鄰接表(優先隊列)寫

題目連結:http://codevs.cn/problem/2038/

題目描述 Description

農夫John發現做出全威斯康辛州最甜的黃油的方法:糖。把糖放在一片牧場上,他知道N(1<=N<=500)隻奶牛會過來舔它,這樣就能做出能賣好價錢的超甜黃油。當然,他将付出額外的費用在奶牛上。

農夫John很狡猾。他知道他可以訓練這些奶牛,讓它們在聽到鈴聲時去一個特定的牧場。他打算将糖放在那裡然後下午發出鈴聲,以至他可以在晚上擠奶。

農夫John知道每隻奶牛都在各自喜歡的牧場呆着(一個牧場不一定隻有一頭牛)。給出各頭牛在的牧場和牧場間的路線,找出使所有牛到達的路程和最短的牧場(他将把糖放在那)。

輸入描述 Input Description

第一行: 三個數:奶牛數N,牧場數P(2<=P<=800),牧場間道路數C(1<=C<=1450).

第二行到第N+1行: 1到N頭奶牛所在的牧場号.

第N+2行到第N+C+1行: 每行有三個數:相連的牧場A、B,兩牧場間距(1<=D<=255),當然,連接配接是雙向的.

輸出描述 Output Description

一行 輸出奶牛必須行走的最小的距離和.

樣例輸入 Sample Input

3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5      
樣例圖形      
P2  
P1 @[email protected] C1
    \    |\
     \   | \
      5  7  3
       \ |   \
        \|    \ C3
      C2 @[email protected]
         P3    P4      

樣例輸出 Sample Output

8      
{說明: 放在4号牧場最優. }      

說明:通過集合存邊,找最近的邊,意思是剛剛入隊的邊,有點像bfs。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
using namespace std;
int n,p,c,tot=0;
struct node {
    int v,w,next;
} edge[1500*10];
struct Node {
    int id,v;
    bool operator <(const Node&a)const {
        return v>a.v;
    }
};
int dis[801],vis[801],num[550],head[1500*4];
void Insert(int u,int v,int w) {
    edge[tot].v=v;
    edge[tot].w=w;
    edge[tot].next=head[u];
    head[u]=tot++;
}
void spfa(int temp) {
    mst(vis,0);
    priority_queue<Node> qu;
    while(!qu.empty())
        qu.pop();
    for(int i=1; i<=p; i++)
        dis[i]=maxn;
    dis[temp]=0;
    Node kk;
    kk.id=temp;
    kk.v=dis[temp];
    qu.push(kk);
    while(!qu.empty()) {
        Node now=qu.top();
        qu.pop();
        if(vis[now.id]==1)
            continue;
        vis[now.id]=1;
        for(int i=head[now.id]; i!=-1; i=edge[i].next) {
            int v=edge[i].v;
            int w=edge[i].w;
            if(!vis[v] && dis[now.id]+w<dis[v]) {
                dis[v]=dis[now.id]+w;
                Node aa;
                aa.id=v;
                aa.v=dis[v];
                qu.push(aa);
            }
        }
    }
}
int main() {
    cin.sync_with_stdio(false);
    cin>>n>>p>>c;
    mst(head,-1);
    for(int i=1; i<=n; i++)
        cin>>num[i];
    for(int i=1; i<=c; i++) {
        int a,b,len;
        cin>>a>>b>>len;
        Insert(a,b,len);
        Insert(b,a,len);
    }
    int ans=maxn;
    for(int i=1; i<=p; i++) {
        spfa(i);
        int sum=0;
        for(int i=1; i<=n; i++)
            sum+=dis[num[i]];
        ans=min(sum,ans);
    }
    cout<<ans<<endl;
    return 0;
}