簡體   English   中英

如何減少執行此問題的時間限制

[英]How can I decrease the time limit of execution of this problem

from collections import Counter
def main() :

    n = int(input())
    x1 =tuple(map(int,input().split(' ')))
    n2 = int(input())
    res = []
    memo1 = []
    memo2 = []
    for s1 in range(n2):
        c = 0
        p = list(map(int, input().split(' ')))
        if p in memo1:
            c = memo2[memo1.index(p)]
        else:
            x = x1[p[0]-1 : p[1]]
            y = x1[p[2]-1 : p[3]]
            x = Counter(x)
            y = Counter(y)
            f = x - y
            common = x - f
            g = y - common
            f = f + g
            for v1 in f:
                if v1 in common:
                    c = c + (f[v1]*common[v1])
            for v1 in common:
                c = c + common[v1]**2
            memo1.append(p)
            memo2.append(c)
        res.append(c)
    print(*res,sep='\n')
 main()

這是一個針對codeforces.com 問題的程序

請建議我如何解決這個問題...

一些通用指針:

  1. 在程序開始時只處理一次輸入
  2. 問題陳述中的條件 2 和 3 告訴您哪些索引是有效的。 l1 <= i <= r1 和 l2 <= j <= r2。 不要浪費時間遍歷輸入列表中所有可能的 position。 只檢查那些不會違反 2 和 3 的索引。
  3. 預處理。 條件 1 要求您驗證 a_i 和 a_j 是否相等。 你會經常這樣做。 因此,當您處理輸入時,請跟蹤(在 map / 字典中)哪些值是相同的。 這樣以后跟蹤就更容易了。

特定問題的指針:

查看不相交的集合數據結構。 它通常用於快速評估對象之間的等效性。 在您的情況下,您可以對其進行設置,以便它評估諸如“如果 a_i 等於 a_j,則 i 等於 j”之類的東西。

然后您可以查詢數據結構以獲取所有等價類(所有指向相等值的索引)。

一旦你有了一組數字(索引),你只需要找到匹配條件 2 和 3 的所有可能的索引對。

我很確定Segment Tree可以輕松解決這個問題。 我試圖解決但仍然無法通過所有測試用例。
不過,我正在發布我的解決方案,如果您可以進一步優化它

from collections import Counter

' create segment tree in which each node will contain Counter of values'
def create(current,s,e):
    if s==e:
        tree[current]=Counter([array[s]])
        return tree[current]
    else:
        mid=(s+e)//2
        tree[current]=create(2*current+1,s,mid)+create(2*current+2,mid+1,e)
        return tree[current]

' query elements from l to r and return their counter'
def query(current,s,e,l,r):
    if s>=l and e<=r:
        return tree[current]
    if (r<s and r<e) or (l>s and l>e):
        return Counter()
    mid=(s+e)//2
    return query(2*current+1,s,mid,l,r)+query(2*current+2,mid+1,e,l,r)

n=int(input())
array=list(map(int,input().split( )))
tree=[0]*(4*n+1)
create(0,0,n-1)
#print(tree)
for _ in range(int(input())):
    l1,r1,l2,r2=map(int,input().split( ))
    ans1=query(0,0,n-1,l1-1,r1-1)
    ans2=query(0,0,n-1,l2-1,r2-1)
    ans=0
    for v in ans1:
        ans+=ans1[v]*ans2[v]
    print(ans)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM