思路:因为位置为0的地方是没有办法免费的,所以为0的点必须购买,所以当我们从后往前遍历的时候,遇到0时候直接购买,遇到1的时候找当前位置前一个0,并将这个位置的0改为-1,下次遇到的时候就跳过,如果当前1位置前面没有0了,则从第一个位置往后以此购买。
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const ll Q = 4e5 + 9;
void solve(){
ll n;cin>>n;
string s;cin>>s;
s="0"+s;
ll ans=0;
ll it=n;
ll fre=1;
while(s[it]!='0') it--;
for (ll i = n; i >= fre; i--)
{
// cout<<i<<" "<<it<<" "<<fre<<" "<<ans<<"\n";
if(s[i]=='1'){
if(it>=i) {
it=i-1;
while(s[it]!='0') it--;
}
if(s[it]=='0' and it>=1){
ans+=it;
s[it]='-';
it--;
while(s[it]!='0') it--;
}else{
while(s[fre]=='-') fre++;
ans+=fre;
s[fre]='-';
fre++;
//cout<<endl<<fre<<" ";
}
}else if(s[i]=='0'){
ans+=i;
}
}
cout<<ans<<"\n";
}
int main()
{
ll _ = 1;cin>>_;
while(_--)solve();
return 0;
}
1292

被折叠的 条评论
为什么被折叠?



