跳到正文

题解

题解:CF898F Restoring the Expression

2022linzhiyi约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年11月28日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 4 分钟
题目
CF898F

版本

  1. v1当前

题意

在一个数字字符串中按顺序添加一个加号和等于号,使得算式成立。

做法

首先枚举等号后面的数,记其长度为 kk,由于加法的性质,前面两个数的较大数的位数一定是 kk 或 k−1k-1,因此只需要枚举 2×2=42 \times 2 = 4 次,利用 base=10base = 10 的哈希判断相加是否相等即可。

代码

C++
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int N=1e6+10,P=10,mod=998444333;
int n;
char ch[N];
ull h[N],p[N]={1};
ull get(int l,int r) {
	return ((h[r]-h[l-1]*p[r-l+1]%mod)+mod)%mod;
}
bool pd(int l,int r) {
	if (l > r) return false;
	if (l < 1) return false;
	if (l == r) return true;
	if (ch[l] == '0') return false;
	return true;
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> (ch+1);
	n=strlen(ch+1);
	for (int i=1;i<=n;i++) h[i]=(h[i-1]*P+ch[i]-'0')%mod, p[i]=p[i-1]*10%mod;
	for (int i=1;i<=n;i++) {
		int l1,r1,l2,r2;
		l1=1, r1=n-i, l2=n-i+1, r2=i-1;		
		if (r1 < i && pd(l1,r1) && pd(l2,r2) && (get(l1,r1)+get(l2,r2))%mod == get(i,n)) {
			for (int j=l1;j<=r1;j++) cout << ch[j];
			cout << '+';
			for (int j=l2;j<=r2;j++) cout << ch[j];
			cout << '=';
			for (int j=i;j<=n;j++) cout << ch[j];
			return 0;
		}
		l1=1, r1=n-i+1, l2=n-i+2, r2=i-1;
		if (r1 < i && pd(l1,r1) && pd(l2,r2) && (get(l1,r1)+get(l2,r2))%mod == get(i,n)) {
			for (int j=l1;j<=r1;j++) cout << ch[j];
			cout << '+';
			for (int j=l2;j<=r2;j++) cout << ch[j];
			cout << '=';
			for (int j=i;j<=n;j++) cout << ch[j];
			return 0;
		}
		l1=1, r1=i*2-n-1, l2=i*2-n, r2=i-1;
		if (r1 < i && pd(l1,r1) && pd(l2,r2) && (get(l1,r1)+get(l2,r2))%mod == get(i,n)) {
			for (int j=l1;j<=r1;j++) cout << ch[j];
			cout << '+';
			for (int j=l2;j<=r2;j++) cout << ch[j];
			cout << '=';
			for (int j=i;j<=n;j++) cout << ch[j];
			return 0;
		}	
		l1=1, r1=i*2-n-2, l2=i*2-n-1, r2=i-1;
		if (r1 < i && pd(l1,r1) && pd(l2,r2) && (get(l1,r1)+get(l2,r2))%mod == get(i,n)) {
			for (int j=l1;j<=r1;j++) cout << ch[j];
			cout << '+';
			for (int j=l2;j<=r2;j++) cout << ch[j];
			cout << '=';
			for (int j=i;j<=n;j++) cout << ch[j];
			return 0;
		}	
	}
	return 0;
}
原文