D. Binary String Sorting

该文描述了一个Codeforces的竞赛问题,涉及对二进制字符串的排序。解决方案是通过枚举分界点,计算交换次数,找到使交换次数最少的策略。关键在于处理1到i之间的1和0,避免不必要的交换,从而得出最小的交换次数。
摘要由CSDN通过智能技术生成

Problem - 1809D - Codeforces

 

 思路:最后得到的结果就是前面是一串0后面是一串1,那么我们可以枚举分界点,如果枚举到i,那么就将1~i变为0,将i+1变为1,我们发现如果一个1在1~i中,如果他是第i-1个,那么他需要两次交换才能够到另一边,那么就不如直接删除它更优,所以如果需要交换两次以上,则我们直接将它删除,那么只会存在一种交换的情况就是str[i]=='1'&&str[i+1]=='0'才会发生交换,其他的则直接进行删除,然后我们只枚举一下得到最小值即可

// Problem: D. Binary String Sorting
// Contest: Codeforces - Educational Codeforces Round 145 (Rated for Div. 2)
// URL: https://codeforces.com/problemset/problem/1809/D
// Memory Limit: 256 MB
// Time Limit: 2000 ms

#include<iostream>
#include<cstring>
#include<string>
#include<sstream>
#include<bitset>
#include<deque>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<vector> 
#include<set>
#include<cstdlib>
#define fi first
#define se second
#define i128 __int128
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
typedef pair<int,pair<int,int> > PIII;
const double eps=1e-7;
const int N=5e5+7 ,M=5e5+7, INF=0x3f3f3f3f,mod=1e9+7,mod1=998244353;
const long long int llINF=0x3f3f3f3f3f3f3f3f;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
inline void write(ll x) {if(x < 0) {putchar('-'); x = -x;}if(x >= 10) write(x / 10);putchar(x % 10 + '0');}
inline void write(ll x,char ch) {write(x);putchar(ch);}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
bool cmp0(int a,int b) {return a>b;}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
void hack() {printf("\n----------------------------------\n");}

int T,hackT;
int n,m,k;
char str[N];
int f[N][2];

void solve() {
	scanf("%s",str+1);
	n=strlen(str+1);
	
	if(n==1) {
		printf("0\n");
		return ;
	}
	
	ll a=1e12,b=1e12+1;
	ll ans=llINF;
	for(int i=1;i<=n;i++) {
		f[i][0]=f[i-1][0],f[i][1]=f[i-1][1];
		if(str[i]=='1') f[i][1]++;
		else f[i][0]++;
	}
	
	for(int i=1;i<n;i++) {
		ll res=0;
		if(str[i]=='1'&&str[i+1]=='0') res+=a;
		res+=(ll)f[i-1][1]*b;
		res+=(f[n][0]-f[i+1][0])*b;
		ans=min(ans,res);
	}
	
	printf("%lld\n",ans);
}   

int main() {
    // init();
    // stin();

    scanf("%d",&T);
    // T=1; 
    while(T--) hackT++,solve();
    
    return 0;       
}          

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值