题解:AT_genocon2021_c Practice 3

· · 题解

题目跳楼机

正文开始:

阅读理解

给定 m 个字符串,在它们当中加入最少的 - 号使它们长度相同。

思路:

这道题挺简单的,我们只需要在最前面加入 - 号即可。那加多少个呢?定义长度最长的字符串长度为 n,第 i 个字符串长度为 len_i,加入的 - 号数量为 x,那么就可以得到:

将公式代入代码即可。

代码实现:

先从前往后遍历一遍,寻找长度最大值,再给每个字符串套公式、输出自己即可。

#include<bits/stdc++.h>
using namespace std;
int m,ma;
string s[100005];
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>m;
    for(int i=1;i<=m;i++){//遍历寻找最大值 
        cin>>s[i];
        int len=s[i].size();
        ma=max(ma,len);
    }
    for(int i=1;i<=m;i++){
        for(int j=1;j<=ma-s[i].size();j++)cout<<'-';//套用公式 
        cout<<s[i]<<'\n';
    }
    return 0;
}