PS/그리디 알고리즘[Greedy]

백준 2170 선 긋기(c++)

SeungbeomKim 2022. 8. 6. 16:12
반응형

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

 

2170번: 선 긋기

첫째 줄에 선을 그은 횟수 N(1 ≤ N ≤ 1,000,000)이 주어진다. 다음 N개의 줄에는 선을 그을 때 선택한 두 점의 위치 x, y(-1,000,000,000 ≤ x < y ≤ 1,000,000,000)가 주어진다.

www.acmicpc.net

<코드>

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;


int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int x,y;
	int n;	
	cin>>n;
	vector<pair<int,int>>v;
	for(int i=0;i<n;i++)
	{
		cin>>x>>y;
		v.push_back(make_pair(x,y));
	}
	sort(v.begin(),v.end());
	
	int sum=0;
	int start = v[0].first;
	int end = v[0].second;
	for(int i=1;i<n;i++)
	{
		if(v[i].first <= end)
		{
			end = max(end,v[i].second);
		}
		else{
			sum+= (end-start);
			start = v[i].first;
			end = v[i].second;
		}
	}
	sum += (end -start);
	cout<<sum<<'\n';	
	
}

 

반응형

'PS > 그리디 알고리즘[Greedy]' 카테고리의 다른 글

백준 3135 라디오(c++)  (0) 2022.09.18
백준 20044 Project Teams(c++)  (0) 2022.09.18
백준 1339 단어 수학(c++)  (0) 2022.07.22
백준 1781 컵라면(c++)  (0) 2022.07.21
백준 1049 기타줄(c++)  (0) 2022.07.21