pku 2001 Shortest Prefixes 排序

这题我的做法是排序后, 对前一字符串和后一字符串推断出该字符串的最短前缀.

做完看discuss中, 有人说可以用字典树, 我还没用过, 有时间时打算看一下.

 

#include <iostream> #include <algorithm> #include <map> #include <string> using namespace std; #define MAX(a,b) ((a>b)?(a):(b)) struct Node { char str[21]; int index; bool operator<(const Node& rhs) { return (strcmp(str, rhs.str)<0); } }; Node arr[1000]; char ret1[1000][21]; char ret2[1000][21]; int compare(const char* p1, const char* p2) { int index = 0; while(*p1++ == *p2++ && p1 != '/0' && p2 != '/0') index++; return index; } int main() { int n = 0; while(gets(arr[n].str)) { arr[n].index = n; n++; } if(n == 1) { printf("%s %s", arr[0].str, arr[0].str); return 0; } sort(arr, arr+n); int index = compare(arr[0].str, arr[1].str); strcpy(ret1[arr[0].index], arr[0].str); strncpy(ret2[arr[0].index], arr[0].str, index+1); for(int i = 1; i < n-1; ++i) { int index1 = compare(arr[i-1].str, arr[i].str); int index2 = compare(arr[i].str, arr[i+1].str); strcpy(ret1[arr[i].index], arr[i].str); strncpy(ret2[arr[i].index], arr[i].str, MAX(index1, index2)+1); } index = compare(arr[n-2].str, arr[n-1].str); strcpy(ret1[arr[n-1].index], arr[n-1].str); strncpy(ret2[arr[n-1].index], arr[n-1].str, index+1); for(int i = 0; i < n; ++i) printf("%s %s/n", ret1[i], ret2[i]); return 0; }

你可能感兴趣的:(pku 2001 Shortest Prefixes 排序)