1238D - AB-string - CodeForces Solution


binary search combinatorics dp strings *1900

Please click on ads to support us..

Python Code:

n=int(input())
s=input()

ans=(n-1)*n//2
ab=0
for _ in range(2):
    con=1
    for i in range(n-1):
        if s[i]==s[i+1]:
            con+=1
        else:
            ans-=con
            con=1
            ab+=1
    s=s[::-1]
print(ans+ab//2)

C++ Code:

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ull unsigned long long
#define pb push_back
#define foru(i,a,b) for(int i = a; i <= b; i++)
#define ford(i,a,b) for(int i = a; i >= b; i--)
#define fi first
#define se second
#define endl "\n"

typedef pair<ll,ll> ii;
typedef vector<ii> vii;

const int maxn = 3e5 + 7;
const int oo = 1e9 + 7;
const int MOD = 1e9 + 7;
const int block_size = 750;

void init() {
    if(fopen("1238D.inp", "r")) {
        freopen("1238D.inp","r",stdin);
        freopen("1238D.out","w",stdout);
    }
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
}


int main() {
    init();
    int n; string str;
    cin >> n >> str;

    ll sub = 0;
    for(int i = 0; i < n; i++) {
        for(int j = i + 1; j < n && str[j] != str[i]; j++) sub++;
        for(int j = i - 1; j >= 0 && str[j] != str[i]; j--) sub++;
        if(i > 0 && str[i - 1] != str[i]) sub--;
//        cout << i << ' ' << sub << endl;
    }

    ll res = 1ll * n * (n - 1) / 2 - sub;
    cout << res;
}



Comments

Submit
0 Comments
More Questions

Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices
Happy segments
Cyclic shifts
Zoos
Build a graph
Almost correct bracket sequence
Count of integers
Differences of the permutations
Doctor's Secret
Back to School
I am Easy
Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement
Numbers in a matrix