URAL 1095 Nikifor 3 (注意读题)

题目: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
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值