Keep the largest rooted connected subtree containing the CEO so all kept salaries fit within a range of width D.
Hard8TreeSliding windowSortingSegment treeNo attempts yetTime limit10sMemory limit512 MBFairland regulates how companies organize and pay their employees with these laws.
The government has just passed one more law.
Marie is the CEO of Fairland General Stuff Corporation, and she has to make the company comply with the new law. That may require laying off some employees. She knows the list of employees, each employee's manager, and each employee's salary. Find the largest number of employees she can keep, including herself.
The first line contains the number of test cases T. T test cases follow.
The first line of each test case contains two space separated integers, the number of employees N and the maximum allowed salary difference D. The second line contains four space separated integers S0, As, Cs, Rs, and the third line contains four space separated integers M0, Am, Cm, Rm. These eight integers define two sequences.
Si+1=(Si×As+Cs)modRs
Mi+1=(Mi×Am+Cm)modRm
Marie's employee ID is 0, and the other employees have IDs from 1 to N−1. The salary of employee i is Si. For every employee i other than Marie, the manager is Mimodi. So M0 has nothing to do with Marie's manager. Marie has none.
For each test case, print one line in the format Case #x: y, where x is the test case number starting from 1 and y is the largest number of employees Marie can keep, including herself, so that laws 1 through 7 all hold.
In the first test case of the sample input the company has only the CEO and no other employees. It breaks none of the laws, so nobody is laid off.
In the second test case the sequences for employees 1 through 5 are these.
The org chart is therefore this. Marie (employee 0) manages employee 1, employee 1 manages employees 2, 3 and 5, and employee 2 manages employee 4. The salaries of employees 0 through 5 are 10, 13, 16, 2, 5, 8, and D=5.
The best choice keeps employees 0, 1 and 5, whose salaries are 10, 13 and 8. Employee 2, for instance, cannot be kept. Her salary is more than 5 away from employee 0's salary of 10, and employee 0 cannot be laid off, so employee 2 and everyone reporting to her must go.