【模板】【高精度】

据hws和dwt大佬说不会考,先扔在这吧。

#include<bits/stdc++.h>
using namespace std;

#define rg register
const int maxn=2005,bas=10000;
struct big{
	int num[maxn],len;
	bool f;
	big(){
		memset(num,0,sizeof(num));
		len=f=0;
	}
	friend bool operator <(const big& A,const big& B){
		if(A.len<B.len) return 1;
		else if(A.len>B.len) return 0;
		for(rg int i=A.len;i>=1;i--){
			if(A.num[i]<B.num[i]) return 1;
			else if(A.num[i]>B.num[i]) return 0;
		}
		return 0;
	}
	friend big operator + (const big& A,const big& B){
		rg big C;
		C.len=std::max(A.len,B.len);
		for(rg int i=1;i<=C.len;i++){
			C.num[i]+=A.num[i]+B.num[i];
			if(C.num[i]>=bas){
				C.num[i]-=bas;
				C.num[i+1]++;
			}
		}
		if(C.num[C.len+1]) C.len++;
		return C;
	}
	friend big operator -(const big& A,const big& B) {
		rg big C;
		int js[maxn];
		if(A<B){
			C.len=B.len;
			for(rg int i=1;i<=C.len;i++){
				if(B.num[i]+js[i]>=A.num[i]){
					C.num[i]=B.num[i]+js[i]-A.num[i];
				} else {
					C.num[i]=B.num[i]+js[i]-A.num[i]+bas;
					js[i+1]-=1;
				}
			}
			C.f=1;
		} else {
			C.len=A.len;
			for(rg int i=1;i<=C.len;i++){
				if(A.num[i]+js[i]>=B.num[i]){
					C.num[i]=A.num[i]+js[i]-B.num[i];
				} else {
					C.num[i]=A.num[i]+js[i]-B.num[i]+bas;
					js[i+1]-=1;
				}
			}
			C.f=0;
		}
		while(!C.num[C.len]) C.len--;
		return C;
	}
	friend big operator * (const big& A,const big& B){
		rg big C;
		C.len=A.len+B.len;
		for(rg int i=1;i<=A.len;i++){
			for(rg int j=1;j<=B.len;j++){
				C.num[i+j-1]+=A.num[i]*B.num[j];
				if(C.num[i+j-1]>=bas){
					C.num[i+j]+=C.num[i+j-1]/bas;
					C.num[i+j-1]%=bas;
				}
			}
		}
		if(!C.num[C.len]) C.len--;
		return C;
	}
	friend big operator /(const big &A,const int &B){
		rg big C;
		C.len=A.len;
		rg long long nans=0;
		for(rg int i=A.len;i>=1;i--){
			nans=nans*bas+A.num[i];
			if(nans>=B){
				C.num[i]=nans/B;
				nans%=B;
			}
		}
		while(!C.num[C.len]) C.len--;
		return C;
	}
	friend int operator %(const big &A,const int &B){
		rg long long nans=0;
		for(rg int i=A.len;i>=1;i--){
			nans=nans*bas+A.num[i];
			if(nans>=B) nans%=B;
		}
		return nans;
	}
	void read(rg int val){//读入单精 
		len=0,f=0,memset(num,0,sizeof(num));
		while(val){
			num[++len]=val%bas;
			val/=bas;
		}
	}
	void autoread(){
		char s[maxn];
		scanf("%s",s+4);
		rg int len2=strlen(s+4);
		s[0]=s[1]=s[2]=s[3]='0';
		len=0;
		for(rg int i=len2+3;i>=4;i-=4){
			num[++len]=(s[i-3]-'0')*1000+(s[i-2]-'0')*100+(s[i-1]-'0')*10+s[i]-'0';
		}
		while(num[len] && !len) len--;
	}
	void write(){//输出 
		if(len && f) printf("-");
		if(!len) printf("0\n");
		if(len) printf("%d",num[len]);
		for(rg int i=len-1;i>=1;i--){
			printf("%04d",num[i]);
		}
		printf("\n");
	}
};
signed main()
{
    big a,b;
    a.read(100000);b.read(9999);
    big ans=a+b;
    ans.write();
    big x,y;
	x.autoread();y.autoread();
	big ans1=x+y;
	ans1.write(); 
	return 0;
}

上一篇:Terraform 学习笔记


下一篇:bzoj4426 - 最大生产率