2014年8月24日星期日

[UVa] 642 - Word Amalgamation

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//字元比較
int n,m;
char word[2000][10], sorted[2000][10], scramble[2000][10], sorted2[2000][10];
int cmp_char(const void* _a, const void* _b){
  char* a = (char*)_a;
  char* b = (char*)_b;
  return *a-*b;
}
//字串比較
int cmp_string(const void* _a, const void* _b){
  char* a = (char*)_a;
  char* b = (char*)_b;
  return strcmp(a,b);
}
int main(){
  n = 0;
  
  //輸入字典單字,將每個單字存入word[n]中
  for(;;){
    scanf("%s", word[n]); //會自動以空白分隔單字
 if(word[n][0]=='X'&&word[n][1]=='X'&&word[n][2]=='X'&&word[n][3]=='X'&&word[n][4]=='X'&&word[n][5]=='X')break;
 n++;
  }
  //題目的OUTPUT中有敘述,輸出要按字典排序,故此排序為必要
  qsort(word, n, sizeof(word[0]), cmp_string);  //幫所有單字排序(由小到大),引入cmp_string為qsort必要之參照
  for(int i = 0; i<n; i++){
    strcpy(sorted[i], word[i]);
 qsort(sorted[i], strlen(sorted[i]), sizeof(char), cmp_char); //幫每個單字的字母各自排序 
  }
  
  //輸入欲檢查之單字
  char s[10];  
  while(scanf("%s", s)!=EOF && s[0]!='X') {  
    qsort(s, strlen(s), sizeof(char), cmp_char);  //將其內的字母做排序
    int found = 0;    
    for(int i = 0; i < n; i++){  
      if(strcmp(sorted[i], s) == 0) {  
        found = 1;  
        printf("%s\n", word[i]);  
      }  
    }  
    if(!found) printf("NOT A VALID WORD\n");  
    printf("******\n");  
  }  
  return 0;
} 

沒有留言: