A Great Alchemist

Time limit : 2sec / Stack limit : 256MB / Memory limit : 256MB

Problem
Carol is a great alchemist.

In her world, each metal has a name of 2N (N is an integer) letters long, which consists of uppercase alphabets.

Carol can create metal S3 from S1 and S2 alchemical when she can make the name of S3 by taking N letters each from S1 and S2 then rearranging them properly.

You are given 3 names of the metal S1, S2, S3. Determine wether Carol can create S3 from S1 and S2 or not.

Input
The input will be given in the following format from the Standard Input.

S1
S2
S3
On the first line, you will be given the name of the first metal material S1.
On the second line, you will be given the name of the second metal material S2.
On the third line, you will be given the name of the metal S3, which Carol wants to create.
Each character in the S1, S2, and S3 will be an uppercase English alphabet letter.
Each string S1, S2 and S3 has same number of letters and the number is always even.
It is guaranteed that 2≦|S1|≦100000
Output
If Carol can create S3 from S1 and S2, output YES, if not, output NO in one line. Make sure to insert a line break at the end of the output.

Input Example 1
AABCCD
ABEDDA
EDDAAA
Output Example 1
YES
You can make EDDAAA by picking AAD from the first metal, and AED from the second metal.

Input Example 2
AAAAAB
CCCCCB
AAABCB
Output Example 2
NO
To make AAABCB, you have to take at least four letters from the first material. So this can't be created alchemical.

用回溯法TLE。看了同学的代码,在执行回溯前执行一些检查就能过了。哎。

 #include <iostream>
#include <string>
#include <vector>
using namespace std; bool backtrack(string &S3, int charsFromS1, int charsFromS2, int current,
vector<int> &charsInS1, vector<int> &charsInS2) {
if (current >= S3.length()) return true;
char index = S3[current] - 'A';
if (charsInS1[index] > && charsFromS1 < S3.length() / ) {
charsInS1[index]--;
if (backtrack(S3, charsFromS1 + , charsFromS2, current + , charsInS1, charsInS2)) return true;
charsInS1[index]++;
}
if (charsInS2[index] > && charsFromS2 < S3.length() / ) {
charsInS2[index]--;
if (backtrack(S3, charsFromS1, charsFromS2 + , current + , charsInS1, charsInS2)) return true;
charsInS2[index]++;
}
return false;
} int main(int argc, char** argv) {
string S1, S2, S3;
cin >> S1 >> S2 >> S3;
vector<int> charsInS1(, ), charsInS2(, ), charsInS3(, ); for (int i = ; i < S1.length(); ++i) {
charsInS1[S1[i] - 'A']++;
charsInS2[S2[i] - 'A']++;
charsInS3[S3[i] - 'A']++;
} int common13 = , common23 = ;
for (int i = ; i < ; ++i) {
if (charsInS3[i] > charsInS1[i] + charsInS2[i]) {
cout << "NO" << endl;
return ;
}
common13 += min(charsInS3[i], charsInS1[i]);
common23 += min(charsInS3[i], charsInS2[i]);
} if (common13 < S3.length() / || common23 < S3.length() / ) {
cout << "NO" << endl;
} else {
bool ans = backtrack(S3, , , , charsInS1, charsInS2);
cout << (ans ? "YES" : "NO") << endl;
}
return ;
}
上一篇:HDUOJ----2512一卡通大冒险


下一篇:Armitage主屏幕说明与命令行启动