2021 CCPC 女生赛 B. 攻防演练(补题)

思路

倍增,开一个数组,记录每个字母跳到下一个离它最远的一个,比如abcdefgh,a的下一个最远就是h。但是最远那个又得是离它最近的那个,比如aabbcc,a跳到c,c最远,离它最近的c是5号。预处理出跳到r + 1所需要的最小步数。

Ac Code

#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
#define enl , writestr("\n")
#define int long long
#define endl "\n"
#define PII pair<int, int>
#define ULL unsigned long long
#define xx first
#define yy second
#define PI acos(-1)
const int P = 131;//131,13331
const int N = 2e5 + 10;
const int M = 1e3 + 10;
const int INF = 1e18;
const int ENF = -1e18;
const int mod = 1e9 + 7;//998244353
const int modd = 998244353;
void ClearFloat() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); }int read() { int ret = 0, f = 1; char ch = getchar(); while ('0' > ch || ch > '9') { if (ch == '-')f = -1; ch = getchar(); }while ('0' <= ch && ch <= '9') { ret = ret * 10 + ch - '0'; ch = getchar(); }return ret * f; }void write(int x) { char num[30]; int cnt = 0; if (x == 0) { putchar('0'); return; }if (x < 0) { putchar('-'); x = -x; }while (x > 0) { num[cnt++] = x % 10 + '0'; x /= 10; }while (cnt > 0) { putchar(num[--cnt]); } }double readdou() { double x = 0; int flag = 0; char ch = 0; while (!isdigit(ch)) { flag |= (ch == '-'); ch = getchar(); } while (isdigit(ch)) { x = x * 10 + (ch - '0'); ch = getchar(); }if (ch != '.') return flag ? -x : x; int f = 1; ch = getchar(); while (isdigit(ch)) { x = x + (ch - '0') * pow(10, -f); f++; ch = getchar(); }return flag ? -x : x; }void wridou(int x) { char num[30]; int cnt = 0; if (x == 0) { putchar('0'); return; }if (x < 0) { putchar('-'); x = -x; }while (x > 0) { num[cnt++] = x % 10 + '0'; x /= 10; }while (cnt > 0) { putchar(num[--cnt]); } }int gcd(int a, int b) { if (b) while ((a %= b) && (b %= a)); return a + b; }int lcm(int a, int b) { return a * b / gcd(a, b); }
int m, n, q, l, r, pos[30], f[N][20];
string s;//f[i][j]表示从i为起点,跳2^j次方步跳到哪个序号
signed main()
{
	ClearFloat();
	cin >> m >> n >> s >> q;
	s = ' ' + s;
	for (int i = 0; i < m; i++)     pos[i] = n + 1;//由于是倒着遍历,先将每个字母都初始化下一个跳到n + 1
	for (int i = n; i >= 0; i--)//倒着遍历预处理每个序号跳一步会跳到哪
	{
		for (int j = 0; j < m; j++)//判断哪个字母离这个序号最远
		{
			f[i][0] = max(f[i][0], pos[j]);//跳到离它最远的字母
		}
		if(i != 0) pos[s[i] - 'a'] = i;//更新当前字母的序号
	}
	f[n + 1][0] = n + 1;//预处理n + 1
	for (int i = n + 1; i >= 0; i--)
	{
		for (int j = 1; (1 << j) <= n; j++)//利用倍增来看跳2^j次方步会跳到哪个序号
		{
			f[i][j] = f[f[i][j - 1]][j - 1];//理解举例:256是从128跳了128过来的
		}
	}
	while (q--)
	{
		cin >> l >> r; 
		int ans = 1;
		l--;//要跳到r + 1
		for (int i = log2(n); i >= 0; i--)
		{
			if (f[l][i] <= r)
			{
				ans += (1 << i);//跳了2^i步
				l = f[l][i];
			}
		}
		cout << ans << endl;
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值