본문 바로가기
공부

BOJ 1181, 10828 문제 해결과 고찰

by 뜨응 2022. 1. 6.

# 1181

#include<iostream>
#include<algorithm>

using namespace std;

int a, b;
string arr[200001];

bool compare(string const a, string const b) {
	if (a.length() == b.length())
		return (a < b);
	return a.length() < b.length();
}
int main() {

	cin >> a;

	for (int i = 0; i < a; i++) {
		cin >> arr[i];
	}
	
	sort(&arr[0], &arr[a], compare);
	


	for (int i = 0; i < a; i++) {
		
	}
	for (int i = 0; i < a; i++) {
		if (arr[i] == arr[i + 1])
			continue;
		cout << arr[i]<<"\n";

	}
	
	}
  • 일단 sort(a , b , compare)함수 이용법에 대해 알게 되었다. 
  • 배열을 사용했기 때문에  sort  안에 ab자리에는 주소값이 전달되어야해서 '&'를 꼭 붙여줘야한다.
  • sort 함수에 들어가는 compare 함수는 return 값이 false일 때만 sorting 된다.
  • 어떤 값이 중복될 때 중복되는 값은 빼야할 때 그 index 생략하고 출력하면 된다.
  • continue를 사용하면 반복문에서 건너뛰고 다음 i로 넘어갈 수 있다.

#10828

#include<iostream>
#include<stack>

using namespace std;

stack<int> st;
string arr;
int a , n;

int main() {

	cin >> a;

	for (int i = 0; i < a; i++) {

		cin >> arr;

		if (arr == "push") {
			cin >> n;
			st.push(n);
			
		}
		else if (arr == "top") {
			if (st.empty() == 1)
				cout << -1 << "\n";
			else 
				cout << st.top()<<"\n";
		}
		else if (arr == "size") {
			cout << st.size() << "\n";
		}
		else if (arr == "pop") {
			if (st.empty() == 1)
				cout << -1 << "\n";
			else {
				cout << st.top() << "\n";
				st.pop();
			}
		}
		else if (arr == "empty") {
			cout << st.empty()<<"\n";
		}
	}
	
	}

 

  • stack 헤더는 push() , pop , top, size, empty 기능이 있다.
  • pop, top은 empty를 이용해 stack이 비어있는지 확인해야한다.
  • 처음에 나는 arr[10001]을 사용해 string을 담았었다. 하지만 반복문으로 계속 string을 새로 받기에 그럴 필요가 없다. 그래서 string arr을 선언해주었다. 
  • empty는 비어있으면 1을 출력한다.
  • 나머지 top, size, empty 들은 cout으로 출력을 해주어야한다.
  • 처음에 pop과 top에 if문을 작성한 뒤 else를 작성하지 않아 계속 오류가 났었다. 

 

 

'공부' 카테고리의 다른 글

BOJ 11004 해결, 시간 초과  (0) 2022.01.13
BOJ 9012 해결과 고찰.....(최악)  (0) 2022.01.12
BOJ 11365 3가지 풀이와 고찰  (0) 2022.01.10
BOJ 1475 해결과 고찰  (9) 2022.01.07
BOJ 10808  (0) 2022.01.06