http://codeforces.com/problemset/problem/405/A
A. Gravity Flip
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange.
Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the n columns after the gravity switch!
Input
The first line of input contains an integer n (1 ≤ n ≤ 100), the number of the columns in the box. The next line contains n space-separated integer numbers. The i-th number ai (1 ≤ ai ≤ 100) denotes the number of cubes in the i-th column.
Output
Output n integer numbers separated by spaces, where the i-th number is the amount of cubes in the i-th column after the gravity switch.
Examples
inputCopy
4
3 2 1 2
output
1 2 2 3
inputCopy
3
2 3 8
output
2 3 8
Note
The first example case is shown on the figure. The top cube of the first column falls to the top of the last column; the top cube of the second column falls to the top of the third column; the middle cube of the first column falls to the top of the second column.
In the second example case the gravity switch does not change the heights of the columns.
思路:开始想的有点复杂,通过每一列的方块数目,确定每一行的方块数目。因为重力向右,所以每一行从最右开始依次排开,再重新确定每一列的数目输出。
但是其实只要每一列按从小到大的顺序输出即可,因为方块是水平移动,不影响盒子中包含的列数,只是靠右重新拍序。
方法一:
#include<iostream>
//#include<cstdlib> memset的头文件不是stdlib 是string
#include<cstring>
using namespace std;
int n;
int row[105];
int col[105];
int main()
{
cin>>n;
int max = 0;
for(int i = 1;i<=n;i++)
{
cin>>col[i];
if(max<col[i]) max = col[i];//记录最大值为了知道有效的一共多少行
for(int j= 1;j<=col[i];j++)
{
row[j]++;
}
}
memset(col,0,sizeof(col));
for(int i = 1;i<=max;i++)
{
for(int j= 1;j<=row[i];j++)
{
col[n-j+1]++;//从右到左填满
}
}
for(int i = 1;i<=n;i++)
{
cout<<col[i]<<' ';
}
cout<<endl;
return 0;
}
方法二:使用vector 动态数组更加方便
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<int> cube;
int n;
cin>>n;
int x;
for(int i = 0;i<n;i++)
{
cin>>x;
cube.push_back(x); //注意不能直接用cin>>cube;
}
sort(cube.begin(),cube.end());
for(int i = 0;i<cube.size();i++)
{
cout<<cube[i]<<' ';
}
cout<<endl;
return 0;
}