b_zj_用户喜好(逆向思维记录喜好值的下标+二分查找)

给定每个用户的对文章的喜爱值,对于多个查询,l,r,k代表一组查询,查询标号为l<=i<=r的用户中对这类文章喜好值为k的用户的个数

思路:直接遍历给定的查询区间再去统计数量肯定会超时,由于要查的喜爱值是固定的,直接用map<int,list>的结构存储喜爱值的用户标号,然后对于每一个喜爱值k都取map(k)对应的列表查出给定查询区间中的数量即可

import collections
import bisect
def solve():
    n=int(input())
    mp=collections.defaultdict(list)
    A=list(map(int, input().split()))
    for i in range(n):
        mp[A[i]].append(i+1)
    m=int(input())
    for i in range(m):
        q=list(map(int, input().split()))
        B=mp[q[2]]
        l=bisect.bisect_left(B,q[0])
        r=bisect.bisect(B,q[1])
        print(r-l)
solve()
原文地址:https://www.cnblogs.com/wdt1/p/14167155.html