这是我的代码
#include <bits/stdc++.h>
using namespace std;
struct d
{
long long l, r;
long long a;
} ans[1000010];
bool operator>(const d &x, const d &y)
{
if (x.a != y.a)
{
return x.a > y.a;
}
}
struct per
{
char sex;
long long val;
long long prev, next;
} p[2000005];
priority_queue<d, vector<d>, greater<d>> h;
bool vis[2000005];
long long sum;
long long n;
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> p[i].sex;
for (int i = 1; i <= n; i++)
cin >> p[i].val;
for (int i = 1; i <= n; i++)//Input
p[i].prev = i - 1, p[i].next = i + 1;
p[1].prev = 1;
p[n].next = n;//init
for (int i = 1; i < n; i++) {
if (p[i].sex != p[i + 1].sex)
{
d v;
v.a = abs(p[i].val - p[i + 1].val); //计算差值
v.l = i;
v.r = i + 1;
h.push(v);//加入堆中
}
}
while (!h.empty()) {
d x = h.top();
if (vis[x.l] || vis[x.r]) {
h.pop();
continue;
}
ans[++sum] = x;
vis[x.l] = vis[x.r] = 1; //标记
h.pop();
int q = p[x.l].prev; //更新队伍信息让断开的地方重新连接
int b = p[x.r].next;
p[q].next = b;
p[b].prev = q;
if (p[q].sex != p[b].sex)
{
d t;
t.l = q;
t.r = b;
t.a = abs(p[q].val - p[b].val);
h.push(t);
}
}
cout << sum << endl;
for (int i = 1; i <= sum; i++)
cout << ans[i].l << " " << ans[i].r << endl;//output
}
只有50分,求帮助
解决之后肯定关注