SRM150 Div.2 Easy WidgetRepairs
この頃なんか親から色々言われて
結構耳が痛いです(笑)
分けて考える
PROBLEM STATEMENT When a widget breaks, it is sent to the widget repair shop, which is capable of repairing at most numPerDay widgets per day. Given a record of the number of widgets that arrive at the shop each morning, your task is to determine how many days the shop must operate to repair all the widgets, not counting any days the shop spends entirely idle. For example, suppose the shop is capable of repairing at most 8 widgets per day, and over a stretch of 5 days, it receives 10, 0, 0, 4, and 20 widgets, respectively. The shop would operate on days 1 and 2, sit idle on day 3, and operate again on days 4 through 7. In total, the shop would operate for 6 days to repair all the widgets. Create a class WidgetRepairs containing a method days that takes a sequence of arrival counts arrivals (of type vector) and an int numPerDay, and calculates the number of days of operation. DEFINITION Class:WidgetRepairs Method:days Parameters:vector , int Returns:int Method signature:int days(vector arrivals, int numPerDay) CONSTRAINTS
- arrivals contains between 1 and 20 elements, inclusive.
- Each element of arrivals is between 0 and 100, inclusive.
- numPerDay is between 1 and 50, inclusive.
一日の仕事量が決まっていて、日毎に入ってくる仕事の数与えられるからそれを何日で終えられるか?ただし仕事がない日はカウントしない。
という問題。
仕事が増えていく(配列の長さ分)と、余った仕事を片付けるという二つのループで考えるとうまくいきます。
class WidgetRepairs { public: int days(vector <int> arrivals, int numPerDay) { int count = 0, sum = 0, i = 0; while (i<arrivals.size()) { sum += arrivals[i]; if (sum == 0) { i++; continue; } else { sum -= numPerDay; } if (sum < 0) sum = 0; count++; i++; } while (sum > 0) { sum -= numPerDay; count++; } return count; } };
一つのループでダメだったときはこういう思考も大事ですね。