관리 메뉴

Mini

백준 1107 리모컨 c++ // 완탐, 초기값 잘 설정하는법 본문

Algorithm/완전탐색

백준 1107 리모컨 c++ // 완탐, 초기값 잘 설정하는법

Mini_96 2023. 11. 28. 16:44

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

 

1107번: 리모컨

첫째 줄에 수빈이가 이동하려고 하는 채널 N (0 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 고장난 버튼의 개수 M (0 ≤ M ≤ 10)이 주어진다. 고장난 버튼이 있는 경우에는 셋째 줄에는 고장난 버튼이

www.acmicpc.net

1. 초기값 잘 설정하는법

ret=abs(100-n)

초기값을 100번에서 노가다하는 경우로 설정 => 이것보다 작은게 있을때만 정답이 갱신됨

 

2. 전체코드

#include <bits/stdc++.h>
using namespace std;

int n,m,dead[10],ret1,ret2;

//번호n을 누를수 잇는지 체크
int check(int n) {
	string s = to_string(n);
	for (int i = 0; i < s.size(); ++i) {
		if (dead[s[i] - '0']) return 0;
	}
	return 1;
}
int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);

	cin >> n >> m;
	for (int i = 0; i < m; ++i) {
		int temp;
		cin >> temp;
		dead[temp] = 1;
	}

	if (n == 100) {
		cout << 0;
		return 0;
	}
	ret1 = abs(100 - n); //초기값: 100에서 노가다하는 경우!

	for (int i = 0; i <= 500000 * 2; ++i) {
		if (!check(i)) continue;
		//2. 누르고 노가다
		int a = abs(n - i);
		int b = to_string(i).size();
		//if (ret2 > a) cout << a << "\n";
		ret1 = min(ret1, a+b);

	}
	string s = to_string(n);
	cout << ret1;
	
	return 0;
}