题目:http://acm.timus.ru/problem.aspx?space=1&num=1095
题意:
给你N个正整数,它们都含有数码1、2、3、4,不超过20位,要求你调整每个正整数中数字的顺序,使它能被7整除。
分析:
做这题的时候没看清题意,没看到都含有1,2,3,4,用的记忆化搜所~~当然T了。
如果每个数都有1,2,3,4,可以把1,2,3,4的全排列,计算一下,发现余数0~6都有,所以剩下的数随便找个排列就好,然后用1,2,3,4去吧余数抵消即可。注意某种情况是1234000。
代码:
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
int n, num[10];
string ans;
int last;
int dfs (int pos, int pre, string s) {
if (pos == 0) {
ans = s;
last = pre;
return 1;
}
for (int i = 0; i <= 9; i++) {
if (pos == n - 4 && i == 0) continue;
if (num[i]) {
num[i]--;
return dfs (pos - 1, (pre * 10 + i) % 7, s + (char) (i + '0') );
}
}
return 1;
}
char str[22];
vector<string>vec[7];
void init() {
string s = "1234";
do {
int x = 0;
for (int i = 0; i < 4; i++) x = (x * 10 + (s[i] - '0') ) % 7;
vec[x].push_back (s);
} while (next_permutation (s.begin(), s.end() ) );
// for (int i = 0; i < 7; i++) {
// for (int j = 0; j < vec[i].size(); j++) cout << vec[i][j] << ' ';
// printf ("\n");
// }
}
int main() {
int T;
//freopen ("f.txt", "r", stdin);
init();
scanf ("%d", &T);
while (T--) {
scanf ("%s", str);
n = strlen (str);
memset (num, 0, sizeof (num) );
for (int i = 0; i < n; i++) num[str[i] - '0']++;
num[1]--;
num[2]--;
num[3]--;
num[4]--;
ans = "";
if(num[0]==n-4){
for(int i=0;i<num[0];i++)ans+='0';
cout<<vec[0][0]+ans<<endl;
continue;
}
dfs (n - 4, 0, ans);
last = last * 10000 % 7;
cout << ans + vec[ (7 - last) % 7][0] << endl;
}
return 0;
}
/*
input
2
1234
531234
output
4123
354123
*/