- 论坛徽章:
- 0
|
my code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include <iconv.h>
#define max 100
struct BaiduLang
{
char f[10];
char s[255];
};
typedef struct BaiduLang BL;
//quickly sort
int partition(BL langs[],int low,int high);
void Qsort(BL langs[],int low,int high);
//search by key using binary search
int Search(BL langs[],char *key,int n)
{
int mid,low,high;
low=0;
high=n-1;
int flag;
while(low<=high)
{
mid=(low+high)/2;
flag=strcmp(key,langs[mid].f);
if(flag==0)
return mid;
else if(flag>0)
high=mid-1;
else
low=mid+1;
//fprintf(stderr,"key");
}
//printf("%d %d\n",low,high);
if(low>high)
{
fprintf(stderr,"can not find key\n");
return -1;
}
else
return mid;
}
int readfromfile(FILE *file,BL langs[],char *result)
{
int i=0;
int j=0;
int n;
if(fscanf(file,"%d",&n)==-1)
{
fprintf(stderr,"failed to read n \n");
return -1;
}
BL temps[n+1];
for(i=0;i<n+1;i++)
{
if(i==0)
continue;
fscanf(file,"%s",langs[j].f);
fscanf(file,"%s",langs[j].s);
j++;
}
fscanf(file,"%s",result);
return n;
}
////////////////////////////////////////////////////
/*******************quickly sort*******************/
int partition(BL *langs,int i,int j)
{
int low=i;
int high=j;
char pk[10];
char record[255];
strcpy(pk,langs[i].f);
strcpy(record,langs[i].s);
while(low<high)
{
while((low<high) && (strcmp(pk,langs[high].f)>=0))
high=high-1;
strcpy(langs[low].f,langs[high].f);
strcpy(langs[low].s,langs[high].s);
while((low<high) && (strcmp(pk,langs[low].f)<=0))
low=low+1;
strcpy(langs[high].f,langs[low].f);
strcpy(langs[high].s,langs[low].s);
}
strcpy(langs[low].f,pk);
strcpy(langs[low].s,record);
return low;
}
void Qsort(BL *langs,int low,int high)
{
int i;
if(low<high)
{
i=partition(langs,low,high);
Qsort(langs,low,i-1);
Qsort(langs,i+1,high);
}
}
////////////////////////////////////////////////////
int main()
{
BL langs1[max];
BL *langs;
char *result;
char *real;
if((result=(char *)malloc(1000000))==NULL || (real=(char *)malloc(1000000))==NULL)
{
printf("failed to malloc\n");
return 1;
}
int n;
size_t i,j,k;
i=j=k=0;
FILE *file=fopen("in.txt","r");
n=readfromfile(file,langs1,result);
langs=langs1;
Qsort(langs,0,n-1);
int count=0;
while(result[i]!='\0')
{
char temp[10]="";
while(isupper(*(result+i)) && isalpha(*(result+i)))
{
//printf("%d ",isupper(*(result+i)));
//printf("[%d]",i);
temp[j]=result[i];
j=j+1;
i++;
}
if(j>0)
{
//printf("%s\n",temp);
int index=Search(langs,temp,n);
//printf("%d\n",index);
if(index!=-1)
{
int len=strlen(langs[index].s);
strcat(real,langs[index].s);
k=k+len;
}
}
if(count==0 && i!=0)
i=0;
*(real+k)=*(result+i);
i++;
k++;
count++;
j=0;
}
printf("%s\n",real);
fclose(file);
free(result);
free(real);
return 0;
} |
|