1. 程式人生 > >浪潮杯第九屆山東acm程式設計賽C題 Cities

浪潮杯第九屆山東acm程式設計賽C題 Cities

題目描述

There are n cities in Byteland, and the i city has a value a . The cost of building a bidirectional road between two cities is the sum of their values. Please calculate the minimum cost of connecting these cities, which means any two cities can reach each other.

輸入描述:

The first line is an integer T(T<= 1e5) representing the number of test cases.

For each test case, the first line is an integer n(n <= 1e5), representing the number of cities, the second line are n positive integers a (a <= 1e5), representing their values.

輸出描述:

For each test case, output an integer, which is the minimum cost of connecting these cities.

示例1

輸入

2

4

1 2 3 4

1

1

輸出

12

0

/*題意: Byteland有n個城市,i城市有價值a。 在兩個城市之間建立雙向道路的成本是它們的價值的總和。 請計算連線這些城市的最低成本,這意味著任何兩個城市都可以相互聯絡*/

思路:

第一眼以為最小生成樹,看了點數10的5次方,需要求出每個邊的值,邊樹大約有10的9次方個,然後prim演算法進行尋找,資料量太大,定會超時。。。。。

由此想到貪心演算法:

想要將任意兩個城市連線且道路花費之和最小,那可使每條道路的花費最少,道路的花費等於兩端城市value之和,由此可知,只要每個城市與最小value的那個城市相連通,所得的花費必定是最小的。

因此,將最小value的城市放於中間與其他城市一一相連。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define p 100001
using namespace std;
int main(){
    int t;
    int a[p];
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%d",&a[i]);
        }
         if(n==1){
            printf("0\n");
            continue;
        }
        sort(a,a+n);
        int minn=a[0];
        long long sum=0;
        for(int i=1;i<n;i++){
            sum=sum+a[i]+minn;
        }
        printf("%lld\n",sum);
    }
}