题解,不喜勿喷
2025-07-12 10:41:24
发布于:上海
1阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
int read() {
char ch=getchar();
int f=1,x=0;
while(ch<'0'||ch>'9') {
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') {
x=x10+ch-'0';
ch=getchar();
}
return fx;
}
const int maxn=1e6+10;
int n;
struct snakes {
int id,len;
bool operator <(snakes b) const {
if(len!=b.len) {
return len<b.len;
}
return id<b.id;
}
snakes operator -(snakes b) {
snakes ret;
ret.len=len-b.len;
ret.id=id;
return ret;
}
}a[maxn];
deque<snakes> q1,q2,q;
void work() {
q1.clear();
q2.clear();//记得多组数据初始化
q.clear();
for (int i = 1; i <= n; ++i) {
q1.push_back(a[i]);
}
while(1) {
if(q1.size()+q2.size()==2) {
printf("1\n"); //还剩下 2 条蛇直接输出
return ;
}
snakes st=q1.front();
q1.pop_front();
snakes ed=q1.back();
if(!q2.empty()&&ed<q2.back()) {
ed=q2.back();
q2.pop_back();//如果 q2 中的蛇较长,取 q2 中的蛇
}
else {
q1.pop_back();
}
snakes tmp;
tmp.len=ed.len-st.len;
tmp.id=ed.id;
if(q1.front()<tmp) {
q2.push_front(tmp);
}//将新蛇根据单调性放入队列中
else {
q1.push_front(tmp);
break;
//现在这条蛇吃了一口,发现变成最短的了
//那么进入第二阶段
//注意此时放到 q1 还是 q2 中没有任何区别了
}
}
while(!q1.empty()&&!q2.empty()) {
if(q1.front()<q2.front()) {
q.push_back(q1.front());
q1.pop_front();
}
else {
q.push_back(q2.front());
q2.pop_front();
}
}
while(!q1.empty()) {
q.push_back(q1.front());
q1.pop_front();
}
while(!q2.empty()) {
q.push_back(q2.front());
q2.pop_front();
}
//为了操作方便把两个队列合并
//和归并时 O(n) 合并有序数组的做法一致
int ans=q.size();
int eat=0;
while(q.size()>1) {
snakes st=q.front();
q.pop_front();
snakes ed=q.back();
q.pop_back();
snakes tmp;
tmp.len=ed.len-st.len;
tmp.id=ed.id;
eat++;
if(q.size()==0||q.front()<tmp) {
break;
}
else {
q.push_front(tmp);//还是可爱的单调性
}
}//用 while 模拟递归判断,本质上无差别
printf("%d\n",ans+(eat&1? 1:0));
//注意我们这份代码中和上一份有所不同
//上面是假设还没吃,判断是否要吃 -1
//这里是已经吃了,判断是否要吐出来 +1
}
signed main() {
int t;
t=read();
for(int Q=1;Q<=t;Q++) {
if(Q==1) {
n=read();
for (int i = 1; i <= n; ++i) {
a[i].len=read();
a[i].id=i;
}
}
else {
int k=read();
for(int i=1;i<=k;i++) {
int x=read();
int y=read();
a[x].len=y;
}
}
work();//求解
}
return 0;
}
别直接抄,留个点赞再走吧
这里空空如也
有帮助,赞一个