输入样例:
在这里给出一组输入。例如:
4 6
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
输出样例:
在这里给出相应的输出。例如:
1,2,1
1,4,1
2,3,3
思路:
题目过目一遍,基本可以确认就是最小生成树的题目了,最小生成树那不是模板题吗?所以题目不难,结合并查集就可以做出这道题目了。
唯一需要注意的是,题目为了输出的唯一性,要求依次优先考虑修建路程最短、道路1编号最小、道路2编号最小,因此只需要在原本的按照边排序中加入两个新要求就可以满足题意了。
参考代码:
#include<bits/stdc++.h>
using namespace std;
const int MAXSIZE = 21;
int uf[MAXSIZE];
void initUionFind() {
for(int i=0;i<MAXSIZE;++i) {
uf[i] = i;
}
}
int find(int son) {
return uf[son]==son?son:find(uf[son]);
}
void unionTow(int son1, int son2) {
uf[find(son1)] = find(son2);
}
bool isConnect(int son1, int son2) {
return find(son1) == find(son2);
}
struct Edge{
int from, to, weight;
};
vector<Edge> edges;
// 题意的排序要求
bool cmp(const Edge e1, const Edge e2) {
if(e1.weight != e2.weight)
return e1.weight < e2.weight;
if(e1.from != e2.from)
return e1.from < e2.from;
return e1.to < e2.to;
}
int main() {
int n, m;
cin>>n>>m;
initUionFind();
while(m--) {
int from, to, weight;
cin>>from>>to>>weight;
if(from > to) swap(from, to);
edges.push_back({from, to, weight});
}
sort(edges.begin(), edges.end(), cmp);
for(auto edge:edges) {
if(!isConnect(edge.from, edge.to)) {
unionTow(edge.from, edge.to);
cout<<edge.from<<","<<edge.to<<","<<edge.weight<<endl;
}
}
return 0;
}