USACO算法系列三十六——lgame

    题目:http://www.nocow.cn/index.php/Translate:USACO/lgame

    这道题看起来数据量很大,而且不知道40000字典,实际上经过处理以后数据量不大。

    第一步预处理,读入数据的时候,如果长度超过现有的字符串长度,删除。

    第二步预处理,读入数据的里面字符的个数多于我们拥有的字符个数删除。

    第三步词对组合判断完以后,能够得到最大的字符值,此时,我们打印结果时,只要打印字符串的值为最大值的字符串,或者和为这个值,并且词对满足要求的情况就可以了。这样就可以很大程度上的减少数据量。

    代码如下:

#include <iostream> #include <fstream> #include <string.h> #define SIZE 40000 #define LETTER 26 #define WORD 9 using namespace std; int length =0; int lvalue[LETTER] = {2,5,4,4,1,6,5,5,1,7,6,3,5,2,3,5,7,2,1,2,4,6,6,7,5,7}; int letter[LETTER] = {0}; char dict[SIZE][WORD]; int value[SIZE] = {0}; int dl=0; //是否是词语 int accord(char * w) { int wletter[LETTER]={0}; int len = strlen(w); int sum =0; for (int i=0; i < len; i ++) { int index = w[i] - 'a'; sum += lvalue[index]; wletter[index] ++; if (wletter[index] > letter[index]) { return -1; }//end if wletter[index]>letter[index] }//end for return sum; } //词对是否满足要求 bool accordpair(char * str1, char * str2) { int len1 = strlen(str1); int len2 = strlen(str2); if (len1 + len2 > length) { return false; } int wletter[LETTER]={0}; for (int i=0; i < len1; i ++) { int index = str1[i] - 'a'; wletter[index] ++; }//end for for (int i=0; i < len2; i ++) { int index = str2[i] - 'a'; wletter[index] ++; if (wletter[index] > letter[index]) { return false; } } return true; } //输入输出流 ifstream fin("lgame.in"); ifstream fdict("lgame.dict"); ofstream fout("lgame.out"); int main() { char * str = new char[WORD]; //输入数据 fin.getline(str, WORD); length = strlen(str); for (int i=0; i < length; i ++) { letter[str[i]-'a'] ++; } //读取字典 fdict.getline(str,WORD); while (strcmp(str,".") != 0) { int sum = accord(str); if ( sum > 0) { strcpy(dict[dl], str); value[dl] = sum; dl ++; } fdict.getline(str,WORD); }//end while int result = 0; //词对 for(int i=0; i < dl; i ++) { int large = value[i]; for (int j = i; j < dl; j ++) { large = value[i]; char * str1 = dict[i]; char * str2 = dict[j]; if (accordpair(str1, str2)) { large += value[j]; } if (large> result) { result = large; } }//end for j }//end for i fout << result << endl; //词对 for(int i=0; i < dl; i ++) { if (value[i] == result) { fout << dict[i] << endl; continue; } for (int j = i; j < dl; j ++) { if (value[i] + value[j] == result) { char * str1 = dict[i]; char * str2 = dict[j]; if (accordpair(str1, str2)) { fout << str1 << " " << str2 << endl; } } }//end for j }//end for i return 0; }  

    运行结果如下:

Executing... Test 1: TEST OK [0.022 secs, 3520 KB] Test 2: TEST OK [0.011 secs, 3520 KB] Test 3: TEST OK [0.022 secs, 3520 KB] Test 4: TEST OK [0.032 secs, 3520 KB] Test 5: TEST OK [0.022 secs, 3520 KB] Test 6: TEST OK [0.022 secs, 3520 KB] Test 7: TEST OK [0.000 secs, 3520 KB] Test 8: TEST OK [0.011 secs, 3520 KB] Test 9: TEST OK [0.032 secs, 3520 KB] Test 10: TEST OK [0.022 secs, 3520 KB] Test 11: TEST OK [0.022 secs, 3520 KB] Test 12: TEST OK [0.011 secs, 3520 KB] All tests OK.  

你可能感兴趣的:(USACO算法系列三十六——lgame)