题目比较简单,可以不使用heap优化,这里作为练习
- #include <iostream>
- #include <algorithm>
- using namespace std;
- const int N = 600, INF = 1000000000;
- int dist[N], g[N][N], map[N], heap[3*N], del[N];
- int n, size;
- void heap_up(int root)
- {
- int t = heap[root], fa = root>>1;
- while(root > 1 && dist[t] < dist[heap[fa]])
- {
- heap[root] = heap[fa];
- map[heap[root]] = root;
- root = fa;
- fa >>= 1;
- }
- heap[root] = t;
- map[heap[root]] = root;
- }
- void heap_down(int root)
- {
- int t = heap[root], ch = root<<1;
- while(ch <= size)
- {
- if(ch+1 <= size && dist[heap[ch+1]] < dist[heap[ch]]) ch++;
- if(dist[heap[ch]] < dist[t])
- {
- heap[root] = heap[ch];
- map[heap[root]] = root;
- root = ch;
- ch <<= 1;
- }
- else break;
- }
- heap[root] = t;
- map[heap[root]] = root;
- }
- int heap_pop()
- {
- int t = heap[1];
- heap[1] = heap[size--];
- map[heap[1]] = 1;
- heap_down(1);
- return t;
- }
- int prime()
- {
- int i, j, k, t, u;
- for(i = 1; i <= n; i++)
- {
- dist[i] = INF;
- heap[i] = i;
- map[i] = i;
- del[i] = 0;
- }
- size = n;
- dist[1] = 0;
- for(i = 1; i <= n; i++)
- {
- u = heap_pop();
- del[u] = 1;
- for(j = 1; j <= n; j++)
- {
- if(!del[j] && g[u][j] < dist[j])
- {
- dist[j] = g[u][j];
- heap_up(map[j]);
- }
- }
- }
- for(i = 1, t = 0; i <= n; i++) t >?= dist[i];
- return t;
- }
- /*
- 2
- 4
- 0 10 5 200
- 10 0 200 10
- 5 200 0 20
- 200 10 20 0
- ans=10
- */
- int main()
- {
- int i, j, k, t;
- scanf("%d", &t);
- while(t--)
- {
- scanf("%d", &n);
- for(i = 1; i <= n; i++)
- {
- for(j = 1; j <= n; j++)
- {
- scanf("%d", &g[i][j]);
- }
- g[i][i] = INF;
- }
- printf("%d/n", prime());
- }
- return 0;
- }