SPOJ CRAYON

https://www.spoj.com/problems/CRAYON/

๋ฌธ์ œ ๐Ÿ˜ฅ

Mary๋Š” ๊ทธ๋ฆผ ๊ทธ๋ฆฌ๋Š” ๊ฑธ ์ข‹์•„ํ•˜๊ธดํ•˜๋Š”๋ฐ ์ž˜ ๊ทธ๋ฆฌ์ง„ ๋ชปํ•œ๋‹ค.

Mary๊ฐ€ ํ•˜๋Š” ์ง“์€ ์„ธ ๊ฐ€์ง€๋‹ค.

  1. D L R : [L, R]์— segment๋ฅผ ๊ทธ๋ฆฐ๋‹ค.
  2. C I: i๋ฒˆ์งธ์— ์žˆ๋Š” segment๋ฅผ ์ง€์šด๋‹ค. ์ฆ‰, i๋ฒˆ์งธ์— ์˜ฌ๋ผ์™€์žˆ๋Š” ๋ชจ๋“  segment๋Š” ์ œ๊ฑฐ๋œ๋‹ค.
  3. Q L R: [L, R]์—์„œ ์ตœ์†Œ ํ•˜๋‚˜์˜ ๊ณตํ†ต ํฌ์ธํŠธ๋ฅผ ๊ณต์œ ํ•˜๋Š” segment์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค. (์ฆ‰, ๊ฒน์น˜๋Š”)

ํ’€์ด

https://github.com/tr0j4n034/SPOJ/blob/master/CRAYON.cpp

ํŽœ์œ…ํŠธ๋ฆฌ๋ฅผ ์ด์šฉํ•˜์—ฌ O(Nร—logN)O(N \times logN) ์‹œ๊ฐ„์— ํ’€ ์ˆ˜ ์žˆ๋‹ค.

์ผ๋‹จ ์ˆ˜์˜ ๋ฒ”์œ„๊ฐ€ ๋งค์šฐ ํฌ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ์ดํ„ฐ๋ฅผ ์••์ถ•ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

๋ฐ์ดํ„ฐ ์••์ถ•ํ•˜๊ธฐ

Offline ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•œ๋‹ค.

int main() {
  vector<char> type(N); 
  vector<int> l(N), r(N), who(N), c(N); 
  vector<int> data; 
  
  int id = 0;
  for (int i = 0; i < N; ++i) {
      cin >> type[i];
      if (type[i] == 'C') {
          cin >> c[i];
      } else if (type[i] == 'D') {
          cin >> l[i] >> r[i];
          who[++id] = i;
      } else {
          cin >> l[i] >> r[i];
      }
  }
  
  data = vector<int>(l.begin(), l.end()); 
  data.insert(data.end(), r.begin(), r.end()); 
  sort(data.begin(), data.end());
  data.erase(unique(data.begin(), data.end()), data.end());
}

๐Ÿ˜„ std::unique

Remove consecutive duplicates in range. ๋ฒ”์œ„ ๋‚ด ์ค‘๋ณต๋œ ์›์†Œ๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค.

์‹ค์ œ๋กœ ์ œ๊ฑฐํ•˜๋Š” ๊ฒƒ์€ ์•„๋‹˜์— ์ฃผ์˜. ์•ž์— ์œ ์ผํ•œ ๊ฐ’๋“ค์„ ์ฑ„์›Œ ๋„ฃ๊ณ , ์ •๋ ฌ๋˜์ง€ ์•Š์€ ์‹œ์ž‘ ํฌ์ธํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๋˜ํ•œ unique ํ•จ์ˆ˜๋Š” ์•ž๊ณผ ๋’ค์˜ ์›์†Œ๋“ค์„ ๋น„๊ตํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ˜๋“œ์‹œ ์ž…๋ ฅ ๋ฒกํ„ฐ๊ฐ€ ์ •๋ ฌ๋œ ์ƒํƒœ์ด์–ด์•ผ ํ•œ๋‹ค.

template <class FowardIterator> ForwardIterator unique (ForwardIterator first, ForwardIterator last) {
  if (first == last) return last; 
  
  ForwardIterator result = first; 
  while(++first != last) {
    if(!(*result == *first))
      *(++result) = *first;
  }
  return ++result;
}

Segment ์„ธ๊ธฐ

๋ฌธ์ œ์˜ ์กฐ๊ฑด์€ ๊ต์ฐจํ•˜๋Š” segment์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ผ๋Š” ๊ฒƒ์ด๋‹ค. ๊ทธ๋Ÿฐ๋ฐ, ๊ต์ฐจํ•˜๋Š” segment๊ฐ€ ์•„๋‹Œ ๊ต์ฐจํ•˜์ง€ ์•Š๋Š” segment์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค๋ฉด ์–ด๋–จ๊นŒ?

์˜ˆ๋ฅผ ๋“ค์–ด, [l ,r]์—์„œ ๊ต์ฐจํ•˜๋Š” segment์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค๊ณ  ํ•˜์ž. ๊ทธ๋Ÿฌ๋ฉด ํ•„์š”ํ•œ ๊ฒƒ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

  • ์‹œ์ž‘์ ์ด r๋ณด๋‹ค ํฐ ์„ธ๊ทธ๋จผํŠธ์˜ ๊ฐœ์ˆ˜
  • ๋งˆ์ง€๋ง‰์ ์ด l๋ณด๋‹ค ์ž‘์€ ์„ธ๊ทธ๋จผํŠธ์˜ ๊ฐœ์ˆ˜

์ „์ฒด ์„ธ๊ทธ๋จผํŠธ์˜ ๊ฐœ์ˆ˜์—์„œ ์œ„์˜ ๋‘ ๊ฐœ๋ฅผ ๋นผ์ฃผ์ž. ๐Ÿ‘€ ์˜ค~ ๋˜‘๋˜‘ํ•˜๋‹ค.


[jungin]
Written by@[jungin]
์•ˆ๋…•ํ•˜์„ธ์š”

GitHub