HDU 1102 Constructing Roads (prime algorithm)

Source: Internet
Author: User

Link: Click to open link

The subject of another algorithm (prime algorithm) algorithm is to use a two-dimensional array map of its subscript, respectively, the two villages connected to the label, the content is the length of the road, that is, the weight value. Using a mark Array to mark a connected village, a one-dimensional array lowcost is stored as the weight of the end of the following, some of which are connected no longer need to be constructed, and the value of the corresponding map array is labeled 0 (one path corresponds to two map). For details, see the code:

#include <stdio.h> #include <string.h> #define INF 0xffffffint map[110][110];int mark[110],lowcost[110]; void prime (int n) {int sum=0;memset (mark,0,sizeof (Mark)); for (int i=1;i<=n;i++) lowcost[i]=map[1][i];mark[1]=1; lowcost[1]=0;for (int i=1;i<n;i++)//There are n villages, it is necessary to find n-1 times {int vir,min=inf;for (int j=1;j<=n;j++)//Traverse all points to find the point with the least weight, Record its subscript {if (!mark[j]&&lowcost[j]<min) {min=lowcost[j];vir=j;}} The mark[vir]=1;//will sum+=lowcost[vir];//the weighted value for this minimum spanning tree for (int k=1;k<=n;k++) with the found tag,//Update the non-fetching point to the weighted if (!mark[k]&& LOWCOST[K]>MAP[VIR][K]) lowcost[k]=map[vir][k];} printf ("%d\n", sum);} int main () {int n,m;while (scanf ("%d", &n)!=eof) {memset (map,inf,sizeof (map));//initialize diagram to infinity for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) scanf ("%d", &map[i][j]);//input Graph scanf ("%d", &m), int x,y;while (m--) {scanf ("%d%d",& X,&y) map[x][y]=map[y][x]=0;//to mark the repaired road weight as 0}prime (n);} return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

HDU 1102 Constructing Roads (prime algorithm)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.