题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4550
题意:有n(n <= 100)个0~9之间的卡片,从左往右将卡片放到之前的卡片最左边或者最右边;使得最后得到的数值最小,且无前导0;
input:
4
0101
2342001
9876105432
9876543210
output:
1001
1002234
1678905432
1234567890
思路:如果没有0,则直接用双指针,模拟前后插入值即可;但是由于存在0,所以需要找出最小的非零0,使得最前面以mn开头,之后是可填入的若干个0.所谓可填入的即指在最后一个mn填入之前的0,这就需要记录mn的个数,每次插入mn时,--cnt;当已经在前面填入了0时,将最后最后一个mn时填入会使得值最小,或者是在没有填入0时,但只剩下一个mn时填入mn,这样之后只能在最后加值了;
#include<iostream> #include<cstdio> #include<cstring> #include<string.h> #include<algorithm> #include<vector> #include<cmath> #include<stdlib.h> #include<time.h> #include<stack> #include<set> #include<map> #include<queue> using namespace std; #define rep0(i,l,r) for(int i = (l);i < (r);i++) #define rep1(i,l,r) for(int i = (l);i <= (r);i++) #define rep_0(i,r,l) for(int i = (r);i > (l);i--) #define rep_1(i,r,l) for(int i = (r);i >= (l);i--) #define MS0(a) memset(a,0,sizeof(a)) #define MS1(a) memset(a,-1,sizeof(a)) #define MSi(a) memset(a,0x3f,sizeof(a)) #define inf 0x3f3f3f3f #define lson l, m, rt << 1 #define rson m+1, r, rt << 1|1 typedef pair<int,int> PII; #define A first #define B second #define MK make_pair typedef __int64 ll; template<typename T> void read1(T &m) { T x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} m = x*f; } template<typename T> void read2(T &a,T &b){read1(a);read1(b);} template<typename T> void read3(T &a,T &b,T &c){read1(a);read1(b);read1(c);} template<typename T> void out(T a) { if(a>9) out(a/10); putchar(a%10+'0'); } #define N 222 int f[N],len,mn,l,r,flag,cnt; char s[N]; void solve(int a) { if(flag){ f[r++] = a; return ; } if(a <= f[l]){// 没填入0,但是mn用完了 f[--l] = a; if(a == mn && --cnt == 0) flag = 1; } else if(a == mn && cnt-- == 1){//前面为0,但是只剩下一个mn了,填入 flag = 1,f[--l] = a; } else f[r++] = a; } int main() { int T; read1(T); while(T--){ gets(s); len = strlen(s),mn = 10; l = r = 100;f[l] = 10;cnt = 0; rep0(i,0,len)if(s[i] != '0') if(mn > s[i]-'0') mn = s[i]-'0',cnt = 1; else if(mn == s[i] - '0') cnt++; flag = 0; rep0(i,0,len) solve(s[i]-'0'); rep0(i,l,r) putchar('0'+f[i]); puts(""); } return 0; }