题意:n件物品,获得第i件物品有两种方式,可以花费ci来购买,也可以用两件其它的物品来换取,输出获得第一件物品最少需要多少花费?
思路:开始我考虑不周到,认为物品之间的换取关系是一个二叉树了,实际上是构成了一张图,图是这样构成的,假设a能用b和c物品来换取,那么mp[b][a] = cost[c] mp[c][a] = cost[b],对所有结点进行spfa
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
typedef long long ll;
using namespace std;
ll dis[10005];
bool vis[10005];
int n,m;
struct node{
//到达to这个结点需要此节点和w结点
//这里存的是w结点,而不是w结点需要的花费
//因为花费是随着松弛而更新的
int to;
int w;
node(){}
node(int to,int w){
this -> to = to;
this -> w = w;
}
};
vector<node> v[10005];
ll Spfa(){
queue<int> q;
//把所有的点都加入队列中
for(int i = 1; i <= n; i++){
q.push(i);
vis[i] = true;
}
while(!q.empty()){
int u = q.front();
q.pop();
vis[u] = false;
for(int i = 0; i < v[u].size(); i++){
int to = v[u][i].to,w = v[u][i].w;
//对to这个结点进行松弛
if(dis[to] > dis[u] + dis[w]){
dis[to] = dis[u] + dis[w];
if(!vis[to]){
q.push(to);
vis[to] = true;
}
}
}
}
return dis[1];
}
int main(void){
freopen("dwarf.in","r",stdin);
freopen("dwarf.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++){
cin >> dis[i];
}
int a,b,c;
for(int i = 1; i <= m; i++){
scanf("%d%d%d",&a,&b,&c);
//建图
v[b].push_back(node(a,c));
v[c].push_back(node(a,b));
}
cout << Spfa() << endl;
return 0;
}