Description
Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1.
You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other 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.
You would like to see what the final state of the row is after you’ve added all n slimes. Please print the values of the slimes in the row from left to right.
Input
The first line of the input will contain a single integer, n (1 ≤ n ≤ 100 000).
Output
Output a single line with 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 Input
Input
1
Output
1
Input
2
Output
2
Input
3
Output
2 1
Input
8
Output
4
题目大意
给你一个整数n表示有n个1,每两个相同的数a可以合成a+1,比如n=3,表示有3个1,其中两个1可以合成2,剩下一个1,所以输出2 1。
思路
实现方法很多,我是用栈来实现的,每次都将当前准备进栈的数同栈顶元素比较,相等则栈顶元素出栈并+1,再重复上述步骤知道当前进栈元素和栈顶元素不相同时,进栈。最后用数组存栈中的数据,逆序输出就好了(因为栈是先进后出)
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
const int maxn=1e5+5;
int ans[maxn];
int main()
{
int n;
while(~scanf("%d",&n))
{
stack<int> q;
int temp=-1,tem=-1;
for(int i=1;i<=n;i++)
{
if(!q.empty()) temp=q.top();
else temp==-1;
q.push(1);
while(q.top()==temp)
{
tem=q.top()+1;
q.pop();q.pop();
if(!q.empty()) temp=q.top();
else temp==-1;
q.push(tem);
}
}
int k=q.size();
for(int i=0;i<k;i++)
{
ans[i]=q.top();
q.pop();
}
for(int i=k-1;i>=0;i--)
{
if(i==k-1) printf("%d",ans[i]);
else printf(" %d",ans[i]);
}
printf("\n");
}
return 0;
}