Completed SRM 597.cpp