19010 最小的特殊数字
时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 编程题 语言: G++;GCC;VC;JAVA
Description
用全部N(N<=10)个0-9的数字组成一个“有效”整数(即没有前置0的整数), 求这些组成的数中能被K(0<K<10^10)整除的最小数字。
输入格式
输入分两行,第一行输入N, K,第二行输入N个数字。
输出格式
输出满足条件的最小的数(不含前置0),如果没有满足条件的数输出 -1。
输入样例
4 7 4 0 1 3
输出样例
1043
提示
413 % 7 = 0, 但是有前置0,所以满足条件的最小数是 1043 % 7 = 0。 此类题目需注意特殊情况,比如n=1时,如只输入一个0,答案只能是0。 注意long long
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
LL n, aim;
bool f=0;//全局判断是否有答案
vector<int> num;
vector<int> ans;
vector<bool> v;
void output() {
for (LL i = 0; i < n; i++) {
cout << ans[i];
}
cout << endl;
}
void dfs(int t, LL sum) {
if (t == n) {
if (sum % aim == 0) {
output();
f=1;
}
return ;
}
for (LL i = 0; i < n; i++) {
if (!t && !num[i]) {
continue; //前置零跳过
}
if (!v[i]) {
v[i] = true;
ans[t] = num[i];
dfs(t + 1, sum * 10 + num[i]);
if(f){
return;
}
v[i] = false;
}
}
}
int main() {
cin >> n >> aim;
num.resize(n);
ans.resize(n);
v.resize(n, false);
for (LL i = 0; i < n; i++) {
cin >> num[i];
}
if(n==1&&num[0]==0){
cout<<0;
return 0;
}//特殊情况判断
sort(num.begin(), num.end());
dfs(0, 0);
if(!f){
cout<<-1;
}
return 0;
}