Coursera PekingUniversity《C程序设计进阶》个别题目记载(from openjudge)

文字排版


描述:
给一段英文短文,单词之间以空格分隔(每个单词包括其前后紧邻的标点符号)。请将短文重新排版,要求如下:
每行不超过80个字符;每个单词居于同一行上;在同一行的单词之间以一个空格分隔;行首和行尾都没有空格。

输入:
第一行是一个整数n,表示英文短文中单词的数目. 其后是n个以空格分隔的英文单词(单词包括其前后紧邻的标点符号,且每个单词长度都不大于40个字母)。
输出:
排版后的多行文本,每行文本字符数最多80个字符,单词之间以一个空格分隔,每行文本首尾都没有空格。

样例输入(已有):
84
One sweltering day, I was scooping ice cream into cones and told my four children they could “buy” a cone from me for a hug. Almost immediately, the kids lined up to make their purchases. The three youngest each gave me a quick hug, grabbed their cones and raced back outside. But when my teenage son at the end of the line finally got his turn to “buy” his ice cream, he gave me two hugs. “Keep the changes,” he said with a smile.
样例输出:
One sweltering day, I was scooping ice cream into cones and told my four //
children they could “buy” a cone from me for a hug. Almost immediately, the kids //
lined up to make their purchases. The three youngest each gave me a quick hug,//
grabbed their cones and raced back outside. But when my teenage son at the end //
of the line finally got his turn to “buy” his ice cream, he gave me two hugs. //
“Keep the changes,” he said with a smile.

样例输入(手码):
来源: 2015.07 <Banyan: The lose-lose election>头两句话

44
A date has now been set for an election that will mark a defining moment in Myanmar’s slow march away from military dictatorship and towards democracy. On 78 November 8th voters will go to the polls for the first free national ballot since 1990.
样例输出:
A date has now been set for an election that will mark a defining moment in //
Myanmar’s slow march away from military dictatorship and towards democracy. On//
November 8th voters will go to the polls for the first free national ballot// since 1990.

其实,最简单的样例是一个单词的情况。之前想了很久为什么WA,最后测试了一个单词,发现了细节问题。

#include<iostream>
using namespace std;
int main()
{
 int i,j,n,cl[5000]={0},flag=0,sum=0;
 cin>>n;
 char c[5000][41];
 for(j=0;j<n;j++){   //输入n个单词,每个单词占一行字符数组,并计算每个单词的长度
  cin>>c[j];

  for(i=0;c[j][i]!='\0';i++) cl[j]++;

 }
 
 i=0;//重新赋值,否则无法输出单个单词
while(i<n){
 for(i=flag;i<n;i++){
  sum=sum+cl[i]+1; 
  if(sum<=81){
   if(sum+cl[i+1]<=80 && i!=(n-1)) cout<<c[i]<<' ';
   if((sum+cl[i+1]<=80 && i==(n-1)) || (sum+cl[i+1]>80) ||sum==80 ||sum==81) cout<<c[i];
  }
  if(sum>81){
   flag=i;
   sum=0;
   cout<<endl;
   break;
  }
 } 
}
 return 0;
}

我个人的感觉是,用的方法十分基础。先用二维字符数组输入,再定义一维数组存放长度,虽然这样感觉很蠢,但我实在想不到其他输入方法了。。。
关于“句尾不能有空格”“换行条件”“每行结尾不能有空格”,想了很久的分类讨论,所以if里的条件十分冗长。
总之是基础薄弱半路出家,毕竟现在一点编程的人不会也是少见,硬着头皮也要会点基础的。能做出一题就给自己打点气吧。
希望大佬指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值