Nothing for nothing( 九 )

題目:Ugly Pairs

題意:給你一個字符串,讓你改變字符的順序,使字符任意相鄰的字符在字母表中的位置都不相鄰。
思路:就是把字符的奇數位置s1和偶數位置s2,單獨提取出來,然後判斷一下這兩個字符串能否拼接在一起,如果不能就輸出No answer.
參考博客:【題解】B. Ugly Pairs(貪心 思維)⭐⭐
代碼:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int T, num[30];
    string s, s1, s2;
    cin >> T;
    while(T--){
        memset(num, 0, sizeof(num)); s1 = s2 = "";
        cin >> s;
        for(int i = 0; i < s.length(); i++)
            ++num[s[i]-'a'];
        for(int i = 0; i < 26; i+=2)
            while(num[i]--) s1 += ('a'+i);
        for(int i = 1; i < 26; i+=2)
            while(num[i]--) s2 += ('a'+i);

        if(abs(s1.back()-s2.front())!=1) cout << s1 << s2 << endl;//判斷能否拼接
        else if(abs(s2.back()-s1.front())!=1) cout << s2 << s1 << endl;
        else cout << "No answer" << endl;
    }

	return 0;
}


題目: Multicolored Cars

思路:去更新當前位置比cnt[A]大,如果小的就直接拋棄,然後遍歷一遍,找到比最終cnt[A]大的。
參考博客:CodeForces - 818D - Multicolored Cars (貪心水題)被誤導是線段樹。。。
代碼:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+10;
int n,m,x;
int cnt[maxn],ret=0;

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&x);
        if(x==m)  ret++;
        else  if(cnt[x]>=ret) cnt[x]++;///不選他作爲答案
    }
    int ans=-1;
    for(int i=1;i<maxn;i++)
    {
        if(i==m) continue;
        if(cnt[i]>=ret) {ans=i;break;}
    }
    printf("%d\n",ans);
    return 0;
}

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