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
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <stdint.h>
#include <vector>

struct CacheKey {
  CacheKey(int start, int size, int teams_nr) : start(start), size(size), teams_nr(teams_nr) {}

  int start;
  int size;
  int teams_nr;

  friend bool operator<(const CacheKey &l, const CacheKey &r) {
    return std::tie(l.start, l.size, l.teams_nr) < std::tie(r.start, r.size, r.teams_nr);
  }
};

std::map<CacheKey, int64_t> g_cache;

std::vector<int64_t> count_teams(const std::vector<int64_t> &soldiers,
                                 const int K) {
  std::vector<int64_t> teams(soldiers.size() - K + 1);

  teams[0] = std::accumulate(soldiers.begin(), soldiers.begin() + K, 0);

  for (int i = 1; i < ((int)soldiers.size()) - K + 1; ++i) {
    teams[i] = teams[i - 1] - soldiers[i - 1] + soldiers[i + K - 1];
  }

  // DEBUG
  //  for (auto i : teams) {
  //    fprintf(stderr, "%ld\n", i);
  //  }

  return teams;
}

int64_t count_max(const std::vector<int64_t> &soldiers,
                  const std::vector<int64_t> &teams, const int K, int start,
                  int size, int teams_nr) {
  // DEBUG
  //  fprintf(stderr, "start: %d size: %d teams_nr: %d\n", start, size,
  //  teams_nr);

  if (teams_nr == 0 || size < K) {
    return 0;
  }

  CacheKey key(start, size, teams_nr);
  {
    auto iter = g_cache.find(key);
    if (iter != g_cache.end()) {
      return iter->second;
    }
  }

  int64_t max = 0;

  const int end = start + size - K + 1;
  for (int i = start; i < end; ++i) {
    // DEBUG
    //    fprintf(stderr, "i: %d, size: %d max: %ld\n", i, end, max);

    max = std::max(max,
                   teams[i] + count_max(soldiers, teams, K, i + K,
                                        size - (i + K - start), teams_nr - 1));
  }

  // DEBUG
  //  fprintf(stderr, "max: %ld\n", max);

  g_cache.insert(std::make_pair(key, max));
  return max;
}

int main() {
  int N = 0;
  int K = 0;
  int Q = 0;

  std::cin >> N;
  std::cin >> K;
  std::cin >> Q;

  std::vector<int64_t> soldiers(N);

  for (int i = 0; i < N; ++i) {
    std::cin >> soldiers[i];
  }

  ///////////////////////////

  const std::vector<int64_t> teams = count_teams(soldiers, K);

  for (int i = 0; i < Q; ++i) {
    int L = 0;
    int R = 0;

    std::cin >> L;
    std::cin >> R;

    std::cout << count_max(soldiers, teams, K, L - 1, R - L + 1,
                           (R - L + 1) / K)
              << std::endl;

    // DEBUG
    //    break;
  }

  return 0;
}