Los greedy Valley P4995

Topic Link https://www.luogu.com.cn/problem/P4995

analysis

You said he was a water main topic, greedy thoughts and good, you say do not water it, it is indeed quite water.
Because the sum of the maximum so let ask directly greedy ends after each taking sort of like, and then I wrote the enigmatic double pointer, the last to record what \ (last \) because the last time will not jump on record , and then nothing, I feel this idea is to be a good experience of.

Open \ (longlong !!!!! \)

#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
const int N=1e3+10;
ll a[N];
int main(){
    int n;
    ll ans=0;
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    sort(a+1,a+n+1);
    ans+=a[n]*a[n];
    int i=1,j=n,cnt=1,last=a[n];
    while(i!=j){
        ans+=(a[i]-a[j])*(a[i]-a[j]);
        if(cnt)last=a[i],j--;
        else last=a[j],i++;
        cnt^=1;
    }
    ans+=(a[i]-last)*(a[i]-last);    
    cout<<ans;
}

Guess you like

Origin www.cnblogs.com/anyixing-fly/p/12634453.html