首页 > 代码库 > USACO 3.2 butter 最短路

USACO 3.2 butter 最短路

堆优化dijkstra

 

 1 /* 2 PROB:butter 3 LANG:C++ 4 */ 5  6 #include <iostream> 7 #include <cstdio> 8 #include <queue> 9 #include <vector>10 using namespace std;11 const int Ni = 10000;12 const int INF = 1<<27;13 struct node{14     int x,d;15     node(){}16     node(int a,int b){x=a;d=b;}17     bool operator < (const node & a) const18     {19         if(d==a.d) return x<a.x;20         else return d > a.d;21     }22 };23 vector<node> eg[Ni];24 int dis[Ni],cow[Ni],ans,p,c,n;25 26 void Dijkstra(int s)27 {28     int i;29     for(i=0;i<=p;i++) dis[i]=INF;30     dis[s]=0;31     priority_queue<node> q;32     q.push(node(s,dis[s]));33     while(!q.empty())34     {35         node x=q.top();q.pop();36         for(i=0;i<eg[x.x].size();i++)37         {38             node y=eg[x.x][i];39             if(dis[y.x]>x.d+y.d)40             {41                 dis[y.x]=x.d+y.d;42                 q.push(node(y.x,dis[y.x]));43             }44         }45     }46 }47 int main()48 {49     freopen("butter.in","r",stdin);50     freopen("butter.out","w",stdout);51 52     ans=INF;53     scanf("%d %d %d",&n,&p,&c);54     for (int i=1;i<=n;i++)55         scanf("%d",&cow[i]);56     for (int i=1;i<=c;i++)57     {58         int x,y,t;59         scanf("%d %d %d",&x,&y,&t);60         //a[x][y]=t;        a[y][x]=t;61         eg[x].push_back(node(y,t));62         eg[y].push_back(node(x,t));63     }64 65     for (int k=1;k<=p;k++)66     {67         Dijkstra(k);68 69         int tmp=0;70         for (int i=1;i<=n;i++)71             tmp+=dis[cow[i]];72         if (tmp<ans)73             ans=tmp;74     }75     printf("%d\n",ans);76 77     return 0;78 }
View Code

 

USACO 3.2 butter 最短路