Codeforces Round #624 (Div. 3)(题解)

Codeforces Round #624 (Div.3)

题目地址:https://codeforces.ml/contest/1311


B题:WeirdSort

题意:给出含有n个元素的数组a,和m个元素的数组p,p中元素表示可调换(p=[3,2]表示a中下标为3和下标为3+1的元素可调换,2和2+1可调换),问能否使得原数组成为非降序数组

思路:暴力,模仿冒泡排序

AC代码:

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int maxn = 2e5+10;
int main()
{
    
    int T;
    cin>>T;
    while(T--)
    {
        int node[110];//记录原数组 
        int f[110];//记录可调换下标 
        int n,m;
        cin>>n>>m;
        for(int i=1;i<=n;i++) cin>>node[i];
        for(int i=1;i<=m;i++) cin>>f[i];
        
        for(int i=1;i<=n;i++)
        {
            
            for(int j = 1;j<=m;j++)
            {
                if(node[f[j]]>node[f[j]+1])//如果前边的大于后面的则调换 
                swap(node[f[j]],node[f[j]+1]);
            }
        }
        // 所有可调换位置均以成为非递减 
        if(is_sorted(node+1,node+1+n)) // 判断是否和升序排序后的数组相同 
        puts("YES");
        else 
        puts("NO");
    }
    return 0;
}

C题:Perform the Combo

题意:判断字母出现次数,给定字符串,和m个数记录在数组中,记录字母出现次数时每次从第1位开始,直到数组中所给数又重新开始记录,最后在从第一位到最后一位记录一遍,输出每个字母出现的次数

思路:如果按照题意一一模拟遍历发现会超时,因为所给数组中的数可能相同,多次做相同遍历,浪费时间 可以用前缀和 * 相同数字出现次数

AC代码:

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int maxn = 2e5+10;
int main()
{
    
    int T;
    cin>>T;
    while(T--)
    {
        int n,m;
        string s;
        int ans[30]={0};//每个字母出现次数 
        int sum[30]={0};//前缀和 
        int node[maxn]={0}; 
        cin>>n>>m>>s;
        for(int i=0;i<m;i++)
        {
            int t;
            cin>>t;
            node[t]++;//记录每个数的出现次数 
        }
        
        for(int i=0;i<s.length();i++)
        {
            ans[s[i]-'a']++;
            sum[s[i]-'a']++; 
            if(node[i+1])//node中数是从1开始的而ans的下标是从0开始的 
            {
                for(int j=0;j<26;j++)
                {
                    ans[j]+= sum[j]*node[i+1];
                }
            }
        }
        
        for(int i=0;i<26;i++)
        {
            cout<<ans[i];
            if(i!=25) cout<<" ";
        }
        puts("");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/subject/p/12369072.html