#include<cstdio> #include<vector> #include<set> using namespace std; const int inf = 1000000003; int n,m; vector< vector< pair<int,int> > > adj; vector<bool> vis; vector<int> waga; struct cmp { bool operator() (const int &a, const int &b) { if (waga[a] < waga[b]) return true; if (waga[a] > waga[b]) return false; return a<b; } }; set<int, cmp> kopiec; void prim_dijkstra(int s) { int i,v,u,c; waga.clear(); waga.resize(n, inf); vis.clear(); vis.resize(n,false); waga[s] = 0; kopiec.clear(); for (i=0; i<n; i++) kopiec.insert(i); while( !kopiec.empty() ) { u = *(kopiec.begin()); kopiec.erase(kopiec.begin()); vis[u]=true; for (i=0; i<adj[u].size(); i++) { v = adj[u][i].first; if (!vis[v]) { c = adj[u][i].second; if (c < waga[v]) { kopiec.erase(kopiec.find(v)); waga[v] = c; kopiec.insert(v); } } } } } int main(void) { int c,i,j; scanf("%d", &n); m = (n*(n+1))/2; n++; adj.resize(n); for (i=0; i<n; i++) for(j=i+1; j<n; j++) { scanf("%d",&c); adj[i].push_back(make_pair(j,c)); adj[j].push_back(make_pair(i,c)); } prim_dijkstra(0); long long int suma = 0; for (i=1; i<n; i++) suma += waga[i]; printf("%lld\n", suma); return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | #include<cstdio> #include<vector> #include<set> using namespace std; const int inf = 1000000003; int n,m; vector< vector< pair<int,int> > > adj; vector<bool> vis; vector<int> waga; struct cmp { bool operator() (const int &a, const int &b) { if (waga[a] < waga[b]) return true; if (waga[a] > waga[b]) return false; return a<b; } }; set<int, cmp> kopiec; void prim_dijkstra(int s) { int i,v,u,c; waga.clear(); waga.resize(n, inf); vis.clear(); vis.resize(n,false); waga[s] = 0; kopiec.clear(); for (i=0; i<n; i++) kopiec.insert(i); while( !kopiec.empty() ) { u = *(kopiec.begin()); kopiec.erase(kopiec.begin()); vis[u]=true; for (i=0; i<adj[u].size(); i++) { v = adj[u][i].first; if (!vis[v]) { c = adj[u][i].second; if (c < waga[v]) { kopiec.erase(kopiec.find(v)); waga[v] = c; kopiec.insert(v); } } } } } int main(void) { int c,i,j; scanf("%d", &n); m = (n*(n+1))/2; n++; adj.resize(n); for (i=0; i<n; i++) for(j=i+1; j<n; j++) { scanf("%d",&c); adj[i].push_back(make_pair(j,c)); adj[j].push_back(make_pair(i,c)); } prim_dijkstra(0); long long int suma = 0; for (i=1; i<n; i++) suma += waga[i]; printf("%lld\n", suma); return 0; } |