一道比较裸的 Dijkstra。
不过好像还是在某些。。细节上卡了。。。很久
我对 Dijkstra 的理解:维护一个优先队列,优先让当前路径估计值最短的结点出队,并对其邻接点进行松弛。
可以保证出队结点的路径估计即为源点到该点的最短路,因为如果还存在更优的解,则表示还存在路径估计更小的点,出现矛盾。
#include <cstdio>
#include <cstring>
#include <queue>
#include <utility>
using namespace std;
typedef long long LL;
const int maxv = 61000, maxe = 121000;
const LL inf = 10000000000ll;
int head[maxv], next[maxe];
int fr[maxe], to[maxe];
LL wt[maxe], dis[maxv], vt[maxv];
int v, e;
void read()
{
scanf("%d%d", &v, &e);
memset(head, -1, sizeof(head));
for(int i = 0; i < v; i++) scanf("%I64d", &vt[i]);
for(int i = 0; i < e * 2; ) {
scanf("%d%d%I64d", &fr[i], &to[i], &wt[i]);
fr[i]--; to[i]--;
bool ex = false;
for(int j = head[fr[i]]; j != -1; j = next[j]) {
if(to[j] == to[i]) {
ex = true;
if(wt[j] > wt[i])
wt[j] = wt[j^1] = wt[i];
break;
}
}
if(ex) {
i += 2;
continue;
}
fr[i^1] = to[i];
to[i^1] = fr[i];
wt[i^1] = wt[i];
for(int j = 0; j < 2; j++, i++) {
next[i] = head[fr[i]];
head[fr[i]] = i;
}
}
}
typedef pair<LL, int> pii;
priority_queue<pii, vector<pii>, greater<pii> > que;
bool done[maxv];
bool dijkstra()
{
memset(done, false, sizeof(bool)*(v+1));
dis[0] = 0;
for(int i = 1; i < v; i++) dis[i] = inf;
que.push(make_pair(dis[0], 0));
while(!que.empty()) {
pii cp = que.top(); que.pop();
int cur = cp.second;
if(done[cur]) continue;
done[cur] = true;
for(int i = head[cur]; i != -1; i = next[i]) {
int tar = to[i];
if(dis[tar] > dis[cur] + wt[i]) {
dis[tar] = dis[cur] + wt[i];
que.push(make_pair(dis[tar], tar));
}
}
}
for(int i = 0; i < v; i++)
if(!done[i]) return false;
return true;
}
int main()
{
int t;
scanf("%d", &t);
while(t--) {
read();
if(dijkstra()) {
LL ans = 0;
for(int i = 1; i < v; i++)
ans += dis[i]*vt[i];
printf("%I64d\n", ans);
}
else puts("No Answer");
}
return 0;
}