結果

問題 No.956 Number of Unbalanced
ユーザー りあん
提出日時 2019-12-20 00:26:15
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 80 ms / 2,000 ms
コード長 1,717 bytes
コンパイル時間 3,141 ms
コンパイル使用メモリ 210,664 KB
最終ジャッジ日時 2025-01-08 13:06:08
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 6
other AC * 24
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
using P = pair<int, int>;
const int M = 1000000007;

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    vector<vector<int>> vv(100010);
    for (int i = 0; i < n; ++i) {
        int a;
        cin >> a;
        vv[a].push_back(i + 1);
    }
    long long ans = 0;
    for (const auto& v : vv) {
        if (v.size() == 0) continue;
        stack<P> st, st2;
        st.push({0, 0});
        st2.push({0, 0});
        unordered_map<int, long long> mp;
        mp[0] = 0;
        int pd = 0, pj = 0;
        for (int j : v) {
            int d = pd - (j - pj - 1) + 1;
            if (pj != j - 1 && mp.count(d - 1)) {
                ans += mp[d - 1];
            }

            while (!st.empty() && st.top().first < d) {
                st.pop();
            }
            bool fir = true;
            while (!st2.empty() && st2.top().first >= d) {
                if (!fir) ans += mp[st2.top().first];
                fir = false;
                st2.pop();
            }
            if (!st.empty()) {
                int k = st.top().second + st.top().first - d;
                mp[d] += j - k - 1;
                ans += mp[d];
            }
            else {
                mp[d] = j;
                ans += j;
            }
            st.push({d, j});
            st2.push({d, j});
            pd = d;
            pj = j;
        }
        {
            bool fir = true;
            while (!st2.empty() && st2.top().first >= pd - n + pj) {
                if (!fir) ans += mp[st2.top().first];
                fir = false;
                st2.pop();
            }
        }
    }
    cout << ans << '\n';

    return 0;
}
0