[UVA] 11155 - Be Efficient
|
Consider an integer sequence consisting of N elements, where -
X0 = A
Xi = (( (Xi-1) * B + C ) % M)+1 ���� for i = 1 to N-1
You will be given the values of A, B, C, M and N. Find out the number of� �consecutive subsequences� whose sum is a multiple of M.
Consider an example where A = 2, B = 1, C = 2, M = 4 and N = 4.
So, X0 = 2, X1 = 1, X2 = 4 and X3 = 3.
The consecutive subsequences are {2}, {2 1}, {2 1 4}, {2 1 4 3}, {1}, {1 4}, {1 4 3}, {4}, {4 3} and {3}.
Of these 10 �consecutive subsequences�, only two of them adds up to a figure that is a multiple of 4 �{1 4 3} and {4}.
Input
The first line of input is an integer T(T<500) that indicates the number of test cases. Eact case consists of 5 integers A, B, C, M and N. A, B and C will be non-negative integers not greater than 1000.� N and M will be a positive integers not greater than 10000.
Output
For each case, output the case number followed by the result.
Sample Input |
Output for Sample Input |
2 2 1 2 4 4 923 278 195 8685 793 |
Case 1: 2 Case 2: 34 |
Problem Setter: Mohiul Alam Prince
Moderator and Alternate Solution: Sohel Hafiz
題目描述:
根據給定的方程將陣列建出來,問有多少組區間總合是 M 的倍數。
題目解法:
記錄一個累計值 A[i] = sigma(X[i])%M。
對於一個區間 X[l ... r] 的總合,可以看成 A[r]-A[l-1],如果存在是 M 的倍數,
那麼 A[l] 和 A[r] 具有相同的餘數,因此用掃描線的思路去看,找 0...i-1 有多少組餘數等於 A[i]。
但是如果餘數為 0 要特別考慮自己本身。
#include <stdio.h>
int X[10005];
int main() {
int A, B, C, M, N;
int testcase, cases = 0;
int i;
scanf("%d", &testcase);
while(testcase--) {
scanf("%d %d %d %d %d", &A, &B, &C, &M, &N);
X[0] = A;
for(i = 1; i < N; i++)
X[i] = (X[i-1]*B+C)%M+1;
int sum = 0, mark[10005] = {};
int ret = 0;
for(i = 0; i < N; i++) {
sum = (sum+X[i])%M;
ret += mark[sum];
if(sum == 0) ret++;
mark[sum]++;
}
printf("Case %d: %d\n", ++cases, ret);
}
return 0;
}