fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5.  
  6. const ll INF = (ll)(1e18);
  7.  
  8. struct Event {
  9. int typ; // 1 - otwarcie, -1 - zamkniecie
  10. int poz;
  11. };
  12.  
  13. bool comp(Event a, Event b) {
  14. if (a.poz != b.poz) return a.poz < b.poz;
  15.  
  16. return a.poz > b.poz;
  17. }
  18.  
  19. int main() {
  20. ios_base::sync_with_stdio(0);
  21. cin.tie(0);
  22.  
  23. int n;
  24. cin >> n;
  25.  
  26. vector<Event> events;
  27. for (int i = 0; i < n; i++) {
  28. int a, b;
  29. cin >> a >> b;
  30.  
  31. events.push_back({1, a});
  32. events.push_back({-1, b});
  33. }
  34.  
  35. sort(events.begin(), events.end(), comp);
  36.  
  37. int X = 0;
  38. int Y = n;
  39. ll still_not_open_sum = 0LL;
  40. ll max_time = events.back().poz;
  41. ll already_closed_sum = 0LL;
  42.  
  43. for (int i = 0; i < events.size(); i++) {
  44. if (events[i].typ == 1) {
  45. still_not_open_sum += max_time - events[i].poz;
  46. }
  47. }
  48.  
  49. ll ans = INF;
  50. int meeting_time = -1;
  51.  
  52. for (int i = 0; i < events.size(); i++) {
  53. int typ = events[i].typ;
  54. ll poz = events[i].poz;
  55.  
  56. if (typ == 1) {
  57. Y--;
  58. still_not_open_sum -= max_time - poz;
  59. } else {
  60. X++;
  61. already_closed_sum += poz;
  62. }
  63.  
  64. ll cost_left = X*poz - already_closed_sum;
  65. ll cost_right = Y*(max_time - poz) - still_not_open_sum;
  66.  
  67. if (ans > cost_left + cost_right) {
  68. ans = cost_left + cost_right;
  69. meeting_time = poz;
  70. }
  71. }
  72.  
  73. cout << meeting_time << ' ' << ans;
  74.  
  75. return 0;
  76. }
  77.  
Success #stdin #stdout 0.01s 5516KB
stdin
5
1 2
3 3
4 5
1 3
3 5
stdout
3 2