Array's force
Practice
3.4 (78 votes)
Approved
Easy
Greedy algorithms
Math
Open
Problem
77% Success 10416 Attempts 30 Points 2s Time Limit 256MB Memory 1024 KB Max Code

Let's consider some array A. The following algorithm calculates it's force:

  1. Find all the continuous blocks where all the elemens of A are equal.
  2. Calculate sum of squared lengths of these blocks.

For example if array A = {2, 3, 3, 1, 1, 1, 4, 2, 2} its force will be 12 + 22 + 32 + 12 + 22 = 19

We can reorder some elements and get array with greater force. In the example above we can move the first element of A to the end and get array A = {3, 3, 1, 1, 1, 4, 2, 2, 2} with force 22 + 32 + 12 + 32 = 23.

You are given an array. What is the maximum force you can get by reordering some of its elements?

Input
The first line contains integer T denoting the number of test cases. The following T lines contain 4 integers each: A[0], A[1], N, MOD.

Array A of N elements is generated by the following way:

  • A[0], A[1] are given
  • A[i] = (A[i - 1] + A[i - 2]) modulo MOD for 1 < i < N.

Output
For each test case output one integer on the separate line - answer for the question.

Constraints

  • 1 <= T <=100
  • 0 <= A[0], A[1] <= 10^6
  • 2 <= N <= 10^6
  • max(A[0] , A[1]) < MOD < 10^6

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
10 votes
Tags:
SortingAlgorithmsBasics of Greedy AlgorithmsGreedy Algorithms
Points:30
16 votes
Tags:
AlgorithmsEasyGreedy Algorithms
Points:30
17 votes
Tags:
AlgorithmsBasics of Greedy AlgorithmsC++Greedy Algorithms