본문 바로가기
알고리즘/SWEA

SWEA(Solution코드만 수정하면 끝) - C++ 보물상자 비밀번호

by 꾸준하곰 2021. 10. 13.

단순 구현문제이다. 시뮬레이션 문제라고 한다.

 

vector에 rotation(= N / 4)만큼의 인덱스를 추가하면, 문제가 간단해진다.

 


1. Solution 코드

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

vector<string> numbers;

void Rotate(vector<string> num, int N);
void Sort(vector<string>& numbers, int rotation);

int main(int argc, char** argv) {
	int test_case;
	int T;
	int N, K;

	freopen("input.txt", "r", stdin);

	cin >> T;

	for (test_case = 1; test_case < T; ++test_case) {
		// 여러분의 구현이 들어갑니다.
		cin >> N >> K;	
		string n;
		cin >> n;
		vector<string> num(N);
		for (int i = 0; i < N; i++)
			num[i] = n.substr(i, 1);

		Rotate(num, N);

		cout << '#' << test_case << " " << numbers[K - 1] << '\n';
	}

	return 0;
}

void Rotate(vector<string> num, int N) {
	numbers.assign(N, "");
	int rotation = N / 4;
	int index = 0;

	for (int point = 0; point < 4; point += (rotation - 1)) {
		for (int cnt = 0; cnt < N; cnt += rotation) {
			int count = 0;
			for (int k = point+ cnt; count < rotation; k++) {
				if (k > N - 1) {
					k %= N;
				}
				numbers[index] += num[k];
				count++;
			}
			index++;
		}
	}
	Sort(numbers, rotation);
}

void Sort(vector<string>& numbers, int rotation) {
	vector<int> dex;

	// 16진법 -> 10진법
	for (int i = 0; i < numbers.size(); i++) 
		dex[i] = strtol(numbers[i], NULL, 16);
	

	// 내림차순
	sort(dex.rbegin(), dex.rend());

	// dex에 중복 있으면 하나 삭제
	for (int i = 0; i < numbers.size(); i++) {
		if (numbers[i] == numbers[i + 1] && i < numbers.size() - 1)
			numbers.erase(numbers.begin() + i);
	}
}

input.txt 은 프로젝트의 리소스 파일에 포함시켜주기

더보기

5
12 10
1B3B3B81F75E
16 2
F53586D76286B2D8
20 14
88F611AE414A751A767B
24 16
044D3EBA6A647B2567A91D0E
28 11
8E0B7DD258D4122317E3ADBFEA99

 

2. 알아야 할 개념

1) 내림차순

// 오름차순
sort(vector.begin(), vector.end());

// 내림차순
sort(vector.rbegin(), vector.rend());

2) 삼성 코딩테스트 꿀팁

// cout에서 endl 대신 '\n' 사용하기
cout <<   << endl;
cout <<   << '\n';

 

3) 부분 문자열 출력

// substr(시작위치, 길이)
string str = "Hello";
str.substr(1, 3);


=> 출력 : ell

 

4) freopen("input.txt", "r", stdin)

#include <stdlib.h>

int main(){
	int T, N, K;
    
	freopen("input.txt", "r", stdin);
    
    cin >> T;
    cin >> N;
    cin >> K;
}



=> input.txt에 저장된 값을 cin이 입력받을 변수 T, N, K에 입력해준다.
   즉, 사용자의 입력이 필요없다.

 

5) sting to int

// string to int
stoi(str);

// string to float
stof(str);

 

6) 16진수 -> 10진수 변환

hex2dec(string str)함수를 구현하자

int hex2dec(string hex) {
	int len = hex.length();
	int base = 1;
	int ret = 0;

	for (int i = len - 1; i >= 0; i--) {
		if (hex[i] >= '0' && hex[i] <= '9')
			ret += (hex[i] - 48) * base;
		else if (hex[i] >= 'A' && hex[i] <= 'F')
			ret += (hex[i] - 55) * base;
		else if (hex[i] >= 'a' && hex[i] <= 'f')
			ret += (hex[i] - 87) * base;

		base *= 16;
	}

	return ret;
}

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

[삼성기출] 백준 - C++ 상어 중학교  (0) 2021.10.23

댓글