http://acm.uva.es/p/v4/482.html
Well this is a general problem i am facing for these kind of inputs and parsing. The above is just an example
for this problem i am reading input using fgets then using strtok to parse the input and then collecting them into an array but somehow my code is going into infinite loop or TLE. Is there an elegant way of solving this problem.
Code: Select all
back:
fgets(str, MAX, stdin);
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
goto back;
}
sv = str;
y = str;
while ((z = strtok(y, " ")) != NULL) {
if((k=strtoul(z,NULL,10))>0)
arr[i++] = k - 1;
y = NULL;
}
My complete code which is TLE
Code: Select all
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 10000
char str[MAX];
int arr[MAX];
char fl[MAX][100];
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void swapl(char a[][100], char b[][100])
{
char tmp[100];
strcpy(tmp, *a);
strcpy(*a, *b);
strcpy(*b, tmp);
}
int main()
{
int i, no, j, k, tmp, len;
char *y, *z, *sv;
final:
fgets(str, MAX, stdin);
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
goto final;
}
no = strtoul(str, NULL, 10);
while (no--) {
memset(str, 0, sizeof(str));
memset(arr, 0, sizeof(arr));
i = 0;
back:
fgets(str, MAX, stdin);
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
goto back;
}
sv = str;
y = str;
while ((z = strtok(y, " ")) != NULL) {
if((k=strtoul(z,NULL,10))>0)
arr[i++] = k - 1;
y = NULL;
}
j = 0;
newback:
fgets(str, MAX, stdin);
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
goto newback;
}
y = str;
while ((z = strtok(y, " ")) != NULL) {
len = strlen(z);
if(len > 0){
if (z[len - 1] == '\n')
z[len - 1] = '\0';
}
strcpy(fl[j++], z);
y = NULL;
}
for (k = 0; k < i; k++) {
if (arr[k] != k) {
while (arr[k] != k) {
tmp = arr[k];
swap(&arr[k], &arr[tmp]);
swapl(&fl[k], &fl[tmp]);
}
}
}
for (k = 0; k < i; k++)
printf("%s\n", fl[k]);
if (no != 0)
printf("\n");
}
return 0;
}