第八届蓝桥杯java b组第十题

标题: k倍区间

给定一个长度为N的数列,A1, A2, ... AN,如果其中一段连续的子序列Ai, Ai+1, ... Aj(i <= j)之和是K的倍数,我们就称这个区间[i, j]是K倍区间。  

你能求出数列中总共有多少个K倍区间吗?  

输入
-----
第一行包含两个整数N和K。(1 <= N, K <= 100000)  
以下N行每行包含一个整数Ai。(1 <= Ai <= 100000)  

输出
-----
输出一个整数,代表K倍区间的数目。  


例如,
输入:
5 2
1  
2  
3  
4  
5  

程序应该输出:
6

资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗  < 2000ms

import java.util.Scanner;
import java.util.Stack;

public class Test10 {
    private static int N=0;
    private static int K=0;
    private static int count=0;
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        N=scanner.nextInt();
        K=scanner.nextInt();
        int[] A=new int[N];
        for(int i=0;i<N;i++){
            A[i]=scanner.nextInt();
        }
        fun(A);
        System.out.println(count);
    }
    private static int fun(int[] a) {
        Stack<Integer> stack =new Stack<Integer>();
        for(int i=0;i<a.length;i++){
            fun1(stack,a,i);
        }
        return 0;
    }
    private static void fun1(Stack<Integer> stack, int[] a, int i) {
        for(int j=i;i<a.length;i++){
            stack.add(a[i]);
            if(sumStack(stack)%K==0){
                ++count;
            }
        }
    }
    private static int sumStack(Stack<Integer> stack) {
        int sum=0;
        for(int i=0;i<stack.size();i++){
            sum=stack.get(i);
        }
        return sum;
    }

}
恐惧源于无知,代码改变世界
原文地址:https://www.cnblogs.com/ad-zhou/p/8643578.html