http://poj.org/problem?id=3013

dij priority queue 

  1 #include<cstdio>
  2 #include<queue>
  3 using namespace std;
  4 typedef __int64 LL;
  5 const LL inf=0x3f3f3f3f3f3f3f3fLL;
  6 class Dijkstra { ///单源最短路 o(ME*log(MV))
  7     typedef LL typec;///边权的类型
  8     static const int ME=1e5+10;///边的个数
  9     static const int MV=5e4+10;///点的个数
 10     struct Q {
 11         int id;
 12         typec w;
 13         friend bool operator <(const Q &a,const Q &b) {
 14             return a.w>b.w;
 15         }
 16     } now;
 17     priority_queue<Q> q;
 18     struct E {
 19         int v,next;
 20         typec w;
 21     } e[ME];
 22     int n,le,head[MV],u,v,i;
 23     typec dist[MV],w;
 24     bool used[MV];
 25 public:
 26     void init(int tn) {///传入点的个数
 27         n=tn;
 28         le=0;
 29         for(i=0; i<=n; i++) head[i]=-1;
 30     }
 31     void add(int u,int v,typec w) {
 32         e[le].v=v;
 33         e[le].w=w;
 34         e[le].next=head[u];
 35         head[u]=le++;
 36     }
 37     void solve(int s) {///传入起点
 38         for(i=0; i<=n; i++) {
 39             used[i]=true;
 40             dist[i]=inf;
 41         }
 42         dist[s]=0;
 43         now.id=s;
 44         now.w=0;
 45         while(!q.empty()) q.pop();
 46         q.push(now);
 47         while(!q.empty()) {
 48             now=q.top();
 49             q.pop();
 50             u=now.id;
 51             if(used[u]) {
 52                 used[u]=false;
 53                 for(i=head[u]; ~i; i=e[i].next) {
 54                     v=e[i].v;
 55                     w=e[i].w;
 56                     if(used[v]&&dist[v]>w+dist[u]) {
 57                         dist[v]=w+dist[u];
 58                         now.id=v;
 59                         now.w=dist[v];
 60                         q.push(now);
 61                     }
 62                 }
 63             }
 64         }
 65     }
 66     typec getdist(int id) {
 67         return dist[id];
 68     }
 69 } g;
 70 int val[50010];
 71 int main(){
 72     int t,n,m,u,v,w;
 73     while(~scanf("%d",&t)){
 74         while(t--){
 75             scanf("%d%d",&n,&m);
 76             for(int i=1;i<=n;i++){
 77                 scanf("%d",&val[i]);
 78             }
 79             g.init(n);
 80             while(m--){
 81                 scanf("%d%d%d",&u,&v,&w);
 82                 g.add(u,v,w);
 83                 g.add(v,u,w);
 84             }
 85             g.solve(1);
 86             bool flag=true;
 87             LL sum=0;
 88             for(int i=1;i<=n;i++){
 89                 if(g.getdist(i)==inf){
 90                     flag=false;
 91                     break;
 92                 }
 93                 sum+=g.getdist(i)*val[i];
 94             }
 95             if(!flag){
 96                 puts("No Answer");
 97             }
 98             else{
 99                 printf("%I64d\n",sum);
100             }
101         }
102     }
103     return 0;
104 }
View Code

相关文章: