zoukankan      html  css  js  c++  java
  • 985. Sum of Even Numbers After Queries

    We have an array A of integers, and an array queries of queries.

    For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].  Then, the answer to the i-th query is the sum of the even values of A.

    (Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)

    Return the answer to all queries.  Your answer array should have answer[i] as the answer to the i-th query.

    有一个数组A,和一个query数组,每次query,会在数组A下标为query[i][1]的地方加上query[i][0],然后统计下偶数的和。

    n2 可以每次query之后重新求一次偶数和

    min(m,n)的方法是一开始就统计好偶数和,然后根据query的值和原始值的加和得到的数的奇偶来判断这个和应该加减多少。

    value = query[i][0], index = query[i][1]

    如果A[index] 是奇数,相加后的数变成偶数了,那就可以给加这个偶数否则就没有变化

    如果A[index]是偶数,相加后的数还是偶数,那就加上这个value,否则减去A[index]

    class Solution(object):
        def sumEvenAfterQueries(self, A, queries):
            """
            :type A: List[int]
            :type queries: List[List[int]]
            :rtype: List[int]
            """
            even_sum = 0
            ans = []
            for value in A:
                if value % 2 == 0:
                    even_sum += value
            for query in queries:
                value = query[0]
                index = query[1]
                if A[index] % 2 == 0:
                    if (A[index] + value) % 2 == 0:
                        even_sum += value
                    else:
                        even_sum -= A[index]
                    A[index] += value
                else:
                    if (A[index] + value) % 2 == 0:
                        even_sum += A[index] + value
                    else:
                        pass
                    A[index] += value
                ans.append(even_sum)
            return ans
  • 相关阅读:
    「SPOJ10707」Count on a tree II
    UVA 11021 /概率
    power oj/2360/Change
    POJ1613 147/思维题
    Power oj2498/DP/递推
    HDU4815/计数DP
    444A/CF
    观光公交noip<贪心>
    2014 Shanghai Invitation Contest
    POJ1734/Floyd求最小环
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13220464.html
Copyright © 2011-2022 走看看