첫째 줄에 채널 N으로 이동하기 위해 버튼을 최소 몇 번 눌러야 하는지를 출력한다.
이 문제는 예전에 C++으로 풀었던 적이 있는데 파이썬으로도 풀어보고 싶어졌다.
아래는 C++로 풀었을 때의 코드이다.
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
bool channel[10];
int check(int i);
int main()
{
ios_base::sync_with_stdio(false);
//freopen("input.txt","r",stdin);
int N, M;
cin >> N >> M;
memset(channel,false,sizeof(channel));
for(int i=0; i<M; i++)
{
int num;
cin >> num;
channel[num] = true;
}
int result = abs(N-100);
for(int i=0; i<=1000000; i++)
{
int len = check(i);
if(len != 0)
{
result = min(result,len+abs(N-i));
}
}
cout << result << '\n';
return 0;
}
int check(int i)
{
string str = to_string(i);
int len = str.length();
int count=0;
for(int i=0; i<len ; i++)
{
if( channel [ int(str.at(i)-'0') ] == true )
{
return 0;
}
else
{
count++;
}
}
return count;
}
고장나지 않은 채널들로 구성할 수 있는지를 체크하는 방법이다.
그러나 이번 파이썬으로는 조금 다르게 풀어보았다.
import sys
sys.stdin = open("input.txt","r",encoding="utf-16")
remote_controller = ['0','1','2','3','4','5','6','7','8','9','+','-']
goal_channel = int( input() )
num_malfun = int( input() )
malfun_list=[]
if num_malfun != 0:
malfun_list = list(input().split())
for i in malfun_list:
remote_controller.remove(i)
cur_channel = 100
# only + or -
only_up_down = None
if goal_channel >= cur_channel and '+' in remote_controller:
only_up_down = goal_channel - cur_channel
elif goal_channel < cur_channel and '-' in remote_controller:
only_up_down = cur_channel - goal_channel
# +,- and channel btn
use_anything = [500000]
if remote_controller != ['+','-']:
permutation_length = len(str(goal_channel))
permutations = set()
temp = [''] * permutation_length
remote_controller_only_btn = list(remote_controller)
remote_controller_only_btn.remove('+')
remote_controller_only_btn.remove('-')
def make_permutation(deepness, length):
if deepness == length:
if only_up_down > abs(goal_channel-int(''.join(temp))):
permutations.add( ''.join(temp) )
else:
for i in remote_controller_only_btn:
temp[deepness] = i
make_permutation(deepness+1,length)
for i in range(-1,2,1):
if permutation_length+i <1:
continue
else:
temp = [''] * (permutation_length+i)
make_permutation(0,permutation_length+i)
try:
permutations.remove( "0"*(permutation_length+i) )
permutations.add("0")
except:
pass
if permutations != set():
permutations = map(lambda x : abs( int(x) - goal_channel)
, permutations)
m = min(permutations)
use_anything.append( m + permutation_length+i )
permutations= set()
print( min( [only_up_down, min(use_anything)] ) )
먼저 채널버튼으로만 이동할 수 있는 최솟값을 구하고.
채널버튼으로만 이동할 수 있는 최솟값이랑 비교하여 더 작을 경우 저장한다.
이렇게 순열로 만든 값들중에 최솟값을 구한다.