题意:KCM 市要造一个大的圣诞树,现在给你含n个点和m条边的图,要你从中选出若干边,从而建成一颗圣诞树。原始图中每个节点都有权值,每条边也有一个权值代表其单位造价。建一颗圣诞树的造价等于树上每个节点的造价之和。每个节点的造价等于从根节点(固定为1)到该结点的最短路径*该节点权值。
分析:理解题意后其实就没什么难度了,就是求最短路径,因为是稀疏图,所以用spfa要更好些。另外,要注意n=0 或n=1 的情况,直接输出0就行了。
代码如下:
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define lrt rt << 1
#define rrt rt << 1|1
#define root 1,m,1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const LL INF = (((LL)1)<<62)+1;
using namespace std;
const double eps = 1e-5;
const int MAXN = 300 + 10;
const int MOD = 1000007;
const double M=1e-8;
const int N=100100;
typedef pair<int, int> pii;
typedef pair<int, string> pis;
int n,m,cnt,q[N];
LL v[N],u[N],w[N],d[N],a[N],p[N],first[N],next[N] ;
bool vis[N];
void add(LL a,LL b,LL c)
{
u[cnt]=a,v[cnt]=b,w[cnt]=c;
next[cnt]=first[a];
first[a]=cnt++;
}
void build()
{
int i,j;
cnt=0;
MS(first,-1);
for(i=0;i<m;i++) {
LL a,b,c;
scanf("%lld%lld%lld",&a,&b,&c);
add(a,b,c);
add(b,a,c);
}
}
void spfa(int s)
{
int i,j;
int front,tail;
front=tail=0;
q[tail++]=s;
MS(vis,false);
for (i=1;i<=n;i++) d[i]=INF;
d[s]=0;
for (i=1;i<=n;i++) p[i]=i;
while(front<tail)
{
int t=q[front++];
vis[t]=false;
for (i=first[t];i!=-1;i=next[i]) if (d[t]+w[i]<d[v[i]]) {
d[v[i]]=d[t]+w[i];
p[v[i]]=u[i];
if (!vis[v[i]]) {
q[tail++]=v[i];
vis[v[i]]=true;
}
}
}
//for (i=1;i<=n;i++) cout<<d[i]<<" "; cout<<endl;
}
LL slove()
{
LL ans=0;
for (int i=2;i<=n;i++) {
if (d[i]==INF) return -1; // 无法建立一颗树
ans+=d[i]*a[i];
}
return ans;
}
int main()
{
int i,j,T;
cin>>T;
while(T--)
{
scanf("%d%d",&n,&m);
for (i=1;i<=n;i++) {
scanf("%lld",a+i);
}
if (n<=1) {
puts("0");
continue;
}
build();
spfa(1);
LL t=slove();
if (t<0) puts("No Answer");
else printf("%lld\n",t);
}
}