題目描述
時間限制:C/C++ 1秒,其他語言2秒
空間限制:C/C++ 65536K,其他語言131072K
64bit IO Format: %lld
題目描述:
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
題目分析
我做這道題目是在比賽後做的,因爲比賽的時候時間上安排不過來,所以報名了比賽但是水了 @@
看了下牛客上邊的榜單,顯然這道題目就是簽到題嘛,阿西吧
認真讀了下題目,發現題目描述還蠻簡單的,我這英語渣都能直接讀懂,_
一開始感覺這道題目就是一道圖論,求最小生成樹。
二話不說就開始打開Code:Blocks,阿西吧
看着軟件打開,我心裏構思了下這道題目的解法,我的天,這什麼玩意兒的最小生成樹,根本就沒有好吧,
想了下,就一個簡單的配對求和,求最值
真正的思路:_
要想花費最小,其實就是每條邊都要最小,我們從定義出發,邊的大小取決於點的value,那麼,value越小就意味着邊最小,對於當前點來說,本身value一定,那麼找圖中value最小的點進行配對,則花費最小。
坑點在於當點只有一個的時候,花費爲0(樣例已經給出了這種情況,簽到嘛)
AC代碼
#include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
long long res = 0;
int minVal = 99999999; //此處設置爲大於a的上限即可
for(int i=0;i<n;i++){
int temp;
cin>>temp;
if(temp < minVal){
minVal = temp;
}
res += temp;
}
if(n == 1){
cout<<0<<endl;
} else{
cout<<res + (n-2)*minVal<<endl;
}
}
return 0;
}
注:
如有錯誤,歡迎dalao指正 _