B. Lucky Numbers (easy)
time limit per test
2 seconds
memory limit per test
256 megabytes
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.
One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.
Input
The only line contains a positive integer n (1 ≤ n ≤ 109). This number doesn't have leading zeroes.
Output
Output the least super lucky number that is more than or equal to n.
Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
input
4500
output
4747
input
47
output
47
思路:全排列:首先算出最小的超过n的幸运数的的位数,由于4和7的个数相等,所以可以先初始化一个序列,然后用全排列排出所有可能性,然后在满足条件的情况中选择最小的那个。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int tot,minn=2147483644;
char ch[10],ans[10];
string s,tmp;
/*
*/
int main(){
cin>>ch;
tot=int(strlen(ch));
if (tot%2==1){
++tot;
for (int i=0;i<tot/2;++i)
cout<<4;
for (int i=0;i<tot/2;++i)
cout<<7;
cout<<endl;
}
else{
for (int i=0;i<tot/2;++i) ans[i]='7';
for (int i=tot/2;i<tot;++i) ans[i]='4';
if (strcmp(ch,ans)>0){
cout<<4;
for (int i=tot-1;i>=0;--i)
cout<<ans[i];
cout<<7;
cout<<endl;
}
else{
for (int i=0;i<tot/2;++i) ans[i]='4';
for (int i=tot/2;i<tot;++i) ans[i]='7';
do{
int x=strcmp(ch,ans);
// for (int i=0;i<tot;++i) cout<<ans[i];
// cout<<endl;
// for (int i=0;i<tot;++i) cout<<ch[i];
// cout<<endl;
// cout<<"x="<<x<<endl<<endl;
if (x<=0){
for (int i=0;i<tot;++i)
cout<<ans[i];
cout<<endl;
break;
}
}while(next_permutation(ans,ans+tot));
}
}
return 0;
}
暴力思路2(借鉴网上,成功):打表