Shuffle the Digits | ||||||
| ||||||
Description | ||||||
Leyni gets an integer n. He wants to shuffle the digits in the integer n to produce a smallest possible integer without leading zeros. (None of the digits in the integer can be removed or replaced.) Please help him solve this problem! | ||||||
Input | ||||||
There are multiple test cases. The first line of input is an integer T indicating the number of test cases. Then T test cases follow. For each test case: Line 1. This line contains an integer n (0 ≤ n ≤ 109). | ||||||
Output | ||||||
For each test case: Line 1. Output the new integer that Leyni wants. | ||||||
Sample Input | ||||||
1 4321 | ||||||
Sample Output | ||||||
1234 | ||||||
Source | ||||||
哈理工2012春季校赛 - 现场赛 | ||||||
Author | ||||||
齐达拉图@HRBUST |
思路:
对于没有0出现的数字重组满足这样的条件就能使得输出的数字最小:从出现的最小的数开始输出,对应输出出现的次数,直到所有数字输出完毕。
对于有0出现的数字重组满足这样的条件就能使得输出的数字最小:先输出一个非0的最小的数字,然后输出0,剩下的部分按照没有0的规则输出,模拟代码直接AC:
#include<stdio.h>
#include<string.h>
using namespace std;
int vis[10];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[200];
memset(vis,0,sizeof(vis));
scanf("%s",a);
for(int i=0;i<strlen(a);i++)
{
vis[a[i]-'0']++;
}
if(vis[0]==0)
{
for(int i=1;i<10;i++)
{
for(int j=1;j<=vis[i];j++)
printf("%d",i);
}
printf("\n");
}
else
{
int f=0;
for(int i=1;i<10;i++)
{
if(vis[i]!=0)
{
printf("%d",i);
vis[i]--;
break;
}
}
for(int i=1;i<=vis[0];i++)
{
printf("0");
}
for(int i=1;i<10;i++)
{
for(int j=1;j<=vis[i];j++)
printf("%d",i);
}
printf("\n");
}
}
}