A. Slime Combining
time limit per test
memory limit per test
input
output
n slimes all initially with value 1.
n - 1 slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value v, you combine them together to create a slime with value v + 1.
n
Input
n (1 ≤ n ≤ 100 000).
Output
k integers, where k is the number of slimes in the row after you've finished the procedure described in the problem statement. The i-th of these numbers should be the value of the i-th slime from the left.
Sample test(s)
input
1
output
1
input
2
output
2
input
3
output
2 1
input
8
output
4
Note
大体题意:
给你n个泥巴,每个泥巴初始值为1,当最右边两个泥巴值一样的话,就可以合在一起,并且值加1,问最后排完之后,从左到右依次输出有的泥巴,并且输出他们的值!
方法1:(数学规律)
先自己随便写几个n,慢慢就会看出:泥巴和n有关系,正好对应n的二进制为1的下标,比如说11吧 结果应该是4 2 1,他的二进制是1011, 1,2,4位置上正好是1.
因此:代码如下:
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<sstream>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
const int maxn = 1000 + 10;
const int maxt = 100 + 10;
const double eps = 1e-8;
int main()
{
ios::sync_with_stdio(false);
int n;
while(cin >> n){
for (int i = 31; i > -1; --i)
if (n & (1 << i))cout << i + 1 << " ";
cout << endl;
}
return 0;
}
方法2:(栈模拟)
很明显,这个游戏规则类似于栈:不断往里放,只判断栈顶,和第二个元素。
放一个元素就check一次,因为放的话必然有两个或以上的元素,一个元素只能出现在循环入栈的时候,所以在check里面可以先放,放完了发现size > 1就在check不断递归!不过有个缺点,没法遍历栈,我这里用了vector,还以为会超时,,结果过了!
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<sstream>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
const int maxn = 1000 + 10;
const int maxt = 100 + 10;
const double eps = 1e-8;
stack<int>s;
void check(){
int top1=s.top();s.pop();
int top2=s.top();s.pop();
if(top1==top2){
s.push(top1+1);
if (s.size() > 1)check();
}
else {s.push(top2);s.push(top1);}
}
int main()
{
ios::sync_with_stdio(false);
int n;
while(cin >> n){
s.push(1);
for (int i = 0; i < n-1;++i){
s.push(1);
check();
}
vector<int>v;
while(!s.empty()){v.push_back(s.top());s.pop();}
for (int i = v.size()-1; i > -1; --i)cout << v[i] << " ";
cout<<endl;
}
return 0;
}