Skip to content

Instantly share code, notes, and snippets.

@smatsuodev
Last active May 20, 2022 11:48
Show Gist options
  • Save smatsuodev/75231effa470f54971bce060a73e8e74 to your computer and use it in GitHub Desktop.
Save smatsuodev/75231effa470f54971bce060a73e8e74 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define MAX_SIZE 100000
int main() {
char str[MAX_SIZE], last_c, c;
int lines_len = 0;
int line_indice[MAX_SIZE];
for (int i = 0; i < MAX_SIZE; ++i) line_indice[i] = -1;
int i = 0;
while ((c = getchar()) != EOF) {
if (i != 0) last_c = c;
str[i] = c;
if (c == '\n') {
line_indice[lines_len] = i;
++lines_len;
}
++i;
}
if (last_c != '\n') {
line_indice[lines_len] = i - 1;
++lines_len;
}
int size = i, order[MAX_SIZE];
for (i = 0; i < MAX_SIZE; ++i)
if (i < lines_len)
order[i] = i;
else
order[i] = -1;
int sizes[MAX_SIZE];
for (i = 0; i < MAX_SIZE; ++i) {
if (i == 0)
sizes[i] = line_indice[i] + 1;
else if (i < lines_len)
sizes[i] = line_indice[i] - line_indice[i - 1];
}
for (i = 0; i < lines_len; ++i) {
for (int j = lines_len - 1; j > i; --j) {
if (sizes[order[j]] > sizes[order[j - 1]]) {
int tmp = order[j];
order[j] = order[j - 1];
order[j - 1] = tmp;
}
}
}
for (i = 0; i < lines_len; ++i) {
int start = 0, end = line_indice[order[i]];
if (order[i] > 0) start = line_indice[order[i] - 1] + 1;
for (int j = start; j <= end; ++j) {
printf("%c", str[j]);
if (j == end && str[j] != '\n') {
printf("\n");
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment