“浪潮杯”第九届山东省ACM大学生程序设计竞赛重现赛 C-Cities

时间:2023-03-09 07:08:31
“浪潮杯”第九届山东省ACM大学生程序设计竞赛重现赛 C-Cities

题目描述:There are n cities in Byteland, and the ith city has a value ai. 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.

输入描述:第一行是一个表示测试用例数量的整数  t(t<=105)。对于每个测试用例,第一行是一个整数n(n<=105),代表城市的数量,第二行是n个 正整数ai(ai<=105) ,代表它们的值。

输出描述

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-1个城市直接相连,这就是修道路所花费最低成本的方法。
AC代码:
 #include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+;
int a[maxn];
int main()
{
int t,n;long long sum;//这里要用long long,以防数据溢出
cin>>t;
while(t--){
cin>>n;sum=;
for(int i=;i<n;++i)
cin>>a[i];
sort(a,a+n);
for(int i=;i<n;++i)
sum+=a[i];
if(sum>)cout<<(sum+a[]*(n-))<<endl;
else cout<<''<<endl;//表示只有一个城市
}
return ;
}