而如果让第 i + 1 个人排在第 i 个人前面,这两人的等待时间为 ti+1,显然优于交换前的等待时间,优化了 ti−ti+1 的时间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<algorithm> #include<iostream> usingnamespace std; constint N = 1e5 + 10; int t[N]; intmain(){ int n; cin >> n; for (int i = 0; i < n; i++) { cin >> t[i]; } sort(t, t + n); longlong res = 0; for (int i = 0; i < n; i++) res += t[i] * (n - i - 1); cout << res << endl; return0; }
intmain(){ cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); int res = 0; for (int i = 0; i < n; i++) { res += abs(a[i] - a[n / 2]); } cout << res << endl; return0; }
intmain(){ cin >> n; for (int i = 0; i < n; i++) { int w, s; cin >> w >> s; cow[i] = {w + s, w}; } sort(cow, cow + n); int res = -2e9, sum = 0; for (int i = 0; i < n; i++) { int w = cow[i].second, s = cow[i].first - w; res = max(res, sum - s); sum += w; } cout << res << endl; return0; }