#include <stdio.h> #include <set> #include <vector> int tab[2002][2002]; const int INF = 2000000000; int wagi[2002]; struct Cmp { bool operator()(int a, int b) const { return wagi[a] < wagi[b] || wagi[a] == wagi[b] && a < b; } }; int main() { int N, val; scanf("%d\n", &N); for(int i = 0 ; i < N ; ++i) { for(int j = i + 1 ; j <= N ; ++j) { scanf("%d", &tab[i][j]); tab[j][i] = tab[i][j]; } } for(int i = 0 ; i <= N ; ++i) { tab[i][i] = INF; wagi[i] = INF; } long long int result = 0; std::vector<bool> odwiedzone(N+1); odwiedzone[0] = true; std::multiset<int, Cmp> S; wagi[0] = 0; S.insert(0); while(!S.empty()) { int s = *S.begin(); S.erase(*S.begin()); odwiedzone[s] = true; result += wagi[s]; for(int i = 0 ; i <= N ; ++i) { if(!odwiedzone[i]) { if(wagi[i] > tab[s][i]) { S.erase(i); wagi[i] = tab[s][i]; S.insert(i); } } } } printf("%lld\n", result); 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 | #include <stdio.h> #include <set> #include <vector> int tab[2002][2002]; const int INF = 2000000000; int wagi[2002]; struct Cmp { bool operator()(int a, int b) const { return wagi[a] < wagi[b] || wagi[a] == wagi[b] && a < b; } }; int main() { int N, val; scanf("%d\n", &N); for(int i = 0 ; i < N ; ++i) { for(int j = i + 1 ; j <= N ; ++j) { scanf("%d", &tab[i][j]); tab[j][i] = tab[i][j]; } } for(int i = 0 ; i <= N ; ++i) { tab[i][i] = INF; wagi[i] = INF; } long long int result = 0; std::vector<bool> odwiedzone(N+1); odwiedzone[0] = true; std::multiset<int, Cmp> S; wagi[0] = 0; S.insert(0); while(!S.empty()) { int s = *S.begin(); S.erase(*S.begin()); odwiedzone[s] = true; result += wagi[s]; for(int i = 0 ; i <= N ; ++i) { if(!odwiedzone[i]) { if(wagi[i] > tab[s][i]) { S.erase(i); wagi[i] = tab[s][i]; S.insert(i); } } } } printf("%lld\n", result); return 0; } |