[백준 2565] 전깃줄 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
전깃줄 (A, B)가 주어질 때, 교차하는 전선이 없도록 제거해야 할 최소 전선의 개수를 구하는 문제입니다.
전선을 A 좌표 기준으로 정렬하면, 두 전선이 교차하는 조건은 B 좌표가 역전되는 경우입니다. 따라서 교차 없이 남길 수 있는 최대 전선은 B 좌표의 가장 긴 증가하는 부분 수열(LIS)이 됩니다.
접근법
먼저 전선들을 A 좌표 기준으로 정렬합니다.
다음으로 B 좌표들에 대해 이분 탐색 기반 LIS 알고리즘으로 길이를 구합니다.
이후 제거해야 할 최소 전선 수는 N - LIS 길이가 됩니다.
시간 복잡도는 O(N log N)입니다.
Code
C#
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
using System;
using System.Collections.Generic;
namespace Solution {
class Program {
static void Main(string[] args) {
var n = int.Parse(Console.ReadLine()!);
var wires = new List<(int a, int b)>();
for (var i = 0; i < n; i++) {
var parts = Array.ConvertAll(Console.ReadLine()!.Split(), int.Parse);
wires.Add((parts[0], parts[1]));
}
wires.Sort((x, y) => x.a.CompareTo(y.a));
var lis = new int[n];
var len = 0;
for (var i = 0; i < n; i++) {
var x = wires[i].b;
var idx = Array.BinarySearch(lis, 0, len, x);
if (idx < 0)
idx = ~idx;
lis[idx] = x;
if (idx == len)
len++;
}
Console.WriteLine(n - len);
}
}
}
C++
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
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef vector<pii> vp;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
vp w(n);
for (int i = 0; i < n; i++)
cin >> w[i].first >> w[i].second;
sort(w.begin(), w.end());
vi lis(n);
int len = 0;
for (int i = 0; i < n; i++) {
int x = w[i].second;
auto it = lower_bound(lis.begin(), lis.begin() + len, x);
*it = x;
if (it == lis.begin() + len)
len++;
}
cout << n - len << "\n";
return 0;
}