zoukankan      html  css  js  c++  java
  • Verbal Arithmetic Puzzle

    2020-01-02 12:09:09

    问题描述:

    问题求解

    这个问题不就是小学奥数题么?都知道要暴力枚举,但是如何巧妙的枚举才是问题的关键。在打比赛的时候,我用了全排列算法,TLE了。

    借鉴了别人的解法,确实实现的要优雅很多,因此在此做一个记录。

        public int[] pow_num = new int[]{1, 10, 100, 1000, 10000, 100000, 1000000};
        public boolean isSolvable(String[] words, String result) {
            Set<Character> seen = new HashSet<>();
            boolean[] isFirst = new boolean[128];
            int[] char_count = new int[128];
            for (String word : words) {
                for (int i = 0; i < word.length(); i++) {
                    char c = word.charAt(i);
                    if (!isFirst[c] && i == 0 && word.length() > 1) isFirst[c] = true;
                    char_count[c] += pow_num[word.length() - i - 1];
                    seen.add(c);
                }
            }
            for (int i = 0; i < result.length(); i++) {
                char c = result.charAt(i);
                if (!isFirst[c] && i == 0 && result.length() > 1) isFirst[c] = true;
                char_count[c] -= pow_num[lresult.length() - i - 1];
                seen.add(c);
            }
            char[] chs = new char[seen.size()];
            int idx = 0;
            for (char c : seen) chs[idx++] = c;
            return helper(char_count, isFirst, chs, new boolean[10], 0, 0);
        }
        
        private boolean helper(int[] char_count, boolean[] isFirst, char[] chs, boolean[] used, int step, int diff) {
            if (step == chs.length) return diff == 0;
            for (int i = 0; i < 10; i++) {
                char c = chs[step];
                if (used[i] || (i == 0 && isFirst[c])) continue;
                used[i] = true;
                if (helper(char_count, isFirst, chs, used, step + 1, diff + char_count[c] * i)) return true;
                used[i] = false;
            }
            return false;
        }
    

      

  • 相关阅读:
    数据库范式那些事[转]
    C# 之值类型与引用类型参数[基础]
    C# 实体类生成工具
    《浅谈线程池》笔记
    提高网站性能之 —— 减少图片HTTP 请求的方案
    SQL Server 2005 For XML[学习]
    关于数据类型导致的精确计算
    SQL Server 数据库实现之TSQL语句[备忘]
    C# 关键字ref 和out 的详细区别
    关于XML中的名称空间
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/12132264.html
Copyright © 2011-2022 走看看