Stay Hungry,Stay Foolish!

E - Make it Palindrome

E - Make it Palindrome

https://atcoder.jp/contests/abc290/tasks/abc290_e

 

思路

参考:

https://zhuanlan.zhihu.com/p/608325900

双指针部分,添加解释:

Code

https://zhuanlan.zhihu.com/p/608325900

#include <bits/stdc++.h>

#define x first
#define y second
#define endl '\n'
#define int long long
#define NO {puts("NO"); return;}
#define YES {puts("YES"); return;}

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const int mod = 1e9 + 7;
const int N = 1e6 + 10, INF = 1e18; 

int n, m;
int a[N], b[N];

void solve()
{
    cin >> n;
    map<int, vector<int>> mp;
    for(int i = 1; i <= n; i ++ ) cin >> a[i], mp[a[i]].push_back(i);
    int res = 0;
    for(int i = 1; i <= n; i ++ ) res += (i * (n - i + 1) - min(i, n - i + 1));
    res >>= 1;
    for(auto it : mp)
    {
        int val = it.x;
        int l = 0, r = mp[val].size() - 1;
        while(l < r)
        {
            int left = mp[val][l];
            int right = n - mp[val][r] + 1;
            if(left <= right) res -= left * (r - l), l ++ ;
            else res -= right * (r - l), r -- ;
        }
    }
    cout << res << endl;
    return;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    while(t -- ) solve();
    return 0;
}

 

posted @ 2023-03-01 00:03  lightsong  阅读(34)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel