【离散数学】最小生成树失败普罗米
生活随笔
收集整理的這篇文章主要介紹了
【离散数学】最小生成树失败普罗米
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include<iostream>
#include<vector>
using namespace std;void showtree(int tree[], int n)
{cout << "最小生成樹為:{";for (int i = 0; i < n; i += 2){cout << "(" << tree[i] << "," << tree[i + 1] << ")";}cout << "}";
}typedef struct Edge
{int v1, v2;int weight;
}Edge;//結構體定義邊int main()
{int n, m, sum = 0, sum_e = 0;cout << "請輸入頂點數、邊數,用一個空格間隔:" << endl;cin >> n >> m;Edge* t = new Edge[m + 1];vector<int>node(n + 5);//判斷該點是否已經在樹中int tree[100] = { 0 };//記錄頂點for (int i = 1; i <= n; i++){node[i] = 1;}int cnt = 0;cout << "請按照權重升序,分別輸入頂點序號、權重,用一個空格間隔:" << endl;for (int i = 0; i < m; i++){cout << "請輸入第" << i + 1 << "組數據:" << endl;cin >> t[i].v1 >> t[i].v2 >> t[i].weight;if (node[t[i].v1] || node[t[i].v2])//判斷定點是否已經在樹中{node[t[i].v1] = 0;node[t[i].v2] = 0;sum += t[i].weight;tree[cnt] = t[i].v1;cnt++;tree[cnt] = t[i].v2;cnt++;sum_e++;cout << "連接第" << sum_e << "條邊:" << endl;cout << t[i].v1 << ' ' << t[i].v2 << endl;}else{cout << "該邊不符合連接規則。" << endl;}if (sum_e == n - 1)break;}showtree(tree, sum_e * 2);cout << "最小生成樹的權之和為:";cout << sum;return 0;
}/*
8 13
1 4 1
2 4 1
5 7 1
1 6 2
2 3 2
2 5 2
4 7 2
6 7 2
7 8 2
1 2 3
2 7 3
3 8 3
3 5 4
*/
/*
5 7
1 5 1
1 4 1
2 4 1
1 3 2
2 5 2
2 3 3
3 5 7
*/
總結
以上是生活随笔為你收集整理的【离散数学】最小生成树失败普罗米的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 好句
- 下一篇: 【我的Android进阶之旅】解决使用D