USACO TRAINING GATEWAY SECTION 3.1 AGRI-NET

Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.

Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.

Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.

The distance between any two farms will not exceed 100,000.

PROGRAM NAME: agrinet

INPUT FORMAT

Line 1:
The number of farms, N (3 <= N <= 100).
Line 2..end:The subsequent lines contain the N x N connectivity matrix, where each element shows the distance from on farm to another. They are N lines of N space-separated integers.

SAMPLE INPUT (file agrinet.in)

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

OUTPUT FORMAT

The single output contains the integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.

SAMPLE OUTPUT (file agrinet.out)

28

Analysis:

This question is just a standard minimum spanning tree implementation exercise. I chose to use Prim’s algorithm which runs in O(n^2) time. But you could also use Kruskal’s algorithm instead.

Code:

/*
 ID: ~~~~~~~~
 LANG: C++
 TASK: agrinet
 */
 include 
 using namespace std;
 int minKey(int key[], bool mstSet[],int V){
     int min = INT_MAX, min_index;
     for (int v = 0; v < V; v++)
         if (mstSet[v] == false && key[v] < min)
             min = key[v], min_index = v;
     return min_index;
 }
 int printMST(int parent[], vector> graph,int V){
     int a=0;
     for (int i = 1; i < V; i++)
         a+=graph[i][parent[i]];
     return a;
 }
 int primMST(vector> graph,int V){
     int parent[V];
     int key[V];
     bool mstSet[V];
     for (int i = 0; i < V; i++)
         key[i] = INT_MAX, mstSet[i] = false;
     key[0] = 0;
     parent[0] = -1;
     for (int count = 0; count < V - 1; count++){
         int u = minKey(key, mstSet,V);
         mstSet[u] = true;
         for (int v = 0; v < V; v++)
             if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
                 parent[v] = u, key[v] = graph[u][v];
     }
     return printMST(parent, graph,V);
 }
 int main(){
     ifstream in;
     ofstream out;
     in.open("agrinet.in");
     out.open("agrinet.out");
     int V;
     in>>V;
     vector> graph;
     vector temp1;
     int temp2;
     for (int i=0;i>temp2;
             temp1.push_back(temp2);
         }
         graph.push_back(temp1);
         temp1.clear();
     }
     out<<primMST(graph,V)<<endl;
     return 0;
 }

Leave a comment