“浪潮杯”第九届山东省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代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e5+5; 4 int a[maxn]; 5 int main() 6 { 7 int t,n;long long sum;//这里要用long long,以防数据溢出 8 cin>>t; 9 while(t--){ 10 cin>>n;sum=0; 11 for(int i=0;i<n;++i) 12 cin>>a[i]; 13 sort(a,a+n); 14 for(int i=1;i<n;++i) 15 sum+=a[i]; 16 if(sum>0)cout<<(sum+a[0]*(n-1))<<endl; 17 else cout<<'0'<<endl;//表示只有一个城市 18 } 19 return 0; 20 }