JZOJ6547 USACO USOpen 2020 Haircut 題解

口胡一下各種時間複雜度(也許吧)的方法

So1ution1So1ution1:直接上暴力

時間複雜度O(n2logn)\text{時間複雜度}O(n^{2}logn)

Solution2Solution2: 考慮到相鄰 kk 之間變化量等於所有 k+1k+1 變到 kk 導致逆序對的減量之和,因此算這個然後逆着推。

Solution3Solution3(正解):優化一下的方法應該很容易想到吧,可以轉化爲一個類似求逆序對的一個東東,然後就顯然了。

注意開long long

CodeCode

#include<cstdio>
#define ll long long

const int N = 1e5 + 5;
ll n, a[N], s[N], ans, t[N];

ll lowbit(ll x){return x & (-x);}
void update(ll x){while(x <= n) t[x]++, x += lowbit(x);}
ll query(ll x){ll ret = 0; while(x) ret += t[x], x -= lowbit(x); return ret;}

int main()
{
    freopen("haircut.in","r",stdin);
    freopen("haircut.out","w",stdout);
    scanf("%lld", &n);
    for(int i = 1; i <= n; i++) scanf("%lld", &a[i]), a[i]++;
    for(int i = 1; i <= n; i++)
        s[a[i]] += query(n - a[i] + 1), update(n - a[i] + 2);
    for(int i = 0; i < n; i++) ans += s[i], printf("%lld\n", ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章