位运算处理字符组合。HOJ2241 Crabbles。
通过位运算将所有组合列出后 搜索。
| Time limit: | 5sec. | Submitted: | 45 |
| Memory limit: | 32M | Accepted: | 32 |
Jennifer is practicing for a Crabbles tournament. She pulls out a handful of Crabbles tiles out of a bag, and tries to form the word with the highest possible score. Each tile contains a letter (used to form the word) and a number (its score value). She can use each tile at most once in her word, and she is not required to use every tile. The word that she forms must appear in her dictionary. Her score is the sum of the values of the tiles used in the word.
Note that in Crabbles, different tiles with the same letter may have different score values.
To check her work, Jennifer would like a program to tell her the maximum score possible for the set of tiles. Your task is to write this program.
Input Specification
The first line contains an integer 1 ≤ N ≤ 100,000 indicating the number of words in the dictionary. N lines follow, with one dictionary word on each line. Each dictionary word consists of only lowercase letters. The following line contains an integer 1 ≤ M ≤ 1000 indicating the number of Crabbles hands Jennifer wants to play. M hands follow. Each hand begins with a line containing an integer 1 ≤ P ≤ 10 indicating the number of tiles in the hand. This is followed by P lines, one for each tile. Each of these lines consists of a lowercase letter (the letter on the tile), a space, and an integer 0 ≤ V ≤ 10 (the value of the tile).
Output Specification
For each hand in the input, output a line containing the maximum score possible with that hand.
Sample Input
2 abcd hgfe 1 10 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10
Sample Output
26
说明:
给出1到10个字母的权值。 求出能拼成字典中某单词的最大值是多少。
暴力map搜索超时。。
通过位运算找出字母的所有组合。 匹配。 求最大即可。
代码如下:#include<iostream>
#include<algorithm>
#include<set>
using namespace std;
int main() {
int n;
cin >> n;
string tmp;
set<string>dic;
while (n--) {
cin >> tmp;
sort(tmp.begin(), tmp.end());
dic.insert(tmp);
}
int m, p;
cin >> m;
while (m--) {
cin >> p;
pair<char, int> tile[16];
for (int i = 0; i < p; i++)
cin >> tile[i].first >> tile[i].second;
sort(tile, tile + p);
int s = 1 << p, max = 0;
for (int i = 1; i <= s; i++) {
tmp.clear();
int sum = 0;
for (int j = 0; j < p; j++) {
if ((i >> j)&1 == 1) {
tmp += tile[j].first;
sum += tile[j].second;
}
}
if (sum > max && dic.find(tmp) != dic.end())
max = sum;
}
cout << max << endl;
}
return 0;
}

浙公网安备 33010602011771号