C언어/문제풀다 하나씩

binary search 구현2 서재에서 책 찾기

mcdn 2020. 5. 23. 12:49
반응형

 

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int n;
string shelf[10];
int m;
int ans = 100;
string mlist[10];
int timelist[10];
int bin_search(int start, int end, string target, int lev) {
	//cout << lev << "st:" << start << "en:" << end << endl;
	if (start > end) {
		ans = 100;
		return 100;
	}
	int mid = (start + end) / 2;
	if (shelf[mid] == target) {
		ans = lev;
		return lev;
	}
	else if (shelf[mid] > target) {
		bin_search(start, mid - 1, target, lev + 1);
	}
	else {
		bin_search(mid + 1, end, target, lev + 1);
	}
	return ans;
}

int main() {
	cin >> n;
	for (int i = 0; i < n;i++) {
		cin >> shelf[i];
	}
	sort(&shelf[0], &shelf[n]);
	cin >> m;
	for (int i = 0;i < m;i++) {
		cin >> mlist[i] >> timelist[i];
	}
	for (int i = 0;i < m;i++) {
		
		int lev = bin_search(0, n-1, mlist[i], 1);
		if (lev <= timelist[i]) {
			cout <<"pass" << endl;
		}
		else {
			cout << "fail" << endl;
		}
	}
}

입력 예제

6 Rabbit Moon Opening Alien Power Ai 3 Opening 5 Alien 2 Ai 2

출력 결과

pass fail pass

 

 

으어 계속 에러남 

 

int bin_search(int start, int end, string target, int lev) {
//cout << lev << "st:" << start << "en:" << end << endl;
if (start > end) {
ans = 100;
return 100;
}

이부분에서 ans = 100 안해주니까 계속 에러남;; abcde 10 에서

왜지???????

반응형