UVa Problem Solution: 848 - Fmt


At the first look, this problem seems to be tricky to solve. However, if you implement all the specifications precisely, it would be already solved. There's no need to "translate" the problem's specifications.

Code:
  1. /*************************************************************************
  2.  * Copyright (C) 2008 by liukaipeng                                      *
  3.  * liukaipeng at gmail dot com                                           *
  4.  *************************************************************************/
  5. /* @JUDGE_ID 00000 848 C++ "Fmt" */
  6. #include <iostream>
  7. #include <fstream>
  8. #include <string>
  9. #include <vector>
  10. using namespace std;
  11.      
  12. int const linesize = 72;
  13. int const buffsize = 2*1024*1024;
  14. int fmt(char *src, int isize, char *dest)
  15. {
  16.   int osize = 0;
  17.   for (int first = 0, last = first; first < isize; first = last) {
  18.     for (int next = last, nonblank = 0, word = 0; last < isize; last = next) {
  19.       // search for the next word
  20.       for (; next < isize && src[next] != ' ' && src[next] != '/n'; ++next) { 
  21.         ++nonblank;
  22.       }
  23.       ++word;
  24.       // keep line break
  25.       if (next < isize && src[next] == '/n' && 
  26.           (src[next+1] == ' ' || src[next+1] == '/n' ||
  27.            nonblank == 0 || next + 1 == isize)) {
  28.         last = next + 1;
  29.         break;
  30.       }
  31.       // break the line
  32.       if (next - first > linesize) {
  33.         // exhaust all blanks
  34.         for (last = word > 1 ? last : next + 1; src[last] == ' '; ++last) {}
  35.         src[last-1] = '/n';
  36.         break;
  37.       }
  38.       src[next++] = ' '// eliminate newline
  39.     }
  40.     copy(src + first, src + last, dest + osize);
  41.     osize += last - first;
  42.     if (dest[osize-1] == '/n') { // eliminate trailing spaces
  43.       for (; osize > 1 && dest[osize-2] == ' '; --osize) {}
  44.       dest[osize-1] = '/n';
  45.     }
  46.   }
  47.   return osize;
  48. }
  49. int main(int argc, char *argv[])
  50. {
  51. #ifndef ONLINE_JUDGE
  52.   filebuf in, out;
  53.   cin.rdbuf(in.open((string(argv[0]) + ".in").c_str(), ios_base::in));
  54.   cout.rdbuf(out.open((string(argv[0]) + ".out").c_str(), ios_base::out));
  55. #endif
  56.   char src[buffsize];
  57.   char dest[buffsize];
  58.   cin.read(src, buffsize);
  59.   int isize = cin.gcount();
  60.   int osize = fmt(src, isize, dest);
  61.   cout.write(dest, osize);
  62.   return 0;
  63. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值