我现在有两组代码: 首先是AC代码,直接记录表达式乘号的位置
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <string.h>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
inline ll read() {
ll x=0,w=1;char ch=getchar();
for(;ch>'9'||ch<'0';ch=getchar()) if(ch=='-') w=-1;
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
return x*w;
}
#define maxn 1000000
char c[1000005];
ll a[1000005];int sum=0;
int main() {
sum++;
while(c[sum]!='\n') {
sum++;
cin>>a[sum];
a[sum]%=10000;
c[sum]=getchar();
}
for(int i=sum;i>=1;i--) {
if(c[i]=='*') {
a[i]*=a[i+1];
a[i]%=10000;
a[i+1]=0;
}
}
ll ans=0;
for(int i=1;i<=sum;i++) {
ans+=a[i];
ans%=10000;
}
cout<<ans<<endl;
return 0;
}
然后我又搞了一搞,重新写了一个基于分块的方法
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <string.h>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
inline ll read() {
ll x=0,w=1;char ch=getchar();
for(;ch>'9'||ch<'0';ch=getchar()) if(ch=='-') w=-1;
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
return x*w;
}
#define maxn 1000000
const int mod=10000;
ll f[mod];
ll power(ll x,ll y){
if(y==0)return 1;
ll sum=1;
while(y){
if(y&1){
sum=sum*x%mod;
}
x=x*x%mod;
y=y>>1;
}
return sum;
}
string a;
ll toNum(ll l,ll r) {
int sum=0;
for(int i=l;i<=r;i++) {
sum=sum*10+a[i]-'0';
}
return sum;
}
int flag=0;
ll calc(ll l,ll r) {
int pos1=-1,pos2=-1;
for(int i=l;i<=r;i++) {
if(a[i]=='+') pos1=i;
else if(a[i]=='*') pos2=i;
}
if(pos1==-1&&pos2==-1) return toNum(l,r);
else if(pos1!=-1) {
if(a[pos1]=='+') return (calc(l,pos1-1)+calc(pos1+1,r))%mod;
}
else if(pos2!=-1) {
if(a[pos2]=='*') return (calc(l,pos2-1)*calc(pos2+1,r))%mod;
}
return 0;
}
int main() {
f[0]=1;
for(int i=1;i<mod;i++) f[i]=f[i-1]*i%mod;
cin>>a;flag=0;
ll ans=calc(0,a.size()-1)%mod;
if(flag==0) cout<<ans<<endl;
else cout<<"ArithmeticException"<<endl;
return 0;
}
现在后面的一种方法TLE了两个点,我想问这两种方法的复杂度有什么差别吗,为什么后面的方法会TLE两个点