Nowcoder Xiaobao's lucky array (remainder in number theory)

Topic link

Link: https://ac.nowcoder.com/acm/contest/11746/B
Source: Niuke.com

Topic description
For Xiaobao, if the sum of an array can divide his lucky number k, it is his lucky array, and other arrays Xiaobao are very annoying. Now there is an array of length n, and Xiaobao wants to know how long the longest lucky sub-array is among the sub-arrays of this array.

For the definition of a sub-array, if it is possible to obtain array a from array b by deleting several elements from the beginning and the end respectively (it can be zero or all, the number of deletions before and after it does not have to be the same), then array a is said to be a sub Array. (The sub-array contains the original array, but does not contain the empty string)

Input description:
Multiple groups of input. The first line contains an integer T (1≤T≤10), indicating that there are T groups of test data.

Each set of test data contains two rows. The first row contains two integers n and k ( 1≤n≤10 5, 1≤k≤10 5), which represent the length of the array and Xiaobao’s lucky number, respectively. The second line contains n space-separated integers a1, a2,., an (0≤ai≤10^9), which are elements of the array.

Output description:
For each group of data, output the length of the longest sub-array that can be divisible by k. If there is no such sub-array, output −1.
Example 1
Input
Copy
4
3 3
1 2 3
3 5
1 2 3
3 7
1 2 3
1 6
5
Output
Copy
3
2
-1
-1

Calculate the prefix and when the remainder operation value is equal, it means that the sum in the middle is a multiple of k

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
int main(){
    
    
	int t;
	cin>>t;
	while(t--){
    
    
		int n,k,sum=0,nk[100009],mx=-1;
		memset(nk,-1,sizeof(nk));
		cin>>n>>k;
		nk[0]=0;//
		for(int i=1;i<=n;i++){
    
    
			int x;
			cin>>x;
			sum+=x;
			sum%=k;
			if(nk[sum]==-1)nk[sum]=i;
			else mx=max(mx,i-nk[sum]);
		}
		cout<<mx<<endl;
	}

	return 0;
	
}

Guess you like

Origin blog.csdn.net/Minelois/article/details/114106559