algorithm 헤더에 들어있다.

vector 내 중복 원소들을 없애고 하나만 남겨준다.

다만 의도한 결과를 내고싶으면 정렬을 한 뒤에 사용해야 한다.

 

unique(iter_begin, iter_end);

 

검색해보니 벡터만 언급되는걸로 봐선 벡터만 사용 가능하거나 벡터 말고는 잘 사용을 안하는듯 하다.

반환값은 중복된 값을 모두 지우고 난 뒤의 iterator를 반환해준다.

벡터의 크기 자체는 변하지 않기때문에 실제 삭제가 이뤄지지 않으므로 삭제까지 하고싶다면 erase와 같이 사용해야 한다.

 

vector.erase(unique(iter_begin, iter_end), iter_end);

 

'C++ > 기타' 카테고리의 다른 글

[algorithm] find, find_if  (0) 2022.08.03
[algorithm] 순열과 조합  (0) 2022.07.31
[algorithm] 교집합, 합집합, 차집합  (0) 2022.07.28
map, set  (0) 2022.07.27
[algorithm] find  (0) 2022.07.27

연습문제 : BOJ 10799 [쇠막대기], BOK 2504 [괄호의 값]

 

- 10799 : 쇠막대기. 45분 못풀고 해답 봤음

#include <iostream>
#include <string>
#include <stack>

using namespace std;

int main(void)
{
	ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	
	stack<char> pipes;

	string	str;
	size_t	str_len = 0;
	size_t	answer = 0;

	cin >> str;
	str_len = str.length();

	for (int i = 0; i < str_len; ++i)
	{
		if (str[i] == '(')
		{
			pipes.push(str[i]);
		}
		else
		{
			pipes.pop();

			if (str[i-1] == '(')
			{
				answer += pipes.size();
				// 레이저 컷팅
			}
			else
			{
				answer += 1;
				// 파이프의 끝. 한번 잘린거나 다름없어서 한개 추가해줌
			}
		}
	}

	cout << answer;

	return 0;
}

 

연습 문제

 

2493: 탑

더보기
#include <iostream>
#include <stack>

#define X first
#define Y second

using namespace std;

int N;
stack<pair<int, int>> tower;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	
	cin >> N;
	tower.push({ 100000001, 0 }); // 넘을 수 없는 최대치의 벽 미리 삽입
	for (int i = 1; i <= N; i++) { // 인덱스 출력을 위해 1부터 시작
		int height;
		cin >> height;
		while (tower.top().X < height) // 더 높은 이전타워 탐색
			tower.pop();
		cout << tower.top().Y << " "; // 더 높은 타워의 레이저 송수신 결과
		tower.push({ height, i }); // 현재 타워 스택에 추가
	}
}

 

바킹독님의 소스. 나중에 다시 리벤지 하는걸로

핵심은 스택에 맨 먼저 넘을수 없는 최대높이, 인덱스 0의 값을 준다

 

#include <iostream>
#include <vector>

using namespace std;

int main(void)
{
	ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);

	int n;
	vector<int> towers;
	vector<int> temp_towers;
	vector<int> answer;

	cin >> n;

	int data;
	for (int i = 0; i < n; ++i)
	{
		cin >> data;
		towers.push_back(data);
	}

	int count = 0;

	while (true)
	{
		int tower = towers.back();
		towers.pop_back();

		temp_towers.push_back(tower);

		//count += 1;

		if (towers.empty())
		{
			break;
		}

		while (!temp_towers.empty() && temp_towers.back() < towers.back())
		{
			answer.push_back(towers.size());
			temp_towers.pop_back();
		}

		
	}

	while (!temp_towers.empty())
	{
		answer.push_back(0);
		temp_towers.pop_back();
	}

	for (int i = 0; i < n; ++i)
	{
		cout << answer.back() << " ";
		answer.pop_back();
	}

	return 0;
}

 

내가 원래 작성하던 코드

 

6198: 옥상 정원 꾸미기

더보기
#include <iostream>
#include <stack>

using namespace std;

#define MAXIMUM 1000000000

int main(void)
{
	ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);

	stack<pair<int, int>> building;
	int n;
	long long answer = 0;

	cin >> n;

	building.push({MAXIMUM + 1, 0});

	for (int i = 1; i <= n; ++i)
	{
		int h;
		cin >> h;

		if (h < building.top().first)
		{
			building.push({h, i});
		}
		else
		{
			while (h >= building.top().first)
			{
				answer += i - building.top().second - 1;
				building.pop();
			}
			building.push({ h, i });
		}

		// 남은 빌딩에 대한 처리
		if (i == n)
		{
			while (MAXIMUM >= building.top().first)
			{
				answer += i - building.top().second;
				building.pop();
			}
			break;
		}
	}

	cout << answer;

	return 0;
}

 

바로 위 탑의 개념을 활용함.

 

17298: 오큰수

더보기
#include <bits/stdc++.h>
using namespace std;

int a[1000000];
int ans[1000000];
int main(void) {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> a[i];
  stack<int> S;
  for (int i = n - 1; i >= 0; i--) {
    while (!S.empty() && S.top() <= a[i]) S.pop(); // 현재수보다 스택안에 있는 큰수 싹다 정리
    if (S.empty())
      ans[i] = -1;
    else
      ans[i] = S.top();
    S.push(a[i]);
  }
  for (int i = 0; i < n; i++) cout << ans[i] << ' ';
}

아직 못풀어서 바킹독 해답코드 들고옴. 배열 역순으로 접근해서 기준 숫자보다 큰 숫자를 다 없앤다.

 

'알고리즘 > 바킹독의 실전 알고리즘' 카테고리의 다른 글

[0x0A] DFS  (0) 2022.07.30
[0x09] BFS  (0) 2022.07.28
[0x07] 덱(Deque)  (0) 2022.07.25
[0x06] 큐  (0) 2022.07.25
[0x05] 스택  (0) 2022.07.25

원소의 추가/제거 O(1)

제일 앞/뒤 원소 확인이 O(1)

나머지 원소들의 확인/변경이 원칙적으로 불가능 하지만 c++ STL deque에서는 인덱스로 원소에 접근할 수 있음

 

양쪽 끝에서 삽입과 삭제가 모두 가능하다.

Double ended Queue라는 뜻을 가지고 있음.

양방향 큐라는 느낌보다는 vector랑 비슷한데, front에도 O(1)에 추가/제거가 가능한 느낌임

deque은 모든 원소들이 메모리 상에 연속하게 배치되어 있지 않다.

 

연습 문제

 

1021: 회전하는 큐

더보기
#include <iostream>
#include <deque>
#include <algorithm>

using namespace std;

int main(void)
{
	ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);

	int n, m;
	int answer = 0;

	deque<int> rq;
	deque<int> nums;

	cin >> n >> m;

	for (int i = 0; i < m; ++i)
	{
		int data;
		cin >> data;
		nums.push_back(data);
	}

	for (int i = 1; i <= n; ++i)
	{
		rq.push_back(i);
	}

	for (int num : nums)
	{
		// algorithm 헤더에 포함. 값을 찾으면 해당 위치의 iterator를 반환. 못찾으면 end.
		// 여기에 begin을 빼면 인덱스를 알 수 있음.
		int idx = find(rq.begin(), rq.end(), num) - rq.begin();
		while (num != rq.front())
		{
			// 왼쪽으로 밀기
			if (idx < (int)rq.size() - idx)
			{
				rq.push_back(rq.front());
				rq.pop_front();
			}
			else
			{
				rq.push_front(rq.back());
				rq.pop_back();
			}
			answer++;
		}
		rq.pop_front();
	}

	cout << answer;

	return 0;
}

 

접근은 괜찮게 했는데 나는 인덱스를 왼쪽으로 밀면 +1, 오른쪽으로 밀면 -1인 누적값을 하나 사용해서 덱사

이즈/2에 더해줘서 구해줬더니 정답이 아니길래 해답을 봤음.

코드 딱 두줄 추가하고 정답처리 받긴 했는데 좀 아쉽다.

 

 

'알고리즘 > 바킹독의 실전 알고리즘' 카테고리의 다른 글

[0x09] BFS  (0) 2022.07.28
[0x08] 스택의 활용  (0) 2022.07.25
[0x06] 큐  (0) 2022.07.25
[0x05] 스택  (0) 2022.07.25
[0x04] 연결 리스트  (0) 2022.07.25

원소의 추가/제거가 O(N)

앞/뒤의 원소 확인이 O(1)

앞뒤가 아닌 나머지 원소들의 확인/변경이 원칙적으로 불가능

STL 큐에서는 인덱스로 내부원소 접근하는 기능은 없음.

BFS와 Flood Fill을 할 때 쓰게 됨

'알고리즘 > 바킹독의 실전 알고리즘' 카테고리의 다른 글

[0x08] 스택의 활용  (0) 2022.07.25
[0x07] 덱(Deque)  (0) 2022.07.25
[0x05] 스택  (0) 2022.07.25
[0x04] 연결 리스트  (0) 2022.07.25
[0x03] 배열  (0) 2022.07.25

원소의 추가/제거 O(1)

최상단 원소 확인 O(1)

나머지 원소들의 확인/변경이 원칙적으로는 불가능함

배열 혹은 연결리스트를 이용해서 구현할 수 있음

 

'알고리즘 > 바킹독의 실전 알고리즘' 카테고리의 다른 글

[0x07] 덱(Deque)  (0) 2022.07.25
[0x06] 큐  (0) 2022.07.25
[0x04] 연결 리스트  (0) 2022.07.25
[0x03] 배열  (0) 2022.07.25
[0x02] 기초 코드 작성 요령  (0) 2022.07.25

+ Recent posts