Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- import java.math.*;
- import java.awt.geom.*;
- import static java.lang.Math.*;
- public class Solution implements Runnable {
- public void solve() throws Exception {
- int n = sc.nextInt();
- String str = in.readLine();
- int[] balance = new int[n + 1];
- for (int i = 0; i < n; i++) {
- if (str.charAt(i) == 'a') {
- balance[i + 1] = balance[i] + 1;
- } else {
- balance[i + 1] = balance[i] - 1;
- }
- }
- Arrays.sort(balance);
- long ans = 0;
- for (int i = 0; i <= n; ) {
- int j = i;
- while (j <= n && balance[j] == balance[i]) {
- j++;
- }
- long cnt = j - i;
- ans += cnt * (cnt - 1) / 2;
- i = j;
- }
- out.println(ans);
- }
- static Throwable uncaught;
- BufferedReader in;
- FastScanner sc;
- PrintWriter out;
- @Override
- public void run() {
- try {
- in = new BufferedReader(new InputStreamReader(System.in));
- out = new PrintWriter(System.out);
- sc = new FastScanner(in);
- solve();
- } catch (Throwable uncaught) {
- Solution.uncaught = uncaught;
- } finally {
- out.close();
- }
- }
- public static void main(String[] args) throws Throwable {
- Thread thread = new Thread(null, new Solution(), "", (1 << 26));
- thread.start();
- thread.join();
- if (Solution.uncaught != null) {
- throw Solution.uncaught;
- }
- }
- }
- class FastScanner {
- BufferedReader in;
- StringTokenizer st;
- public FastScanner(BufferedReader in) {
- this.in = in;
- }
- public String nextToken() throws Exception {
- while (st == null || !st.hasMoreTokens()) {
- st = new StringTokenizer(in.readLine());
- }
- return st.nextToken();
- }
- public int nextInt() throws Exception {
- return Integer.parseInt(nextToken());
- }
- public long nextLong() throws Exception {
- return Long.parseLong(nextToken());
- }
- public double nextDouble() throws Exception {
- return Double.parseDouble(nextToken());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment