단속카메라

108번뇌·2021년 10월 27일

https://programmers.co.kr/learn/courses/30/lessons/42884
이문제 테스트케이스는 맞췄는데 틀렸음.
[답지]

include <string>
#include <vector>
#include <algorithm>
using namespace std;



int solution(vector<vector<int>> routes) {
	//기본 카메라 1대
	int answer = 1;
	//들어온 리스트 정렬
	sort(routes.begin(), routes.end());
	//비교를 위해 처음차가 나가는 부분 체크
	int temp = routes[0][1];
	//리스트 순회하기
	for (auto a : routes) {
		//현재 차가 나가는 부분보다 뒤에 차가 들어온다면
		if (temp < a[0]) {
			//카메라 설치
			answer++;
			//나가는 부분 정정
			temp = a[1];
		}
		//현재 차보다 뒤차가 먼저나가면 
		if (temp >= a[1])
		{
			temp = a[1];// 나가는 부분을 뒷차로 수정
		}
	}
	return answer;
}

[내 소스]

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int solution(vector<vector<int>> routes) {
	int answer = 0;

	sort(routes.begin(), routes.end(), [](vector<int> a, vector<int> b) {
		return a[0] < b[0];
	});

	int Start(0);
	int End(0);
	for (int i = 0; i < routes.size() ; i++)
	{
		if (i == 0)
		{
			Start = routes[i][0];
			End = routes[i][1];
			answer++;
		}
		else
		{
			if (Start <= routes[i][0] && routes[i][0] <= End)
			{
				continue;
			}
			else
			{
				if (End <= routes[i][1])
				{
					End = routes[i][1];
				}
				Start = routes[i][0];
				answer++;
			}
		}
	}



	return answer;
}

int main()
{

	vector<vector<int>> vvTemp = { {-20, -15},{-14, -5},{-18, -13},{-5, -3 }};	
	int rst = 2;
	
	int vResult = solution(vvTemp);

	return 0;
}

틀린이유 -> 현재보다 나중에 오는게
현재보다 먼저 나가면 범위를 좁혀야 하는데(교집합을 구하는것)
나는 그부분을 하지 않았음
//현재 차보다 뒤차가 먼저나가면
if (temp >= a[1])
{
temp = a[1];// 나가는 부분을 뒷차로 수정
}
이렇게 해야 그 다음에 오는 차의 [i][0]과 비교가 가능하다.

profile
내일 아침 눈을 떳을 때, '기대되는 오늘 하루를 만들기 위해' 나는 오늘도 생각하고 고민한다.

0개의 댓글