题目不再说了,由于是刚开始做poj上面的题,很是吃力。这道题提交了好多次,有一次是TLE。我觉得主要是由于排序的关系。之前用的是插入排序,即将val[i]赋值给array[i]的时候,进行插入排序,复杂度为O(n^2+n^2+n)结果就超时了。后来自己实现了一个快速排序,变成O(n^2+nlogn+n)。
#include <cstdio> #include <cstdlib> #include <cstring> #define MAX 100000 using namespace std; char hash[] = {'2','2','2','3','3','3','4','4','4','5','5','5', '6','6','6','7','Q','7','7','8','8','8','9','9','9','Z'}; char key[MAX][100] = {{0}}; char val[MAX][100] = {{0}}; char *array[MAX] = {NULL}; void convert (char key[], int j) { int i = 0, k = 0, count = 0; while (key[i] != '/0') { if (count == 3) { val[j][k] = '-'; ++count; ++k; continue; } else if (key[i] == '-') ++i; else if ('A' <= key[i] && key[i] <= 'Z') { val[j][k] = hash[key[i]-'A']; ++count; ++k; ++i; } else if ('0' <= key[i] && key[i] <= '9') { val[j][k] = key[i]; ++count; ++k; ++i; } }; } void swap (char*& p1, char*& p2) { char *temp = p1; p1 = p2; p2 = temp; } void sort (char* s[], int begin, int end) { if (begin >= end) return; int mid = (begin + end)/2; if (strcmp(s[begin], s[end]) > 0) swap(s[begin], s[end]); if (strcmp(s[mid], s[end]) > 0) swap(s[mid], s[end]); else if (strcmp(s[mid], s[begin]) < 0) swap(s[mid], s[begin]); int i = begin, j = end-1; while (i <= j) { if (strcmp(s[i], s[end]) < 0) { ++i; continue; } if (strcmp(s[j], s[end]) > 0) { --j; continue; } swap(s[i], s[j]); ++i; --j; }; swap(s[i], s[end]); sort(s, begin, i-1); sort(s, i+1, end); } void poj1002 () { int d; scanf("%d", &d); int i = 0; while (i < d) { scanf("%s", key[i]); ++i; }; for (int j=0; j<d; ++j) { convert(key[j], j); array[j] = val[j]; } sort(array, 0, d-1); int count = 1, flag = 0; for (int j=0,k=1; j<d;) { if (k < d) { if (strcmp(array[j], array[k]) == 0) { ++count; ++k; continue; } else if (count > 1) { flag = 1; printf("%s %d/n", array[j], count); count = 1; } j = k; ++k; } else { if (count > 1) { flag = 1; printf("%s %d/n", array[j], count); } break; } } if (!flag) printf("No duplicates./n"); } int main() { poj1002(); return 0; }