荔园在线
荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀
[回到开始]
[上一篇][下一篇]
发信人: huhaiming (一生只爱她), 信区: Program
标 题: 排序题目我写的程序
发信站: 荔园晨风BBS站 (Tue Jun 3 16:14:19 2003), 站内信件
好像都没什么人提交,我也比较忙,就公开吧,这题是浙大的1225题
我的处理方法是用flag数组标记各个位置的状态(究竟是word还是num)
对原始的单词存到一个结构体,同时转换成全小写形式的单词字符串
然后对转换后的结构体排序,对数字num的数组排序,然后根据flag
数组的标记输出就搞掂了。
数据输出方面用了scanf的%n,是很好用,比strtok好用多了。
比较函数写起来也很简单。scmp()是字符串比较的函数,cmp是数字的比较函数
//zju 1225
//by jhun
//May 8th 2003
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
struct words{
char str[100];
char strsort[100];
};
struct words word[100];
char list[255],temp[100];
int num[100],flag[100],num_count,word_count,list_count;
//结构体的根据字符串的比较函数
int scmp(const void *p1,const void *p2)
{
struct words *r=(struct words*)p1,*s=(struct words*)p2;
return strcmp( r->strsort,s->strsort );
}
//int的比较函数
int cmp(const void *p1,const void *p2)
{
return *(int*)p1-*(int*)p2;
}
int main()
{
int i,j,k,n,len;
char *p;
freopen("1225.in","r",stdin);
freopen("1225.out","w",stdout);
while( gets(list) != NULL )
{
if(strcmp(list,".")==0) break;
p=list,list_count=num_count=word_count=0;
//list的处理,用sscanf
while( sscanf(p, "%s%n", temp, &n) == 1 )
{
p += n, len=strlen(temp), temp[len-1]='\0';
if( isalpha(temp[0]) ){
strcpy(word[word_count].str,temp);
strcpy(word[word_count].strsort,temp);
for(i=0;word[word_count].strsort[i]!='\0';i++)
word[word_count].strsort[i]=tolower(word[word_count].strsort[i]);
flag[list_count++]=1;
word_count++;
}else{
num[num_count++]=atoi(temp);
flag[list_count++]=0;
}
}
//排序
qsort(word,word_count,sizeof(struct words),scmp);
qsort(num,num_count,sizeof(int),cmp);
//输出
for(k=i=j=0,list_count--;k<list_count;k++)
if(flag[k]) printf("%s, ",word[i++].str);
else printf("%d, ",num[j++]);
if(flag[k]) printf("%s.\n",word[i].str);
else printf("%d.\n",num[j]);
}
return 0;
}
--
菩提本无树,明镜亦非台
本来无一物,何处惹尘埃
※ 修改:·huhaiming 於 Jun 3 16:16:33 修改本文·[FROM: 192.168.0.200]
※ 来源:·荔园晨风BBS站 bbs.szu.edu.cn·[FROM: 192.168.0.200]
[回到开始]
[上一篇][下一篇]
荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店