TOJ Open Ural FU Championship 2013 B
B. Electrification Plan
Time limit: 0.5 second
Memory limit: 64 MB
Memory limit: 64 MB
Some country has n cities. The government has decided to electrify all these cities. At first, power stations in k different cities were built. The other cities should be connected with the power stations via power lines. For any cities i, j it is possible to build a power line between them in cij roubles. The country is in crisis after a civil war, so the government decided to build only a few power lines. Of course from every city there must be a path along the lines to some city with a power station. Find the minimum possible cost to build all necessary power lines.
Input
The first line contains integers n and k (1 ≤ k ≤ n ≤ 100). The second line contains k different integers that are the numbers of the cities with power stations. The next n lines contain an n × n table of integers {cij} (0 ≤ cij ≤ 105). It is guaranteed that cij = cji , cij > 0 for i ≠ j; cii = 0.
Output
Output the minimum cost to electrify all the cities.
Sample
| input | output |
|---|---|
4 2 1 4 0 2 4 3 2 0 5 2 4 5 0 1 3 2 1 0 |
3 |
Problem Author: Mikhail Rubinchik
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 #include <algorithm> 5 using namespace std; 6 #define maxn 1001 7 #define ll long long 8 #define INF 0x7fffffff 9 //#define ll __int64 10 int a[maxn]; 11 int b[maxn][maxn]; 12 struct Edge{ 13 int from, to, cost; 14 }; 15 struct Node{ 16 int u, cost; 17 bool operator<(const Node& rhs)const{ 18 return cost>rhs.cost; 19 } 20 }; 21 priority_queue<Node> q; 22 vector<Edge>edges; 23 vector<int>G[maxn]; 24 int vis[maxn]; 25 int m, n; 26 int from, to, cost; 27 void AddEdge(int from, int to, int cost){ 28 edges.push_back((Edge){ from, to, cost }); 29 int m = edges.size(); 30 G[from].push_back(m - 1); 31 edges.push_back((Edge){ to, from, cost }); 32 G[to].push_back(m); 33 } 34 void init() 35 { 36 memset(vis, 0, sizeof vis); 37 for (int i = 0; i<n; i++)G[i].clear(); 38 edges.clear(); 39 while (!q.empty())q.pop(); 40 } 41 void Prim() 42 { 43 int cost = 0, t = 0; 44 Node x; 45 from=0; 46 x.u = from;//选择起点 47 x.cost = 0; 48 q.push(x); 49 while (!q.empty() && t<=n) 50 { 51 x = q.top(); q.pop(); 52 if (vis[x.u])continue; 53 vis[x.u] = 1; 54 cost += x.cost; 55 t++; 56 for (int i = 0; i<G[x.u].size(); i++){ 57 Edge e = edges[G[x.u][i]]; 58 if (!vis[e.to])q.push((Node){ e.to, e.cost }); 59 } 60 } 61 printf("%d\n", cost); 62 } 63 int main(){ 64 while (~scanf("%d%d", &n, &m)){ 65 memset(a, 0, sizeof a); 66 memset(b, 0, sizeof b); 67 init(); 68 for(int i=0;i<=n;i++) 69 for(int j=0;j<=n;j++)AddEdge(i,j,INF); 70 for (int i = 1; i <= m; i++){ 71 scanf("%d", &a[i]); 72 AddEdge(0, a[i], 0); 73 } 74 for (int i = 1; i <= n;i++) 75 for (int j = 1; j <= n; j++){ 76 scanf("%d", &b[i][j]); 77 AddEdge(i, j, b[i][j]); 78 } 79 Prim(); 80 } 81 return 0; 82 }
浙公网安备 33010602011771号