题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6776
题意:有n个小朋友,已知每个小朋友离小沃沃的距离为a[i],求每个小朋友之间最短距离之和。
思路:当每个小朋友在同一直线上最短,排个序。
#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <queue> #include <cstring> #include <cmath> #include <stack> #include <map> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <unordered_map> typedef long long ll; using namespace std; ll a[100005]; int main() { ios::sync_with_stdio(0); cin.tie(0);cout.tie(0); int t; cin >> t; while(t--) { memset(a, 0, sizeof(a)); int n; cin >> n; for(int i = 1; i <= n; i++) { cin >> a[i]; } sort(a + 1, a + 1 + n); ll ans = 0,s = 0; for(int i = 2; i <= n; i++) { s += 1ll*(i - 1)*(a[i]-a[i - 1]); ans += s; } cout << ans << endl; } return 0; }