信友队初级组T2题解
题目传送门
赛时打了半天差点没过,太惊险了
题目大意
给定
题目思路
初步想法
思路证明
让我们先证明一个思路。
当数组
初步写法
在了解了上述的思路后,我们可以不难写出一个排序后再选择连续
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n, m, k, ans = 1e18 + 7, maxn, a[200001], b[200001], c[200001];
signed main()
{
cin >> n >> k;
m = (k + 1) / 2;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
}
sort(a + 1, a + 1 + n);
for(int i = 1; i <= n; i++)
{
b[i] = b[i - 1] + a[i];
}
for(int i = 1; i <= n - k + 1; i++)
{
int x = i + m - 1, y = i + k - 1, cnt = 0;
for(int j = i; j <= y; j++)
{
cnt += (a[x] - a[j]) * (a[x] - a[j]);
}
ans = min(ans, cnt);
}
cout << ans;
}
交上去后运行,发现超时了。问题出在哪里呢?就是出在这多了一次计算连续
所以这段代码的复杂度是没有办法 AC 的。
正解想法
对于刚才的代码,超时的问题出在哪里呢?就出在这计算连续
但是这道题目有一个坑点,注意求的是
不过,我们先来推一个方程:
那么推完方程之后,我们再来看这道题。刚才的方程计算的就是
那么该如何
那么接下来就好办了。我们需要知道的,只有
代码如下:
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n, m, k, ans = 1e18 + 7, maxn, a[200001], b[200001], c[200001], d[200001];
signed main()
{
cin >> n >> k;
m = (k + 1) / 2;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
}
sort(a + 1, a + 1 + n);
for(int i = 1; i <= n; i++)
{
b[i] = a[i] * a[i];
c[i] = c[i - 1] + b[i];
d[i] = d[i - 1] + a[i];
}
for(int i = 1; i <= n - k + 1; i++)
{
int x = i + m - 1, y = i + k - 1;
int cnt = 0;
int a1 = d[y] - d[i - 1] - a[x], a2 = c[y] - c[i - 1] - b[x];
cnt = a2;
cnt -= 2 * a1 * a[x];
cnt += a[x] * a[x] * (k - 1);
ans = min(ans, cnt);
}
cout << ans;
}