題意:就是給出你圖,然後求最小生成樹的值即可。注意輸入。
思路:完全裸的最小生成樹,kruskal水之。好久不寫最小生成樹,仔細想了想,還是寫了出來。
代碼:
- #include
- #include
- #include
- #include
- #include
- using namespace std;
-
- #define CLR(arr,val) memset(arr,val,sizeof(arr))
- const int N = 32;
- vector vv[N];
- int numedge,father[N];
- struct edge{
- int leftp,rightp,value;
- }ee[1000];
- bool cmp(edge a,edge b){
- return a.value < b.value;
- }
- int find(int x){
- if(x == father[x])
- return father[x];
- return find(father[x]);
- }
- bool union_set(int lp,int rp){
- int flp = find(lp);
- int frp = find(rp);
- if(flp == frp){
- return false;
- }
- else{
- father[flp] = frp;
- return true;
- }
- }
- int kruskal(){
- int sum = 0;
- for(int i = 0; i < numedge; ++i){
- int lp = ee[i].leftp;
- int rp = ee[i].rightp;
- if(union_set(lp,rp))
- sum += ee[i].value;
- }
- return sum;
- }
- int main(){
- //freopen(1.txt,r,stdin);
- int n;
- while(scanf(%d,&n)&&n){
- char ch;
- int num,x;
- numedge = 0;
- for(int i = 1; i < n; ++i){
- cin >> ch;
- scanf(%d,&num);
- while(num--){
- cin >> ch;
- scanf(%d,&x);
- int y = (int)(ch - 'A' + 1);
- ee[numedge].leftp = i;
- ee[numedge].rightp = y;
- ee[numedge].value = x;
- numedge++;
- }
- }
- sort(ee,ee+numedge,cmp);
- for(int i = 1; i < N; ++i)
- father[i] = i;
- int ans = kruskal();
- printf(%d ,ans);
- }
- return 0;
- }