AcWing第40场周赛

AcWing 4305. 斐波那契字符串

#include 
#include 
#include 

using namespace std;
const int N = 2010;

int cnt = 2;
bool st[N];

int main()
{
    int n;
    cin >> n;
    
    int a = 1, b = 1;
    st[1] = true;
    for (int i = 2; b <= n; i ++ )
    {
        int c = a + b;
        a = b, b = c;
        st[b] = true;
    }
    
    for (int i = 1; i <= n; i ++ )
        if (st[i])
            cout << 'O';
        else cout << 'o';
    
    return 0;
}

AcWing 4306. 序列处理:贪心、并查集

并查集解法

#include 
#include 
#include 

using namespace std;
const int N = 1100010;

int n, cnt;
int p[N];

int find(int x)
{
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int main()
{
    cin >> n;
    
    for (int i = 1; i < N; i ++ ) p[i] = i;
    
    for (int i = 0; i < n; i ++ )
    {
        int x;
        scanf("%d", &x);
        int t = find(x);
        cnt += t - x;
        p[t] = t + 1;
    }
    cout << cnt << endl;
    return 0;
}

贪心解法

#include 
#include 
#include 

using namespace std;
const int N = 3010;

int n, cnt;
int a[N];

int main()
{
    cin >> n;
    
    for (int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
    
    sort(a, a + n);
    
    for (int i = 0, last = 0; i < n; i ++ )
    {
        int cur = max(last + 1, a[i]);
        cnt += cur - a[i];
        last = cur;
    }
    cout << cnt << endl;
    return 0;
}

AcWing 4307. 数字重构

#include 
#include 
#include 

using namespace std;

int cnt[10];

string get_min(int x)
{
    string ans = to_string(x);
    
    cnt[x] -- ;
    for (int i = 0; i < 10; i ++ )
        for (int j = 0; j < cnt[i]; j ++ )
            ans += to_string(i);
    cnt[x] ++ ;
    return ans;
}

int main()
{
    string a, b;
    cin >> a >> b;
    
    if (a.size() < b.size())
    {
        sort(a.begin(), a.end(), greater<char>());
        cout << a << endl;
    }
    else 
    {
        for (auto& c : a) cnt[c - 'a'] ++ ;
        string res;
        
        for (int i = 0; i < a.size(); i ++ )
            for (int j = 9; j >= 0; j -- )
                if (cnt[j] && res + get_min(j) <= b)
                {
                    res += to_string(j);
                    cnt[j] -- ;
                    break;
                }
        cout << res << endl;
    }
    return 0;
}

你可能感兴趣的:(周赛,c++,AcWing周赛,算法)