fork download
  1. // ~~ icebear ~~
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7. typedef pair<int, ii> iii;
  8.  
  9. template<class T>
  10. bool minimize(T &a, const T &b) {
  11. if (a > b) return a = b, true;
  12. return false;
  13. }
  14.  
  15. template<class T>
  16. bool maximize(T &a, const T &b) {
  17. if (a < b) return a = b, true;
  18. return false;
  19. }
  20.  
  21. #define FOR(i,a,b) for(int i=(a); i<=(b); ++i)
  22. #define FORR(i,a,b) for(int i=(a); i>=(b); --i)
  23. #define REP(i, n) for(int i=0; i<(n); ++i)
  24. #define RED(i, n) for(int i=(n)-1; i>=0; --i)
  25. #define MASK(i) (1LL << (i))
  26. #define BIT(S, i) (((S) >> (i)) & 1)
  27. #define mp make_pair
  28. #define pb push_back
  29. #define fi first
  30. #define se second
  31. #define all(x) x.begin(), x.end()
  32. #define task "investitie"
  33. /*END OF TEMPLATE. ICEBEAR AND THE CAT WILL WIN VOI26 */
  34.  
  35. const int MOD = 1e9 + 7;
  36. const int inf = 1e9 + 27092008;
  37. const ll INF = 1e18 + 27092008;
  38. const int N = 2e5 + 5;
  39. int numComp, numDay, numQuery, perm[N], nxt[N][33];
  40. ll sum[N][33];
  41.  
  42. ll calcSum(int i, int k) {
  43. ll ans = 0;
  44. FOR(j, 0, 30) if (BIT(k, j)) {
  45. ans += sum[i][j];
  46. i = nxt[i][j];
  47. }
  48. return ans;
  49. }
  50.  
  51. void init(void) {
  52. cin >> numComp >> numDay;
  53. FOR(i, 1, numComp) cin >> perm[i];
  54. cin >> numQuery;
  55. }
  56.  
  57. void process(void) {
  58. FOR(i, 1, numComp) {
  59. nxt[i][0] = perm[i];
  60. sum[i][0] = perm[i];
  61. }
  62. FOR(j, 1, 30) FOR(i, 1, numComp) {
  63. nxt[i][j] = nxt[nxt[i][j - 1]][j - 1];
  64. sum[i][j] = sum[i][j - 1] + sum[nxt[i][j - 1]][j - 1];
  65. }
  66.  
  67. while(numQuery--) {
  68. int lday, rday, lcomp, rcomp;
  69. cin >> lday >> rday >> lcomp >> rcomp;
  70. ll ans = 0;
  71. FOR(i, lcomp, rcomp) ans += calcSum(i, rday) - calcSum(i, lday - 1);
  72. cout << ans << '\n';
  73. }
  74. }
  75.  
  76. int main() {
  77. ios_base::sync_with_stdio(0);
  78. cin.tie(0); cout.tie(0);
  79. if (fopen(task".in", "r")) {
  80. freopen(task".in", "r", stdin);
  81. freopen(task".out", "w", stdout);
  82. }
  83. int tc = 1;
  84. // cin >> tc;
  85. while(tc--) {
  86. init();
  87. process();
  88. }
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
Standard output is empty