SRM168 Div2 Easy : StairClimb

書いてる途中で全選択→BSのコンボを決めてしまった…

TopCoder参戦のための練習として過去問から適当に問題を選んでC++で書いていきます。俺のC++経験は"Hello, World"止まりなので、C++の勉強も兼ねてます。

この記事を読んで「ここはこうした方がいい」とか「こんなコード書く奴はクソ」とか思ったらバシバシ指摘して頂けるとありがたいです。よろしくお願いします。

問題

Div2 Easyという一番簡単なところから。

You are climbing a staircase. The staircase consists of some number of flights of stairs separated by landings. A flight is a a continuous series of stairs from one landing to another. You are a reasonably tall athletic person, so you can climb a certain number of stairs in one stride. However, after each flight, there is a landing which you cannot skip because you need to turn around for the next flight (which continues in the opposite direction).


You will be given the number of stairs in each flight in a int[] flights. Element 0 of flights represents the number of stairs in the first flight, element 1 is the number of stairs in the second flight, etc. You will also be given an int stairsPerStride, which is how many continuous stairs you climb in each stride. If it takes two strides to turn around at a landing, return the number of strides to get to the top of the staircase. You do not need to turn at the top of the staircase.

適当に訳すと

踊り場の間の階段の段数教えてやるから、何歩で頂上まで行けるか教えれ。お前背高いから結構段飛ばしでいけるよな。でも踊り場はいくらお前でも2歩かかるんだわ。

ということで特に何も考えずそのまま実装。その実装がしんどかったんだけれども…。

プログラム

stairClimb.cpp

#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <fstream>
#include <cstring>
using namespace std;

class StairClimb {
public:
  int stridesTaken(vector<int> flights, int stairsPerStride) {
    int i, n = flights.size();
    int strides = 0;

    for (i = 0; i < n; i++) {
      flights[i] % stairsPerStride == 0 ? strides += flights[i] / stairsPerStride : strides += flights[i] / stairsPerStride + 1;
    }

    strides += (n - 1) * 2;
    
    return strides;
  }
};
  
int main(int argc, char** argv) {
  vector<int> f;
  int sps = atoi(argv[1]);
  
  for (int i = 2; i < argc; i++) {
    int j = atoi(argv[i]);
    f.push_back(j);
  }

  StairClimb sc;
  int strds = sc.stridesTaken(f, sps);

  cout << strds << endl;
}

実行例

./stairClimb.cpp 5 25 18 24 5 24 24 17 23 10 9 22 25 27 22 16 17 12                                               
102

所感

とにかくC++で書くのがキツかった。Twitterでかなり恥ずかしいPostを連発していた。最初配列で書こうとして、配列の要素数をsizeof()で取ろうとしたところ、関数の引数で渡した場合はポインタで渡されるので要素数が全然取れずにハマった。vector使うとあっさりできて感動した。あとincludeしてるライブラリは id:cou929_la さんのからかっぱらってきただけなのでさっぱり理解していない。