Novo problema de strings! Justificador II é um problema de alinhamento de texto. O problema é simples, mas a implementação exige bastante código :)
Confira abaixo a solução e conte nos comentários se a sua ficou diferente! Abraços!
Plataforma: URI (BEECROWD)
Problema: 1278
Enunciado:
Nós temos alguns textos e queremos formatá-los e justificá-los à direita, ou seja, alinhar suas linhas à margem direita de cada um. Crie um programa que, após ler um texto, reimprima esse texto com apenas um espaço entre as palavras e suas linhas justificadas à direita em todo o texto.
Linguagens: C e C++
Solução:
Código em C:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int n, i, j, k, maior, pos, lock = 0, tamLinhas[100], palavrasPorLinha[100]; char palavras[100][60][60], resposta[100][60], linhaFinal[100][60]; char *linha = (char *) malloc(60 * sizeof(char *)); char *token; while (scanf("%i ", &n) != EOF) { memset(tamLinhas, 0, n); maior = 0; if (!n) break; if (lock) printf("\n"); else lock = 1; for (i = 0; i < n; i++) { fgets(linha, 60, stdin); token = strtok(linha, " \n"); j = 0; while (token != NULL) { if (strlen(token) > 0) { strncpy(palavras[i][j++], token, 60); } token = strtok(NULL, " \n"); } palavrasPorLinha[i] = j; } for (i = 0; i < n; i++) { strcpy(linhaFinal[i], palavras[i][0]); for (j = 1; j < palavrasPorLinha[i]; j++) { strcat(linhaFinal[i], " "); strcat(linhaFinal[i], palavras[i][j]); } tamLinhas[i] = (int) strlen(linhaFinal[i]); strcpy(resposta[i], linhaFinal[i]); } for (i = 0; i < n; i++) if (tamLinhas[i] > maior) maior = tamLinhas[i]; for (i = 0; i < n; i++) printf("%*s\n", maior, resposta[i]); memset(palavras, 0, sizeof(palavras)); memset(resposta, 0, sizeof(resposta)); } return 0; }
#include <iostream> #include <vector> #include <string> using namespace std; int main() { int n, i, j, pos, maior; string linha, token, linhaFinal; bool lock = false; while (cin >> n) { cin.ignore(); vector<string> palavras[n], resposta[n]; int tamLinhas[n] = {0}; if (!n) break; if (lock) cout << endl; else lock = true; for (i = 0; i < n; i++) { getline(cin, linha); pos = 0; while ((pos = linha.find(" ")) != string::npos) { token = linha.substr(0, pos); if (token.size() > 0) palavras[i].push_back(token); linha.erase(0, pos + 1); } if (linha.size() > 0) palavras[i].push_back(linha); } for (i = 0; i < n; i++) { linhaFinal = palavras[i].at(0); for (j = 1; j < palavras[i].size(); j++) linhaFinal += " " + palavras[i].at(j); tamLinhas[i] = linhaFinal.size(); resposta[i].push_back(linhaFinal); } maior = 0; for (i = 0; i < n; i++) if (tamLinhas[i] > maior) maior = tamLinhas[i]; for (i = 0; i < n; i++) { cout.width(maior); cout << right << resposta[i].at(0) << endl; } for (auto& w : palavras) w.clear(); } return 0; }
Nenhum comentário:
Postar um comentário