fork download
  1. //{ Driver Code Starts
  2. // Initial Template for C++
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6.  
  7. // } Driver Code Ends
  8.  
  9. // User function Template for C++
  10.  
  11. class Solution {
  12. public:
  13. int countSubarrays(vector<int> &arr, int k) {
  14. // code here
  15. int n=arr.size();
  16. unordered_map<int,int>mp;
  17. int count=0;
  18. int sum=0;
  19. mp[0]=1;
  20. for(int i=0;i<n;i++){
  21. sum+=arr[i];
  22. if(mp.find(sum-k)!=mp.end()){
  23. count+=mp[sum-k];
  24. }
  25. mp[sum]++;
  26. }
  27. return count;
  28. }
  29. };
  30.  
  31.  
  32. //{ Driver Code Starts.
  33.  
  34. int main() {
  35.  
  36. int t;
  37. cin >> t;
  38. cin.ignore();
  39. while (t--) {
  40.  
  41. string ks;
  42. getline(cin, ks);
  43. int k = stoi(ks);
  44. vector<int> arr;
  45. string input;
  46. getline(cin, input);
  47. stringstream ss(input);
  48. int number;
  49. while (ss >> number) {
  50. arr.push_back(number);
  51. }
  52. Solution obj;
  53. cout << obj.countSubarrays(arr, k);
  54. cout << endl;
  55. cout << "~"
  56. << "\n";
  57. }
  58.  
  59. return 0;
  60. }
  61.  
  62. // } Driver Code Ends
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Standard output is empty