POJ-2408 Anagram Groups(字符串排序問題)

點我看題目

題目大意

輸入多個單詞,相同字母異序詞歸爲一組,按照每組單詞數量從大到小輸出前5組(不夠全輸出),兩組數量相同則按照字典序輸出,並按照字典序輸出每組的單詞。

思路

先將每個單詞s1的每個字母按照字典序排序(目的是使單詞同源)得到s2,並把排序前後的兩個字符串打包到一個結構體中。然後按照優先s2,其次s1的規則sort排序,得到有序(字典序)的一組結構體數組。for循環遍歷找出有幾組相同字母異序詞,並按照優先數量其次字典序的規則排序,輸出前五組即可。

AC代碼

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <math.h>
using namespace std;

struct node//存放每個單詞
{
    char s1[40];
    char s2[40];
} str[30005];

struct xu //存放每組相同字母異序詞的信息
{
    int start;//在str數組中開始的位置
    int con;//數量
    char s[40];//組中字典序最小的單詞
} Node[30005];
bool cmpw(node a,node b)
{
    if(strcmp(a.s2,b.s2)==0)
        return strcmp(a.s1,b.s1)<0;
    else
        return strcmp(a.s2,b.s2)<0;
}

bool cmp(xu a,xu b)
{
    if(a.con==b.con)
        return strcmp(a.s,b.s)<0;
    else
        return a.con>b.con;
}
int main()
{
    int n=0;
    while(~scanf("%s",str[n].s1))
    {
        int len=strlen(str[n].s1);
        strcpy(str[n].s2,str[n].s1);
        sort(str[n].s2,str[n].s2+len);//這裏可以直接用sort非常方便!看了別人的代碼是用桶排的
        n++;//統計單詞個數
    }
    sort(str,str+n,cmpw);//按照字典序排序
    int m=1;//統計組數
    Node[0].start=0;
    Node[0].con=1;
    strcpy(Node[0].s,str[0].s1);//注意是將s1賦過去,因爲前面已經按照字典序最小排序了,所以易知此爲組中最小單詞
    for(int i=1; i<n; i++)//遍歷全部單詞,統計共有多少不同的組
    {
        if(strcmp(str[i].s2,str[i-1].s2)==0)
            Node[m-1].con++;
        else
        {
            strcpy(Node[m].s,str[i].s1);
            Node[m].start=i;
            Node[m].con=1;
            m++;
        }
    }
    sort(Node,Node+m,cmp);//按照數量和字典序排序
    for(int i=0; i<5; i++)//輸出前5組
    {
        int t=Node[i].start;
        if(i>=m)//不足5組全部輸出後break;
        {
            printf("\n");
            break;
        }
        printf("Group of size %d:",Node[i].con);
        printf(" %s",str[t].s1);
        for(int j=1;j<Node[i].con;j++)
        {
            if(strcmp(str[t+j].s1,str[t+j-1].s1)==0)
                continue;
            printf(" %s",str[t+j].s1);
        }
        printf(" .\n");
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章