Problem p02618 (C++) — buggy submission, verdict: Time Limit Exceeded

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)
#define reps(i, n) for (int i = 1, i##_len = (n); i <= i##_len; ++i)
#define rrep(i, n) for (int i = ((int)(n)-1); i >= 0; --i)
#define rreps(i, n) for (int i = ((int)(n)); i > 0; --i)
#define range_for(i, b, e) for (int i = (b), i##_len = (e); i <= i##_len; ++i)
#define step(n) rep(_, n)
#define ALL(x) (x).begin(), (x).end()
#define RALL(x) (x).rbegin(), (x).rend()
#define Unique(a) a.erase(unique(ALL(a)), a.end())
#define pb push_back
#define len(x) ((int)(x).size())
#define optimize_cin()                                                         \\
  cin.tie(0);                                                                  \\
  ios::sync_with_stdio(false)
#define debug(x) std::cerr << #x << ": " << (x) << endl;
#define LINT_MAX (LLONG_MAX)
#define LINT_MIN (LLONG_MIN)
#define cauto const auto
#define int long long
#define float long double
using namespace std;
template <class Type> inline constexpr Type Square(Type x) { return x * x; }
template <class Type>
inline constexpr bool InRange(const Type &x, const Type &i, const Type &a) {
  return (i <= x) && (x <= a);
}
template <class Integer> bool chmax(Integer &a, const Integer &b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class Integer> bool chmin(Integer &a, const Integer &b) {
  if (b < a) {
    a = b;
    return 1;
  }
  return 0;
}
template <class Integer> bool IsOdd(Integer &n) { return n & 1; }
template <class Integer> bool IsEven(Integer &n) { return !(n & 1); }
long long gcd(long long a, long long b) {
  while (b) {
    long long A = a;
    (a = b), (b = A % b);
  }
  return a;
}
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
int ctoi(const char c) { return ('0' <= c && c <= '9') ? (c - '0') : -1; }
string YesNo(bool b) { return b ? "Yes" : "No"; }
string YESNO(bool b) { return b ? "YES" : "NO"; }
string yesno(bool b) { return b ? "yes" : "no"; }
void _cin() {}
template <class Head, class... Tail> void _cin(Head &&head, Tail &&...tail) {
  cin >> head;
  _cin(forward<Tail>(tail)...);
}
#define Cin(Type, ...)                                                         \\
  Type __VA_ARGS__;                                                            \\
  _cin(__VA_ARGS__)
#define Cinv(Type, xs, n)                                                      \\
  vector<Type> xs(n);                                                          \\
  rep(i, n) cin >> xs[i]
#define Cinv2(Type, xs, ys, n)                                                 \\
  vector<Type> xs(n), ys(n);                                                   \\
  rep(i, n) cin >> xs[i] >> ys[i]
#define Cinv3(Type, xs, ys, zs, n)                                             \\
  vector<Type> xs(n), ys(n), zs(n);                                            \\
  rep(i, n) cin >> xs[i] >> ys[i] >> zs[i]
#define Cinvv(Type, xs, h, w)                                                  \\
  vector<vector<Type>> xs(h, vector<int>(w));                                  \\
  rep(i, h) rep(j, w) cin >> xs[i][j]
void Print() { cout << endl; }
template <class Head, class... Tail> void Print(Head &&head, Tail &&...tail) {
  cout << head;
  if (sizeof...(tail) != 0)
    cout << " ";
  Print(forward<Tail>(tail)...);
}
template <class Type> void Print(vector<Type> &vec) {
  for (auto &a : vec) {
    cout << a;
    if (&a != &vec.back())
      cout << " ";
  }
  cout << endl;
}
template <class Type> void Print(vector<vector<Type>> &df) {
  for (auto &vec : df) {
    Print(vec);
  }
}
void Debug() { cerr << endl; }
template <class Head, class... Tail> void Debug(Head &&head, Tail &&...tail) {
  cerr << head;
  if (sizeof...(tail) != 0)
    cerr << " ";
  Debug(forward<Tail>(tail)...);
}
template <class Type> void Debug(vector<Type> &vec) {
  for (auto &a : vec) {
    cerr << a;
    if (&a != &vec.back())
      cerr << " ";
  }
  cerr << endl;
}
template <class Type> void Debug(vector<vector<Type>> &df) {
  for (auto &vec : df) {
    Debug(vec);
  }
}

std::chrono::system_clock::time_point start, end__;

int Score(int D, const vector<int> &c, const vector<vector<int>> &s,
          const vector<int> &t) {
  vector<int> last(26);
  int value = 0;
  rep(d, D) {
    int i = t[d];
    value += s[d][i];
    last[i] = d + 1;
    rep(k, 26) { value -= c[k] * (d + 1 - last[k]); }
  }
  return value;
}

using P = pair<int, int>;
bool comp(const P &firstElof, const P &secondElof) {
  return firstElof.second > secondElof.second;
}

struct State {
  State() : score(0), idx(0) {}
  State(const vector<int> &_t, int _score, int i)
      : t(_t), score(_score), idx(i) {}
  static void Init(int _D, const vector<int> &_c,
                   const vector<vector<int>> &_s) {
    D = _D;
    c = _c;
    s = _s;
  }
  State added(int _t) {
    vector<int> tmp_t = t;
    int tmp_score = score;
    int tmp_idx = idx;
    tmp_t.pb(_t);
    tmp_score = Score(tmp_idx + 1, c, s, tmp_t);
    return State(tmp_t, tmp_score, tmp_idx + 1);
  }

  int score;
  vector<int> t;
  int idx;

  static int D;
  static vector<int> c;
  static vector<vector<int>> s;
};

bool operator<(const State &left, const State &right) {
  return left.score < right.score;
}

int State::D = 0;
vector<int> State::c = vector<int>();
vector<vector<int>> State::s = vector<vector<int>>();

vector<int> Beam(int D, const vector<int> &c, const vector<vector<int>> &s) {
  double elapsed;
  State::Init(D, c, s);
  State fst = State();
  priority_queue<State> que;
  que.push(fst);
  priority_queue<State> q;
  while (!que.empty()) {
    assert(!que.empty());
    State now = que.top();
    que.pop();
    q.push(now);
    if (now.idx == 6 - 1)
      continue;

    rep(type, 26) {
      State next = now.added(type);
      if (len(que) < 100000) {
        que.push(next);
      }
    }

    end__ = chrono::system_clock::now();
    elapsed =
        std::chrono::duration_cast<std::chrono::milliseconds>(end__ - start)
            .count();
    if (elapsed > 800) {
      break;
    }
  }
  State top_state = q.top();
  vector<int> t = top_state.t;
  range_for(d, len(t), D - 1) {
    int m = INT_MIN;
    int index = 0;
    t.push_back(0);
    rep(type, 26) {
      t[d] = type;
      if (chmax(m, s[d][type])) {
        index = type;
      }
    }

    t[d] = index;
  }
  return t;
}

vector<int> greedy(int D, const vector<int> &c, const vector<vector<int>> &s) {
  static random_device rnd;
  static mt19937 mt(rnd());

  vector<int> t(D);
  queue<P> que;
  rep(d, D) {
    int m = INT_MIN;
    int index = 0;
    rep(type, 26) {
      t[d] = type;
      if (chmax(m, Score(d, c, s, t))) {
        index = type;
      }
    }

    t[d] = index;
  }

  return t;
}

vector<int> calc_t(int D, const vector<int> &c, const vector<vector<int>> &s) {
  static random_device rnd;
  static mt19937 mt(rnd());
  static uniform_int_distribution<> randday(0, D - 1);
  static uniform_int_distribution<> randtype(0, 25);
  vector<int> t = Beam(D, c, s);
  // vector<int> t = random_method(D);

  assert(len(t) == D);
  double elapsed;
  bool changed = true;
  int old_score, new_score;
  vector<int> buff;
  int cnt = 0;
  do {
    cnt = (cnt + 1) % 100;
    int day = randday(mt);
    int type = randtype(mt);

    int old = t[day];
    if (changed) {
      old_score = Score(D, c, s, t);
    }
    t[day] = type;
    new_score = Score(D, c, s, t);

    if (old_score >= new_score) {
      t[day] = old;
      changed = false;
    } else {
      changed = true;
    }

    int left_idx = randday(mt);
    int right_idx = randday(mt);
    if (changed) {
      old_score = Score(D, c, s, t);
    }
    swap(t[left_idx], t[right_idx]);
    new_score = Score(D, c, s, t);
    if (old_score >= new_score) {
      swap(t[left_idx], t[right_idx]);
      changed = false;
    } else {
      changed = true;
    }

    end__ = chrono::system_clock::now();
    elapsed =
        std::chrono::duration_cast<std::chrono::milliseconds>(end__ - start)
            .count();
  } while (elapsed < 1800);

  return t;
}

signed main() {
  start = chrono::system_clock::now();
  // in
  Cin(int, D);
  Cinv(int, c, 26);
  Cinvv(int, s, D, 26);
  vector<int> t = calc_t(D, c, s);
  // vector<int> t = greedy(D,c,s);

  rep(i, len(t)) Print(t[i] + 1);

  // Debug("=== score ===");
  // Debug(score(D, c, s, t));
  // Debug("=============");

  return 0;
}


Error: TLE

Fixed submission:

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)
#define reps(i, n) for (int i = 1, i##_len = (n); i <= i##_len; ++i)
#define rrep(i, n) for (int i = ((int)(n)-1); i >= 0; --i)
#define rreps(i, n) for (int i = ((int)(n)); i > 0; --i)
#define range_for(i, b, e) for (int i = (b), i##_len = (e); i <= i##_len; ++i)
#define step(n) rep(_, n)
#define ALL(x) (x).begin(), (x).end()
#define RALL(x) (x).rbegin(), (x).rend()
#define Unique(a) a.erase(unique(ALL(a)), a.end())
#define pb push_back
#define len(x) ((int)(x).size())
#define optimize_cin()                                                         \\
  cin.tie(0);                                                                  \\
  ios::sync_with_stdio(false)
#define debug(x) std::cerr << #x << ": " << (x) << endl;
#define LINT_MAX (LLONG_MAX)
#define LINT_MIN (LLONG_MIN)
#define cauto const auto
#define int long long
#define float long double
using namespace std;
template <class Type> inline constexpr Type Square(Type x) { return x * x; }
template <class Type>
inline constexpr bool InRange(const Type &x, const Type &i, const Type &a) {
  return (i <= x) && (x <= a);
}
template <class Integer> bool chmax(Integer &a, const Integer &b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class Integer> bool chmin(Integer &a, const Integer &b) {
  if (b < a) {
    a = b;
    return 1;
  }
  return 0;
}
template <class Integer> bool IsOdd(Integer &n) { return n & 1; }
template <class Integer> bool IsEven(Integer &n) { return !(n & 1); }
long long gcd(long long a, long long b) {
  while (b) {
    long long A = a;
    (a = b), (b = A % b);
  }
  return a;
}
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
int ctoi(const char c) { return ('0' <= c && c <= '9') ? (c - '0') : -1; }
string YesNo(bool b) { return b ? "Yes" : "No"; }
string YESNO(bool b) { return b ? "YES" : "NO"; }
string yesno(bool b) { return b ? "yes" : "no"; }
void _cin() {}
template <class Head, class... Tail> void _cin(Head &&head, Tail &&...tail) {
  cin >> head;
  _cin(forward<Tail>(tail)...);
}
#define Cin(Type, ...)                                                         \\
  Type __VA_ARGS__;                                                            \\
  _cin(__VA_ARGS__)
#define Cinv(Type, xs, n)                                                      \\
  vector<Type> xs(n);                                                          \\
  rep(i, n) cin >> xs[i]
#define Cinv2(Type, xs, ys, n)                                                 \\
  vector<Type> xs(n), ys(n);                                                   \\
  rep(i, n) cin >> xs[i] >> ys[i]
#define Cinv3(Type, xs, ys, zs, n)                                             \\
  vector<Type> xs(n), ys(n), zs(n);                                            \\
  rep(i, n) cin >> xs[i] >> ys[i] >> zs[i]
#define Cinvv(Type, xs, h, w)                                                  \\
  vector<vector<Type>> xs(h, vector<int>(w));                                  \\
  rep(i, h) rep(j, w) cin >> xs[i][j]
void Print() { cout << endl; }
template <class Head, class... Tail> void Print(Head &&head, Tail &&...tail) {
  cout << head;
  if (sizeof...(tail) != 0)
    cout << " ";
  Print(forward<Tail>(tail)...);
}
template <class Type> void Print(vector<Type> &vec) {
  for (auto &a : vec) {
    cout << a;
    if (&a != &vec.back())
      cout << " ";
  }
  cout << endl;
}
template <class Type> void Print(vector<vector<Type>> &df) {
  for (auto &vec : df) {
    Print(vec);
  }
}
void Debug() { cerr << endl; }
template <class Head, class... Tail> void Debug(Head &&head, Tail &&...tail) {
  cerr << head;
  if (sizeof...(tail) != 0)
    cerr << " ";
  Debug(forward<Tail>(tail)...);
}
template <class Type> void Debug(vector<Type> &vec) {
  for (auto &a : vec) {
    cerr << a;
    if (&a != &vec.back())
      cerr << " ";
  }
  cerr << endl;
}
template <class Type> void Debug(vector<vector<Type>> &df) {
  for (auto &vec : df) {
    Debug(vec);
  }
}

std::chrono::system_clock::time_point start, end__;

int Score(int D, const vector<int> &c, const vector<vector<int>> &s,
          const vector<int> &t) {
  vector<int> last(26);
  int value = 0;
  rep(d, D) {
    int i = t[d];
    value += s[d][i];
    last[i] = d + 1;
    rep(k, 26) { value -= c[k] * (d + 1 - last[k]); }
  }
  return value;
}

using P = pair<int, int>;
bool comp(const P &firstElof, const P &secondElof) {
  return firstElof.second > secondElof.second;
}

struct State {
  State() : score(0), idx(0) {}
  State(const vector<int> &_t, int _score, int i)
      : t(_t), score(_score), idx(i) {}
  static void Init(int _D, const vector<int> &_c,
                   const vector<vector<int>> &_s) {
    D = _D;
    c = _c;
    s = _s;
  }
  State added(int _t) {
    vector<int> tmp_t;
    int tmp_score = score;
    int tmp_idx = idx;
    tmp_t.pb(_t);
    tmp_score = Score(idx, c, s, t);
    return State(tmp_t, tmp_score, ++tmp_idx);
  }

  int score;
  vector<int> t;
  int idx;

  static int D;
  static vector<int> c;
  static vector<vector<int>> s;
};

bool operator<(const State &left, const State &right) {
  return left.score < right.score;
}

int State::D = 0;
vector<int> State::c = vector<int>();
vector<vector<int>> State::s = vector<vector<int>>();

vector<int> Beam(int D, const vector<int> &c, const vector<vector<int>> &s) {
  State::Init(D, c, s);
  State fst = State();
  priority_queue<State> que;
  que.push(fst);
  while (!que.empty()) {
    assert(!que.empty());
    State now = que.top();
    que.pop();
    if (now.idx == D - 1)
      continue;

    rep(type, 26) {
      State next = now.added(type);
      if (next.idx < D or len(que) < 100000) {
        que.push(next);
      }
    }

    end__ = chrono::system_clock::now();
    double elapsed =
        std::chrono::duration_cast<std::chrono::milliseconds>(end__ - start)
            .count();
    if (elapsed > 900) {
      break;
    }
  }
  State top_state = que.top();
  vector<int> t = top_state.t;
  range_for(d, len(t), D - 1) {
    int m = INT_MIN;
    int index = 0;
    t.push_back(0);
    rep(type, 26) {
      t[d] = type;
      if (chmax(m, s[d][type])) {
        index = type;
      }
    }

    t[d] = index;
  }
  return t;
}

vector<int> greedy(int D, const vector<int> &c, const vector<vector<int>> &s) {
  static random_device rnd;
  static mt19937 mt(rnd());

  vector<int> t(D);
  queue<P> que;
  rep(d, D) {
    int m = INT_MIN;
    int index = 0;
    rep(type, 26) {
      t[d] = type;
      if (chmax(m, Score(d, c, s, t))) {
        index = type;
      }
    }

    t[d] = index;
  }

  return t;
}

vector<int> calc_t(int D, const vector<int> &c, const vector<vector<int>> &s) {
  static random_device rnd;
  static mt19937 mt(rnd());
  static uniform_int_distribution<> randday(0, D - 1);
  static uniform_int_distribution<> randtype(0, 25);
  vector<int> t = Beam(D, c, s);
  // vector<int> t = random_method(D);

  assert(len(t) == D);
  double elapsed;
  bool changed = true;
  int old_score, new_score;
  vector<int> buff;
  int cnt = 0;
  do {
    cnt = (cnt + 1) % 100;
    int day = randday(mt);
    int type = randtype(mt);

    int old = t[day];
    if (changed) {
      old_score = Score(D, c, s, t);
    }
    t[day] = type;
    new_score = Score(D, c, s, t);

    if (old_score >= new_score) {
      t[day] = old;
      changed = false;
    } else {
      changed = true;
    }

    int left_idx = randday(mt);
    int right_idx = randday(mt);
    if (changed) {
      old_score = Score(D, c, s, t);
    }
    swap(t[left_idx], t[right_idx]);
    new_score = Score(D, c, s, t);
    if (old_score >= new_score) {
      swap(t[left_idx], t[right_idx]);
      changed = false;
    } else {
      changed = true;
    }

    end__ = chrono::system_clock::now();
    elapsed =
        std::chrono::duration_cast<std::chrono::milliseconds>(end__ - start)
            .count();
  } while (elapsed < 1900);

  return t;
}

signed main() {
  start = chrono::system_clock::now();
  // in
  Cin(int, D);
  Cinv(int, c, 26);
  Cinvv(int, s, D, 26);
  vector<int> t = calc_t(D, c, s);
  // vector<int> t = greedy(D,c,s);

  rep(i, len(t)) Print(t[i] + 1);

  // Debug("=== score ===");
  // Debug(score(D, c, s, t));
  // Debug("=============");

  return 0;
}