#P2965. [USACO09NOV] The Grand Farm-off S

[USACO09NOV] The Grand Farm-off S

Description

Farmer John owns 3N3N cows (with 1N500,0001 \le N \le 500{,}000), numbered 03N10 \ldots 3N - 1. Each cow ii has an integer weight WiW_i and a utility rating UiU_i.

He may enter a group of NN cows into the Grand Farm-off. He wants to choose NN cows whose total utility is maximized. If multiple sets of NN cows achieve the same maximum total utility, he prefers the set with the minimum possible total weight.

Among all selections of NN cows that maximize the total utility, find the minimum possible total weight, and output the remainder when this total weight is divided by MM (with 10,000,000M1,000,000,00010{,}000{,}000 \le M \le 1{,}000{,}000{,}000).

To speed up input, the weights and utilities are generated by polynomials. For each cow 0i<3N0 \le i < 3N,

Wi=(a×i5+b×i2+c)moddW_i=(a\times i^5+b\times i^2+c)\mod d Ui=(e×i5+f×i3+g)modhU_i=(e\times i^5+f\times i^3+g)\mod h (0a,b,c,d,e,f,g,h109)(0\le a,b,c,d,e,f,g,h\le 10^9)

Note that these formulae can generate duplicate values; your algorithm should handle this properly. Also, 0Wi<d0 \le W_i < d and 0Ui<h0 \le U_i < h.

Input Format

Line 1: Ten space-separated integers NN, aa, bb, cc, dd, ee, ff, gg, hh, MM.

Output Format

Line 1: A single integer — the remainder when the minimum possible total weight (among all selections of NN cows that maximize total utility) is divided by MM.

2 0 1 5 55555555 0 1 0 55555555 55555555 

51 

Hint

The functions generate weights of 5, 6, 9, 14, 21, and 30 along with utilities of 0, 1, 8, 27, 64, and 125.

The two cows with the highest utility are cows 5 and 6, and their combined weight is 21+30=5121 + 30 = 51.

Translated by ChatGPT 5