UVa400 算法竞赛入门经典 刘汝佳

#include<stdio.h>
#include<string>
#include<algorithm>
#include<vector>
#include<iostream>
#include <iomanip>

using namespace std;

vector<string>Vstr;

void print(const string& s, int length , char a){
        cout<<s;
        int len = s.length();
        for(int i = 0 ; i<length-len ; i++){
            printf("%c",a);
        }
}

int main(){
    // freopen("in2.txt","r",stdin);
     int n,row,column,BigestLength=0;
     int num = 0;
     string s;
     while(scanf("%d",&n)!=EOF){
          BigestLength=0;
          Vstr.clear();
          for(int i = 0 ; i<n ; i++){
                cin>>s;
                if(s.length()>BigestLength) BigestLength = s.length();
                Vstr.push_back(s);
                //printf("vector的大小为%d\n",Vstr.size());
          }
          sort(Vstr.begin() , Vstr.end());
          column = (60 - BigestLength) / (BigestLength + 2) + 1, row = (n - 1) / column + 1;
          //printf("现在row的值为%d ,column的值为%d ,n的值为%d ,BigestLength的值为%d\n",row,column,n,BigestLength);
          printf("------------------------------------------------------------\n");
         // printf("现在column为%d row为%d n为%d BigestLength为%d\n",column,row,n,BigestLength);
         for(int i = 0 ; i<row ; i++){
             for(int j = 0 ; j<column ; j++){
                  num = row*j+i;    //这里是个很好的想法,如果根据算式算出的下标超出,则不打印
                  if(num<n) {print(Vstr[num] , (j == column-1)? BigestLength : BigestLength+2 , ' ');}
             }
             cout<<"\n";
         }

     }
     return 0;
}


/*
      知识点:  1. 小数点.后“*”表示输出位数,具体的数据来自参数表
                       printf格式字符串中,与宽度控制和精度控制有关的常量都可以换成变量,
                       方法就是使用一个“*”代替那个常量,然后在后面提供变量给“*”。同样,
                       小数点.前也可以添加*,也要用户输入一个位宽值来代替,表示输出的字符所
                       占位宽。

                  2. setfill('0')   <iomanip>   填充                          cout输出高阶
                      setw(10)    字符串所占位数
                      internal  在符号位和数值的中间插入需要数量的填充字符以使串两端对齐
                      left  在串的末尾插入填充字符以使串居左对齐
                      right  在串的前面插入填充字符以使串居右对齐

*/
/*
     !!!!注意: 1. 对于输入输出格式的问题,特别注意在某值取端点的情况

                  2. 对于求输入输出格式的算式,一定要仔仔细细检查至少两遍看是否出错,确认
                      无误之后才照算式计算!(这道题调试了两三个小时都是因为没有注意以上两种情况)

                  3. 题目看错导致花费一天多的时间都在检查问题(o(╥﹏╥)o)
                      切记不是排完行再排列,而是先排列再排行

*/
 

猜你喜欢

转载自blog.csdn.net/m0_37632283/article/details/81139120