挑战用很多种方法解决A+B(c++)

写在前面的

本文章主要是博主自己想写。水篇文章。

正常作法

#include<bits/stdc++.h>
using namespace std;
int main(){
	int a,b;
	cin>>a>>b;
	cout<<a+b;
	return 0;
}

数组

#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[3];
	cin>>a[1]>>a[2];
	cout<<a[1]+a[2];
	return 0;
}

枚举

#include<bits/stdc++.h>
using namespace std;
int main(){
	int a,b;
	cin>>a>>b;
	for(int i=INT_MIN;i<=INT_MAX;i++){
		if(i==a+b){
			cout<<i;
			break;
		}
	}
	return 0;
}

二分

#include<bits/stdc++.h>
using namespace std;
int main(){
	int a,b;
	cin>>a>>b;
	int l=INT_MIN,r=INT_MAX;
	while(l<=r){
		int mid=l+r>>1;
		if(mid==a+b){
			cout<<mid;
			break;
		}
		else if(mid<a+b)l=mid+1;
		else r=mid-1;
	}
	return 0;
}

前缀和

#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[10],s[10];
	for(int i=1;i<=2;i++){
		cin>>a[i];
		s[i]=s[i-1]+a[i];
	}
	cout<<s[2]-s[0];
	return 0;
}

表达式

#include<bits/stdc++.h>
using namespace std;
#define int long long
stack<int>num;
stack<char>op;
map<char,int>h;
string s;
void eval(){
	int b=num.top();num.pop();
	int a=num.top();num.pop();
	char opt=op.top();op.pop();
	if(opt=='+')num.push(a+b);
	else if(opt=='-')num.push(a-b);
	else if(opt=='*')num.push(a*b);
	else if(opt=='/')num.push(a/b);
	else if(opt=='^')num.push(pow(a,b));
	return;
}
signed main(){
	h['+']=1,h['-']=1,h['*']=2,h['/']=2,h['^']=3;
	int a,b;
	cin>>a>>b;
    if(a==0)return cout<<b,0;
    if(b==0)return cout<<a,0;
	string aa,bb;
    if(a<0)s+="0-";
    a=abs(a);
	while(a){
		aa+=char(a%10+'0');
		a/=10;
	}
    reverse(aa.begin(),aa.end());
	s+=aa;
	s+="+";
    if(b<0)s+="0-";
    b=abs(b);
    while(b){
		bb+=char(b%10+'0');
		b/=10;
	}
    reverse(bb.begin(),bb.end());
	s+=bb;
	for(int i=0;i<s.size();i++){
		if(s[i]>='0'&&s[i]<='9'){
			int tmp=0,j=i;
			while(j<s.size()&&s[j]>='0'&&s[j]<='9'){
				tmp=tmp*10+(s[j]-'0');
				j++;
			}
			num.push(tmp);
			i=j-1;
		}
		else if(s[i]=='('){
			op.push(s[i]);
		}
		else if(s[i]==')'){
			while(op.size()>1&&op.top()!='(')eval();
			op.pop();
		}
		else{
			while(op.size()&&h[op.top()]>=h[s[i]])
				eval();
			op.push(s[i]);
		}
	}
	while(op.size())eval();
	cout<<num.top();
	return 0;
}

BFS

持续更新中。

posted @ 2023-10-22 16:02  Xu_dh  阅读(31)  评论(1)    收藏  举报