*[hackerrank]Consecutive Subsequences

https://www.hackerrank.com/contests/w6/challenges/consecutive-subsequences

求数组中被k整除的子段和有几个。这个要利用sum[i..j] = sum[j] - sum[i-1],注意这样还要保留一个sum[-1]=0(根据下标的起点怎么定)。那么能被k整除的子段sum[i..j]的sum[j]和sum[i-1] %k的值是一样的。

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int T;
    cin >> T;
    while (T--) {
        int n, k;
        cin >> n >> k;
        int sum = 0;
        vector<int> cnt(k);
        cnt[0] = 1;
        for (int i = 0; i < n; i++) {
            int tmp;
            cin >> tmp;
            sum += tmp;
            sum %= k;
            cnt[sum]++;
        }
        long long count = 0;
        for (int i = 0; i < k; i++) {
            count += ((long long)cnt[i] * (cnt[i] - 1) / 2);
        }  
        cout << count << endl;
    }
    return 0;
}

  

posted @ 2014-08-13 13:28  阿牧遥  阅读(447)  评论(0编辑  收藏  举报