prim算法,为什么我另一道题就错了呢。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <map>
using namespace std;
const int INF = 0x3f3f3f;
const int MAX = 1e3 + 5;
int flag[MAX], min_cost[MAX];
struct EDGE
{
int to, cost;
EDGE(int a, int b)
: to(a), cost(b) {}
};
vector<EDGE> g[MAX];
typedef pair<int, int> P;
int main()
{
int n, m;
scanf("%d%d", &n, &m);
int from, to, cost;
for (int i = 1; i <= m; ++i)
{
scanf("%d%d%d", &from, &to, &cost);
g[from].push_back(EDGE(to, cost));
g[to].push_back(EDGE(from, cost));
}
int res = 0;
priority_queue<P, vector<P>, greater<P> > store;
memset(min_cost, INF, sizeof(min_cost));
store.push(P(0, 1));
min_cost[1] = 0;
flag[1] = 0;
while (!store.empty())
{
P tmp = store.top();
store.pop();
if (flag[tmp.second])
continue;
res += tmp.first;
flag[tmp.second] = 1;
int lenth = g[tmp.second].size();
for (int i = 0; i < lenth; ++i)
{
EDGE t = g[tmp.second][i];
if(min_cost[t.to] > t.cost)
{
min_cost[t.to] = t.cost;
store.push(P(t.cost, t.to));
}
}
}
printf("%d\n", res);
}