方法一:数论分析简单
分析 x%30 == 0 等价于 x % 3 == 0 && x % 10 == 0
如果想要%10 则最后一位为0;
如果想要%3 则各位的数字之和可以%3 ==0;
所以如果想要最大值,那么一定是逆序排列!
#include <bits/stdc++.h>
using namespace std;
#define int long long
//typedef long long ll;
//typedef pair<int, int> PII;
// const double PI = 3.14159265358979;
//const int MOD=998244353
const int N=2e5+7;
const int INF = 0x3f3f3f3f;
//vector<int>ve;
void solve()
{
string s;
cin >> s;
sort(s.begin(), s.end(),greater<>());
if(stoi(s) % 30 ==0) cout << s <<endl;
else cout << -1 <<endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int T=1;
// cin >> T;
while(T--) solve();
return 0;
}
方法二:dfs搜索
#include <bits/stdc++.h>
using namespace std;
// #define int long long
// typedef long long ll;
// typedef pair<int, int> PII;
// const double PI = 3.14159265358979;
// const int MOD=998244353
const int N = 2e5 + 7;
const int INF = 0x3f3f3f3f;
// vector<int>ve;
string s;
int cnt[9];
int res = -1;
int n;
void dfs(int u, int s)
{
if (u == n && s % 30 == 0)
{
res = max(res, s);
return;
}
for (int i = 0; i <= 9; i++)
{
if (cnt[i])
{
cnt[i]--;
dfs(u + 1, s * 10 + i);
cnt[i]++;
}
}
}
void solve()
{
cin >> s;
n = s.size();
for (int i = 0; i < s.size(); i++)
cnt[s[i] - '0']++;
dfs(0,0);
cout << res << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T = 1;
// cin >> T;
while (T--)
solve();
return 0;
}
方法三:搜索,使用next_permutation()函数
#include <bits/stdc++.h>
using namespace std;
string s;
int n;
int a[9];
int ans = -1;
int main()
{
cin >> s;
n = s.size();
for (int i = 0; i < n; i++)
a[i] = s[i] - '0';
sort(a, a + n);
do
{
int res = 0;
for (int i = 0; i < n; i++)
res = res * 10 + a[i];
if (res % 30 == 0)
ans = max(ans, res);
} while (next_permutation(a, a + n));
cout << ans << endl;
return 0;
}