#K47482. Sum of Distances in Clusters

    ID: 28208 Type: Default 1000ms 256MiB

Sum of Distances in Clusters

Sum of Distances in Clusters

In this problem, you are given a binary string of length (n). A cluster is defined as a contiguous block of '1's. In each cluster, the first '1' is considered the leader and every subsequent '1' in the same cluster contributes a distance equal to its index difference from the leader. Your task is to compute the total sum of these distances over the entire string.

For example, consider the binary string 1100011000 of length 10. The clusters and their distances are as follows:

  • For the first cluster "11": the leader is at index 0 and the next '1' at index 1 contributes (1 - 0 = 1).
  • For the second cluster "11": the leader is at index 5 and the next '1' at index 6 contributes (6 - 5 = 1).

Thus, the total sum (= 1 + 1 = 2).

Formally, if a cluster starts at index (i) (0-indexed) and consists of '1's at positions (i, i+1, \ldots, i+k), then the sum contributed by this cluster is given by: [ \sum_{j=1}^{k} (i+j - i) = \sum_{j=1}^{k} j ]

inputFormat

The input consists of two lines:

  1. The first line contains a single integer (n) denoting the length of the binary string.
  2. The second line contains a binary string (S) of length (n), composed only of the characters '0' and '1'.

outputFormat

Output a single integer: the sum of distances between each '1' (except the leader) and the leader of its cluster.## sample

10
1100011000
2