公式
B - DNA Sequence 解説
by
B - DNA Sequence 解説
by
satashun
まず、どのような文字列が条件を満たすかについてですが、
- A の相手は T
- T の相手は A
- C の相手は G
- G の相手は C
なので
- Aの個数 = Tの個数
- Cの個数 = Gの個数
が必要十分です。
各区間が条件を満たすかは例えば左端が同じ区間をまとめて処理するなどで簡単に判定できるので、全体として \(\mathrm{O}(N^2)\) の時間計算量で解けます。
bonus : \(N \leq 2 \times 10^5\)
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
string S;
cin >> N >> S;
int ans = 0;
for (int i = 0; i < N; ++i) {
int c1 = 0, c2 = 0;
for (int j = i; j < N; ++j) {
if (S[j] == 'A')
c1++;
else if (S[j] == 'T')
c1--;
else if (S[j] == 'C')
c2++;
else
c2--;
if (c1 == 0 && c2 == 0) ans++;
}
}
cout << ans << endl;
return 0;
}
投稿日時:
最終更新: