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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /*건물의 목표 전력량과 시간별 전력량을 비교하여라.*/ #include <iostream> #include <string> using namespace std; int main(){ int count; //테스트케이스 수 char *time_w; //건물의 시간별 사용 전력량 int w; //건물의 목표 전력량 string time; //시간별 전력량을 연산하기 위해 필요한 임시변수 int sum_w = 0; //시간별 전력량을 모두 더한 값을 저장할 변수 string *result; //목표전력량을 지켰는지를 저장할 변수 string sub_time; //시간별 전력량을 숫자로 변환하기 위해 필요한 변수 time_w = new char[4*9+9]; cin>>count; result = new string[count]; //테스트케이스만큼 YES/NO 입력하므로 동일하게 할당 cin.ignore(); for(int i=0;i<count;i++){ cin>>w; //목표 전력량 입력받음 cin.ignore(); fgets(time_w, 4*9+9, stdin); //0~1000까지 4자가 9번 들어감+ 빈칸 8 + null 1 입력받음 time = time_w; time.pop_back(); //개행문자 삭제 while(!time.empty()){ //문자열이 빌 때 까지 - 모든 시간별 전력량을 더했을 시 sub_time = time.substr(0, time.find(" ")); sum_w += atoi(sub_time.c_str()); if(time.length()==sub_time.length()){ time.erase(0, sub_time.length()); } time.erase(0, time.find(" ")+1); } if(sum_w<=w){ result[i] = "YES"; } else{ result[i] = "NO"; } //사용한 변수 초기화 time.clear(); sum_w = 0; } for(int i=0;i<count;i++){ cout<<result[i]<<endl; } delete []result; delete []time_w; return 0; } | cs |
멍청하게 식을 잡는 바람에 고생했다ㅠㅠ
당연히 입력받는 시간들이 2자리 고정이 아닌데 2자리 고정으로 생각하고 프로그래밍했다;
string 임시변수를 하나 만들어서 공백을 찾을 수 없는 맨 끝 수치는 길이만큼 삭제했다.
find+1이 빠를까 아님 length+1이 더 빠를까. 후자가 더 빠를거 같음.