- Title Description
In a given sequence of integers, a small L wanted to find a continuous range, and this range can be divisible by k, would you please help small L count to meet the conditions of the longest interval length is.
Entry
The first line of the input two integers n, k. (1 <= n <= 105,1 <= k <100)
the next line of input integer n, the number of sequences in FIG.
the next line of input integer n, the number of sequences in FIG.
Export
Output an integer, satisfying the condition longest length section, and if not, outputs 0
- Sample input
5 7
1 2 4 1 1
- Sample Output
3
Solution:
Prefix and an array of arrays built up first. K mold during construction, and so in this case the array of all the number of prefixes belonging to [0, K-1], if there are two positions i, j, and the prefix array pre [i] == pre [j ], then do not K and prefix die array pre [j] -pre [i] result must be a multiple of K, ji is the length.
So we aim to become a constantly looking for: pre [i] == pre [ j], save length = ji and updates. The following code is used: map is first initialized to -1, then encountered during traversal of the recording position on pre [i] of the first occurrence of
#include <bits / STDC ++ H.> the using namespace STD; typedef Long Long LL; const int NN = 1E5; int N, K; int A [NN + 10 ]; // source array int pre [NN + 10 ]; // prefix and array Map < int , int > MP; // MP [n] = i represents the prefix and the number n in the array occurs first at position i int main () { CIN >> N >> K; for ( int i = . 1 ; I <= N; I ++) { // read data Scanf ( " % D " , & A [I]); } for ( int I = . 1 ; I <= N; I ++) { // Construction prefix and the array and modulo K pre [I] = (A [I] + pre [I- . 1 ])% K; MP [pre [I]] = - . 1 ; // initialized to -1 } int the maxlen = 0 ; // longest length for ( int I = . 1 ; I <= N ; I ++ ) { IF (MP [pre [I]] == - . 1 ) { MP [pre [I]] = I; // position into the first occurrence } The else { the maxlen = max (the maxlen, I-mp [pre [i]]); // I is pre [i] At this time, a position mp [pre [i]] is the location of pre [i] of the first time , two subtraction of multiples k } } COUT << the maxlen << endl; return 0 ; }
Another writing position with the vector, vector and array elements stored prefixes appear
#include <bits / STDC ++ H.> the using namespace STD; typedef Long Long LL; const int NN = 1E5; int N, K; int A [NN + 10 ]; // source array int pre [NN + 10 ]; // prefix and an array of Vector < int > VE [ 110 ]; int main () { CIN >> N >> K; for ( int I = . 1 ; I <= N; I ++) { // read data Scanf ( " % D",&a[i]); } ve[0].push_back(0); for(int i = 1;i<=N;i++){ //构建前缀和数组并取余K pre[i] = (a[i]+pre[i-1])%K; ve[pre[i]].push_back(i); } int maxlen = 0; for(int i = 0;i<K;i++){ if(ve[i].size()>1) maxlen = max(maxlen,ve[i][ve[i].size()-1] - ve[i][0]); // last occurrence position - the position of the first occurrence } COUT << the maxlen << endl; return 0 ; }