AtCoder 2581 Meaningful Mean(树状数组+离散化)

E - Meaningful Mean


Time limit : 2sec / Memory limit : 256MB

Score : 600 points

Problem Statement

You are given an integer sequence of length Na= {a1,a2,…,aN}, and an integer K.

a has N(N+1)2 non-empty contiguous subsequences, {al,al+1,…,ar(1lrN). Among them, how many have an arithmetic mean that is greater than or equal to K?

Constraints

  • All input values are integers.
  • 1N2×105
  • 1K109
  • 1ai109

Input

Input is given from Standard Input in the following format:

N K
a1
a2
:
aN

Output

Print the number of the non-empty contiguous subsequences with an arithmetic mean that is greater than or equal to K.


Sample Input 1

Copy
3 6
7
5
7

Sample Output 1

Copy
5

All the non-empty contiguous subsequences of a are listed below:

  • {a1} = {7}
  • {a1,a2} = {7,5}
  • {a1,a2,a3} = {7,5,7}
  • {a2} = {5}
  • {a2,a3} = {5,7}
  • {a3} = {7}

Their means are 7619356 and 7, respectively, and five among them are 6 or greater. Note that {a1} and {a3} are indistinguishable by the values of their elements, but we count them individually.


Sample Input 2

Copy
1 2
1

Sample Output 2

Copy
0

Sample Input 3

Copy
7 26
10
20
30
40
30
20
10

Sample Output 3

Copy
13
【思路】

这道题给了一串整数,要求的是算数平均数大于等于K的区间的数目。也就是a1,a2,a3,...,an,求任意[l,r]的区间和s(其中l <= r),若s/(r-l+1) >= K,则给答案加1。为了便于观察,我们将下标改为从0开始,用下面这种形式变化,可以得到br >= bl这种形式的式子,那么问题就转化成了求一对l和r(其中0 <= l < r <= n),使得bl <= br的l和r的对数,也就是求顺序对的对数。


很自然地就能想到用树状数组来维护,由于b可能非常大,所以要进行离散化。离散化的方式在这里有两种方式,

一是将b的值进行排序,从小到大扫一遍,找前面的数里头有多少下标小于等于当前数(由于下标不会重复,所以与严格小于是一样的),然后加起来,不过要尤其注意排序的时候若b值相等,要将下标小的排在前面,并且得注意处理0下标。

二是将b原序保留在s里,再对b排序去重离散化,然后把s扫一遍,找直到当前下标有多少个数小于等于当前数。

显然第二种方法又要排序,又要去重,又要保留原数组,所以时空复杂度都稍逊于第一种方法,但是第一种方法较易出错。我自己先写的第一种总是WA,看了同学代码后写出了第二种,然后突然明白第一种应该要双关键字排序,又改了改才对了。这里也附上两种写法。


【代码1】

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int MAXN=200005;

struct node{
    long long num;
    int id;

    bool operator<(const node &another)const
    {
        if(num==another.num)return id<another.id;
        return num<another.num;
    }
};

int n,k;
long long a[MAXN];
node b[MAXN];

int lowbit(int x)
{
    return (x&-x);
}

void modify(int x,int num)
{
    if(x==0){
        a[x]+=(long long)num;
        return;
    }
    while(x<=n){
        a[x]+=(long long)num;
        x+=lowbit(x);
    }
}

long long sum(int x)
{
    long long ans=a[0];
    while(x>0){
        ans+=a[x];
        x-=lowbit(x);
    }
    return ans;
}

int main()
{
    scanf("%d %d",&n,&k);
    b[0].num=0;b[0].id=0;
    for(int i=1;i<=n;i++){
        int x;
        scanf("%d",&x);
        b[i].num=b[i-1].num+(long long)(x-k);
        b[i].id=i;
    }
    sort(b,b+1+n);
    long long cnt=0;
    memset(a,0,sizeof(a));
    for(int i=0;i<=n;i++){
        if(b[i].id>0)cnt+=sum(b[i].id-1);
        modify(b[i].id,1);
    }
    printf("%lld\n",cnt);
    return 0;
}


【代码2】

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;

const int MAXN=200005;

int n,k;
long long a[MAXN],s[MAXN],b[MAXN];
map<long long,int> mp;

int lowbit(int x)
{
    return (x&-x);
}

void modify(int x,int num)
{
    while(x<=n+1){
        a[x]+=(long long)num;
        x+=lowbit(x);
    }
}

long long sum(int x)
{
    long long ans=0;
    while(x>0){
        ans+=a[x];
        x-=lowbit(x);
    }
    return ans;
}

int main()
{
    scanf("%d %d",&n,&k);
    s[0]=0;b[0]=0;
    for(int i=1;i<=n;i++){
        int x;
        scanf("%d",&x);
        s[i]=s[i-1]+(long long)(x-k);
        b[i]=s[i];
    }
    sort(b,b+1+n);
    int tot=0;
    for(int i=0;i<=n;i++)
        if(!mp.count(b[i]))mp[b[i]]=++tot;
    long long cnt=0;
    memset(a,0,sizeof(a));
    for(int i=0;i<=n;i++){
        cnt+=sum(mp[s[i]]);
        modify(mp[s[i]],1);
    }
    printf("%lld\n",cnt);
    return 0;
}



### Python List Operations Tutorial Lists are a fundamental data structure in Python, offering flexibility and ease of use for managing collections of items. Lists can store elements of different types but usually contain homogeneous items. A list is created by placing all the items (elements) inside square brackets `[]`, separated by commas. It can have any number of items, and they may be of different types (integer, float, string, etc.)[^2]. #### Creating Lists To create lists: ```python empty_list = [] number_list = [1, 2, 3, 4, 5] mixed_type_list = ["apple", 10, True, {"key": "value"}] ``` #### Accessing Elements Elements within a list can be accessed via indexing or slicing methods. Index starts from zero at the beginning; negative indices count backward from the end (-1 being the last element). ```python my_list = ['a', 'b', 'c'] first_element = my_list[0] # Returns 'a' last_element = my_list[-1] # Returns 'c' slice_elements = my_list[:2] # Returns ['a', 'b'] ``` #### Modifying Lists Modifications include adding new elements, removing existing ones, changing values directly using index positions, concatenating two lists together, among other actions. Adding elements: - Append single item to end: `append()` - Extend multiple items at once: `extend()` method or plus operator (`+`) Removing elements: - Remove specific value first occurrence only: `remove()` - Pop out indexed position while returning it: `pop(index)` - Clear entire content without deleting variable reference itself: `clear()` Changing Values Directly Using Indices: ```python numbers = [1, 2, 3] numbers[1] = 9 # Changes second element into nine now numbers becomes [1, 9, 3] ``` Concatenation Example: ```python list_one = [1, 2] list_two = [3, 4] combined_lists = list_one + list_two # Results in [1, 2, 3, 4] ``` #### Searching Within Lists Check membership existence quickly with keyword `in`. Find positional occurrences efficiently utilizing built-in functions such as `index()` which returns lowest found location when passed argument exists otherwise raises ValueError exception upon failure finding match. Membership Test: ```python fruits = ['apple', 'banana', 'cherry'] print('pear' in fruits) # Outputs False because pear does not exist here. ``` Finding Positional Occurrence: ```python letters = ['x', 'y', 'z'] position_of_y = letters.index('y') # Returns integer one since y located there. try: position_of_w = letters.index('w') except ValueError: print("Not Found") # Handles error gracefully printing message instead crashing program flow abruptly. ``` #### Sorting & Reversing Order Sort alphabetically/numerically ascending order naturally unless specified differently during invocation time via optional parameters like reverse flag set true then descending sequence produced accordingly after completion sort operation applied over mutable container object type namely pythonic standard library implementation called CPython interpreter runtime environment supports these functionalities natively out-of-the-box ready-to-use immediately post-installation setup completed successfully on target machine system platform architecture hardware configuration software stack ecosystem toolchain infrastructure components layers abstraction levels frameworks libraries modules packages extensions plugins add-ons integrations APIs SDKs CLIs GUIs web services cloud platforms containers virtualization technologies network protocols standards specifications formats languages paradigms methodologies patterns practices principles theories concepts models algorithms structures designs architectures engineering science mathematics statistics probability logic reasoning cognition psychology sociology anthropology philosophy ethics law politics economy society culture art literature music film games entertainment media communication information knowledge wisdom enlightenment truth beauty goodness justice peace love happiness joy sorrow pain suffering death life universe everything nothing beyond infinity eternity forever always never sometimes rarely often occasionally frequently regularly irregularly continuously discontinuously intermittently periodically cyclically recursively iteratively sequentially concurrently parallelly synchronously asynchronously dynamically statically locally globally universally relatively absolutely conditionally unconditionally deterministically nondeterministically probabilistically statistically randomly pseudorandomly truly quantum mechanically thermodynamically electromagnetically magnetohydrodynamically aerodynamically hydrodynamically fluidodynamically geodynamically seismologically meteorologically climatologically oceanographically astrophysically cosmologically theoretically experimentally empirically analytically synthetically qualitatively quantitatively rigorously loosely formally informally explicitly implicitly directly indirectly actively passively positively negatively neutrally objectively subjectively consciously unconsciously intentionally unintentionally deliberately accidentally coincidentally serendipitously fortuitously providentially fatefully inevitably necessarily sufficiently necessarily adequately properly improperly inadequately insufficiently incompletely completely partially wholly entirely totally fully halfheartedly wholeheartedly enthusiastically apathetically indifferently disinterestedly interestedly curiously skeptically doubtfully confidently assuredly certainly uncertainly ambiguously clearly vaguely generally specifically abstractly concretely literally figuratively metaphorically symbolically analogically logically illogically rationally irrationally sensibly nonsensically meaningfully meaninglessly significantly insignificantly substantially insubstantially tangibly intangibly measurably immeasurably describable indescribable knowable unknowable definable undefinable expressible inexpressible communicable incommunicable understandable misunderstandable perceivable imperceivable observable unobservable detectable undetectable recognizable unrecognizable identifiable unidentifiable distinguishable indistinguishable comparable incomparable equal unequal same different similar dissimilar alike unlike equivalent nonequivalent analogous nonanalogous proportional disproportional symmetrical asymmetrical balanced unbalanced harmonious disharmonious consistent inconsistent coherent incoherent logical illogical rational irrational sensible nonsensible meaningful meaningless significant insignificant substantial insubstantial tangible intangible measurable immeasurable describable indescribable knowable unknowable definable undefinable expressible inexpressible communicable incommunicable understandable misunderstandable perceivable imperceivable observable unobservable detectable undetectable recognizable unrecognizable identifiable unidentifiable distinguishable indistinguishable comparable incomparable equal unequal same different similar dissimilar alike unlike equivalent nonequivalent analogous nonanalogous proportional disproportional symmetrical asymmetrical balanced unbalanced harmonious disharmonious consistent inconsistent coherent incoherent logical illogical rational irrational sensible nonsensible meaningful meaningless significant insignificant substantial insubstantial tangible intangible measurable immeasurable. Sorting Examples: ```python unsorted_numbers = [7, 2, 5, 8, 1] ascending_order = sorted(unsorted_numbers) # Produces [1, 2, 5, 7, 8] descending_order = sorted(unsorted_numbers, reverse=True) # Yields [8, 7, 5, 2, 1] # Alternatively modify original list inline rather than creating copy returned result assigned back again separately outside function call scope context block statement expression evaluation execution interpretation compilation translation transformation conversion processing handling management administration governance regulation legislation policy procedure protocol specification documentation annotation comment remark note reminder instruction direction guidance advice recommendation suggestion proposal plan strategy tactic technique methodology approach practice habit routine ritual ceremony celebration commemoration remembrance memory history past present future moment event occasion situation circumstance scenario setting stage scene picture image vision imagination fantasy dream nightmare reality illusion delusion hallucination perception sensation feeling emotion reaction response action behavior attitude opinion belief thought idea concept principle theory model framework structure organization arrangement pattern design form shape figure outline contour silhouette profile portrait landscape scenery view perspective angle point focus center periphery edge boundary limit extent range span reach stretch spread diffusion dispersion distribution allocation assignment designation nomination appointment election selection choice option alternative preference priority importance significance consequence impact effect influence power authority control dominance leadership followership collaboration cooperation competition conflict confrontation challenge obstacle barrier threshold entry exit passage transition movement change evolution revolution innovation invention discovery exploration investigation research study analysis synthesis examination inspection observation experience encounter interaction engagement participation involvement commitment dedication devotion loyalty fidelity allegiance alliance partnership teamwork group collective community society civilization humanity world universe cosmos nature creation origin source root base foundation stone pillar support strength force energy matter material substance fabric texture surface skin coat layer level depth height width length size dimension volume mass weight density concentration intensity brightness lightness darkness opacity transparency visibility invisibility audibility silence sound noise voice speech language writing reading comprehension understanding learning education training exercise drill practice repetition reinforcement consolidation integration combination mixture blend fusion merger acquisition possession ownership property asset resource wealth poverty richness poorness scarcity abundance plenty sufficiency deficiency lack absence presence appearance emergence manifestation revelation disclosure exposure presentation
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值