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

 

1920번: 수 찾기

첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들

www.acmicpc.net

import sys

N = int(input())
my_arr_element = list(map(int, input().split()))

my_arr_element.sort()

flag_list =[]

def do_searching(start_idx, end_idx, searching_num):
    if (start_idx > end_idx):
        return

    mid = int((start_idx + end_idx) / 2)
    if my_arr_element[mid] == searching_num:
        flag_list.append(1)
        return

    if (my_arr_element[mid] > searching_num):
        end_idx = mid - 1
        do_searching(start_idx, end_idx, searching_num)
    else:
        start_idx = mid + 1
        do_searching(start_idx, end_idx, searching_num)

    return


M = int(input())
target_element = list(map(int, input().split()))
for i in range(0, M):
    flag_list.clear()
    do_searching(0,N  - 1, target_element[i])
    if (len(flag_list) == 0):
        print(0)
        continue

    print(1)
  1. 이진탐색을 이용하여 풀 수 있는 문제였습니다.
  2. 처음엔 입력으로 들어온 값을 인덱스로 처리하여 쉽게 풀 수 있을거라고 생각했지만, 이는 틀린 생각이었습니다.
  3. 왜냐하면 입력으로 음수가 들어올 수도 있기 때문입니다.
  4. 따라서 이진탐색으로 방법을 변경했습니다.

'문제풀이 > 백준' 카테고리의 다른 글

2661 - 좋은 수열  (0) 2023.01.08
2751 - 수 정렬하기 2  (0) 2023.01.06
5430 - AC  (0) 2023.01.05
6603 - 로또  (0) 2023.01.03
1406 - 에디터  (0) 2023.01.02

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

 

5430번: AC

각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.

www.acmicpc.net

from audioop import reverse
import sys
from collections import deque

t = int(input())

for i in range(t):
    reverse_cnt = 0
    p = sys.stdin.readline().rstrip()
    n = int(input())
    arr = deque(sys.stdin.readline().rstrip()[1:-1].split(","))
    j = True
    for i in range(0, len(p)):
        if p[i] == 'R':
            reverse_cnt += 1

        elif p[i] == 'D':
            if n == 0 or len(arr) == 0:
                print("error")
                j = False
                break

            if reverse_cnt % 2 == 0:
                arr.popleft()
                continue

            arr.pop()

    if (j == False):
        continue

    if reverse_cnt % 2 == 0:
            print("[" + ",".join(arr) + "]")
    else:
        arr.reverse()
        print("[" + ",".join(arr) + "]")
  1. R 함수가 있다해서, 반드시 뒤집을 필요 없습니다. 만날때마다 뒤집기를 실행하면 시간 초과가 발생합니다.
  2. R 함수 카운트가 홀수일 경우만 뒤집어주면 됩니다. 왜냐하면 "RR" 이렇게 두번 나온다면 원래 배열과 동일하기 때문입니다. "R" 또는 "RRR" 이런식의 홀수 카운트라면 뒤집는게 유효합니다.

'문제풀이 > 백준' 카테고리의 다른 글

2751 - 수 정렬하기 2  (0) 2023.01.06
1920 - 수 찾기  (2) 2023.01.05
6603 - 로또  (0) 2023.01.03
1406 - 에디터  (0) 2023.01.02
10828 - 스택  (0) 2022.12.31

 

#include <iostream>
#include <algorithm>
#include <array>
using namespace std;

int element_cnt;
const int lotto_cnt = 6;
array<int, 49 + 1> input_array;

void remark(const int idx, int check_cnt, array<int, lotto_cnt>& lotto)
{
    if (lotto_cnt == check_cnt) {
		for (const auto& i : lotto) {
            cout << i << ' ';
        }

        cout << '\n';
        return;
    }

    for (int i = idx; i <= element_cnt; i++) {
        lotto[check_cnt] = input_array[i];
        remark(i + 1, check_cnt + 1, lotto);
    }
}

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

    while (true) {
        cin >> element_cnt;
        if (!element_cnt) {
            break;
        }

        for (int i = 1; i <= element_cnt; i++) {
            int input_cnt;
            cin >> input_cnt;
            input_array[i] = input_cnt;
        }

        const int check_cnt = 0;
        array<int, lotto_cnt> lotto{ 0, };
        remark(1, check_cnt, lotto);

        cout << '\n';
    }

    return 0;
}

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

 

6603번: 로또

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스는 한 줄로 이루어져 있다. 첫 번째 수는 k (6 < k < 13)이고, 다음 k개 수는 집합 S에 포함되는 수이다. S의 원소는 오름차순으로

www.acmicpc.net

재귀함수를 이용해 풀 수 있는 전형적인 문제였습니다.

'문제풀이 > 백준' 카테고리의 다른 글

1920 - 수 찾기  (2) 2023.01.05
5430 - AC  (0) 2023.01.05
1406 - 에디터  (0) 2023.01.02
10828 - 스택  (0) 2022.12.31
2628 - 종이 자르기  (0) 2022.12.07
#include <iostream>
#include <iterator>
#include <string>
#include <array>
#include <list>
using namespace std;

list<char> editor;

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

    string input_str;
    cin >> input_str;
    for (int i  = 0; i < input_str.size(); i++) {
        editor.push_back(input_str[i]);
    }

    auto current_idx = editor.end();
    int cnt;
    cin >> cnt;
    while (cnt-- > 0) {
        char command;
        cin >> command;
        char append_char;
        switch (command) {
        case 'P':
            cin >> append_char;
            current_idx = editor.insert(current_idx, append_char);
            current_idx++;
             break;

        case 'B':
            if (editor.begin() == current_idx) {
                break;
            }

            --current_idx;
            current_idx = editor.erase(current_idx);
            break;
        case 'D':
            if (editor.end() == current_idx) {
                break;
            }

            ++current_idx;
            break;
        case 'L':
            if (editor.begin() == current_idx) {
                break;
            }

            --current_idx;
            break;

        default:
            break;
        }
    }

    for (auto& i : editor) {
        cout << i;
    }
    cout << '\n';
    return 0;
}

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

 

1406번: 에디터

첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수

www.acmicpc.net

 

문제 descption을 읽어보면 전형적인 linked list 동작이었습니다.

처음엔 string 객체를 이용해 문제를 풀었으나, 시간 초과를 초래했네요.

그래서 std::list로 컨테이너를 교체했습니다.

'문제풀이 > 백준' 카테고리의 다른 글

5430 - AC  (0) 2023.01.05
6603 - 로또  (0) 2023.01.03
10828 - 스택  (0) 2022.12.31
2628 - 종이 자르기  (0) 2022.12.07
1244 - 스위치 켜고 끄기  (0) 2022.09.09
import sys
n = int(sys.stdin.readline())

back = 0
my_q = [0 for i in range (0, 100000 + 1)]
for i in range(n):
    command = sys.stdin.readline().split()
    if command[0] == 'push':
        my_q[back] = command[1]
        back +=1

    elif command[0] == 'pop':
        if 0 == back :
            print(-1)
            continue

        print(my_q[0])
        for i in range(0, back):
            if back - 1 == i:
                continue

            my_q[i] = my_q[i + 1]

        back -= 1

    elif command[0] == 'size':
        print(back)

    elif command[0] == 'empty' :
        if back != 0:
            print(0)
            continue

        print(1)

    elif command[0] == 'front' :
        if 0 == back:
            print(-1)
            continue

        print(my_q[0])

    elif command[0] == 'back' :
        if 0 == back:
            print(-1)
            continue

        print(my_q[back - 1])

큐를 이해하고 있으면 쉽게 풀 수 있습니다.

import sys
n = int(sys.stdin.readline())

sp = 0
my_stack = [0 for i in range (0, 100000 + 1)]
for i in range(n):
    command = sys.stdin.readline().split()
    if command[0] == 'push':
        my_stack[sp] = command[1]
        sp += 1

    elif command[0] == 'pop':
        if 0 == sp :
            print(-1)
            continue

        print(my_stack[sp - 1])
        my_stack[sp - 1] = 0
        sp -= 1

    elif command[0] == 'size': # 크기 조회
        if sp == 0:
            print(0)
            continue

        print(sp)

    elif command[0] == 'empty' : # 크기 조회
        if sp != 0:
            print(0)
            continue

        print(1)

    elif command[0] == 'top' :
        if 0 == sp:
            print(-1)
            continue

        print(my_stack[sp - 1])

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

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

스택을 이해하고 있으면, 쉽게 풀 수 있습니다.

'문제풀이 > 백준' 카테고리의 다른 글

6603 - 로또  (0) 2023.01.03
1406 - 에디터  (0) 2023.01.02
2628 - 종이 자르기  (0) 2022.12.07
1244 - 스위치 켜고 끄기  (0) 2022.09.09
15685 - 드래곤 커브  (0) 2022.04.23

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

 

2628번: 종이자르기

아래 <그림 1>과 같이 직사각형 모양의 종이가 있다. 이 종이는 가로방향과 세로 방향으로 1㎝마다 점선이 그어져 있다. 가로 점선은 위에서 아래로 1번부터 차례로 번호가 붙어 있고, 세로 점선

www.acmicpc.net

제가 40분컷 내버린것을 보면 아주 쉬운 문제였다는 것을 알 수 있습니다.

예제 입력으로 보는 풀이는 아래와 같습니다.

0 3 -> 3행에서 자른다.

1 4 -> 4열에서 자른다.

0 2 -> 2행에서 자른다.

위 경우로는, 아래와 같이 총 6개로 나뉩니다.

(2 - 0) * (4-0)

(2 - 0) * (10 - 4)

(3 - 2) * (4 - 0)

(3 - 2) * (10 - 4)

(8 -3) * (4 - 0)

(8 - 3) * (10 - 4)

가장 큰 것을 찾습니다.

'문제풀이 > 백준' 카테고리의 다른 글

1406 - 에디터  (0) 2023.01.02
10828 - 스택  (0) 2022.12.31
1244 - 스위치 켜고 끄기  (0) 2022.09.09
15685 - 드래곤 커브  (0) 2022.04.23
10026 - 적록색약  (0) 2022.04.23

어떤 클래스의 non static 멤버의 포인터를 가져오고 싶다면 아래와 같이 코딩을 해서 해결할 수 있습니다. thread를 생성하는 방법으로 설명하겠습니다.

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>

#define	IS_STATIC	1	

class foo
{
public:
#if IS_STATIC
	static void bar()
#else
	void bar()
#endif
	{
		for (int i = 0; i < 5; ++i) {
			std::cout << "Thread 3 executing\n";
			//++n;
			std::this_thread::sleep_for(std::chrono::milliseconds(10));
		}
	}
};

int main()
{
	int n = 0;
	foo f;
#if IS_STATIC	
	std::thread t5(foo::bar); // t5 runs foo::bar() on object f
#else
	std::thread t5(&foo::bar, &f); // t5 runs foo::bar() on object f
#endif // 0
	t5.join();

}
std::thread t5(&foo::bar, &f);

인스턴스 f의 bar 함수를 수행하는 스레드를 생성하기 위한 코드입니다. 이를 위해 f의 포인터를 넘기고, member pointer인 &foo::bar까지 같이 넘깁니다.

그러면 static function이 만들어지고 이를 t5가 수행하게 됩니다.

위처럼 코딩하면 non static 멤버의 포인터를 이용할 수 있습니다. getter를 굳이 만들지 않고서도요. 하지만 이는 thread를 생성할때 문법적으로 맞춰줘야 하는 부분이므로 굳이 다른 상황에서 이용할 필요는 없을것 같습니다.

** 만일 static 메서드라면 아래와 같이 이용할 수 있습니다. static이기 때문에 인스턴스는 param에서 제외되도 됩니다.

std::thread t5(foo::bar);

 

'C++ > 코딩' 카테고리의 다른 글

c파일와 cpp파일 mix 빌드  (0) 2022.09.03

+ Recent posts