算法提高 P1003
作为一名网络警察,你的任务是监视电子邮件,看其中是否有一些敏感的关键词。不过,有些狡猾的犯罪嫌疑人会改变某些单词的字母顺序,以逃避检查。请编写一个程序,发现这种调整过顺序的关键词。程序的输入有两行,第一行是关键词列表,第二行是待检查的句子。程序的输出为在该句子中所找到的经过顺序调整的关键词。(单词全部为小写,单词之间以一个空格分隔,每一行的单词个数不限)
输入:
guns mines missiles
aameric ssell snug dan iimsssle ot sit neeemis
输出:
guns missiles
主要是细节的处理。。。。
#include <stdio.h> #include <string.h> #define N 50 //the longest of word #define TRUE 1 typedef struct{ char str[N]; int num[26]; //frequence of word }Word; Word keyword[N],word[2*N]; char keystr[N*N+N],wordstr[2*N*N+2*N],sortword[N][N]; int key_len,word_len,find_len; void Resolve(char *str, Word *w, int n, int *len){ int i,k,t; //initial to zero for( i = 0 ; i < n ; i ++ ) memset(w[i].num,0,sizeof(w[i].num)); k = i = *len = 0; while(TRUE){ if(str[i] == ' ' || str[i] == '\0'){ //after the judge of "str[i]=='\0'", do "Copy"! //Copy for(t = k ; t < i ; t ++ ) w[*len].str[t-k] = str[t]; w[*len].str[i-k] = '\0'; (*len) ++; //next keyword,'++'优先级>'*' if(!str[i]) break; k = i + 1; } else{ w[*len].num[str[i]-'a'] ++; } i ++; } } void Find_Keyword(){ int i,j,k; find_len = 0; for(j = 0 ; j < word_len ; j ++ ){ for(i = 0 ; i < key_len ; i ++ ){ // add the bracket for(k = 0 ; k < 26 ; k ++ ){ if(word[j].num[k] != keyword[i].num[k]) break; } if(k == 26){ //have the adjusted keyword strcpy(sortword[find_len],keyword[i].str); find_len ++; break; //need break } } } } void Sort_Keyword(){ //Bubble Sort int i,j,k,min_len; char tmp[N]; for(i = 0 ; i < find_len - 1; i ++ ) for(j = i + 1 ; j < find_len ; j ++){ if(strcmp(sortword[i],sortword[j]) > 0){ strcpy(tmp,sortword[j]); strcpy(sortword[j],sortword[i]); strcpy(sortword[i],tmp); break; } } for(i = 0 ; i < find_len ; i ++ ){ printf("%s",sortword[i]); if(i < find_len - 1) putchar(' '); else puts(""); } } int main(){ gets(keystr),gets(wordstr); Resolve(keystr,keyword,N,&key_len); Resolve(wordstr,word,2*N,&word_len); //find the keyword from the word Find_Keyword(); Sort_Keyword(); return 0; }
其中,对sortword的排序可以采用更快的快速排序
int Sort_Function(const void *a, const void *b){ return strcmp((const char *)a,(const char *)b); //asending order } qsort((void *)sortword,find_len,sizeof(sortword[0]),Sort_Function); //quciksort,attention:the bit of sortword[i].str keeps N
延伸-----对int数组排序,如int a[5] = {3,7,2,8,1};
int cmp(const void *a , const void *b){ return *(int *)a - *(int *)b; } qsort((void *)a,10,sizeof(a[0]),cmp);