Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- pycon
- 트라이
- Spring Boot
- 트라이 #trie #알고리즘
- Tistory
- trie
- 프로그래머스
- Python
- CleanCode
- bulk update
- 크레인 인형뽑기 게임
- 호텔 방 배정
- 카카오 인턴
- 가사 검색
- 불량 사용자
- 티스토리 open api
- jdbc
- Open API
- 튜플
- 보행자 천국
- 알고리즘
- 징검다리 건너기
- 티스토리
Archives
- Today
- Total
택시짱의 개발 노트
[프로그래머스] 조이스틱 본문
링크
https://programmers.co.kr/learn/courses/30/lessons/42860
코딩테스트 연습 - 조이스틱 | 프로그래머스
조이스틱으로 알파벳 이름을 완성하세요. 맨 처음엔 A로만 이루어져 있습니다. ex) 완성해야 하는 이름이 세 글자면 AAA, 네 글자면 AAAA 조이스틱을 각 방향으로 움직이면 아래와 같습니다. ▲ - 다음 알파벳 ▼ - 이전 알파벳 (A에서 아래쪽으로 이동하면 Z로) ◀ - 커서를 왼쪽으로 이동 (첫 번째 위치에서 왼쪽으로 이동하면 마지막 문자에 커서) ▶ - 커서를 오른쪽으로 이동 예를 들어 아래의 방법으로 JAZ를 만들 수 있습니다. - 첫 번째 위
programmers.co.kr
풀이
이름 name이 매개변수로 주어질 때, 이름에 대해 조이스틱 조작 횟수의 최솟값을 구하는 문제인데.
1. 현재 위치에서 커서를 왼쪽 또는 오른쪽으로 가장 적게 움직여 'A'가 아닌 알파벳을 찾아야 한다.
2. 그 후 알파벳을 올리거나 내렸을때 가장 적게 바꿀수 있는 횟수를 구한다.
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<string>
#include<set>
#include<map>
#include<cstring>
#include<functional>
#include<cmath>
#define SIZE 1010
const int INF = 2000000000;
using namespace std;
typedef long long int ll;
//0에서 왼쪽으로 갈때, 알파벳크기 이상으로 넘어갔을때
int find_index(string name, int index) {
int n_size = name.size();
if (index < 0)
return n_size - 1;
if (index >= n_size)
return 0;
return index;
}
//현재 알파벳과 A와의 거리 차이
int dis(string & name, int index, char alpa) {
name[index] = 'A';
if (alpa <= 'M') {
return alpa - 'A';
}
return 26 - (alpa - 'A');
}
//왼쪽으로 이동
pair<int,int> move_left(string name, int index) {
int cnt = 1;
while (1) {
if (name[index = find_index(name, index - 1)] != 'A')
break;
cnt++;
}
return{ index,cnt };
}
//오른쪽으로 이동
pair<int,int> move_right(string name, int index) {
int cnt = 1;
while (1) {
if (name[index = find_index(name, index + 1)] != 'A')
break;
cnt++;
}
return{ index,cnt };
}
int solution(string name) {
int index = 0, cnt = dis(name,index, name[0]);
string judge (name.size(), 'A');
while (name != judge) {
int left, right; left = right = index;
int l_index,l_cnt, r_index,r_cnt;
tie(l_index,l_cnt) = move_left(name, index);
tie(r_index,r_cnt)= move_right(name, index);
//left가 더 짧을 때
if (l_cnt < r_cnt) {
cnt += l_cnt + dis(name,l_index,name[l_index]);
index = l_index;
}
//right가 더 짧을 때
else {
cnt += r_cnt + dis(name, r_index, name[r_index]);
index = r_index;
}
}
return cnt;
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
string s; cin >> s;
cout << solution(s);
}
반응형
'알고리즘' 카테고리의 다른 글
[프로그래머스] 도둑질 (0) | 2020.03.15 |
---|---|
[프로그래머스] 후보키 (0) | 2020.03.12 |
[프로그래머스] 자물쇠와 열쇠 (0) | 2020.03.08 |
[프로그래머스] 괄호 변환 (0) | 2020.03.08 |
[프로그래머스] 문자열 압축 (0) | 2020.03.08 |
Comments