C语言单词排序问题

zzzzz111112222333333 2017-12-18 05:18:25
问题是这样的
http://noi.openjudge.cn/ch0110/10/

我写的代码是这样的
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
char words[101][52]={0};
int i,cnt=0,j,k;
char word[5100];
char buff[52];
i=0;j=0,k=0;
gets(word);
char*token=strtok(word," ");//分割
while(token!=NULL)
{
strcpy(words[i],token);
token=strtok(NULL," ");
cnt++;i++;
}

for(i=0;i<cnt-1;i++)//选择排序
{
j=i;
for(k=i+1;k<cnt;k++)
{
if(strcmp(words[j],words[k])==1)
{
j=k;
}
}
strcpy(buff,words[i]);
strcpy(words[i],words[j]);
strcpy(words[j],buff);
}
for(i=0;i<cnt;i++)//输出
{
if(strcmp(words[i],words[i+1])==0)
{
continue;
}
if(i!=cnt-1)
puts(words[i]);
else
printf("%s",words[i]);
}

return 0;
}


问题是,提交只有3分,不知哪些数据出了问题。多个空格,重复单词,一开始就有空格这些都没问题,已经解决
...全文
1904 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
hongwenjun 2017-12-19
  • 打赏
  • 举报
回复
提交了第3次才成功,开始忘记删除了重复了,第二次输出没有分行,改正通过,用C++的算法也没事
http://noi.openjudge.cn/ch0110/solution/11872477/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

int main()
{
vector<string> words;
int cnt = 0;

char word[5100];

gets(word);

char* pch = strtok(word, " \t"); //分割
while (pch != NULL) {
words.push_back(string(pch));
pch = strtok(NULL, " \t\n");
cnt++;
}

// 排序和删除重复
std::sort(words.begin(), words.end());
auto it = unique(words.begin(), words.end());
words.erase(it, words.end());

for (auto it = words.begin(); it != words.end(); it++) { //输出
printf("%s\n", it->c_str());
}
return 0;
}
自信男孩 2017-12-19
  • 打赏
  • 举报
回复 1
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
    char words[101][52]={0};
    int i,cnt=0,j,k;
    char word[5100];
    char buff[52];
    i=0;j=0,k=0;
    gets(word);
    char*token=strtok(word," ");//分割
    while(token!=NULL)
    {
        strcpy(words[i],token);
        token=strtok(NULL," ");
        cnt++;
        i++;
    }

    /*
    printf("cnt = %d\n", cnt);
    for (i = 0; i < cnt; i++)
        printf("words[%d] = %s\n", i, words[i]);
    */

    for(i = 0; i < cnt-1; i++)
    {
        j = i;
        for(k = i + 1; k < cnt; k++)
            if(strcmp(words[j], words[k]) > 0)
                j = k;
        if (j != i) {    /*交换条件*/
            strcpy(buff, words[i]);
            strcpy(words[i], words[j]);
            strcpy(words[j], buff);
        }
    }
    /*
    for (i = 0; i < cnt; i++)
        printf("words[%d] = %s\n", i, words[i]);
    */
    for(i = 0; i < cnt; i++)//输出
    {
        if(strcmp(words[i], words[i+1])==0)
        {
            continue;
        }
        if(i!=cnt-1)
            puts(words[i]);
        else
            printf("%s",words[i]);
    }

    return 0;
}
参考一下吧 主要是选择排序的问题,选择排序算法写的有点问题,详见上面的代码;

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧