Data Structure - Week 15


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. 
Input
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N connectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28
 
#include <iostream>
using namespace std;

const int SIZE=101;
const int MAX=100000;

int minLen;
int m[SIZE][SIZE];  //  
bool s[SIZE];   //  
int low[SIZE];   // s 


int main(){
    int n, last;

    cin>>n;
    for(int i=1;i<=n;i++){
        low[i]=MAX; //  low[i]
        for(int j=1;j<=n;j++){
            cin>>m[i][j];
        }
    }

    s[1]=true;  //  
    last=1;
    for(int i=2;i<=n;i++){
        int x, tmp=MAX;
        for(int i=1;i<=n;i++){  //  low[i]
            if((!s[i]) && low[i]>m[last][i])
                low[i]=m[last][i];
        }
        for(int i=1;i<=n;i++){  //  
            if((!s[i]) && tmp>low[i]){
                x=i;
                tmp=low[i];
            }
        }
        minLen+=tmp;
        s[x]=true;
        last=x;
    }

    cout<<minLen<<endl;
    return 0;
}

시간 복잡도 분석
수행 시간이 상수인 단계는 "..."로 간략히 기록됩니다.
…
for(int i=1;i<=n;i++){                       //n
       …
       for(int j=1;j<=n;j++){                //n
              …
       }
}
for(int i=2;i<=n;i++){                       //n-1
       for(int i=1;i<=n;i++){                //n
              …
       }
       for(int i=1;i<=n;i++){                //n
              …
       }
}
…

그러므로 시간의 복잡도는 n^2+(n-1)x2n=O(n^2)이다.(이곳에서 사용한 것은 소박한 Prim 알고리즘으로 데이터 구조를 개선할 수 있다. 예를 들어 무더기 최적화를 사용하여 시간의 복잡도를 낮출 수 있다.)
점수: 85 (니마타 피드백은 없고 내가 보고서 양식에 잘못된 점수를 제출했을 수도 있지)

좋은 웹페이지 즐겨찾기