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);
}
}