【luogu P3366 最小生成树】 题解 Prim

include

include

include

include

using namespace std;
const int maxn = 505000;
int n, m, dis[maxn], vis[maxn], ans;
struct edge{
int from, to, next, len;
}e[maxn<<2];
int head[maxn], cnt;
void add(int u, int v, int w)
{
e[++cnt].from = u;
e[cnt].len = w;
e[cnt].next = head[u];
e[cnt].to = v;
head[u] = cnt;
}
void Prim()
{
//for(int i = 1; i <= n; i++) dis[i] = 9999;
memset(dis, 127, sizeof(dis));
dis[1] = 0;
for(int i = 1; i <= n; i++)
{
int k = -1, minn = 0x7fffffff;
for(int j = 1; j <= n; j++)
if(dis[j] < minn && !vis[j])
{
k = j;
minn = dis[j];
}
if(k == -1)
{
ans = -1; break;
}
vis[k] = 1; ans += dis[k];
for(int j = head[k]; j != -1; j = e[j].next)
{
int v = e[j].to;
if(!vis[v] && dis[v] > e[j].len)
dis[v] = e[j].len;
}
}
}
int main()
{
memset(head, -1, sizeof(head));
scanf("%d%d",&n, &m);
for(int i = 1; i <= m; i++)
{
int u, v, w;
scanf("%d%d%d",&u, &v, &w);
add(u, v, w), add(v, u, w);
}
Prim();
if(ans == -1)
{
printf("orz\n");
return 0;
}
else
{
printf("%d\n",ans);
return 0;
}
}

posted @ 2018-09-07 21:08  Misaka_Azusa  阅读(108)  评论(0编辑  收藏  举报
Live2D