0%

1857E. Power of Points

思路讲解

题目说了一堆花里胡哨的,其实意思很简单,就是把你这个点,和所有点(包括你这个点)组成的线段的长度总和就是答案。

那么想要知道这个,我就想到了前缀和。但前缀和的话短的-长的是负值怎么办?可以对前缀和进行分段,具体的,其实就是这段代码。

1
2
3
4
5
for(int i=1;i<=N;++i){
ll idx=upper_bound(X+1,X+1+N,(arr){X[i][0],INF,INF})-X;
ll lsum=sum[idx-1],rsum=sum[N]-sum[idx-1];
X[i][2]=(X[i][0]+1)*(idx-1)-lsum+rsum+N-idx+1-X[i][0]*(N-idx+1);
}

AC代码

https://codeforces.com/problemset/submission/1857/309735803

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Problem: E. Power of Points
// Contest: Codeforces - Codeforces Round 891 (Div. 3)
// URL: https://codeforces.com/problemset/problem/1857/E
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// by znzryb
//
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
#define FOR(i, a, b) for (long long i = (a); i <= (b); ++i)
#define ROF(i, a, b) for (long long i = (a); i >= (b); --i)
#define all(x) x.begin(),x.end()
#define CLR(i,a) memset(i,a,sizeof(i))
#define fi first
#define se second
#define pb push_back
#define SZ(a) ((int) a.size())

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll> pll;
typedef array<ll,3> arr;
typedef double DB;
typedef pair<DB,DB> pdd;
constexpr ll MAXN=static_cast<ll>(2e5)+10,INF=static_cast<ll>(5e18)+3;

ll N,M,T;
arr X[MAXN];
ll sum[MAXN];

inline bool cmpi(const arr &a,const arr &b){
return a[1]<b[1];
}

inline void solve(){
cin>>N;
for(int i=1;i<=N;++i){
cin>>X[i][0];
X[i][1]=i;
}
sort(X+1,X+1+N);
sum[0]=0;
for(int i=1;i<=N;++i){
sum[i]=X[i][0]+sum[i-1];
}
for(int i=1;i<=N;++i){
ll idx=upper_bound(X+1,X+1+N,(arr){X[i][0],INF,INF})-X;
ll lsum=sum[idx-1],rsum=sum[N]-sum[idx-1];
X[i][2]=(X[i][0]+1)*(idx-1)-lsum+rsum+N-idx+1-X[i][0]*(N-idx+1);
}
// 输出答案阶段
sort(X+1,X+1+N,cmpi);
for(int i=1;i<=N;++i){
cout<<X[i][2]<<" ";
}
cout<<"\n";
}

int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>T;
while(T--){
solve();
}
return 0;
}
/*
AC
https://codeforces.com/problemset/submission/1857/309735803
*/

心路历程(WA,TLE,MLE……)