题意很好理解,需要优先队列
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
typedef long long int ll;
struct Node{
ll a, b, num1, num2;
bool operator < (const Node y) const
{
return this->num2 > y.num2;
}
}node[maxn];
priority_queue<Node>que;//采用默认优先级构造队列
int main()
{
int n, m;
ll ans = 0;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
{
scanf("%d", &node[i].a);
node[i].b = 0;
node[i].num1 = node[i].a * (node[i].a - node[i].b) * (node[i].a - node[i].b);
node[i].num2 = (node[i].a * (node[i].a - node[i].b - 1) * (node[i].a - node[i].b - 1)) - node[i].num1;
que.push(node[i]);
}
while(m--)
{
Node vis = que.top();
que.pop();
vis.b++;
vis.num1 = vis.a * (vis.a - vis.b) * (vis.a - vis.b);
vis.num2 = vis.a * (vis.a - vis.b - 1) * (vis.a - vis.b - 1) - vis.num1;
que.push(vis);
}
while(!que.empty())
{
Node vis = que.top();
ans += vis.num1;
que.pop();
}
printf("%lld\n", ans);
return 0;
}
题目链接 :https://ac.nowcoder.com/acm/contest/1068#question
注意long long类型的inf在初始化时需要ll ans = inf; ans *= ans;
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int maxn = 1e5 + 5;
const int inf = 0x3f3f3f3f;
char str[maxn];
ll dp1[5][maxn], dp2[5][maxn];
int main()
{
scanf("%s", str + 1);
int n = strlen(str + 1);
for(int i = 1; i <= n; i++)
{
//cout << str[i] << " ";
if(str[i] == 'c')
{
dp1[2][i] += dp1[1][i - 1];
dp1[1][i] += 1;
}
else if(str[i] == 's')
{
dp1[3][i] += dp1[2][i - 1];
}
else
{
dp1[4][i] += dp1[3][i - 1];
}
for(int j = 1; j <= 4; j++)
{
dp1[j][i] += dp1[j][i - 1];
//cout << dp1[j][i] << " ";
}
//cout << endl;
}
//cout << endl;
for(int i = n; i; i--)
{
if(str[i] == 'c')
{
dp2[1][i] += dp2[2][i + 1];
dp2[2][i] += dp2[3][i + 1];
}
else if(str[i] == 's')
{
dp2[3][i] += dp2[4][i + 1];
}
else
dp2[4][i] += 1;
for(int j = 1; j <= 4; j++)
{
dp2[j][i] += dp2[j][i + 1];
}
}
ll ans = inf;
ans *= ans;
//cout << ans << endl;
for(int i = 1; i < n; i++)
{
ans = min(ans, abs(dp1[4][i] - dp2[1][i + 1]));
//cout << dp1[4][i] << " " << dp2[1][i + 1] << endl;
//if(ans == 0) cout << i << endl;
}
printf("%I64d\n", ans);
return 0;
}