Daisy chains#10365

Daisy chains (Editorial)

The solution runs in O(n^3). Iterate over all possible intervals [i; j]~(0 \le i \le j < n) and check whether they contain a median flower. For this, there must exist some p_k~(i \le k \le j) such that

p_k = totalPetals / (j - i + 1),

where totalPetals is the total number of petals of the flowers in the interval .

Algorithm implementation — O(n^3)

Declare an array to store the number of petals p_i in each flower.

#define MAX 101
int p[MAX];

Read the input data.

scanf("%d", &n);
for (i = 0; i < n; i++)
  scanf("%d", &p[i]);

The number of photographs that contain a median flower will be stored in the variable .

photos = 0;

Iterate over all possible intervals [i; j]~(0 \le i \le j < n) and check whether the average number of petals of the flowers in this interval matches the number of petals of at least one of them.

for (i = 0; i < n; i++)
for (j = i; j < n; j++)
{

The variable totalPetals stores the total number of petals of the flowers in the interval .

  int totalPetals = 0;
  for (k = i; k <= j; k++)
    totalPetals += p[k];

Iterate over the values p_k in the interval [i; j]~(i \le k \le j). If p_k is equal to the average number of petals among all flowers in the photograph on the interval , then increase the value of by . For this, the following condition must hold:

p_k = totalPetals / (j - i + 1)
  present = 0;
  for (int k = i; k <= j; k++)
    if (p[k] * (j - i + 1) == totalPetals) present = 1;
  if (present) photos++;
}

Print the answer.

printf("%d\n", photos);