栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【CF1430】E. String Reversal(树状数组区间修改)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【CF1430】E. String Reversal(树状数组区间修改)

题目链接:https://codeforces.com/problemset/problem/1430/E

分析

先将字符串reverse一下,然后从后往前遍历,每次遍历一个字符,找到这个字符在原串中的最后一个位置,将其移动过来即可。
简化一下,相当于每次将某个字符的最右边一个移动到最右边(用过以后要去掉),先记录每个字符的位置 p o s pos pos,然后记录这个字符前面有 x x x个字符已经被移走了,答案就加上 n − p o s − x n-pos-x n−pos−x。
每个位置的 x x x值可以用树状数组来维护,维护区间修改。

代码
#include
using namespace std;
typedef long long ll;
#define fi first
#define se second
#define pb push_back
#define MP make_pair

const int inf = 1e9 + 10;
const int N = 2e5 + 10;

int n;
ll c1[N],c2[N];
vector p[26];
char s[N];

int lowbit(int x){return x & -x;}

void update(int x, int y)//区间修改:[1, x]的值+y
{
	for (int i = x;i <= n;i += lowbit(i)) c1[i] += y,c2[i] += 1ll * x * y;
}

ll getsum(int x)//区间查询:[1, x]的值的和
{
	ll ans1 = 0;
    ll ans2 = 0;
    for (int i = x;i > 0;i -= lowbit(i))
    {
        ans1 += (x + 1) * c1[i];
        ans2 += c2[i];
    }
    return ans1 - ans2;
}

int main()
{
	int T = 1;
	//scanf("%d",&T);
	while(T--)
	{
		for(int i=0;i<26;i++) p[i].clear();
		scanf("%d",&n);
		scanf("%s",s + 1);
		for(int i=1;i<=n;i++)
		{
			p[s[i] - 'a'].pb(i);
		}
		reverse(s + 1, s + 1 + n);
		ll ans = 0;
		for(int i=n;i>=1;i--)
		{
			int ch = s[i] - 'a';
			int pos = p[ch][p[ch].size() - 1];
			ans += n - pos;
			p[ch].erase(p[ch].end() - 1);
			ans -= getsum(pos) - getsum(pos - 1);
			update(1, 1);
			update(pos, -1);
		}
		printf("%lld",ans);
	}
	return 0;
}
*/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290493.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号