Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 13935 | Accepted: 7365 |
Description
Your task is to design the network for the area, so that there is a connection (direct or indirect) between every two points (i.e., all the points are interconnected, but not necessarily by a direct cable), and that the total length of the used cable is minimal.
Input
The maximal number of points is 50. The maximal length of a given route is 100. The number of possible routes is unlimited. The nodes are identified with integers between 1 and P (inclusive). The routes between two points i and j may be given as i j or as j i.
Output
Sample Input
1 0 2 3 1 2 37 2 1 17 1 2 68 3 7 1 2 19 2 3 11 3 1 7 1 3 5 2 3 89 3 1 91 1 2 32 5 7 1 2 5 2 3 7 2 4 8 4 5 11 3 5 10 1 5 6 4 2 12 0
Sample Output
0 17 16 26
Code
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 55
#define INF 0x3f3f3f3f
using namespace std;
int map[N][N];
int vis[N];
int dis[N];
int ans,n;
void prim()
{
int i,j,min,pos;
for(i=1;i<=n;i++)
{
dis[i] = map[1][i];
vis[i] = 0;
}
vis[1] = 1;
for(i=1;i<=n-1;i++)
{
min = INF;
for(j=1;j<=n;j++)
{
if(!vis[j] && dis[j] < min)
{
min = dis[j];
pos = j;
}
}
ans += min;
vis[pos] = 1;
for(j=1;j<=n;j++)
{
if(!vis[j] && dis[j] > map[pos][j])
{
dis[j] = map[pos][j];
}
}
}
}
int main()
{
int m,i,j,u,v,w;
while(~scanf("%d %d",&n,&m) && n)
{
ans = 0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i == j)
map[i][j] = 0;
else
map[i][j] = INF;
}
}
for(i=1;i<=m;i++)
{
scanf("%d %d %d",&u,&v,&w);
map[u][v] = map[v][u] = min(w,map[u][v]);
}
prim();
printf("%d\n",ans);
}
return 0;
}
反思:
題目大意:多組輸入,給出n個點和m條邊和邊的權值,求最小權值和,當n爲0時停止。最小生成樹模板題,直接套用prim即可,要注意的是同一組點之間可能有不同邊權值,要保存最小的那條。