题解 CF5B 【Center Alignment】
这题不是很难,大体思路就是while(getline(cin,str))这样读入(若干行要用while,因为有空格要用getline),边读入边更新最大值。
然后挨个处理每个字符串要加多少空格,这是这道题的重头戏:
-
如果可以刚好对齐(即
0 \equiv (maxn-len_i) \pmod 2 的情况)就可以左边的和右边的都要填充\dfrac{max-len_i}{2} 个空格。 -
如果无法刚好对齐(即
1 \equiv (maxn-len_i) \pmod 2 的情况)就需要根据出现这个的次数来决定左边的空格 和右边的空格数量,这就会出现下面两种情况:-
如果出现这种情况的次数不是2的倍数,左边少了一个,那么左边有
\left\lfloor\dfrac{maxn-len_i}{2}\right\rfloor 个,右边则有\left\lfloor\dfrac{maxn-len_i}{2}\right\rfloor+1 个。 -
如果出现这种情况的次数是2的倍数,右边少了一个,那么左边有
\left\lfloor\dfrac{maxn-len_i}{2}+1\right\rfloor 个,右边则有\left\lfloor\dfrac{maxn-len_i}{2}\right\rfloor 个。
-
-
还有一种情况,那就是空行,如果是这样我们直接生成一个和最长长度一样长的空行即可。
题目已经分析完了,上代码!
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string str[10010];
int main()
{
int tot=0,cnt=0,maxn=0,k;
/*tot是多少行要处理的字符串
cnt是出现无法刚好对齐的次数
maxn是长度最大字符串的长度
k临时存储每个字符串的长度。*/
while(getline(cin,str[++tot]))//循环读入
k=str[tot].size(),maxn=max(k,maxn);//更新最长
string ud(maxn+2,'*');tot-=1;//ud是边框
//这里我们会多读入一个东东,所以tot要-1
cout<<ud<<endl;//输出边框
for(int p=1;p<=tot;p++)
if(str[p].size()==0)//特判为空行的情况
{
string s(maxn,' ');
cout<<"*"<<s<<"*"<<endl;
}
else
if((maxn-str[p].size())%2==0) //可以完美对齐
{
string s((maxn-str[p].size())/2,' ');
cout<<"*"<<s<<str[p]<<s<<"*"<<endl;
}
else//不能完美对齐
{
string s((maxn-str[p].size())/2,' ');
cnt++;//出现不能完美对齐的次数+1
if(cnt%2)//如果不是2的倍数靠左
cout<<"*"<<s<<str[p]<<s<<" *"<<endl;
else//否则靠右
cout<<"* "<<s<<str[p]<<s<<"*"<<endl;
}
cout<<ud<<endl;
}