小记:题目都没看清,直接看样例做的,然后输入n以为就有n行,然后样例都没过,改成输入n-1行,直接prim带过
思路:注意路上无向路,处理的时候我直接是读字符串,然后去第一个字符,这样方便多了
算法就是prim
代码:
#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <map> #include <set> #include <vector> #include <stack> #include <queue> #include <algorithm> #include <string> using namespace std; #define mst(a,b) memset(a,b,sizeof(a)) #define REP(a,b,c) for(int a = b; a < c; ++a) #define eps 10e-8 const int MAX_ = 155; const int N = 100010; const int INF = 0x7fffffff; int n; struct node{ int s, t; }; int g[MAX_][MAX_]; int d[MAX_]; bool vis[MAX_]; int m, cnt; int prim(int start) { REP(i, 0, n){ d[i] = INF; vis[i] = 0; } int sum = 0; d[start] = 0; REP(i, 0, n){ int mmin = INF, k; REP(j, 0, n){ if(!vis[j] && d[j] < mmin){ mmin = d[j]; k = j; } } if(mmin == INF)break; vis[k] = 1; sum += mmin; REP(j, 0, n){ if(!vis[j] && g[k][j] != -1 && d[j] > g[k][j]){ d[j] = g[k][j]; } } } return sum; } int main(){ int T, ss, tt; char str[10]; while(~scanf("%d", &n), n){ mst(g, -1); REP(i, 0, n-1){ scanf("%s", str); ss = str[0] - 'A'; scanf("%d", &m); REP(j, 0, m){ scanf("%s%d",str,&tt); g[ss][str[0]-'A'] = g[str[0] - 'A'][ss] = tt; } } /* REP(i, 0, n)REP(j, 0, n){ printf("%d ", g[i][j]); if(j == n-1)printf("\n"); }*/ int ans = prim(0); printf("%d\n", ans); } return 0; }