国王的烦恼

#include#include#includeusing namespace std;

//根据桥的存活周期从大到小构建最小生成树,相同天数视为一次抗议,调用去重函数unique,总的天数去掉重复的天数即为抱怨的总天数

struct Edge

{

int from, to, w;

bool operator < (const struct Edge &t) const

{

return w > t.w;

}

}edge[100000];

int father[10001], a[10001];

int find(int x)

{

int root, i;

for(i = x;father[i] != i;i = father[i]);

root = i;

int tmp;

for(i = x;father[i] != i;i = father[i])

{

tmp = father[i];

father[i] = root;

i = tmp;

}

return root;

}

int main()

{

int n, m;

scanf("%d%d",&n,&m);

for(int i = 0;i < m;i ++)

{

scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].w);

}

sort(edge,edge+m);//根据桥的存活周期从大到小排序

for(int i = 1;i <= n;i ++)

father[i] = i;

int cnt = 0, x, y;

for(int i = 0;i < m;i ++)

{

x = find(edge[i].from);

y = find(edge[i].to);

if(x != y)

{

father[x] = y;

a[cnt++] = edge[i].w;

}

}

int ans = unique(a,a+cnt) - a;

printf("%d\n",ans);

return 0;

}

你可能感兴趣的:(国王的烦恼)