问题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1106
问题分析:
这个问题主要是字符串处理和数字字符串转整数的问题。这里给出两种解题方法,方法一使用自动机来解决;方法二是用库函数strtok()来切割字符串后再将其转换为整数。
程序说明:
方法二:使用C语言的库函数strtok()来切割字符串,并且以数字字符“5”作为分割符,处理起来就简单多了。数字字符串转整数使用库函数atoi()来实现,排序使用库函数qsort()来实现,或者可以使用C++sort()来实现。
方法一:因为5被看为空格,需要注意的点有:
1.开始的若干个5需要跳过去;
2.最后的若干个5需要跳过去;
3.字符串全都是5的时候,需要正确处理;
4.中间的若干个5需要正确跳过去;
函数说明:
1.strtok函数:
strtok函数是用来分解字符串的,其定义为:
#include <string.h>
char * strtok(char *s, const char *delim);
参数指向需要分割的字符串,参数delim则为用于分割字符串集,是的,是字符串集,当strtok()在参数s的字符串中发现到参数delim的分割字符串集是中任意一个字符串时,则会将该字符串替换成为\0字符。在第一次调用时,strtok()必须给予参数s字符串,往后的调用则将参数s设置成null。每次调用成功则返回下一个分割后的字符串指针,因此可以知道如果输入是字符串常量执政的时候,是不能直接传递给strtok函数的第一个参数的,可以将这个字符串常量指针中的内容注意拷贝到一个字符串数组中,再使用该函数进行分割。
函数返回值:返回下一个被分割后的字符串指针,如果已无从分割则返回NULL。
程序代码:
方法二:
#include<bits/stdc++.h>
using namespace std;
const int N = 1000;
char s[N+1];
int a[N+1];
int main(){
int cnt;
char *p;
while(gets(s) != NULL){
cnt = 0;
p = strtok(s, "5");
while(p){
a[cnt++] = atoi(p);
p = strtok(NULL, "5");
}
if(cnt > 0){
sort(a, a+cnt);
for(int i = 0; i < cnt-1; i++)
printf("%d ", a[i]);
printf("%d\n", a[cnt-1]);
}
}
return 0;
}
方法一:
/* HDU1106 排序 */
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a,const void *b)
{
return *(int*)a - *(int*)b;
}
int main(void)
{
char figure;
int val=0, values[2000], count, flag5=1, i;
while(scanf("%c", &figure)!=EOF) {
if(figure == '\n') {
if(flag5 == 0)
values[count++] = val;
if(count > 0) {
qsort(values, count, sizeof(values[0]), cmp);
for(i=0; i<count-1; i++)
printf("%d ", values[i]);
printf("%d\n", values[count-1]);
}
val = 0;
count = 0;
flag5 = 1;
} else if(figure == '5') {
if(flag5 == 0)
values[count++] = val;
val = 0;
flag5 = 1;
} else {
val = val * 10 + figure - '0';
flag5 = 0;
}
}
return 0;
}