您的位置:首页 > 编程语言

UVa 1593代码对齐

2015-12-03 13:46 375 查看
大体题意为

给数行代码

要求将代码左对齐,而且尽量的靠左

每个单词之间至少有一个空格

单词长度不超过80,每行不超过180个字符,最多1000行

值得注意的是每一行的最后是没有任何空格的(在这挂了数次)

解题思想利用vector & string来储存每行代码中的单词和每个单词的长度,统计每一列的最长单词,然后按照最长单词为基准输出即可

注意最后一个单词不需要遵循最长单词的基准

代码:

#include<iostream>
#include<sstream>
#include<vector>
#include<string>
using namespace std;

int main(){
vector<string> s[1100];
int maxlen[1000] = {};
string temp;
int numb = 0, line = 0;
while(getline(cin,temp)){//按行将每行读入temp中
stringstream code(temp);//创建一个新的输入流,从中读取单词,类似sscanf
string word;
while(code>>word){
//统计每一列的最长单词长度
maxlen[numb] = maxlen[numb]>word.size()?maxlen[numb]:word.size();
s[line].push_back(word);//将单词放入该列中
numb++;
}
numb = 0;
line++;
}

for(int i = 0; i<line; ++i){
for(int j = 0; j<s[i].size(); ++j){
cout<<s[i][j];//首先将单词输出
//如果不是最后一个单词,则按照最长长度补空格
for(int k = 0; k<maxlen[j]-s[i][j].size() && j!=s[i].size()-1; ++k){
cout<<' ';
}
//如果是最后一个单词,则加回车否则空格
if(j==s[i].size()-1){
cout<<endl;
}
else{
cout<<' ';
}
}
}

return 0;
}


顺贴一个自己的超原始代码,总是WA,因为没写注释现在也不知道怎么回事了(论注释的重要性)

#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<string.h>
#include<stdlib.h>
using namespace std;

int main()
{
freopen("fin.txt", "w", stdout);
queue<string> s[1100];
char out[1100][300];
char temp[200];
int n = 0;
int maxNumb = 0;
while(gets(temp)){
int numb = 0;
char t[100];
int len = strlen(temp);
int p = 0;
for(int j = 0; j<=len; ++j){
if(temp[j] != ' ' && temp[j]!= '\n' && temp[j] !='\0'){

t[p] = temp[j];
p++;
}
else{
if(p!=0){
t[p] = '\0';
p=0;
s
.push(t);
numb++;
}
}
}
maxNumb = maxNumb > numb ? maxNumb : numb;
n++;
}

int imax = 0;
int pos = 0;
for(int j = 0; j<maxNumb; ++j){
imax = 0;
for(int k = 0; k<n; ++k){
if(!s[k].empty()){
string t = s[k].front();
int tlen = t.length();
imax = imax > tlen ? imax : tlen;
}
}

for(int k = 0; k<n; ++k){
if(!s[k].empty()){
bool f = false;
char t[100];
memset(t,0,sizeof(t));
string ts = s[k].front();
strcpy(t,ts.c_str());
s[k].pop();
if(s[k].empty()){ f = true;}
for(int h = 0; h<=imax; ++h){
if(f){
sprintf(out[k]+pos,"%s",t);
}
else{
if(t[h] != 0){
sprintf(out[k]+pos+h,"%c", t[h]);
}
else{
sprintf(out[k]+pos+h," ");
}
}
}
}
}
pos+=imax+1;
}

for(int j = 0; j<n; ++j){
printf("%s\n", out[j]);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  STL 算法入门 容器