Submission #1282985

#TimeUsernameProblemLanguageResultExecution timeMemory
1282985HiepVu217Fancy Fence (CEOI20_fancyfence)C++20
13 / 100
21 ms3448 KiB
//Proud of You//
#include <bits/stdc++.h>
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
using namespace std;
const int N = 1e5 + 17, M = 1e9 + 7;
int n, r[N], w[N], d2, ans;
pair <int, int> a[N];
bool ex[N], vi[N];
inline int root (int u)
{
    if (u == r[u])
    {
        return u;
    }
    return r[u] = root(r[u]);
}
inline bool join (int x, int y)
{
    int rx = root(x), ry = root(y);
    if (rx == ry)
    {
        return 0;
    }
    r[ry] = rx, w[rx] = (w[rx] + w[ry]) % M;
    return 1;
}
inline int lt (long long a, long long b)
{
    a %= M;
    if (!b)
    {
        return 1;
    }
    if (b == 1)
    {
        return a;
    }
    int z = lt (a, b / 2);
    z = 1LL * z * z % M;
    if (b & 1)
    {
        z = 1LL * z * a % M;
    }
    return z;
}
inline int c2n (int x)
{
    return 1LL * x * (x - 1) % M * d2 % M;
}
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    for (int i = 1, h; i <= n; ++i)
    {
        cin >> h;
        a[i] = {h, i};
    }
    for (int i = 1; i <= n; ++i)
    {
        cin >> w[i];
        r[i] = i;
    }
    sort (a + 1, a + n + 1, greater<>());
    d2 = lt (2, M - 2);
    for (int j = 1; j <= n; ++j)
    {
        int h = a[j].first, k = a[j].first;
        vector <int> vt;
        while (h == k)
        {
            auto [_, i] = a[j++];
            vt.push_back(i);
            ex[i] = 1;
            if (ex[i - 1])
            {
                join (i - 1, i);
            }
            if (ex[i + 1])
            {
                join (i, i + 1);
            }
            k = a[j].first;
        }
        --j;
        for (int i: vt)
        {
            int r = root(i);
            if (!vi[r])
            {
                vi[r] = 1;
                ans = (ans + 1LL * c2n (w[r] + 1) * h) % M;
            }
        }
        for (int i: vt)
        {
            int r = root(i);
            vi[r] = 0;
        }
    }
    cout << ans;
}

#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...