洛谷 P1010 [NOIP 1998 普及组] 幂次方

这题看起来麻烦,实际上挺ez的,会一点点递归就行啦。
分治问题,用栈结构来存储每一层递归传入的大于3的参数的幂次方拆解。
我看洛谷题解用位运算的较少,解释一下,就是把n和1去按位与,并且记录位置,如果true,那么放入栈。每一次循环将n的二进制右移一位即可。

AcCode:

#include<iostream>
#include<stack>
using namespace std;
void dfs(int n){
	stack<int> s;
	for(int i = 0; i <= 16 && n; i++){
		if(n & 1) s.push(i);
		n >>= 1;
	}
	while(!s.empty()){
		int top = s.top();
		s.pop();
		if(top < 3){
			if(top == 2) cout << "2(2)";
			else if(top == 1) cout << "2";
			else cout << "2(0)";
		}else{
			cout << "2(";
			dfs(top);
			cout << ")";
		}
		if(s.size() > 0) cout << "+";
	}
}
int main(){
	int N;
	cin >> N;
	dfs(N);
	return 0;
} 
posted @ 2025-05-07 18:10  Yuhhhhh  阅读(13)  评论(0)    收藏  举报