prithivMLmods/Coder-Stat huggingface dataset:
Problem p02584 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <algorithm>
#include <bits/stdc++.h>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <list>
#include <new>
#include <queue>
#include <stack>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
#define loop(i, x, z) for (int i = x; i < z; i++)
using ll = unsigned long long int;
#define mod 1000000007
/*bool cmp(pair<ll,ll>a,pair<ll,ll>b){
return a.second<b.second;
}*/
int main() {
  ll x, k, d;
  cin >> x >> k >> d;
  x = llabs(x);
  while (k > 0 && llabs(x) > d / 2) {
    k--;
    x = x - d;
  }
  if (k % 2 == 0) {
    cout << llabs(x);
  } else {
    x = min(llabs(x - d), llabs(x + d));
    cout << x;
  }
  return 0;
}


Fixed submission:
#include <algorithm>
#include <bits/stdc++.h>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <list>
#include <new>
#include <queue>
#include <stack>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
#define loop(i, x, z) for (int i = x; i < z; i++)
using ll = unsigned long long int;
#define mod 1000000007
/*bool cmp(pair<ll,ll>a,pair<ll,ll>b){
return a.second<b.second;
}*/
int main() {
  ll x, k, d;
  cin >> x >> k >> d;
  x = llabs(x);
  if (d == 1) {
    if (x >= k) {
      x = x - k;
      k = 0;
    } else {
      k = k - x;
      x = 0;
    }
  }
  while (k > 0 && llabs(x) > d / 2) {
    k--;
    x = x - d;
  }
  if (k % 2 == 0) {
    cout << llabs(x);
  } else {
    x = min(llabs(x - d), llabs(x + d));
    cout << x;
  }
  return 0;
}
Problem p02584 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define printInt(a) printf("%d\n", a)
#define printll(a) printf("%lld\n", a)
#define printdbl(a) printf("%lf\n", a)
#define printYes() printf("Yes\n")
#define printNo() printf("No\n")
#define scanll(a) scanf("%lld", &a)
#define scanInt(a) scanf("%d", &a)
#define scan2Int(a, b) scanf("%d %d", &a, &b)
#define scan3Int(a, b, c) scanf("%d %d %d", &a, &b, &c)
#define scan4Int(a, b, c, d) scanf("%d %d %d %d", &a, &b, &c, &d)
typedef long long ll;
const int INF = 1001001001;
using namespace std;
void swap(int *a, int *b) {
  int tmp = *a;
  *a = *b;
  *b = tmp;
  return;
}
int gdc(int a, int b) {
  int r;
  if (a < b)
    swap(&a, &b);
  r = a % b;
  while (r != 0) {
    a = b;
    b = r;
    r = a % b;
  }
  return b;
}
int factorial(int a) {
  int ans = 1;
  for (int i = 1; i <= a; ++i)
    ans *= i;
  return ans;
}

int main() {
  ll x, k, d;
  scanf("%lld %lld %lld", &x, &k, &d);
  x = abs(x);
  while (x > 0 && k > 0) {
    x -= d;
    k--;
  }
  d *= k % 2;
  x = abs(x - d) < abs(x + d) ? abs(x - d) : abs(x + d);
  printll(x);
  return 0;
}

Fixed submission:
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define printInt(a) printf("%d\n", a)
#define printll(a) printf("%lld\n", a)
#define printdbl(a) printf("%lf\n", a)
#define printYes() printf("Yes\n")
#define printNo() printf("No\n")
#define scanll(a) scanf("%lld", &a)
#define scanInt(a) scanf("%d", &a)
#define scan2Int(a, b) scanf("%d %d", &a, &b)
#define scan3Int(a, b, c) scanf("%d %d %d", &a, &b, &c)
#define scan4Int(a, b, c, d) scanf("%d %d %d %d", &a, &b, &c, &d)
typedef long long ll;
const int INF = 1001001001;
using namespace std;
void swap(int *a, int *b) {
  int tmp = *a;
  *a = *b;
  *b = tmp;
  return;
}
int gdc(int a, int b) {
  int r;
  if (a < b)
    swap(&a, &b);
  r = a % b;
  while (r != 0) {
    a = b;
    b = r;
    r = a % b;
  }
  return b;
}
int factorial(int a) {
  int ans = 1;
  for (int i = 1; i <= a; ++i)
    ans *= i;
  return ans;
}

int main() {
  ll x, k, d;
  scanf("%lld %lld %lld", &x, &k, &d);
  x = abs(x);
  ll tmp = x / d;
  if (tmp <= k) {
    x -= d * tmp;
    k -= tmp;
  } else {
    x -= d * k;
    k = 0;
  }
  d *= k % 2;
  x = abs(x - d) < abs(x + d) ? abs(x - d) : abs(x + d);
  printll(x);
  return 0;
}
Problem p02584 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;
int main() {
  long long x;
  long long k;
  long long d;
  cin >> x >> k >> d;
  long long mostnear = abs(x) % d;
  if (mostnear / d + k <= abs(x) / d) {
    cout << abs(x) - (k * d);
  } else if ((abs(k) % abs(x / d) == 1))
    cout << mostnear;
  else
    cout << abs(mostnear - d);
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;
int main() {
  long long x;
  long long k;
  long long d;
  cin >> x >> k >> d;
  long long mostnear = abs(x) % d;
  if (mostnear / d + k <= abs(x) / d) {
    cout << abs(x) - (k * d);
  } else if (abs(x / d) % 2 == 0 && k % 2 == 0)
    cout << mostnear;
  else if (abs(x / d) % 2 == 1 && k % 2 == 1)
    cout << mostnear;
  else
    cout << abs(mostnear - d);
}
Problem p02584 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <cmath>
#include <ctype.h>
#include <iostream>
#include <limits.h>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long int ll;
typedef vector<int> vi;

// 最大公約数
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }

// 最小公倍数
int lcm(int a, int b) { return a / gcd(a, b) * b; }

// 素数判定
bool isPrime(int x) {
  if (x < 2)
    return 0;
  else if (x == 2)
    return 1;
  if (x % 2 == 0)
    return 0;
  for (int i = 3; i * i <= x; i += 2) {
    if (x % i == 0)
      return 0;
  }
  return 1;
}

// 桁ごとの足し算
int digsum(int n) {
  int res = 0;
  while (n > 0) {
    res += n % 10;
    n /= 10;
  }
  return res;
}

// 約数列挙
vector<int> enum_div(int n) {
  vector<int> ret;
  for (int i = 1; i * i <= n; ++i) {
    if (n % i == 0) {
      ret.push_back(i);
      if (i * i != n) {
        ret.push_back(n / i);
      }
    }
  }
  return ret;
}

// 累乗の計算とあまり,0で累乗そのまま出力
long long modpow(long long a, long long n, long long mod) {
  if (mod == 0)
    mod = __LONG_LONG_MAX__;
  long long res = 1;
  while (n > 0) {
    if (n & 1)
      res = res * a % mod;
    a = a * a % mod;
    n >>= 1;
  }
  return res;
}

ll X;
ll K;
ll D;
int main() {
  cin >> X >> K >> D;
  for (int i = 0; i < K; ++i) {
    ll X2;
    if (X > 0)
      X2 = X - D;
    else
      X2 = X + D;
    if ((X2 <= 0 && 0 <= X) || (X <= 0 && 0 <= X2)) {
      if ((K - 1 - i) % 2)
        break;
      else {
        X = X2;
        break;
      }
    }
    X = X2;
  }
  cout << abs(X) << endl;
}

Fixed submission:
#include <cmath>
#include <ctype.h>
#include <iostream>
#include <limits.h>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long int ll;
typedef vector<int> vi;

// 最大公約数
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }

// 最小公倍数
int lcm(int a, int b) { return a / gcd(a, b) * b; }

// 素数判定
bool isPrime(int x) {
  if (x < 2)
    return 0;
  else if (x == 2)
    return 1;
  if (x % 2 == 0)
    return 0;
  for (int i = 3; i * i <= x; i += 2) {
    if (x % i == 0)
      return 0;
  }
  return 1;
}

// 桁ごとの足し算
int digsum(int n) {
  int res = 0;
  while (n > 0) {
    res += n % 10;
    n /= 10;
  }
  return res;
}

// 約数列挙
vector<int> enum_div(int n) {
  vector<int> ret;
  for (int i = 1; i * i <= n; ++i) {
    if (n % i == 0) {
      ret.push_back(i);
      if (i * i != n) {
        ret.push_back(n / i);
      }
    }
  }
  return ret;
}

// 累乗の計算とあまり,0で累乗そのまま出力
long long modpow(long long a, long long n, long long mod) {
  if (mod == 0)
    mod = __LONG_LONG_MAX__;
  long long res = 1;
  while (n > 0) {
    if (n & 1)
      res = res * a % mod;
    a = a * a % mod;
    n >>= 1;
  }
  return res;
}

ll X;
ll K;
ll D;
int main() {
  cin >> X >> K >> D;
  X = abs(X);
  ll num = X / D;
  if (X % D > 0)
    num++;

  if (num > K)
    X -= D * K;
  else {
    X -= D * num;
    if ((K - num) % 2 == 1)
      X += D;
  }
  cout << abs(X) << endl;
}
Problem p02584 (C++)

Buggy submission (status: Time Limit Exceeded):
// ABC 175 C
#include <bits/stdc++.h>
using namespace std;

int main() {
  long long int x, d, k, ans, fl, flfl, flflfl = 0, fm;
  cin >> x >> k >> d;
  fl = 1;
  if (k % 2 == 0) {
    fl = 0;
  }
  if (x < 0) {
    x *= -1;
  }
  flfl = 0;
  if (d >= x) {
    flfl = 1;
  }
  // cout << flfl<<endl;
  if (flfl == 0) {
    int i = 1;
    while (i >= 0) {
      if (d * i >= x) {
        fm = i - 1;
        i = -2;
      }
      i++;
    }
    if (fm % 2 != 0) {
      flflfl = 1;
    }
    // cout << fm <<endl;
    if (fm <= k) {
      if (fl == 0) {
        if (flflfl == 0) {
          ans = x - fm * d;
        } else {
          ans = (fm + 1) * d - x;
        }
      } else {
        if (flflfl == 0) {
          ans = (fm + 1) * d - x;
        } else {
          ans = x - fm * d;
        }
      }
    } else {
      ans = x - k * d;
    }
  } else {
    if (fl == 0) {
      ans = x;
    } else {
      if (x == d) {
        ans = 0;
      } else {
        ans = d - x;
      }
    }
    // cout << "haha";
  }
  cout << ans;
}

Fixed submission:
// ABC 175 C
#include <bits/stdc++.h>
using namespace std;

int main() {
  long long int x, d, k, ans, fl, flfl, flflfl = 0, fm;
  cin >> x >> k >> d;
  fl = 1;
  if (k % 2 == 0) {
    fl = 0;
  }
  if (x < 0) {
    x *= -1;
  }
  flfl = 0;
  if (d >= x) {
    flfl = 1;
  }
  // cout << flfl<<endl;
  if (flfl == 0) {
    fm = x / d;
    if (fm % 2 != 0) {
      flflfl = 1;
    }
    // cout << fm <<endl;
    if (fm <= k) {
      if (fl == 0) {
        if (flflfl == 0) {
          ans = x - fm * d;
        } else {
          ans = (fm + 1) * d - x;
        }
      } else {
        if (flflfl == 0) {
          ans = (fm + 1) * d - x;
        } else {
          ans = x - fm * d;
        }
      }
    } else {
      ans = x - k * d;
    }
  } else {
    if (fl == 0) {
      ans = x;
    } else {
      if (x == d) {
        ans = 0;
      } else {
        ans = d - x;
      }
    }
    // cout << "haha";
  }
  cout << ans;
}
Problem p02584 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <iostream>

long long abs(long long a) { return (a < 0) ? -a : a; }

int sgn(long long a) { return (a < 0) ? -1 : 1; }

int main() {
  long long X, K, D;
  std::cin >> X >> K >> D;

  while (K > 0) {
    if (abs(X - sgn(X) * D) < abs(X)) {
      long long times = abs(X) / D;
      if (K < times)
        times = K;
      K -= times;
      X -= sgn(X) * times * D;
    } else {
      if (K > 1) {
        K %= 2;
      } else {
        X -= sgn(X) * D;
        K--;
      }
    }
  }

  std::cout << abs(X) << '\n';
  return 0;
}

Fixed submission:
#include <iostream>

long long abs(long long a) { return (a < 0) ? -a : a; }

int sgn(long long a) { return (a < 0) ? -1 : 1; }

int main() {
  long long X, K, D;
  std::cin >> X >> K >> D;

  while (K > 0) {
    if (abs(X - sgn(X) * D) < abs(X)) {
      long long times = abs(X) / D;
      if (times == 0)
        times = 1;
      if (K < times)
        times = K;
      K -= times;
      X -= sgn(X) * times * D;
    } else {
      if (K > 1) {
        K %= 2;
      } else {
        X -= sgn(X) * D;
        K--;
      }
    }
  }

  std::cout << abs(X) << '\n';
  return 0;
}
Problem p02584 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define mod 1000000007
#define pi 3.141592653589793
typedef vector<ll> vcl;

ll gcd(ll a, ll b) {
  if (b > a)
    swap(a, b);
  if (b == 0)
    return a;
  return gcd(b, a % b);
}
ll lcm(ll a, ll b) {
  ll g = gcd(a, b);
  return a / g * b;
}
ll rep_jijo(ll n, ll x) {
  if (x == 0)
    return 1;
  if (x % 2 == 0) {
    ll t = rep_jijo(n, x / 2);
    return t * t % mod;
  }
  return n * rep_jijo(n, x - 1) % mod;
}
ll c2(ll n) { return n * (n - 1) / 2; }

int main() {
  ll x, k, d, ans;
  cin >> x >> k >> d;
  if (x < 0)
    x = -x;
  ll y = x;
  ll i = 0;
  while (y > d) {
    y = y - d;
    i++;
  }
  if (i >= k)
    ans = x - k * d;
  else if ((k - i) % 2 == 0) {
    ans = x - i * d;
  } else
    ans = abs(x - i * d - d);
  cout << ans << endl;
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define mod 1000000007
#define pi 3.141592653589793
typedef vector<ll> vcl;

ll gcd(ll a, ll b) {
  if (b > a)
    swap(a, b);
  if (b == 0)
    return a;
  return gcd(b, a % b);
}
ll lcm(ll a, ll b) {
  ll g = gcd(a, b);
  return a / g * b;
}
ll rep_jijo(ll n, ll x) {
  if (x == 0)
    return 1;
  if (x % 2 == 0) {
    ll t = rep_jijo(n, x / 2);
    return t * t % mod;
  }
  return n * rep_jijo(n, x - 1) % mod;
}
ll c2(ll n) { return n * (n - 1) / 2; }

int main() {
  ll x, k, d, ans;
  cin >> x >> k >> d;
  if (x < 0)
    x = -x;
  ll y = x;
  ll i = 0;
  i = y / d;

  if (i >= k)
    ans = x - k * d;
  else if ((k - i) % 2 == 0) {
    ans = x - i * d;
  } else
    ans = abs(x - i * d - d);
  cout << ans << endl;
}
Problem p02584 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  long long x, pos, plus_min, minus_min;
  unsigned long k, d;
  cin >> x >> k >> d;
  pos = x;
  plus_min = pow(10, 15) + 1;
  minus_min = -pow(10, 15) - 1;

  for (unsigned long i = 1; i <= k; i++) {
    if (pos < 0) {
      pos += d;
      if (pos == plus_min) {
        if ((k - i) % 2) {
          cout << -minus_min;
          return 0;
        } else {
          cout << plus_min;
          return 0;
        }
      }
      if (pos >= 0 && pos < plus_min)
        plus_min = pos;
    } else {
      pos -= d;
      if (pos == minus_min) {
        if ((k - i) % 2) {
          cout << plus_min;
          return 0;
        } else {
          cout << -minus_min;
          return 0;
        }
      }
      if (pos < 0 && pos > minus_min)
        minus_min = pos;
    }
  }

  cout << abs(pos);

  return 0;
}

Fixed submission:
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  long long x, pos, plus_min, minus_min;
  unsigned long k, d;
  cin >> x >> k >> d;
  pos = x;
  plus_min = pow(10, 15) + 1;
  minus_min = -pow(10, 15) - 1;

  long long quotient = abs(x) / d, mod = abs(x) % d;
  if (k * d <= abs(x)) {
    if (x < 0) {
      cout << -x - k * d;
    } else {
      cout << x - k * d;
    }
    return 0;
  } else {
    k -= quotient;
    pos = x < 0 ? -mod : mod;
  }

  for (unsigned long i = 1; i <= k; i++) {
    if (pos < 0) {
      pos += d;
      if (pos == plus_min) {
        if ((k - i) % 2) {
          cout << -minus_min;
          return 0;
        } else {
          cout << plus_min;
          return 0;
        }
      }
      if (pos >= 0 && pos < plus_min)
        plus_min = pos;
    } else {
      pos -= d;
      if (pos == minus_min) {
        if ((k - i) % 2) {
          cout << plus_min;
          return 0;
        } else {
          cout << -minus_min;
          return 0;
        }
      }
      if (pos < 0 && pos > minus_min)
        minus_min = pos;
    }
  }

  cout << abs(pos);

  return 0;
}
Problem p02584 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)
#define rep3(i, n) for (long long i = 0; i < (long long)(n); i++)
using Graph = vector<vector<int>>;
using ll = long long;

//----------素因数分解----------
vector<ll> prime_factorization(ll n) {
  vector<ll> factors(n + 1, 0);
  rep3(i, n + 1) {
    if (i <= 1)
      continue;
    while (n % i == 0) {
      n /= i;
      factors[i]++;
    }
  }
  return factors;
}

int main() {
  ll x, k, d;
  cin >> x >> k >> d;
  rep3(i, k) {
    if (abs(x + d) <= abs(x - d)) {
      x += d;
    } else {
      x -= d;
    }
    if (abs(x) <= abs(d)) {
      if ((k - 1 - i) % 2 == 0) {
        cout << abs(x) << endl;
        return 0;
      } else {
        cout << abs(d) - abs(x) << endl;
        return 0;
      }
    }
  }
  cout << abs(x) << endl;
  return 0;
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)
#define rep3(i, n) for (long long i = 0; i < (long long)(n); i++)
using Graph = vector<vector<int>>;
using ll = long long;

//----------素因数分解----------
vector<ll> prime_factorization(ll n) {
  vector<ll> factors(n + 1, 0);
  rep3(i, n + 1) {
    if (i <= 1)
      continue;
    while (n % i == 0) {
      n /= i;
      factors[i]++;
    }
  }
  return factors;
}

int main() {
  ll x, k, d;
  cin >> x >> k >> d;
  if (abs(x) % d == 0) {
    ll p = abs(x) / d;
    if (k > p) {
      x = 0;
      k -= p;
    } else {
      cout << abs(x) - k * d << endl;
      return 0;
    }
  }
  rep3(i, k) {
    if (abs(x + d) <= abs(x - d)) {
      x += d;
    } else {
      x -= d;
    }
    if (abs(x) <= abs(d)) {
      if ((k - 1 - i) % 2 == 0) {
        cout << abs(x) << endl;
        return 0;
      } else {
        cout << abs(d) - abs(x) << endl;
        return 0;
      }
    }
  }
  cout << abs(x) << endl;
  return 0;
}
Problem p02585 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
  int n, k;
  cin >> n >> k;
  vector<int> p(n);
  vector<ll> c(n);
  for (auto &e : p) {
    cin >> e;
    e--;
  }
  for (auto &e : c)
    cin >> e;

  vector<ll> s1(n), s2(n), d1(n), d2(n);
  for (int i = 0; i < n; i++) {
    if (d1[i])
      continue;
    d1[i] = 1;
    for (int j = i; !d2[p[j]]; j = p[j]) {
      if (!d1[p[j]]) {
        s1[p[j]] = s1[j] + c[p[j]];
        d1[p[j]] = d1[j] + 1;
      } else {
        s2[p[j]] = (d2[j] ? s2[j] : s1[j]) + c[p[j]];
        d2[p[j]] = (d2[j] ? d2[j] : d1[j]) + 1;
      }
    }
  }

  ll r = -1e18;
  for (int i = 0; i < n; i++) {
    ll ri = 0;
    for (int j = i, ki = k; ki;) {
      if (d2[j] && 2 * (d2[j] - d1[j]) <= ki) {
        ri += s2[j] - s1[j];
        ki -= d2[j] - d1[j];
      } else {
        ri += c[p[j]];
        ki--;
        j = p[j];
      }
      r = max(r, ri);
      ri = max(ri, 0ll);
    }
  }
  cout << r << endl;
}


Fixed submission:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
  int n, k;
  cin >> n >> k;
  vector<int> p(n);
  vector<ll> c(n);
  for (auto &e : p) {
    cin >> e;
    e--;
  }
  for (auto &e : c)
    cin >> e;

  vector<ll> s1(n), s2(n), d1(n), d2(n);
  for (int i = 0; i < n; i++) {
    if (d1[i])
      continue;
    d1[i] = 1;
    for (int j = i; !d2[p[j]]; j = p[j]) {
      if (!d1[p[j]]) {
        s1[p[j]] = s1[j] + c[p[j]];
        d1[p[j]] = d1[j] + 1;
      } else {
        s2[p[j]] = (d2[j] ? s2[j] : s1[j]) + c[p[j]];
        d2[p[j]] = (d2[j] ? d2[j] : d1[j]) + 1;
      }
    }
  }

  ll r = -1e18;
  for (int i = 0; i < n; i++) {
    ll ri = 0;
    for (int j = i, ki = k; ki;) {
      if (d2[j] && 2 * (d2[j] - d1[j]) <= ki) {
        ll t = ki / (d2[j] - d1[j]) - 1;
        ri += t * (s2[j] - s1[j]);
        ki -= t * (d2[j] - d1[j]);
      } else {
        ri += c[p[j]];
        ki--;
        j = p[j];
      }
      r = max(r, ri);
      ri = max(ri, 0ll);
    }
  }
  cout << r << endl;
}
Problem p02585 (Python)

Buggy submission (status: Time Limit Exceeded):
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

P = [None] + P
C = [None] + C

all_max = C[1]
for st in range(1, N + 1):
    scores = []
    visit = set()
    p = st

    while p not in visit and len(visit) < K:
        next_p = P[p]
        scores.append(C[next_p])
        visit.add(p)
        p = next_p

    num_elem = len(scores)
    all_sum = sum(scores)

    q, r = divmod(K, num_elem)

    max_ = scores[0]
    temp = scores[0]

    max_r = scores[0]
    temp_r = scores[0]
    for x in range(1, num_elem):
        if x < r:
            temp_r += scores[x]
            max_r = max(max_r, temp_r)

        temp += scores[x]
        max_ = max(max_, temp)

    temp_max = scores[0]
    if all_sum > 0 and q > 0:
        if r > 0:
            temp_max = max(all_sum * (q - 1) + max_, all_sum * q + max_r)
        else:
            temp_max = all_sum * (q - 1) + max_
    else:
        temp_max = max_

    all_max = max(all_max, temp_max)

print(all_max)


Fixed submission:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

P = [None] + P
C = [None] + C

all_max = C[1]
for st in range(1, N + 1):
    scores = []
    visit = set()
    p = st

    while p not in visit and len(visit) < K:
        next_p = P[p]
        scores.append(C[next_p])
        visit.add(p)
        p = next_p

    num_elem = len(scores)
    all_sum = sum(scores)

    q, r = divmod(K, num_elem)

    max_ = scores[0]
    temp = scores[0]

    max_r = scores[0]
    temp_r = scores[0]
    for x in range(1, num_elem):
        if x < r:
            temp_r += scores[x]
            max_r = max(max_r, temp_r)

        temp += scores[x]
        max_ = max(max_, temp)

    temp_max = scores[0]
    if all_sum > 0 and q > 0:
        if r > 0:
            temp_max = max(all_sum * (q - 1) + max_, all_sum * q + max_r)
        else:
            temp_max = all_sum * (q - 1) + max_
    else:
        temp_max = max_

    all_max = max(all_max, temp_max)


print(all_max)
Problem p02585 (C++)

Buggy submission (status: Runtime Error):
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
using ll = long long;
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define rep2(i, s, n) for (ll i = s; i < (n); i++)
using namespace std;

int main() {
  ll n, k;
  cin >> n >> k;
  vector<ll> p(n), c(n);
  rep(i, n) {
    cin >> p[i];
    p[i]--;
  }
  rep(i, n) cin >> c[i];
  ll ans = -1000000000;
  rep(i, n) {
    ll loop_num = 1000000000;
    ll loop_score = -1000000000;
    ll score = 0;
    vector<ll> scores;
    ll next = p[i];
    rep(j, k) {
      score += c[next];
      next = p[next];
      scores.push_back(score);
      if (next == p[i]) {
        loop_num = j + 1;
        loop_score = score;
        break;
      }
    }
    ll a1 = 0, a2 = 0;
    if (loop_num > 0) {
      a1 = k / loop_num; // 一周できる回数
      a2 = k % loop_num; // 一周繰り返した後の余り
    }
    if (a1 > 0 && loop_score > 0) {
      rep(j, loop_num) {
        ll p = 0;
        if (j >= a2)
          p = -1;
        ans = max(ans, scores[j] + loop_score * (a1 + p));
      }
    } else {
      rep(j, loop_num) { ans = max(ans, scores[j]); }
    }
  }
  cout << ans << endl;

  return 0;
}

Fixed submission:
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
using ll = long long;
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define rep2(i, s, n) for (ll i = s; i < (n); i++)
using namespace std;

int main() {
  ll n, k;
  cin >> n >> k;
  vector<ll> p(n), c(n);
  rep(i, n) {
    cin >> p[i];
    p[i]--;
  }
  rep(i, n) cin >> c[i];
  ll ans = -1000000000;
  rep(i, n) {
    ll loop_num = k;
    ll loop_score = -1000000000;
    ll score = 0;
    vector<ll> scores;
    ll next = p[i];
    rep(j, k) {
      score += c[next];
      next = p[next];
      scores.push_back(score);
      if (next == p[i]) {
        loop_num = j + 1;
        loop_score = score;
        break;
      }
    }
    ll a1 = 0, a2 = 0;
    if (loop_num > 0) {
      a1 = k / loop_num; // 一周できる回数
      a2 = k % loop_num; // 一周繰り返した後の余り
    }
    if (a1 > 0 && loop_score > 0) {
      rep(j, loop_num) {
        ll p = 0;
        if (j >= a2)
          p = -1;
        ans = max(ans, scores[j] + loop_score * (a1 + p));
      }
    } else {
      rep(j, loop_num) { ans = max(ans, scores[j]); }
    }
  }
  cout << ans << endl;

  return 0;
}
Problem p02585 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;

int main() {
  int n, k;
  cin >> n >> k;
  vector<int> p(n), c(n);
  rep(i, n) cin >> p[i];
  rep(i, n) cin >> c[i];
  rep(i, n) p[i]--;
  ll ans = -1e18;
  rep(si, n) {
    int x = si;
    vector<int> s;
    ll tot = 0;
    while (1) {
      x = p[x];
      s.push_back(c[x]);
      tot += c[x];
      if (x == si)
        break;
    }
    int l = s.size();
    ll t = 0;
    rep(i, k) {
      t += s[i];
      if (i + 1 > k)
        break;
      ll now = t;
      if (tot > 0) {
        ll e = (k - (i + 1)) / l;
        now += tot * e;
      }
      ans = max(ans, now);
    }
  }
  cout << ans << endl;
  return 0;
}


Fixed submission:
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;

int main() {
  int n, k;
  cin >> n >> k;
  vector<int> p(n), c(n);
  rep(i, n) cin >> p[i];
  rep(i, n) cin >> c[i];
  rep(i, n) p[i]--;
  ll ans = -1e18;
  rep(si, n) {
    int x = si;
    vector<int> s;
    ll tot = 0;
    while (1) {
      x = p[x];
      s.push_back(c[x]);
      tot += c[x];
      if (x == si)
        break;
    }
    int l = s.size();
    ll t = 0;
    rep(i, l) {
      t += s[i];
      if (i + 1 > k)
        break;
      ll now = t;
      if (tot > 0) {
        ll e = (k - (i + 1)) / l;
        now += tot * e;
      }
      ans = max(ans, now);
    }
  }
  cout << ans << endl;
  return 0;
}
Problem p02585 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <iostream>
#include <limits.h>
#include <queue>
#include <vector>
using namespace std;

int main(void) {

  int N;
  long long K;
  cin >> N >> K;

  vector<int> P(N + 1); // move
  for (int i = 1; i < N + 1; i++) {
    cin >> P[i];
  }
  vector<long long> C(N + 1); // point
  for (int i = 1; i < N + 1; i++) {
    cin >> C[i];
  }

  long long max_point = LLONG_MIN;
  long long tmp_point = 0;
  int current_p = 0;

  max_point = LLONG_MIN;
  for (int m_first = 1; m_first < N + 1; m_first++) {
    tmp_point = 0;
    current_p = m_first;
    // cout << "m_first: " << m_first << ", current: " << current_p << endl;
    for (int total = 1; total <= K; total++) {
      // cout << "total: " << total << ", current: " << current_p << endl;
      // cout << "tmp_point: " << tmp_point << endl;
      tmp_point += C[P[current_p]];
      if (max_point <= tmp_point)
        max_point = tmp_point;
      current_p = P[current_p];

      if (m_first == current_p && tmp_point <= 0) {
        tmp_point += C[P[current_p]];
        if (max_point <= tmp_point)
          max_point = tmp_point;
        break;
      }
    }
    // cout << "" << endl;
  }

  cout << max_point << endl;

  return 0;
}


Fixed submission:
#include <iostream>
#include <limits.h>
#include <queue>
#include <vector>
using namespace std;

int main(void) {

  int N;
  long long K;
  cin >> N >> K;

  vector<int> P(N + 1); // move
  for (int i = 1; i < N + 1; i++) {
    cin >> P[i];
  }
  vector<long long> C(N + 1); // point
  for (int i = 1; i < N + 1; i++) {
    cin >> C[i];
  }

  long long max_point = LLONG_MIN;
  long long tmp_point = 0;
  int current_p = 0;

  max_point = LLONG_MIN;
  for (int m_first = 1; m_first < N + 1; m_first++) {
    tmp_point = 0;
    current_p = m_first;
    // cout << "m_first: " << m_first << ", current: " << current_p << endl;
    for (int total = 1; total <= K; total++) {
      // cout << "total: " << total << ", current: " << current_p << endl;
      // cout << "tmp_point: " << tmp_point << endl;
      tmp_point += C[P[current_p]];
      if (max_point <= tmp_point)
        max_point = tmp_point;
      current_p = P[current_p];

      if (m_first == current_p && tmp_point <= 0) {
        tmp_point += C[P[current_p]];
        if (max_point <= tmp_point)
          max_point = tmp_point;
        break;
      } else if (m_first == current_p && tmp_point > 0) {
        int cycle_num = K / total;
        int amari = K % total;
        // cout << "cycle_num: " << cycle_num << endl;
        // cout << "amari: " << amari << endl;
        // cout << "tmp_potnt: " << tmp_point << endl;
        tmp_point = tmp_point * (cycle_num - 1);
        if (max_point <= tmp_point)
          max_point = tmp_point;
        for (int l = 0; l < amari + total; l++) {
          // cout << "tmp_point:" << tmp_point << endl;
          tmp_point += C[P[current_p]];
          if (max_point <= tmp_point)
            max_point = tmp_point;
          current_p = P[current_p];
        }
        break;
      }
    }
    // cout << "" << endl;
  }

  cout << max_point << endl;

  return 0;
}
Problem p02585 (Python)

Buggy submission (status: Runtime Error):
import sys

readline = sys.stdin.readline
MOD = 10**9 + 7
INF = float("INF")
sys.setrecursionlimit(10**5)


def main():
    n, k = map(int, readline().split())
    p = list(map(int, readline().split()))
    p = [x - 1 for x in p]
    c = list(map(int, readline().split()))
    ans = -INF

    for i in range(n):
        cur = i
        nx = -1
        cnt = 0
        score_dict = dict()
        score_dict[0] = 0
        score = 0
        rem = k
        while rem > 0 and nx != i:
            cnt += 1
            rem -= 1
            nx = p[cur]
            score += c[nx]
            score_dict[cnt] = score
            ans = max(ans, score)
            cur = nx

        if rem > 0 and score > 0:
            loop = (rem // cnt) - 1
            if loop > 0:
                score += score * loop
                rem -= loop * cnt
            for j in range(rem + 1):
                st = score + score_dict[j]
                ans = max(ans, st)

    print(ans)


if __name__ == "__main__":
    main()


Fixed submission:
import sys

readline = sys.stdin.readline
MOD = 10**9 + 7
INF = float("INF")
sys.setrecursionlimit(10**5)


def main():
    n, k = map(int, readline().split())
    p = list(map(int, readline().split()))
    p = [x - 1 for x in p]
    c = list(map(int, readline().split()))
    ans = -INF

    for i in range(n):
        cur = i
        nx = -1
        cnt = 0
        score_dict = dict()
        score_dict[0] = 0
        score = 0
        rem = k
        while rem > 0 and nx != i:
            cnt += 1
            rem -= 1
            nx = p[cur]
            score += c[nx]
            score_dict[cnt] = score
            ans = max(ans, score)
            cur = nx

        if rem > 0 and score > 0:
            loop = (rem - 1) // cnt
            if loop > 0:
                score += score * loop
                rem -= loop * cnt
            for j in range(rem + 1):
                st = score + score_dict[j]
                ans = max(ans, st)

    print(ans)


if __name__ == "__main__":
    main()
Problem p02585 (C++)

Buggy submission (status: Memory Limit Exceeded):
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int N, K;
vector<int> P, C;
map<int, vector<pair<ll, int>>> memo;
vector<pair<ll, int>> f(int k) {
  if (memo.count(k))
    return memo[k];
  if (k == 1) {
    vector<pair<ll, int>> r(N);
    for (int i = 0; i < N; ++i) {
      r[i] = {C[P[i]], P[i]};
    }
    return memo[k] = r;
  } else {
    auto a = f(k / 2);
    auto b = f(k - k / 2);
    vector<pair<ll, int>> r(N);
    for (int i = 0; i < N; ++i) {
      auto x = a[i];
      auto y = b[x.second];
      r[i] = {x.first + y.first, y.second};
    }
    return memo[k] = r;
  }
}
int main() {
  cin >> N >> K;
  P.resize(N);
  C.resize(N);
  for (auto &x : P) {
    cin >> x;
    --x;
  }
  for (auto &x : C)
    cin >> x;
  auto res = -(1LL << 62);
  for (int kk = 1; kk <= K; ++kk) {
    if (kk == N + 1 && kk < K - N)
      kk = K - N;
    for (auto x : f(kk)) {
      res = max(res, x.first);
    }
  }
  cout << res << endl;
}


Fixed submission:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int N, K;
vector<int> P, C;
map<int, vector<pair<ll, int>>> memo;
vector<pair<ll, int>> f(int k) {
  if (memo.count(k))
    return memo[k];
  if (k == 1) {
    vector<pair<ll, int>> r(N);
    for (int i = 0; i < N; ++i) {
      r[i] = {C[P[i]], P[i]};
    }
    return memo[k] = r;
  } else {
    int x = k / 2;
    if (N < K - N && k > K - N) {
      x = K - N;
    }
    int y = k - x;
    auto a = f(x);
    auto b = f(y);
    vector<pair<ll, int>> r(N);
    for (int i = 0; i < N; ++i) {
      auto x = a[i];
      auto y = b[x.second];
      r[i] = {x.first + y.first, y.second};
    }
    return memo[k] = r;
  }
}
int main() {
  cin >> N >> K;
  P.resize(N);
  C.resize(N);
  for (auto &x : P) {
    cin >> x;
    --x;
  }
  for (auto &x : C)
    cin >> x;
  auto res = -(1LL << 62);
  for (int kk = 1; kk <= K; ++kk) {
    if (kk == N + 1 && kk < K - N)
      kk = K - N;
    for (auto x : f(kk)) {
      res = max(res, x.first);
    }
  }
  cout << res << endl;
}
Problem p02585 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
  ll N, K;
  cin >> N >> K;
  vector<ll> P(N), C(N);
  for (auto &x : P)
    cin >> x, x--;
  for (auto &x : C)
    cin >> x;
  ll res = -1e18;
  for (int i = 0; i < N; i++) {
    vector<ll> sum;
    ll t = 0;
    int idx = i;
    do {
      t += C[idx];
      sum.push_back(t);
      idx = P[idx];
    } while (idx - i);
    for (int j = 0; j < min<int>(K, sum.size()); j++)
      res = max(res, sum[j]);
    ll s = sum.back() * (K / sum.size());
    ll k = K % sum.size();
    for (int j = 0; j < k, sum.size(); j++) {
      res = max(res, s + sum[j]);
    }
  }
  cout << res << endl;
}


Fixed submission:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
  ll N, K;
  cin >> N >> K;
  vector<ll> P(N), C(N);
  for (auto &x : P)
    cin >> x, x--;
  for (auto &x : C)
    cin >> x;
  ll res = -1e18;
  for (int i = 0; i < N; i++) {
    vector<ll> sum;
    ll t = 0;
    int idx = i;
    do {
      t += C[idx];
      sum.push_back(t);
      idx = P[idx];
    } while (idx - i);
    for (int j = 0; j < min<int>(K, sum.size()); j++)
      res = max(res, sum[j]);
    ll sz = sum.size();
    for (int j = 0; j < sz; j++) {
      if (j < K % sz) {
        res = max(res, K / sz * sum.back() + sum[j]);
      } else {
        int cnt = K / sz - 1;
        if (cnt < 0)
          break;
        res = max(res, cnt * sum.back() + sum[j]);
      }
    }
  }
  cout << res << endl;
}
Problem p02585 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <forward_list>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <tuple>
#include <utility>
#include <vector>
#define rep(i, s, g) for ((i) = (s); (i) < (g); ++(i))
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
const ll MOD = 1e9 + 7;
const ll INF = (1ll << 60);

int main(void) {
  ll n, k;
  ll ans = -INF;
  cin >> n >> k;

  vector<ll> p(n), c(n);

  for (int i = 0; i < n; i++) {
    cin >> p[i];
    p[i]--;
  }

  for (int i = 0; i < n; i++) {
    cin >> c[i];
  }

  for (int i = 0; i < n; i++) {
    ll cycle_sum = 0;
    ll next_i = i;
    ll cycle_cnt = 0;

    while (true) {
      cycle_cnt++;
      next_i = p[next_i];
      cycle_sum += c[next_i];
      if (next_i == i) {
        break;
      }
    }

    next_i = i;
    ll cnt = 0;
    ll path = 0;

    while (true) {
      cnt++;
      path += c[next_i];

      if (cnt > k) {
        break;
      }

      ll score = path + max(0ll, cycle_sum) * ((k - cnt) / cycle_cnt);

      ans = max(ans, score);

      next_i = p[next_i];
    }
  }

  cout << ans << endl;
}


Fixed submission:
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <forward_list>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <tuple>
#include <utility>
#include <vector>
#define rep(i, s, g) for ((i) = (s); (i) < (g); ++(i))
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
const ll MOD = 1e9 + 7;
const ll INF = (1ll << 60);

int main(void) {
  ll n, k;
  ll ans = -INF;
  cin >> n >> k;

  vector<ll> p(n), c(n);

  for (int i = 0; i < n; i++) {
    cin >> p[i];
    p[i]--;
  }

  for (int i = 0; i < n; i++) {
    cin >> c[i];
  }

  for (int i = 0; i < n; i++) {
    ll cycle_sum = 0;
    ll next_i = i;
    ll cycle_cnt = 0;

    while (true) {
      cycle_cnt++;
      next_i = p[next_i];
      cycle_sum += c[next_i];
      if (next_i == i) {
        break;
      }
    }

    next_i = i;
    ll cnt = 0;
    ll path = 0;

    while (true) {
      cnt++;
      path += c[next_i];

      if (cnt > k) {
        break;
      }

      ll score = path + max(0ll, cycle_sum) * ((k - cnt) / cycle_cnt);

      ans = max(ans, score);

      next_i = p[next_i];

      if (next_i == i) {
        break;
      }
    }
  }

  cout << ans << endl;
}
Problem p02585 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
int main() {
  ll n, k;
  ll r;
  cin >> n >> k;
  vector<vector<ll>> v(n);
  vector<ll> p(n), c(n), siz(n, 0);
  for (ll &i : p)
    cin >> i, --i;
  for (ll &i : c)
    cin >> i;
  r = c[0];
  for (ll i = 0; i < n; ++i) {
    ll cur = i, sum = 0;
    do {
      ++siz[i];
      v[i].push_back(sum += c[cur]);
      cur = p[cur];
    } while (cur != i);
  }
  for (ll i = 0; i < n; ++i) {
    ll kt = k, s = 0, tail = v[i].back();
    if (kt > siz[i] * 2 && tail > 0) {
      s = tail * (k / siz[i] - 1);
      kt = k % siz[i] + siz[i];
    }
    for (ll j = 0; j < kt; ++j)
      r = max(r, s + v[i][j % siz[i]] + tail * (j >= siz[i]));
  }
  cout << r;
}


Fixed submission:
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
int main() {
  ll n, k;
  ll r;
  cin >> n >> k;
  vector<vector<ll>> v(n);
  vector<ll> p(n), c(n), siz(n, 0);
  for (ll &i : p)
    cin >> i, --i;
  for (ll &i : c)
    cin >> i;
  r = c[0];
  for (ll i = 0; i < n; ++i) {
    ll cur = i, sum = 0;
    do {
      ++siz[i];
      v[i].push_back(sum += c[cur]);
      cur = p[cur];
    } while (cur != i);
  }
  for (ll i = 0; i < n; ++i) {
    ll kt = k, s = 0, tail = v[i].back();
    if (k > siz[i] * 2) {
      if (tail > 0) {
        s = tail * (k / siz[i] - 1);
        kt = k % siz[i] + siz[i];
      } else
        kt = siz[i];
    }
    for (ll j = 0; j < kt; ++j)
      r = max(r, s + v[i][j % siz[i]] + tail * (j >= siz[i]));
  }
  cout << r;
}
Problem p02585 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#define MOD (long long)(1e9 + 7)
using namespace std;
long long n, k, vis[5005];
long long p[5005], c[5005], sum[5005], ans = -1e18;
int main() {
  cin >> n >> k;
  for (int i = 1; i <= n; i++)
    cin >> p[i];
  for (int i = 1; i <= n; i++)
    cin >> c[i];
  for (int i = 1; i <= n; i++) {

    long long s = c[i];

    vector<long long> ti;
    ti.push_back(s);

    for (int j = p[i]; j != i; j = p[i]) {
      s += c[j];
      ti.push_back(s);
    }
    int len = ti.size();
    for (int j = 0; j < len; j++) {

      long long rest = k - j - 1;
      if (rest < 0)
        break;
      ans = max(ans, rest / len * max(0LL, s) + ti[j]);
    }
  }

  cout << ans;
}


Fixed submission:
#include <bits/stdc++.h>
#define MOD (long long)(1e9 + 7)
using namespace std;
long long n, k, vis[5005];
long long p[5005], c[5005], sum[5005], ans = -1e18;
int main() {
  cin >> n >> k;
  for (int i = 1; i <= n; i++)
    cin >> p[i];
  for (int i = 1; i <= n; i++)
    cin >> c[i];
  for (int i = 1; i <= n; i++) {

    long long s = c[i];

    vector<long long> ti;
    ti.push_back(s);

    for (int j = p[i]; j != i; j = p[j]) {
      s += c[j];
      ti.push_back(s);
    }
    int len = ti.size();
    for (int j = 0; j < len; j++) {

      long long rest = k - j - 1;
      if (rest < 0)
        break;
      ans = max(ans, rest / len * max(0LL, s) + ti[j]);
    }
  }

  cout << ans;
}
Problem p02585 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e2 + 9;
const double ep = 1e-7;
const int mod = 998244353;
const double pi = acos(-1);
const int INF = -1e9;
#define mk make_pair
#define PII pair<int, int>
#define PIII pair<int, PII>
#define PIL pair<int, ll>
#define PLI pair<ll, int>
#define eb emplace_back
typedef long long ll;
ll n, k, p[maxn], c[maxn], ans = -1e9;
int main() {
  scanf("%lld%lld", &n, &k);
  for (int i = 1; i <= n; i++)
    scanf("%lld", &p[i]);
  for (int i = 1; i <= n; i++)
    scanf("%lld", &c[i]);
  for (int i = 1; i <= n; i++) {
    ll now = i, num = 0, sum = 0;
    do {
      now = p[now];
      sum += c[now];
      num++;
    } while (now != i);
    now = i;
    ll ss = 0;
    for (int j = 1; j <= min(k, num); j++) {
      now = p[now];
      ss += c[now];
      ans = max(ans, ss);
      ans = max(ans, ss + sum * ((k - j) / num));
    }
  }
  printf("%lld\n", ans);
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e3 + 9;
const double ep = 1e-7;
const int mod = 998244353;
const double pi = acos(-1);
const int INF = -1e9;
#define mk make_pair
#define PII pair<int, int>
#define PIII pair<int, PII>
#define PIL pair<int, ll>
#define PLI pair<ll, int>
#define eb emplace_back
typedef long long ll;
ll n, k, p[maxn], c[maxn], ans = -1e9;
int main() {
  scanf("%lld%lld", &n, &k);
  for (int i = 1; i <= n; i++)
    scanf("%lld", &p[i]);
  for (int i = 1; i <= n; i++)
    scanf("%lld", &c[i]);
  for (int i = 1; i <= n; i++) {
    ll now = i, num = 0, sum = 0;
    do {
      now = p[now];
      sum += c[now];
      num++;
    } while (now != i);
    now = i;
    ll ss = 0;
    for (int j = 1; j <= min(k, num); j++) {
      now = p[now];
      ss += c[now];
      ans = max(ans, ss);
      ans = max(ans, ss + sum * ((k - j) / num));
    }
  }
  printf("%lld\n", ans);
}
Problem p02585 (Python)

Buggy submission (status: Runtime Error):
n, k = [int(z) for z in input().strip().split()]
p = [int(z) - 1 for z in input().strip().split()]
c = [int(z) for z in input().strip().split()]

visited = [False for _ in range(n)]
cycle = []
for start in range(n):
    if visited[start]:
        continue
    now = start
    route = []
    while not visited[now]:
        visited[now] = True
        route.append(now)
        now = p[now]
    cycle.append(route)

min_c = min(c)
max_value = min_c
for route in cycle:
    full_value = sum([c[i] for i in route])
    double_route = route + route
    v = [c[i] for i in double_route]
    max_sum_step = []
    for step in range(1, len(route)):
        s = sum(v[:step])
        max_sum = max(s, min_c)
        for idx in range(step, step + len(route) - 1):
            s += v[idx]
            if idx >= step:
                s -= v[idx - step]
            max_sum = max(s, max_sum)
        max_sum_step.append(max_sum)
    addition = k % len(route)
    if full_value > 0:
        value1 = int(k / len(route)) * full_value + max(max_sum_step[:addition])
        value2 = (int(k / len(route)) - 1) * full_value + max(max_sum_step)
        value = max(value1, value2)
    else:
        value = max(max_sum_step[: min(k, len(max_sum_step))])
    max_value = max(max_value, value)
print(max_value)


Fixed submission:
n, k = [int(z) for z in input().strip().split()]
p = [int(z) - 1 for z in input().strip().split()]
c = [int(z) for z in input().strip().split()]

visited = [False for _ in range(n)]
cycle = []
for start in range(n):
    if visited[start]:
        continue
    now = start
    route = []
    while not visited[now]:
        visited[now] = True
        route.append(now)
        now = p[now]
    cycle.append(route)

min_c = min(c)
max_value = min_c
for route in cycle:
    full_value = sum([c[i] for i in route])
    double_route = route + route
    v = [c[i] for i in double_route]
    max_sum_step = []
    for step in range(1, len(route)):
        s = sum(v[:step])
        max_sum = max(s, min_c)
        for idx in range(step, step + len(route) - 1):
            s += v[idx]
            if idx >= step:
                s -= v[idx - step]
            max_sum = max(s, max_sum)
        max_sum_step.append(max_sum)
    addition = k % len(route)
    if full_value > 0:
        addition_value = 0 if addition == 0 else max(max_sum_step[:addition])
        value1 = int(k / len(route)) * full_value + addition_value
        value2 = (int(k / len(route)) - 1) * full_value + max(max_sum_step)
        value = max(value1, value2)
    else:
        value = max(max_sum_step[: min(k, len(max_sum_step))])
    max_value = max(max_value, value)
print(max_value)
Problem p02585 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
  ll n, k;
  cin >> n >> k;
  vector<ll> p(n);
  vector<ll> c(n);
  for (ll i = 0; i < n; i++) {
    ll _p;
    cin >> _p;
    p[i] = _p - 1;
  }
  for (ll i = 0; i < n; i++) {
    cin >> c[i];
  }

  ll best = -INFINITY;
  for (ll start = 0; start < n; start++) {
    set<ll> steped;
    ll score = 0;
    ll mode = 0;
    ll turnparloop = INFINITY;
    ll scoreparloop = 0;
    ll loopstart = -1;
    ll _turnls = 0;
    ll _scorels = 0;
    ll now = start;
    ll turn = 0;
    for (; turn < k; turn++) {
      if (mode == 0 && steped.count(now)) {
        mode = 1;
        _turnls = turn;
        _scorels = score;
        loopstart = now;
      } else if (mode == 1 && loopstart == now) {
        mode = 2;
        scoreparloop = score - _scorels;
        turnparloop = turn - _turnls;
        break;
      }
      if (mode == 0)
        steped.insert(now);
      now = p[now];
      score += c[now];
      best = max(best, score);
    }
    if (scoreparloop > 0) {
      ll loops = max(0ll, (k - turn - 1) / turnparloop - 1);
      score += scoreparloop * loops;
      turn += turnparloop * loops;
      best = max(best, score);
      for (; turn < k; turn++) {
        now = p[now];
        score += c[now];
        best = max(best, score);
      }
    }
  }
  cout << best;
  return 0;
}

Fixed submission:
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
  ll n, k;
  cin >> n >> k;
  vector<ll> p(n);
  vector<ll> c(n);
  for (ll i = 0; i < n; i++) {
    ll _p;
    cin >> _p;
    p[i] = _p - 1;
  }
  for (ll i = 0; i < n; i++) {
    cin >> c[i];
  }

  ll best = -INFINITY;
  for (ll start = 0; start < n; start++) {
    unordered_set<ll> steped;
    ll score = 0;
    ll mode = 0;
    ll turnparloop = INFINITY;
    ll scoreparloop = 0;
    ll loopstart = -1;
    ll _turnls = 0;
    ll _scorels = 0;
    ll now = start;
    ll turn = 0;
    for (; turn < k; turn++) {
      if (mode == 0 && steped.count(now)) {
        mode = 1;
        _turnls = turn;
        _scorels = score;
        loopstart = now;
      } else if (mode == 1 && loopstart == now) {
        mode = 2;
        scoreparloop = score - _scorels;
        turnparloop = turn - _turnls;
        break;
      }
      if (mode == 0)
        steped.insert(now);
      now = p[now];
      score += c[now];
      best = max(best, score);
    }
    if (scoreparloop > 0) {
      ll loops = max(0ll, (k - turn - 1) / turnparloop - 1);
      score += scoreparloop * loops;
      turn += turnparloop * loops;
      best = max(best, score);
      for (; turn < k; turn++) {
        now = p[now];
        score += c[now];
        best = max(best, score);
      }
    }
  }
  cout << best;
  return 0;
}