728x90

팰린드롬수 

 

시간 제한         메모리 제한                   제출                          정답                        맞힌 사람                정답 비율

   

1 초 128 MB 59454 33787 29795 57.112%

문제

어떤 단어를 뒤에서부터 읽어도 똑같다면 그 단어를 팰린드롬이라고 한다. 'radar', 'sees'는 팰린드롬이다.

수도 팰린드롬으로 취급할 수 있다. 수의 숫자들을 뒤에서부터 읽어도 같다면 그 수는 팰린드롬수다. 121, 12421 등은 팰린드롬수다. 123, 1231은 뒤에서부터 읽으면 다르므로 팰린드롬수가 아니다. 또한 10도 팰린드롬수가 아닌데, 앞에 무의미한 0이 올 수 있다면 010이 되어 팰린드롬수로 취급할 수도 있지만, 특별히 이번 문제에서는 무의미한 0이 앞에 올 수 없다고 하자.

입력

입력은 여러 개의 테스트 케이스로 이루어져 있으며, 각 줄마다 1 이상 99999 이하의 정수가 주어진다. 입력의 마지막 줄에는 0이 주어지며, 이 줄은 문제에 포함되지 않는다.

출력

각 줄마다 주어진 수가 팰린드롬수면 'yes', 아니면 'no'를 출력한다.

예제 입력 1 복사

121
1231
12421
0

예제 출력 1 복사

yes
no
yes
 
 
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int is_palindrome(char* str, int len) {
	int middle = len / 2; //index of middle array
	if (len % 2 != 0) { //for odd
		for (int i = 0; i < middle; i++) {
			if (str[i] != str[(len - 1) - i]) {
				return 0;
			}
		}
		return 1;
	}
	else { // for even
		middle--;
		for (int i = 0; i <= middle ; i++) {
			if (str[i] != str[(len-1) - i]) {
				return 0;
			}
		}
		return 1;
	}
	
}

int main(int argc, char* argv[]) {
	char user_input[6] = {0,}; //max number length is 5
	int array_size, middle;

	while (1) {
		scanf("%5s", user_input);

		if (user_input[0] == '0')
			return 0;

		array_size = strlen(user_input);

		if (is_palindrome(user_input, array_size))
			printf("yes\n");
		else
			printf("no\n");
	}
	return 0;
}

 

728x90

'C, C++ > 백준' 카테고리의 다른 글

[백준] 2231 분해합  (0) 2024.02.22
[백준] 1546 평균  (1) 2024.02.15
[백준] 1436 영화감독 숌  (1) 2024.02.10
[백준] 1002번 터렛  (0) 2023.12.26
[백준] 10828  (0) 2023.11.20
728x90

단어 정렬

 시간제한         메모리제한                 제출                           정답                         맞힌사람               정답비율
2 초 256 MB 174784 73233 54897 40.354%

문제

 

알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.

  1. 길이가 짧은 것부터
  2. 길이가 같으면 사전 순으로

단, 중복된 단어는 하나만 남기고 제거해야 한다.

 

입력

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

 

출력

조건에 따라 정렬하여 단어들을 출력한다.

예제 입력 1 

13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours

예제 출력 1 

i
im
it
no
but
more
wait
wont
yours
cannot
hesitate
 
 

 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char* argv[]) {
	int input_count = 0;
	scanf("%d", &input_count);
	char** input_string = (char**)malloc(sizeof(char*) * input_count);
	char buffer[51] = { 0 }, temp[51] = { 0 };
	while (getchar() != '\n'); //엔터키 잡기

	for (int i = 0; i < input_count; i++) {
		fgets(buffer, sizeof(buffer), stdin);
		
		buffer[strcspn(buffer, "\n")] = '\0';
		input_string[i] = (char*)malloc(sizeof(char) * 51); 
		strcpy(input_string[i], buffer);
		fflush(stdin);
	}
	
	for (int i = 0; i < input_count - 1; i++) {
		for (int j = 0; j < input_count - 1 - i; j++) {
			if (strlen(input_string[j]) > strlen(input_string[j + 1])) {
				strcpy(temp, input_string[j + 1]);
				strcpy(input_string[j + 1], input_string[j]);
				strcpy(input_string[j], temp);
			}
		}
	}
	
	for (int i = 0; i < input_count - 1; i++) {
		if (strcmp(input_string[i], input_string[i + 1]) == 0) {
			free(input_string[i]);
			for (int j = i; j < input_count - 1; j++) {
				input_string[j] = input_string[j + 1];
			}
			input_count--;
			i--;
		}
	}
	for (int i = 0; i < input_count - 1; i++) {
		for (int j = 0; j < input_count - 1 - i; j++) {
			if (strlen(input_string[j]) == strlen(input_string[j + 1])) {
				if (strcmp(input_string[j], input_string[j + 1]) > 0) {
					strcpy(temp, input_string[j + 1]);
					strcpy(input_string[j + 1], input_string[j]);
					strcpy(input_string[j], temp);
				}
			}
		}
	}
	for (int i = 0; i < input_count; i++) {
		printf("%s\n", input_string[i]);
	}

	for (int i = 0; i < input_count; i++)
		free(input_string[i]);
	free(input_string);

	return 0;
}

 

본래 작성한 코드로, 로직 흐름을 보면

1. 입력한 "입력 수"에 따라 최대 문자 길이 '50'에 null값까지 포함한 51 byte의 크기를 가지는 배열 생성.

-> 공간 비효율적 

 

2. 문자열 길이대로 bubble 정렬, 이후에 사전순 bubble 정렬

-> 시간 복잡도가 O(n^2) + O(n^2)으로 매우 비효율적

 

3. 2중 for문 내에서 strcpy를 3번이나 호출함

 -> 매우매우 비효율적

 

4. 공간이 넉넉하다면, 굳이 겹치는 원소를 free해줄 필요가 없다. 불필요한 쓰기 행위일 수 있음

-> 이전 원소와 비교하여 같지 않은 원소만 출력하는 방향으로 수정할 수 있다.

 

결과 :

 

매우 비효율적인 프로그램으로 시간 초과 오답이다.

 

해당 문제의 정답 코드를 보면, 

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

int cmp(string a, string b) {
	// 1. 길이가 같다면, 사전순으로
	if (a.length() == b.length()) {
		return a < b;
	}
	// 2. 길이가 다르다면, 짧은 순으로 
	else {
		return a.length() < b.length();
	}
}

// 범위가 크기때문에 전역변수로 설정
string word[20000];

int main() {
int main() {
	int N;

	cin >> N;
	for (int i = 0; i < N; i++) {
		cin >> word[i];
	}

	sort(word, word + N, cmp);

	for (int i = 0; i < N; i++) {
		// 중복된 경우 한번만 출력
		if (word[i] == word[i - 1]) {
			continue;
		}
		cout << word[i] << "\n";
	}

	return 0;
}

 

C++의 standard library를 사용하여 간단하게 풀 수 있다.

 

이러한 문제를 "STL 코딩" 문제라 부르며, Standard Library를 잘 활용하는 능력을 확인한다.

 

버블정렬은 비효율적이며, 힙 퀵 병합 정렬을 사용하면 시간이 줄어들것이라 예상할 수 있다.

 

 

 

C로 풀고싶지만 stl로 출제 의도를 생각하고 넘어가겠다..

 

 

728x90

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 1929 소수 구하기  (0) 2024.02.22
[백준] 1920 수 찾기  (0) 2024.02.19
[백준] 1676 팩토리얼 0의 개수  (0) 2024.02.17
[백준] 1654 랜선 자르기  (0) 2024.02.16
[백준] 1018 체스판 다시 칠하기  (4) 2024.01.03
728x90

문제

지민이는 자신의 저택에서 MN개의 단위 정사각형으로 나누어져 있는 M×N 크기의 보드를 찾았다. 어떤 정사각형은 검은색으로 칠해져 있고, 나머지는 흰색으로 칠해져 있다. 지민이는 이 보드를 잘라서 8×8 크기의 체스판으로 만들려고 한다.

체스판은 검은색과 흰색이 번갈아서 칠해져 있어야 한다. 구체적으로, 각 칸이 검은색과 흰색 중 하나로 색칠되어 있고, 변을 공유하는 두 개의 사각형은 다른 색으로 칠해져 있어야 한다. 따라서 이 정의를 따르면 체스판을 색칠하는 경우는 두 가지뿐이다. 하나는 맨 왼쪽 위 칸이 흰색인 경우, 하나는 검은색인 경우이다.

보드가 체스판처럼 칠해져 있다는 보장이 없어서, 지민이는 8×8 크기의 체스판으로 잘라낸 후에 몇 개의 정사각형을 다시 칠해야겠다고 생각했다. 당연히 8*8 크기는 아무데서나 골라도 된다. 지민이가 다시 칠해야 하는 정사각형의 최소 개수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N과 M이 주어진다. N과 M은 8보다 크거나 같고, 50보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에는 보드의 각 행의 상태가 주어진다. B는 검은색이며, W는 흰색이다.

출력

첫째 줄에 지민이가 다시 칠해야 하는 정사각형 개수의 최솟값을 출력한다.

 

예제 입력 1 

8 8
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBBBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW

예제 출력 1 

 

1

예제 입력 2 

10 13
BBBBBBBBWBWBW
BBBBBBBBBWBWB
BBBBBBBBWBWBW
BBBBBBBBBWBWB
BBBBBBBBWBWBW
BBBBBBBBBWBWB
BBBBBBBBWBWBW
BBBBBBBBBWBWB
WWWWWWWWWWBWB
WWWWWWWWWWBWB

예제 출력 2 

12

 

예제 입력 3 

8 8
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB

예제 출력 3 

0

예제 입력 4 

9 23
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBW

예제 출력 4 

31

예제 입력 5 

10 10
BBBBBBBBBB
BBWBWBWBWB
BWBWBWBWBB
BBWBWBWBWB
BWBWBWBWBB
BBWBWBWBWB
BWBWBWBWBB
BBWBWBWBWB
BWBWBWBWBB
BBBBBBBBBB

예제 출력 5 

0

 

예제 입력 6 

8 8
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBBBWBW
WBWBWBWB
BWBWBWBW
WBWBWWWB
BWBWBWBW

예제 출력 6 

2

예제 입력 7 

11 12
BWWBWWBWWBWW
BWWBWBBWWBWW
WBWWBWBBWWBW
BWWBWBBWWBWW
WBWWBWBBWWBW
BWWBWBBWWBWW
WBWWBWBBWWBW
BWWBWBWWWBWW
WBWWBWBBWWBW
BWWBWBBWWBWW
WBWWBWBBWWBW

예제 출력 7 

15

 

 

 

 

이 문제는 브루트포싱을 주제로 하는 문제이다.

최적의 경우를 구하는 문제이고, 해당 문제에 적합한 알고리즘이 생각나지 않으므로 브루트포싱이 접근하는데에 있어서 가장 먼저 시도해야 할 알고리즘일 것이다.

 

우선 생각해야 할 점은, 

 

N X M 행열이 주어졌을때,

1.여러개의 8x8 행렬로 나눈다.

2.선택한 8x8 행렬에 대한 문제에서 제시하는 경우의 수를 구한다.

3.모든 행렬에 대한 경우의 수를 비교하여 최적의 경우를 출력한다.

 

현재 정사각행렬인 8x8 행렬을 사용하므로, 행과 열을 같은 간격의 index로 접근하되, spacial locality만 고려해주면 된다.

 

사용자가 행과 열의 값을 N 과 M으로 입력했을때, 

이차원 배열의 행 인덱스는

0 1 2 ... n-8 n-7 n-6 n-5 n-4 n-3 n-2 n-1,

열 인덱스도 마찬가지로  

0 1 2 ... m-8 m-7 m-6 m-5 m-4 m-3 m-2 m-1

와 같은 형태로 접근할 수 있다.

 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//#include <climits> (use if your compiler need it)


int getCases(int row, int col, char **input) {
	int countW = 0;
	int countB = 0;
	// case W
	for (int i = row; i < row + 8 - 1; i+=2) {
		//first row
		for (int j = col; j < col + 8 - 1; j+=2) {
			if (input[i][j] == 'B') {
				//input[i][j] = 'W';
				countW++;
				if (input[i][j + 1] == 'W') {
					//input[i][j + 1] = 'B';
					countW++;
				} 
			}
			else {
				if (input[i][j + 1] == 'W') {
					//input[i][j + 1] = 'B';
					countW++;
				}
			}
		}
		//second row
		for (int j = col; j < col + 8 - 1; j += 2) {
			if (input[i+1][j] == 'W') {
				//input[i+1][j] = 'B';
				countW++;
				if (input[i+1][j + 1] == 'B') {
					//input[i+1][j + 1] = 'W';
					countW++;
				}
			}
			else {
				if (input[i+1][j + 1] == 'B') {
					//input[i+1][j + 1] = 'W';
					countW++;
				}
			}
		}
	}
	// case B
	for (int i = row; i < row + 8 - 1; i += 2) {
		//first row
		for (int j = col; j < col + 8 - 1; j += 2) {
			if (input[i][j] == 'W') {
				//input[i][j] = 'B';
				countB++;
				if (input[i][j + 1] == 'B') {
					//input[i][j + 1] = 'W';
					countB++;
				}
			}
			else {
				if (input[i][j + 1] == 'B') {
					//input[i][j + 1] = 'W';
					countB++;
				}
			}
		}
		//second row
		for (int j = col; j < col + 8 - 1; j += 2) {
			if (input[i + 1][j] == 'B') {
				//input[i + 1][j] = 'W';
				countB++;
				if (input[i + 1][j + 1] == 'W') {
					//input[i + 1][j + 1] = 'B';
					countB++;
				}
			}
			else {
				if (input[i + 1][j + 1] == 'W') {
					//input[i + 1][j + 1] = 'B';
					countB++;
				}
			}
		}
	}
	return countW < countB ? countW : countB;
}

int main(int argc, char* argv[]) {
	int row, col, temp;
	int min = INT_MAX;
	char** input;
	char ch;

	//user input
	scanf("%d %d ", &row, &col);

	//space allocate
	input = (char**)malloc(sizeof(char*) * row);
	for (int i = 0; i < row; i++) {
		input[i] = (char*)malloc(sizeof(char) * col);
	}
	
	//input value
	for (int i = 0; i < row; i++) {
		for (int j = 0; j < col; j++) {
			ch = getchar();
			if (ch == '\n') {
				ch = getchar();
			}
			input[i][j] = ch;
		}
	}
	
	//func
	for (int i = 0; i <= row - 8; i++) {
		for (int j = 0; j <= col - 8; j++) {
			temp = getCases(i, j, input);
			if (temp < min)
				min = temp;
		}
	}
	printf("%d", min);
    
    	for (int i = 0; i < row; i++) {
		free(input[i]);
	}
	free(input);
    
	return 0;
}

 

 

 

메모리 접근만 신경쓰면 쉽게 해결된다.

728x90

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 1929 소수 구하기  (0) 2024.02.22
[백준] 1920 수 찾기  (0) 2024.02.19
[백준] 1676 팩토리얼 0의 개수  (0) 2024.02.17
[백준] 1654 랜선 자르기  (0) 2024.02.16
[백준] 1181 단어 정렬  (1) 2024.02.09
728x90

 

 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double calculate_distance(int ax, int ay, int bx, int by) {
    return sqrt(pow((ax - bx), 2) + pow((ay - by), 2));
}

int main(int argc, char* argv[]) {
    int num_test_case = 0;
    double distance_of_centers = 0.0;
    int sum_of_radius = 0, sub_of_radius = 0;
    scanf("%d", &num_test_case);

    int* cases = (int*)malloc(sizeof(int) * 6 * num_test_case);

    for (int i = 0; i < num_test_case; i++) {
        scanf("%d %d %d %d %d %d", &cases[6 * i], &cases[6 * i + 1], &cases[6 * i + 2], &cases[6 * i + 3], &cases[6 * i + 4], &cases[6 * i + 5]);
        if (cases[6 * i] < -10000 || cases[6 * i] > 10000 || cases[6 * i + 1] < -10000 || cases[6 * i + 1] > 10000 || cases[6 * i + 2] < 1 || cases[6 * i + 2] > 10000 || cases[6 * i + 3] < -10000 || cases[6 * i + 3] > 10000 || cases[6 * i + 4] < -10000 || cases[6 * i + 4] > 10000 || cases[6 * i + 5] < 1 || cases[6 * i + 5] > 10000)
        {
            printf("Error");
            return -1;
        }
    }

    for (int i = 0; i < num_test_case; i++) {
        distance_of_centers = calculate_distance(cases[6 * i], cases[6 * i + 1], cases[6 * i + 3], cases[6 * i + 4]);
        sum_of_radius = cases[6 * i + 2] + cases[6 * i + 5];
        sub_of_radius = cases[6 * i + 2] > cases[6 * i + 5] ? cases[6 * i + 2] - cases[6 * i + 5] : cases[6 * i + 5] - cases[6 * i + 2];

        if (distance_of_centers > sum_of_radius) //case 1
            printf("0\n");
        else if ((distance_of_centers == sum_of_radius || distance_of_centers == sub_of_radius) && distance_of_centers != 0)//case 2,6
            printf("1\n");
        else if (distance_of_centers > sub_of_radius && distance_of_centers < sum_of_radius)//case 3
            printf("2\n");
        else if (distance_of_centers < sub_of_radius)//case 4
            printf("0\n");
        else if (distance_of_centers == 0 && sub_of_radius == 0)//case 5
            printf("-1\n");
    }
}

 

728x90

'C, C++ > 백준' 카테고리의 다른 글

[백준] 2231 분해합  (0) 2024.02.22
[백준] 1546 평균  (1) 2024.02.15
[백준] 1436 영화감독 숌  (1) 2024.02.10
[백준] 1259 팬린드롬수  (1) 2024.02.10
[백준] 10828  (0) 2023.11.20
728x90

문제

정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 여섯 가지이다.

  • push X: 정수 X를 큐에 넣는 연산이다.
  • pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 큐에 들어있는 정수의 개수를 출력한다.
  • empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
  • front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
 

입력

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

 

'큐' 자료구조는  First In, First Out 의 구조를 가진다. 

따라서 스택과 달리 데이터 접근점이 두개(top, rear 혹은 left, right 혹은 front, back)가 필요하다.

데이터가 들어가는 지점을 하나 지정하고, 나오는 점을 하나 지정해야 한다.

 

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef enum{
    PUSH,
    POP,
    SIZE,
    EMPTY,
    FRONT,
    BACK,
    UNKNOWN    
} CommandType;

void push(int **q_front, int **q_back); //정수 X를 큐에 넣는 연산이다.
int pop(int **q_front, int **q_back); //큐에서 가장 앞에 있는 정수를 빼고, 그 수를 리턴한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 리턴한다.
int size(int **q_front, int **q_back); //큐에 들어있는 정수의 개수를 리턴한다.
int empty(int **q_front, int **q_back); //큐가 비어있으면 1, 아니면 0을 리턴한다.
int front(int **q_front, int **q_back); //큐의 가장 앞에 있는 정수를 리턴한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 리턴한다.
int back(int **q_front, int **q_back); //큐의 가장 뒤에 있는 정수를 리턴한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 리턴한다.

CommandType getCommandType(const char* input){
    if (strcmp(input, "push") == 0 || strcmp(input, "PUSH") == 0)
        return PUSH;
    else if (strcmp(input, "pop") == 0 || strcmp(input, "POP") == 0)
        return POP;
    else if (strcmp(input, "size") == 0 || strcmp(input, "SIZE") == 0)
        return SIZE;
    else if (strcmp(input, "empty") == 0 || strcmp(input, "EMPTY") == 0)
        return EMPTY;
    else if (strcmp(input, "front") == 0 || strcmp(input, "FRONT") == 0)
        return FRONT;
    else if (strcmp(input, "back") == 0 || strcmp(input, "BACK") == 0)
        return BACK;
    else 
        return UNKNOWN;
}

int main(int argc, char *argv[]){
    int number_of_commands = 0;
    int i = 0, j = 0;
    char user_input_command[6];
    int *queue;
    int *q_front, *q_back;

    scanf("%d",&number_of_commands);

    if(number_of_commands > 10000 || number_of_commands < 1)
        return -1;

    queue = (int *)malloc(sizeof(int)*number_of_commands);
    q_front = queue;
    q_back = queue;

    for(i = 0; i < number_of_commands; i++){
        scanf("%s", user_input_command);
        CommandType cmd = getCommandType(user_input_command);
        
        switch(cmd){
            case PUSH:
                push(&q_front, &q_back);
                break;
            case POP:
                printf("%d\n",pop(&q_front, &q_back));
                break;
            case SIZE:
                printf("%d\n",size(&q_front, &q_back));
                break;
            case EMPTY:
                printf("%d\n",empty(&q_front, &q_back));
                break;
            case FRONT:
                printf("%d\n",front(&q_front, &q_back));
                break;
            case BACK:
                printf("%d\n",back(&q_front, &q_back));
                break;
            case UNKNOWN:
                break;
            default:
                printf("Error on switch.\n");
                return -1;                
        }

        //memset(user_input_command, 0, sizeof(user_input_command));
    }
    free(queue);
    return 0;
}

void push(int **q_front, int **q_back){
    int X = 0;
    scanf("%d",&X);
    if(X <= 100000 && X >= 1){
        **q_back = X;
        (*q_back)++; 
    }
    
}//정수 X를 큐에 넣는 연산이다.

int pop(int **q_front, int **q_back){
    if(*q_front == *q_back)
        return -1;
    int temp = **q_front;
    (*q_front)++;
    return temp;
} //큐에서 가장 앞에 있는 정수를 빼고, 그 수를 리턴한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 리턴한다.

int size(int **q_front, int **q_back){
    if(*q_back == *q_front)
        return 0;
    else
        return (*q_back - *q_front);// / sizeof(int)라 생각했으나, 컴파일러에서 포인터간의 차를 계산할때 자동으로 타입 크기로 나눠준다고 한다!;
} //큐에 들어있는 정수의 개수를 리턴한다.

int empty(int **q_front, int **q_back){
    return *q_front == *q_back;
} //큐가 비어있으면 1, 아니면 0을 리턴한다.

int front(int **q_front, int **q_back){
    if(*q_front != *q_back)
        return **q_front;
    else
        return -1;
} //큐의 가장 앞에 있는 정수를 리턴한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 리턴한다.

int back(int **q_front, int **q_back){
    if(*q_front != *q_back)
        return *(*q_back-1);
    else
        return -1;
} //큐의 가장 뒤에 있는 정수를 리턴한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 리턴한다.

 

 

enum을 활용하여 switch_case구문으로 메뉴를 구성하였다. (3개 이상의 if문은 컴파일러에 따라 비효율적일 수 있다고 한다)

 

위 코드의 로직대로 공간을 할당하면, 큐의 크기를 push할 때 확인하지 않아도 된다는 장점이 있지만, 명령의 수만큼 공간을 할당하므로 실제 사용하는 양에 비해서 불필요할 정도로 공간을 할당한다. 따라서, 최적화를 위해서는 push를 할 때마다 malloc하는 방식을 생각해 볼 수도 있을 것 같다.

728x90

'자료구조론 > 백준' 카테고리의 다른 글

[백준] 11866 요세푸스 문제 0  (0) 2024.02.25
[백준] 10866 덱  (0) 2024.02.25
[백준] 2164 카드2  (1) 2024.02.24
[백준] 1966 프린터 큐  (1) 2024.02.24
[백준] 1874 스택 수열  (2) 2024.02.18
728x90

1. 직접 호출

void myFunction() {
    // 함수의 내용
}

int main() {
    myFunction(); // 함수 호출
    return 0;
}

 

2. 함수 포인터를 사용한 호출

void myFunction() {
    // 함수의 내용
}

int main() {
    void (*funcPtr)() = myFunction; // 함수 포인터 선언 및 초기화
    funcPtr(); // 함수 포인터를 통한 호출
    return 0;
}

 

3. 배열에 함수 포인터 저장

void functionA() { /*...*/ }
void functionB() { /*...*/ }

int main() {
    void (*funcArray[2])() = {functionA, functionB}; // 함수 포인터 배열
    funcArray[0](); // functionA 호출
    funcArray[1](); // functionB 호출
    return 0;
}

 

4. 콜백 함수

void myCallback(void (*callbackFunc)()) {
    // 콜백 함수 호출
    callbackFunc();
}

void myFunction() {
    // 함수 내용
}

int main() {
    myCallback(myFunction); // 콜백으로 함수 전달 및 실행
    return 0;
}

 

5. 구조체와 함수 포인터

typedef struct {
    void (*function)();
} MyStruct;

void myFunction() {
    // 함수 내용
}

int main() {
    MyStruct s;
    s.function = myFunction; // 구조체 내 함수 포인터 초기화
    s.function(); // 구조체를 통한 함수 호출
    return 0;
}

 

6. 라이브러리 함수와 함수 포인터

#include <dlfcn.h>

int main() {
    void *handle = dlopen("libmylibrary.so", RTLD_LAZY); // 동적 라이브러리 열기
    void (*myFunction)() = (void (*)())dlsym(handle, "myFunction"); // 함수 포인터 얻기
    myFunction(); // 함수 호출
    dlclose(handle); // 라이브러리 닫기
    return 0;
}
728x90

'C, C++' 카테고리의 다른 글

메타 프로그래밍  (0) 2024.02.15
'함수 이름'을 인자로 받아 해당 함수를 실행하는 방법들  (0) 2023.11.20
728x90
#define _CRT_SECURE_NO_WARNINGS	;
#include <stdio.h>
#include <stdlib.h> //malloc 사용을 위함
#include <string.h> // memset 사용을 위함
 


void clearBuffer() {
	int c;
	while ((c = getchar()) != '\n' && c != EOF) {}
}

int main(int argc, char* argv[])
{
	int reiteration = 0; //반복 횟수
	int arg = NULL; // opcode 인자
	//int result = 0; //fgets 리턴값
	char opcode[17] = { 0 }; //int형의 최대 크기가 10자리 숫자, 공백 1자리, 명령어가 최대 5글자, 스트링 마지막 널값 10 + 1 + 5 + 1= 17
	char input[17] = { 0 };

	scanf("%d", &reiteration);
	if (!(reiteration >= 1 && reiteration <= 10000))
		return 0;
	
	int *arr = (int *)malloc(sizeof(int) * reiteration);
	int index = 0;

	clearBuffer();

	for (int i = 0; i < reiteration; i++) //문자열을 매칭하여 해당하는 함수 실행
	{
		fgets(input, 17, stdin);
		sscanf(input, "%s %d", opcode, &arg);

		
		if (index >= 0) {
			if (strstr(input, "push") != NULL)
				arr[index++] = arg;

			else if (strstr(input, "pop") != NULL)
			{
				if (index != 0)
					printf("%d\n", arr[(index--) - 1]);
				else
					printf("-1\n");
			}
				

			else if (strstr(input, "size") != NULL)
				printf("%d\n",index);

			else if (strstr(input, "empty") != NULL)
				if (index == 0)
					printf("1\n");
				else
					printf("0\n");

			else if (strstr(input, "top") != NULL)
			{
				if (index != 0)
					printf("%d\n", arr[index - 1]);
				else
					printf("-1\n");
			}
				

			else
			{
				printf("opcode Error\n");
				return 0;
			}
		}
		else
			printf("index not valid\n");
		//clearBuffer();
	}
	memset(arr, '0', 17);
	memset(input, '0', 17);

}
728x90

'C, C++ > 백준' 카테고리의 다른 글

[백준] 2231 분해합  (0) 2024.02.22
[백준] 1546 평균  (1) 2024.02.15
[백준] 1436 영화감독 숌  (1) 2024.02.10
[백준] 1259 팬린드롬수  (1) 2024.02.10
[백준] 1002번 터렛  (0) 2023.12.26
728x90

1. 함수 포인터와 switch 문 사용

#include <stdio.h>
#include <string.h>

// 함수 정의
void functionA() { printf("Function A\n"); }
void functionB() { printf("Function B\n"); }
void functionC() { printf("Function C\n"); }

enum FunctionName { A, B, C, UNKNOWN };

// 함수 이름을 열거형 값으로 변환
enum FunctionName getFunctionName(const char *name) {
    if (strcmp(name, "A") == 0) return A;
    if (strcmp(name, "B") == 0) return B;
    if (strcmp(name, "C") == 0) return C;
    return UNKNOWN;
}

int main() {
    char input[50];
    printf("Enter function name: ");
    scanf("%s", input);

    switch (getFunctionName(input)) {
        case A: functionA(); break;
        case B: functionB(); break;
        case C: functionC(); break;
        default: printf("Unknown function\n");
    }

    return 0;
}

 

 

2. 조건문과 함수 매핑

#include <stdio.h>
#include <string.h>

// 함수 정의
void functionA() { printf("Function A\n"); }
void functionB() { printf("Function B\n"); }

int main() {
    char funcName[50];
    printf("Enter the function name: ");
    scanf("%s", funcName);

    if (strcmp(funcName, "functionA") == 0) {
        functionA();
    } else if (strcmp(funcName, "functionB") == 0) {
        functionB();
    } else {
        printf("Function not found.\n");
    }

    return 0;
}

 

 

3. 함수 포인터와 배열 사용

#include <stdio.h>
#include <stdlib.h>

// 함수 정의
void functionA() { printf("Function A\n"); }
void functionB() { printf("Function B\n"); }
void functionC() { printf("Function C\n"); }

// 함수 포인터 배열
void (*functions[3])() = {functionA, functionB, functionC};

int main() {
    int choice;
    printf("Enter the function index (0-2): ");
    scanf("%d", &choice);

    if (choice >= 0 && choice < 3) {
        (*functions[choice])();
    } else {
        printf("Invalid index.\n");
    }

    return 0;
}

 

 

4. 명령 패턴 사용

#include <stdio.h>
#include <string.h>

typedef struct Command {
    void (*execute)();
} Command;

void functionA() { printf("Function A\n"); }
void functionB() { printf("Function B\n"); }

Command createCommand(void (*func)()) {
    Command cmd;
    cmd.execute = func;
    return cmd;
}

int main() {
    char funcName[50];
    printf("Enter the command name (A/B): ");
    scanf("%s", funcName);

    Command cmd;
    if (strcmp(funcName, "A") == 0) {
        cmd = createCommand(functionA);
    } else if (strcmp(funcName, "B") == 0) {
        cmd = createCommand(functionB);
    } else {
        printf("Invalid command.\n");
        return 1;
    }

    cmd.execute();
    return 0;
}
728x90

'C, C++' 카테고리의 다른 글

메타 프로그래밍  (0) 2024.02.15
함수 호출 방법들  (0) 2023.12.24

+ Recent posts