/*
题意:给出n个点,m个边。给出每个点的权值,每个边的权值。求建立一棵树,root=1,求这棵树的最小费用,费用=树上每条边*子树中各顶点的权值。
思路:root的权值是没用的,而其余节点是必须用的,每条边*子树中各定点的权值=各个点*点到根的最短路,于是转化成了root到各个点的最短路。
*/
#include<cstdlib>
#include<iostream>
#include<sstream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include <algorithm>
#include<vector>
#include<set>
#include<queue>
#define LL long long
#define inf ((LL)1<<63-1)//1<<63-1=0!!!注意wa了n次
#define E 1e-9
#define N 50005
#define M 2000000
using namespace std;
int n,m;
int q[N],w[N];//循环队列
LL d[N],sum;
int inq[N];
struct Node
{
int w,v;
};
int head[N];
Node temp[N*2];
int top,next[N*2];
void init()
{
memset(inq,0,sizeof(inq));
fill(d+1,d+n+1,inf);
// for (int i=0;i<n;i++)
// cout<<d[i]<<" ";
// cout<<endl;
d[1]=0;
sum=0;
}
void spfa()
{
init();
int r=0,f=0;
q[r++]=1;
inq[1]=1;
while(f!=r)
{
int u=q[f++];
if(f==N-1)
f=0;
for(int i=head[u]; i!=-1; i=next[i])
{
Node *p=&temp[i];
if(d[p->v]>d[u]+p->w)
{
d[p->v]=d[u]+p->w;
if(!inq[p->v])
{
q[r++]=p->v;
if(r==N-1)
r=0;
inq[p->v]=1;
}
}
}
inq[u]=0;
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("ex.in","r",stdin);
#endif
//printf("%I64d\n",(LL)1<<63-1);
//printf("%I64d\n",1<<63-1);
//printf("%I64d\n",inf);
int ncase;
scanf("%d",&ncase);
while(ncase--)
{
int x,y,z;
scanf("%d%d",&n,&m);
for (int i=1; i<=n; i++)
scanf("%d",&w[i]);
memset(head,-1,sizeof(head));
top=0;
for(int i=0; i<m; ++i)
{
scanf("%d%d%d",&x,&y,&z);
temp[top].v=y;
temp[top].w=z;
next[top]=head[x];
head[x]=top++;
temp[top].v=x;
temp[top].w=z;
next[top]=head[y];
head[y]=top++;
}
// cout<<"top="<<top<<endl;
// for(int i=1; i<=n; i++)
// {
// cout<<"head[i]="<<head[i]<<endl;
// for(int j=head[i]; j!=-1; j=next[j])
// {
// Node *p=&temp[j];
// cout<<p->v<<" ";
// }
// cout<<endl;
// }
spfa();
int flag=0;
for(int i=2; i<=n; i++)
{
if(d[i]==inf)
{
flag=1;
break;
}
sum+=d[i]*w[i];
}
if(flag)
printf("No Answer\n");
else
printf("%lld\n",sum);
}
return 0;
}
poj3013-----spfa算法(难题)
最新推荐文章于 2019-02-17 20:30:56 发布