הערה (קובץ קוד)
קובץ זה הוא קובץ קוד מסוג C.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define DONT_KNOW "I_dont_know"
void printIDontKnow()
{
printf("%s", DONT_KNOW);
exit(0);
}
int examB_q2(char **s, int n);
//Do not change these functions
void free_string_arr(char **arr, int n)
{
for (int i = 0; i < n; ++i)
{
free(arr[i]);
}
free(arr);
}
bool read_string(char **s)
{
int len;
if (scanf("%d", &len) != 1)
{
return false;
}
*s = malloc((len + 1) * sizeof(char));
if (!*s)
{
return false;
}
if (scanf("%s", *s) != 1)
{
free(*s);
return false;
}
return true;
}
int main(void)
{
// uncomment next line if you don't know the answer
// printIDontKnow();
int n;
if (scanf("%d", &n) != 1)
return 1;
char **arr = malloc(sizeof(char *) * n);
if (!arr)
return 1;
for (int i = 0; i < n; i++)
{
if (!read_string(arr + i))
{
free_string_arr(arr, i);
return 1;
}
}
printf("%d", examB_q2(arr, n));
free_string_arr(arr, n);
return 0;
}
bool compareStringsLexi(char *checkable, char *later,
int *letterLen, char *letter)
{
int lengthCheck = strlen(checkable), lengthLater = strlen(later); // O(m)
int val = strcmp(checkable, later);
if (val <= 0) // checkable is before(or equal to) later
{
if (*letter != later[0])
{
(*letter) = later[0];
(*letterLen) = lengthLater;
}
else
{
if ((*letterLen) > lengthLater)
{
(*letterLen) = lengthLater;
}
}
if (lengthCheck <= lengthLater)
{
return true;
}
}
else // checkable is after later
{
if (lengthCheck == lengthLater && (*letterLen) >= lengthLater)
{
return true;
}
if (lengthCheck > lengthLater && (*letterLen) > lengthLater)
{
return true;
}
}
return false;
}
bool compareStringsLength(char *shorter, char *longer)
{
int cmp = strcmp(shorter, longer);
if (cmp <= 0)
{
return true;
}
return false;
}
/*
* This function checks if the length-ordered array can be rearanged to be
* also a lexi ordered array.
*
* input:
* 1. char **arr: the array of strings
* 2. int n: the length of the string array
* output(int):
* 1 if you can order and 0 if you can not
*/
int examB_q2(char **arr, int n)
{
if (n < 1)
{
return 1;
}
int indexOfLargestLexi = 0;
int currentLetterShortest = strlen(arr[0]);
char currentLetter = arr[0][0];
for (int i = 1; i < n; i++)
{
int lengthI = strlen(arr[i]), lengthI1 = strlen(arr[i - 1]);
bool lexi = compareStringsLexi(
arr[indexOfLargestLexi], arr[i],
¤tLetterShortest, ¤tLetter
);
bool len = compareStringsLength(arr[i - 1], arr[i]);
if (lexi)
{
indexOfLargestLexi = i;
if (!len && (lengthI1 > lengthI))
{
return 0;
}
}
else
{
return 0;
}
}
return 1;
}