C++の練習を兼ねて, AtCoder Beginner Contest 162 の 問題D (D – RGB Triplets) を解いてみた.
■感想.
1. 累積和を使う方針で, 何とかAC版となった.
2. 時間を見つけて, 引き続き, 過去問を振り返っていきたいと思う.
本家のサイトABC 162 解説をご覧下さい.
■C++版プログラム(問題D/AC版).
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 |
#include <bits/stdc++.h> using namespace std; using LL = long long; #define repex(i, a, b, c) for(int i = a; i < b; i += c) #define repx(i, a, b) repex(i, a, b, 1) #define rep(i, n) repx(i, 0, n) #define repr(i, a, b) for(int i = a; i >= b; i--) LL r[4040], g[4040], b[4040]; // 'R', 'G', 'B' の 出現位置. LL rCum[4040], gCum[4040], bCum[4040]; // 累積和. int main(){ // 1. 入力情報. int N; char c[4040]; scanf("%d %s", &N, c); // 2. 'R', 'G', 'B' の 出現位置を保存. rep(i, N){ if(c[i] == 'R') r[i]++; if(c[i] == 'G') g[i]++; if(c[i] == 'B') b[i]++; } // 3. 累積和. rep(i, N){ rCum[i + 1] = rCum[i] + r[i]; gCum[i + 1] = gCum[i] + g[i]; bCum[i + 1] = bCum[i] + b[i]; } // 4. 条件を満たす組を計算. // 中央の文字 を 変えながら, 集計. LL ans = 0; repx(i, 1, N - 1){ char mc = c[i]; // 左右の文字数. int l = i, r = N - 1 - i; // 'R' の 場合. if(mc == 'R'){ // 'G' < 'R' < 'B'. ans += gCum[i] * (bCum[N] - bCum[i]); // 'B' < 'R' < 'G'. ans += bCum[i] * (gCum[N] - gCum[i]); // 中央の文字から同じ距離で, 異なる文字('G', 'B')だったら, 減算. repx(j, 1, min(l, r) + 1){ if(c[i - j] == 'G' && c[i + j] == 'B') ans--; if(c[i - j] == 'B' && c[i + j] == 'G') ans--; } } // 'G' の 場合. if(mc == 'G'){ // 'R' < 'G' < 'B'. ans += rCum[i] * (bCum[N] - bCum[i]); // 'B' < 'G' < 'R'. ans += bCum[i] * (rCum[N] - rCum[i]); // 中央の文字から同じ距離で, 異なる文字('R', 'B')だったら, 減算. repx(j, 1, min(l, r) + 1){ if(c[i - j] == 'R' && c[i + j] == 'B') ans--; if(c[i - j] == 'B' && c[i + j] == 'R') ans--; } } // 'B' の 場合. if(mc == 'B'){ // 'R' < 'B' < 'G'. ans += rCum[i] * (gCum[N] - gCum[i]); // 'G' < 'B' < 'R'. ans += gCum[i] * (rCum[N] - rCum[i]); // 中央の文字から同じ距離で, 異なる文字('R', 'G')だったら, 減算. repx(j, 1, min(l, r) + 1){ if(c[i - j] == 'R' && c[i + j] == 'G') ans--; if(c[i - j] == 'G' && c[i + j] == 'R') ans--; } } } // 5. 出力. printf("%lld\n", ans); return 0; } |
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 |
[入力例] 4 RRGB [出力例] 1 ※AtCoderテストケースより [入力例] 39 RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB [出力例] 1800 ※AtCoderテストケースより [入力例] 3 RGB [出力例] 0 [入力例] 1000 GGRGBRRGBGBRGBGRGBGRGBGRGRRBBRGGRRGRGBBGGGBGRGRRBRGGBRBGGRBRGBBRGGBRBGRRGGRGGGBBGBGBBBRRBBGGGGGBBBGBGGGGBBGRBRBGGGRRGRGGRBRBRGGBGGRGBRRBBGRBGRGBBRBRRBGRGRRGBGBGGRRGRRBBGGGRGRBBGBBRGGGGGBGGGRBBRBRRGBGRGRGBRRRGGGBRBGRGGBBRBGGRBGRBRBGBGRRGGRRGGGRGRGRBRGGRGBBGRGBGGGGGGBGRGBGBRGRBBRGBBRGGGRBBGGBGGGBBRGBRRRGRRBRGRBRBGBGRBBRRGRGBGGGGGRBGGBBGBR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