BOJ13334: 철로

https://www.acmicpc.net/problem/13334

  • 또다른 라인 스위핑 문제.
  • 라인 스위핑 문제들이 대부분 Priority Queue를 써서 구현을 짧게 한다.
  • Sort로만으로도 푸로, Priority Queue로도 풀었는데, PQ쪽이 구현이 훨씬 짧다.
  • 또다른 교훈: Multimap은 졸라 느리다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <bits/stdc++.h>
using namespace std;

struct Seg {
  int l, r;
  bool operator<(const Seg& b) const {
    return r < b.r;
  }
};

class MaximumSegmentIncludes {
  int N, D;
  vector<Seg> segs;
public:
  void input();
  int sweep();
};

void MaximumSegmentIncludes::input() {
  scanf("%d", &N);
  segs.resize(N);
  for(int i = 0; i < N; i++) {
    int l, r;
    scanf("%d %d", &l, &r);
    if(l > r) swap(l,r);
    segs[i] = {l, r};
  }
  scanf("%d", &D);
}

int MaximumSegmentIncludes::sweep() {
  sort(segs.begin(), segs.end());
  priority_queue<int,vector<int>,greater<int>> pq;
  int ans = 0;
  for(auto [l, r]: segs) {
    pq.push(l);
    while(pq.size() && r-D > pq.top())
      pq.pop();
    ans = max(ans, (int) pq.size());
  }
  return ans;
}

int main() {
  MaximumSegmentIncludes msi;
  msi.input();
  cout << msi.sweep();
}

아래는 Sort로만 푼 버전

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <bits/stdc++.h>
using namespace std;

struct Segment {
  int l, r;
};

class MaximumSegmentIncludes {
  int N, D;
  vector<Segment> left, right;

public:
  long long p2l(Segment p);
  void input();
  void sort();
  int sweep();
};

void MaximumSegmentIncludes::input() {
  scanf("%d", &N);
  left.resize(N);
  for(int i = 0; i < N; i++) {
    scanf("%d %d", &left[i].l, &left[i].r);
    if (left[i].l > left[i].r)
      swap(left[i].l, left[i].r);
  }
  scanf("%d", &D);
}

void MaximumSegmentIncludes::sort() {
  right = left;
  ::sort(left.begin(), left.end(), [](const Segment& a, const Segment& b) {
    return a.l < b.l;
  });
  ::sort(right.begin(), right.end(), [](const Segment& a, const Segment& b) {
    return a.r < b.r;
  });
}

long long MaximumSegmentIncludes::p2l(Segment p) {
  const long long S = 1e8;
  const long long M = 1e9;
  return (p.l+S) * M + (p.r+S);
}

int MaximumSegmentIncludes::sweep() {
  int ans = 0;
  unordered_set<long long> skip;
  unordered_map<long long, int> cur;
  int cnt = 0;
  for(int li = 0, ri = 0, rb = right[0].r; ri < right.size(); rb = right[ri].r) {
    while(ri < right.size() && right[ri].r <= rb) {
      long long h = p2l(right[ri]);
      if(!skip.count(h)) cur[h]++, cnt++;
      ri++;
    }
    while(li < left.size() && left[li].l < rb - D) {
      long long h = p2l(left[li]);
      skip.insert(h);
      if(cur.count(h)) cur[h]--, cnt--;
      li++;
    }
    ans = max(ans, cnt);
  }
  return ans;
}

int main() {
  MaximumSegmentIncludes msi;
  msi.input();
  msi.sort();
  cout << msi.sweep();
}