codeforce 804B - Minimum number of steps 快速幂+推断

本文介绍了一种算法,用于计算在特定字符串变换规则下达到稳定状态所需的最少操作次数。通过观察发现,每次转换实质上是字符位置的交换并增加新的字符,从而推导出计算公式。

题意:在一个只有a和b两种字符的字符串中,将ab边为bba,问知道不能变化为止最少变多少次

思路:ab-》bba 数量上a没少,b多一个,且a移动到左边了。a每和一个b变换成bba,就相当于将a,b对调,并且右边多出一个b,变成bba后,原串中左端还有一个a,a就会和两个b配对,并多出两个b。

所以可以计算b之前有多少个a,

一个a:ab -> bba

两个a:aab ->  ab ba -> bb ab a -> bbbbaa

三个a:aaab -> a abba -> abb aba -> abbbbaa-> bb ab bbaa ->bbbb abbaa -> bbbb bbabaa -> bbbbbbbbaaa

完成操作后a都到右边且数量不变,a的数量numa,进行的操作次数为pow(2,numa)-1

#include<cstdio>
#include<iostream>
#include<string>
#include<cmath>
int mod = 1e9+7;
using namespace std;
int my_pow(int a,int b)//快速幂取模 
{
	if(b==0)return 1;
	long long base=a;
	int ans=1;
	while(b)
	{
		if(b&1)
			ans=(ans*base)%mod;
		base=(base*base)%mod;
		b>>=1;
	}
	ans%=mod;
	return ans;
}
int main()
{
	string s;
	while(cin>>s)
	{
		int n=s.size();
		int a=0;
		long long ans=0;
		for(int i=0;i<n;i++)
		{
			if(s[i]!='b')a++;
			else
			{
				int aa=my_pow(2,a);
				ans=(ans+aa-1)%mod;
			}
		}
		printf("%I64d\n",ans);
	}
} 

### Codeforces Problem 797B Explanation The problem titled "Restoring the Permutation" requires reconstructing a permutation from its prefix sums modulo \( m \). Given an array of integers representing these prefix sums, one must determine whether it is possible to restore such a permutation. In this context, a **permutation** refers to an ordered set containing each integer exactly once within a specified range. The task involves checking if there exists any valid sequence that matches the provided conditions when performing operations as described in the problem statement[^1]. To solve this issue effectively: - Iterate through all elements while maintaining two variables: `current_sum` which tracks cumulative sum during iteration; and `min_value`, used later for adjustments. ```cpp int n, m; cin >> n >> m; vector<int> s(n); for (auto& x : s) cin >> x; ``` Calculate differences between consecutive terms after adjusting initial values appropriately by subtracting minimum value found so far at every step. This adjustment ensures non-negativity throughout calculations without altering relative order among elements. Check feasibility based on properties derived from constraints given in the question text. Specifically, ensure no duplicate residues appear under modulus operation since they would violate uniqueness required for permutations. Finally, construct answer using adjusted difference list obtained previously along with necessary checks ensuring correctness according to rules outlined above.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值