1. 程式人生 > >Codeforces 515C 題解(貪心+數論)(思維題)

Codeforces 515C 題解(貪心+數論)(思維題)

題面

Drazil is playing a math game with Varda.

Let’s define f(x)for positive integer x as a product of factorials of its digits. For example, f(135)=1!3!5!

First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:

  1. x doesn’t contain neither digit 0 nor digit 1.

  2. f(x)=f(a)

Help friends find such number.

題目大意:
定義f(x)為x的每一位的階乘之積
給出一個數a,求滿足條件(x的每一位沒有0或1)的最大x,使f(x)=f(a)

分析:

此題可用貪心求解
貪心的思路是很顯然的,應該讓x的位數儘量多,而每一位儘量小,最大的數應該排在最左邊
這樣,我們就可以把a的每一位拆開
如a=6
6!=6*5*4*3*2*1=6*5!=3!*5!
所以6可以被替換成35

所以我們把0~9的數字拆開(其實0,1應該直接捨去,因為不符合條件)
0!=0!
1!=1!
2!=2!
3!=3!
4!=3!*4=3!*2!*2!
5!=5!
6!=5!*6=5!*3!
7!=7!
8!=7!*8=7!*2!*2!*2!
9!=9*8*7!=7!*3!*3!*2!;

程式碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const string convert[10]={"0","0","2","3","322","5","53","7","7222","7332"};
string s;
string ans;
int n;
int cmp(char x,char y){
    return x>y;
}
int main(){
    scanf
("%d",&n); cin>>s; ans=""; for(int i=0;i<n;i++){ if(s[i]-'0'==0||s[i]-'0'==1) continue; ans=ans+convert[s[i]-'0']; } // cout<<ans<<endl; sort(ans.begin(),ans.end(),cmp); cout<<ans<<endl; }