题解区大部分题解都判断了全正/全负,不太理解。
做法比较显然,先枚举找出一个在最大子段和中的数,然后向左(右)遍历,使所有元素非负,具体操作:
修改区间 ,此时 必定在最大子段和所在子段中,若变大(不变),则修改后 可以在最大子段和所在子段中,否则修改一次, 在最大子段和所在子段中。
然后从左到右依次修改,得到答案。
code
int n, lst, now, p;
int a[_];
vector <ary> pth;
void qry(int l, int r, int &awa){pth.emplace_back(ary{l, r}); cout << "? " << l << " " << r << endl; cin >> awa;}
signed main()
{
int t;
cin >> t;
while(t--)
{
pth.clear();
cin >> n;
qry(1, 1, lst);
rep(i, 1, n)
{
qry(i, i, now);
if(now == lst) continue;
if(now < lst) qry(i, i, now);
lst = now;
p = i; break;
}
urep(i, p-1, 1)
{
qry(i, i, now);
if(now < lst) qry(i, i, now);
lst = now;
}
rep(i, p+1, n)
{
qry(i, i, now);
if(now < lst) qry(i, i, now);
lst = now;
}
rep(i, 1, n-1)
{
qry(i, i, now);
a[i] = now - lst; lst = now;
}
a[n] = lst;
for(auto [ql, qr] : pth)
rep(i, ql, qr) a[i] *= -1;
cout << "! ";
rep(i, 1, n) cout << a[i] << " "; cout << endl;
}
return 0;
}操作次数大于 ,考虑优化。
注意到再逐个修改的时候某个元素可能会修改两次,可以在改后面的时候顺带改回来,那么这个阶段的操作次数便被我们优化到了 (共 个需要修改的位置,两端无法为其它元素顺带修改)。
那么操作次数就变成了 。
我们发现当遍历时花掉了 次操作次数,那么不用往右走,端点就会少一个,所以这个做法的上界是 的!!!
code
int n, lst, now, p;
int a[_];
vector <ary> pth;
void qry(int l, int r, int &awa){pth.emplace_back(ary{l, r}); cout << "? " << l << " " << r << endl; cin >> awa;}
signed main()
{
int t;
cin >> t;
while(t--)
{
pth.clear();
cin >> n;
qry(1, 1, lst);
rep(i, 1, n)
{
qry(i, i, now);
if(now == lst) continue;
if(now < lst) qry(i, i, now);
lst = now;
p = i; break;
}
int f = 0;
urep(i, p-1, 1)
{
qry(i, i + f, now);
if(now < lst) f = 1;
else { lst = now; f = 0; }
}
if(f) qry(1, 1, lst);
f = 0;
rep(i, p+1, n)
{
qry(i - f, i, now);
if(now < lst) f = 1;
else { lst = now; f = 0; }
}
if(f) qry(n, n, lst);
rep(i, 1, n-1)
{
qry(i, i, now);
a[i] = now - lst; lst = now;
}
a[n] = lst;
for(auto [ql, qr] : pth)
rep(i, ql, qr) a[i] *= -1;
if(pth.size() > 3000) return 100;
cout << "! ";
rep(i, 1, n) cout << a[i] << " "; cout << endl;
}
return 0;
}如果有错误请指出,谢谢!