C. Beautiful Lyrics 貪心

傳送

題意:按規則拼詞

思路:先按元音結尾排序取第二種詞,再按數目取第一種詞,貪心的先用第一種詞,如果不夠,就第二種詞可以當第一種用.

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MAXN=1e5+10;
struct node
{
    string word;
    int num;
    char last;
}words[MAXN];
int cmp(node aa,node bb)
{
    if(aa.num==bb.num)
        return aa.last<bb.last;
    return aa.num<bb.num;
}
vector<pair<int, int> > fi, se;
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        string s;
        cin>>s;
        words[i].word=s;
        for(int j=0;j<s.size();j++)
        {
            if (s[j] == 'a' || s[j] == 'e' || s[j] == 'i' || s[j] == 'o' || s[j] == 'u')
            {
                words[i].num++;
                words[i].last = s[j];
            }
        }
    }
    sort(words+1,words+1+n,cmp);
    int pos=1;
    int cnt=0;
    int w=-1;
    while(pos<=n)
    {
        if (words[pos].num == words[pos+1].num && words[pos].last == words[pos+1].last)
        {
            se.push_back({pos, pos+1});
            pos += 2;
            continue;
        }
        if(w==-1)// 如果不符合 那麼和前面的位置進行比較
        {
            w=pos;
            cnt=words[pos].num;
            pos++;
            continue;
        }
        if(words[pos].num==cnt)// 和前位置元音數量一樣 放入數量一樣的容器裏
        {
            fi.push_back({w, pos});
            w = -1;
            pos++;
        }
        else// 否則更新位置 因爲按照元音數量排序的
        {
            w = pos;
            cnt = words[pos].num;
            pos++;
        }
    }
    int s1=fi.size(),s2=se.size();
    int res=0;
    res+=min(s1,s2)+max(0,(s2-s1)/2);
    cout<<res<<endl;
    int i;
    for(i=0;i<min(s1,s2);i++)
    {
        cout << words[fi[i].first].word << ' ' << words[se[i].first].word << endl;
        cout << words[fi[i].second].word << ' ' << words[se[i].second].word << endl;
    }
    for(;i+1<se.size();i+=2)
    {
        cout << words[se[i].first].word << ' ' << words[se[i+1].first].word << endl;
        cout << words[se[i].second].word << ' ' << words[se[i+1].second].word << endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章