POJ 1258 agri-net (prim algorithm)

Source: Internet
Author: User

Test instructions: N Farms, it takes the shortest distance to connect all the farms together.

Idea: Prim algorithm

Textbook Code:

Prim algorithm #include<iostream> #include <stdio.h> #include <cstring>using namespace std;int n;int tot; int V[150][150];int dist[150];//The minimum distance from the memory node to the tree bool use[150];//tag node whether there is an int main () {while (scanf ("%d", &n)!=eof) {memset (use,false,sizeof (use));//initialization node exists Tot=0;use[0]=1;int i,j,k;for (i=0;i<n;i++) for (j=0;j<n;j++) scanf ("%d", &V[I][J]);d ist[0]=0x7fffffff;//assigned to maximum for (i=1;i<n;i++)//initial distance dist[i]=v[0][i];for (i=1;i<n;i++) {//connection remaining n-1 node int tmp=0;for (k=1;k<n;k++)//Find the shortest distance node if (dist[k]<dist[tmp] &&!use[k]) Tmp=k;tot +=dist[tmp];// Add to total distance use[tmp]=true;for (k=1;k<n;k++)//adjust distance if (!use[k]) dist[k]=v[k][tmp]<dist[k]?v[k][tmp]:d ist[k];} printf ("%d\n", tot);} return 0;}

In addition, the problem can also be used Kruskal algorithm, the code is as follows:

Kruskal algorithm #include<iostream>using namespace std;int fa[120];int get_father (int x) {return fa[x]=fa[x]==x?x:get _father (fa[x]);//Determine whether two nodes belong to a subtree (and check set)}int main () {int n;int p[120][120];int mark[100100];while (scanf ("%d", &n)! = EOF) {memset (mark,0,sizeof (Mark)), int i,j,k,m;for (i=0;i<n;i++) for (j=0;j<n;j++) {scanf ("%d", &p[i][j]); Mark[p[i][j]]=1;} for (i=0;i<n;i++) Fa[i]=i;int ans=0;for (k=1;k<=100000;k++)//Kruskal algorithm if (Mark[k]) {//  If no mark is added, timeout for (i=0; i<n;i++) for (int j=0;j<n;j++) if (p[i][j]==k &&get_father (i)!=get_father (j)) {fa[fa[i]]=fa[j];// Merge two subtrees (and look up the set) Ans+=k;}} printf ("%d\n", ans);} return 0;}



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.