链接:https://ac.nowcoder.com/acm/contest/123/C
来源:牛客网
题目描述
There are cities in Byteland, and the city has a value . 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
representing the number of test cases.
For each test case, the first line is an integer , representing the number of cities, the
second line are positive integers ,
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
思维题:
题意:将每座城市用公路连接起来,使得城市之间相连,求花费最少的方案(每条路的花费 = 连接两座城市的和)
思维:用心想想,很明显这是在构造一个n叉树,只要确定最小的根节点即可。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
const int maxn = 1e5+5;
const int INF = 1e9+7;
int a[maxn];
int main()
{
int n;
scanf("%d", &n);
int m = INF;
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
if(n == 1){
printf("0");
return 0;
}
sort(a, a+n);
int sum = 0;
for(int i = 1; i < n; i++) sum += a[i];
sum += a[0];
printf("%d\n", sum);
return 0;
}