标签:str iostream cti using ++ ble tar nod problem
题目链接:https://vjudge.net/problem/POJ-2421
思路:一些村庄,建一些路,使得所有村庄能相连,而且使得所有路长度之和最短。
题目说了,有些村庄之间已经建了路,说明有些路我们不需要建,那么在预处理的时候
把那些已经建过边的两个村庄的距离赋值为0,那么在跑最小生成树板子的时候就完成了
一些路已经建立的情况。
1 #include <stdio.h> 2 #include <iostream> 3 #include <queue> 4 using namespace std; 5 6 const int inf = (int)1e9; 7 const int N = 110; 8 int g[N][N]; 9 int dis[N]; 10 bool vis[N]; 11 int n; 12 13 struct node{ 14 int loc; 15 int v; 16 17 bool friend operator<(const node& a,const node& b){ 18 return a.v > b.v; 19 } 20 }; 21 22 priority_queue<node > que; 23 24 int prime(){ 25 26 que.push(node{1,0}); 27 dis[1] = 0; 28 29 while(!que.empty()){ 30 int u = que.top().loc; 31 que.pop(); 32 33 vis[u] = true; 34 35 for(int v = 1; v <= n; v++){ 36 if(!vis[v] && dis[v] > g[u][v]){ 37 dis[v] = g[u][v]; 38 que.push(node{v,dis[v]}); 39 } 40 } 41 } 42 43 int ans = 0; 44 for(int i = 1; i <= n; i++){ 45 46 // printf("%d ",dis[i]); 47 ans += dis[i]; 48 } 49 50 // printf("\n"); 51 52 return ans; 53 } 54 55 int main(){ 56 57 scanf("%d",&n); 58 59 for(int i = 1; i <= n; i++) 60 for(int j = 1; j <= n; j++) 61 scanf("%d",&g[i][j]); 62 63 for(int i = 1; i <= n; i++) 64 dis[i] = inf; 65 66 int m; 67 scanf("%d",&m); 68 69 int u,v; 70 for(int i = 1; i <= m; i++){ 71 scanf("%d%d",&u,&v); 72 g[u][v] = g[v][u] = 0;//已经有路的村庄 73 } 74 75 printf("%d\n",prime()); 76 77 return 0; 78 }
标签:str iostream cti using ++ ble tar nod problem
原文地址:https://www.cnblogs.com/SSummerZzz/p/11822892.html