zoukankan      html  css  js  c++  java
  • CodeForces#632Div.2C. Eugene and an array

    网址:https://codeforces.ml/contest/1333/problem/C
    题目描述:
    Eugene likes working with arrays. And today he needs your help in solving one challenging task.
    An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
    Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [−1,2,−3] is good, as all arrays [−1], [−1,2], [−1,2,−3], [2], [2,−3], [−3] have nonzero sums of elements. However, array [−1,2,−1,−3] isn't good, as his subarray [−1,2,−1] has sum of elements equal to 0.
    Help Eugene to calculate the number of nonempty good subarrays of a given array a.

    Input
    The first line of the input contains a single integer n (1≤n≤2×105) — the length of array a.
    The second line of the input contains n integers a1,a2,…,an (−109≤ai≤109) — the elements of a.

    Output
    Output a single integer — the number of good subarrays of a.

    Examples
    input
    3
    1 2 -3
    output
    5
    input
    3
    41 -41 41
    output
    3

    Note
    In the first sample, the following subarrays are good: [1], [1,2], [2], [2,−3], [−3]. However, the subarray [1,2,−3] isn't good, as its subarray [1,2,−3] has sum of elements equal to 0.

    In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41,−41,41] isn't good, as its subarray [41,−41] has sum of elements equal to 0.

    题解:对于一个数组a要想找到他所有子数组,只需要从数组a第一个元素开始一直遍历到最后一个元素,每次遍历是从当前元素向前(此元素之前的元素)看。
    这道题就是利用sum(前i个元素之和),使用了map数据结构,map[sum]=i。准确的说是每此遍历找到以a[i]为最后一个元素的good的子数组。
    这里比较重要的就是变量pos(在后面的代码中),理解了pos就可以。
    AC代码:

        #include<iostream>
        #include<cstdio>
        #include<map>
        #define ll long long int
        using namespace std;
    
    int main(){
    	ll n,sum=0,a,ans=0,pos=-1;
    	cin>>n;
    	map<ll,ll>mp;
    	mp[0]=0;
    	for(int i=1;i<=n;i++){
    		cin>>a;
    		sum+=a;
    		if(mp.find(sum)!=mp.end()){//存在sum 
    			pos=max(pos,mp[sum]);
    		}
    		mp[sum]=i;
    		ans=ans+i-pos-1;
    	}
    	cout<<ans<<endl;
    	return 0;
    }
    

    注:碰到了许多的算法题基本都是数学题,但有时数学逻辑是真的想不到,即便是别人稍微一提及自己就能明白,但做的时候自己想着实没有想到。应该还是不熟练所致。


    作者:孙建钊
    出处:http://www.cnblogs.com/sunjianzhao/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    ulimit c unlimited
    2021.9.28 Sqoop
    2021.9.30 利用sqoop将hive数据导出到mysql
    2021.10.2 建造者模式
    111每日博客
    1029每日博客
    112每日博客
    113每日博客
    Panda 交易所视点观察!区块链金融应用迎新规,哪些版块受影响?
    c# 读取word
  • 原文地址:https://www.cnblogs.com/sunjianzhao/p/12667969.html
Copyright © 2011-2022 走看看