Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 23.11.2011, 19:08   #1
Pblcb
Пользователь
 
Регистрация: 22.10.2010
Сообщений: 14
Вопрос [C]Топологическая сортировка_нужно немного изменить программу

Всем доброго времени суток!
Нужна ваша помощь. Имеется решенная "Задача о рассеянном профессоре".
Условие (вкратце): У рассеяного профессора есть несколько элементов одежды. Для каждого из них есть список элементов одежды, которые должны быть надеты до него. Задача — выстроить елементы одежды в том порядке, в котором их можно надеть.
В файле "input.txt" парами указаны предметы одежды, причем первый предмет предшествует второму. Нужно вывести правильный порядок одежды.

Сейчас мне нужно сделать немного по-другому. В первой строчке исходного "input.txt" находятся все возможные слова, во второй и следующих - слова парами (аналогично предыдущей задаче). Так же надо вывести слова в правильном порядке.

Привожу код решенной задачи (Си):
#include <crtdbg.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct tag_popup
{
struct tag_popup * next;
void * el;
}popup_t;

typedef struct tag_el
{
struct tag_el * next;
int before;
char* word;
popup_t * popup;
}list_el;

typedef struct tag_list
{
list_el * head;
}list_t;

void ERROR(char* str)
{
printf("%s\n", str);
}
int countels(list_t* list)
{
list_el* tmp = list->head->next;
int i = 0;
while (tmp != NULL)
{
i++;
tmp = tmp->next;
}
return i;
}

void freepopup(popup_t * el)
{
popup_t * buf;

while (el != NULL)
{
buf = el;
el = el->next;
free(buf);
buf = NULL;
}

}

void destroy(list_t * list)
{
list_el * tmp = list->head;
list_el * buf;
while (tmp != NULL)
{
if (tmp->popup != NULL)
{
freepopup(tmp->popup);
free(tmp->word);
}
buf = tmp;
tmp = tmp->next;
free(buf);
buf = NULL;
}


}

void printpopup(popup_t * el)
{
popup_t * buf = el;
list_el * el1;
while (buf != NULL)
{
el1 = (list_el*)(buf->el);
printf("%s\n", el1->word);
buf = buf->next;
}
}

void printlist(list_t * list)
{
list_el * buf = list->head;
while(buf != NULL)
{
printf("\n************************* **************************\n");
printf("el == %s", buf->word);
printf(", before it %i\n", buf->before);
printf("after it: ");
printpopup(buf->popup);

buf = buf->next;
}
}

char * read_data(FILE* file, int * size_f)
{
char* data = NULL;
if((file = fopen("file.txt", "r")) == NULL)
{
perror("Open is failed on the input file 'sorts.csv' ");
return 0;
}

if (fseek(file, 0L, SEEK_END) == 0)
{
*size_f = ftell(file);
data = (char*)(calloc(*size_f + 1, 1));
fseek(file, 0L, SEEK_SET);
fread(data, sizeof(char), *size_f, file);
data[*size_f+1] = '\0';
fclose(file);
return data;

}
else
{
fclose(file);
return NULL;
}

}
list_el* check(list_t* list, char* word)
{
list_el * tmp = list->head;

while (tmp != NULL)
{
if (0 == strcmp(tmp->word, word))
{
return tmp;
}
tmp = tmp->next;
}
return NULL;

}

int check_popup(popup_t * list, list_el * for_serch)
{
popup_t * buf = list;
while (buf != NULL)
{
if (buf->el == (list_el*)for_serch)
return 1;
buf = buf->next;
}
return 0;
}

Продолжение далее...
Но заклинаю я самым чистым и святым - ни мира, ни любви у сильных не проси!...
(однако помощи то у знающих просить не запрещается! )
Pblcb вне форума Ответить с цитированием
Старый 23.11.2011, 19:09   #2
Pblcb
Пользователь
 
Регистрация: 22.10.2010
Сообщений: 14
По умолчанию

void add_to_list(char* word1, char* word2, list_t * list)
{
list_el * tmp;
list_el * buf1;
list_el * buf2;
popup_t * for_add;
int if_find = -1;

buf1 = check(list, word1);
buf2 = check(list, word2);

if (buf2 == NULL)
{
buf2 = malloc(sizeof(list_el));
buf2->next = list->head->next;
list->head->next = buf2;
buf2->before = 0;
buf2->popup = NULL;
buf2->word = malloc(sizeof(char)*(strlen(word2) + 1));
strcpy(buf2->word, word2);
// buf2->word[strlen(word2) + 1] = '\0';
if (*(buf2->word) == *word2);
}

if (buf1 == NULL)
{
buf1 = malloc(sizeof(list_el));
buf1->next = list->head->next;
list->head->next = buf1;
buf1->before = 0;
buf1->word = malloc(sizeof(char)*(strlen(word1) + 1));
strcpy(buf1->word, word1);

buf1->popup = malloc(sizeof(popup_t));
buf1->popup->next = NULL;
buf1->popup->el = (void*)buf2;
buf2->before++;
printpopup(buf1->popup);

//printlist(list);
}
else
{
if_find = check_popup(buf1->popup, buf2);
if (if_find == 1)
{
return;
}
else
{
for_add = malloc(sizeof(popup_t));
for_add->next = buf1->popup;
buf1->popup = for_add;
for_add->el = (void*)buf2;
buf2->before++;
}
}

}

int create(list_t * list, char* data, int size_f)
{
int i, k, l;
int j = 0;
char * word1 = NULL;
char * word2 = NULL;
int flag = 0;
i = 0;
list->head = malloc(sizeof(list_el));

list->head->next = NULL;
list->head->before = -1;
list->head->popup = NULL;
list->head->word = malloc(sizeof(char)*5);
list->head->word = "head";

do
{
if ((data[i] == ' ') || (data[i] == '\n') || (data[i] == '\0'))
{

if (data[i] == ' ')
{
if ((data[i-1] == ' ') || (i == 0))
{
ERROR("ERROR: wrong data format");
return -1;
}
word1 = (calloc(i+1, 1));
word1[i] = '\0';
for (k = 0; k < i; k++)
word1[k] = data[k];
for (k = 0; k <= i; k++)
for (j = 0; j <= size_f+1; j++)
data[j] = data[j+1];
flag++;
if (flag != 1)
{
ERROR("ERROR: there are too many elements in one of the lines");
return -1;
}

}
else
{
if ((i == 0) || (data[i-1] == ' '))
{
ERROR("ERROR: wrong data format");
return -1;
}
word2 = (calloc(i+1, 1));
word2[i] = '\0';
for (k = 0; k < i; k++)
word2[k] = data[k];
for (k = 0; k <= i; k++)
for (j = 0; j <= size_f+1; j++)
data[j] = data[j+1];
add_to_list(word1, word2, list);
free(word1);
word1 = NULL;
free(word2);
word2 = NULL;
flag = 0;
}
i = 0;
}
else
{
i++;
}
}while (data[i] != '\0');

word2 = (char*)(calloc(i+1, 1));
word2[i] = '\0';
for (k = 0; k < i; k++)
word2[k] = data[k];
add_to_list(word1, word2, list);


free(word1);
word1 = NULL;
free(word2);
word2 = NULL;
free(data);
return 0;
}

void sort(list_t * list, int size_f)
{
list_el * tmp = list->head;
list_el * tmp1;
int flag = 0;
popup_t * buf;
popup_t * buf1;
list_el * el;
int els, i, j, k;
int sorted = 0;
char* data = malloc(size_f * sizeof(char));
char* str;
els = countels(list);
tmp1 = tmp;
i = 0;
j = 0;
k = 0;


while (flag != els)
{
if (tmp->before == 0)
{

tmp->before = -1;
buf = tmp->popup;

while (buf != NULL)
{
el = (list_el*)buf->el;
el->before--;
buf = buf->next;
}
//printf("!!%s\n", tmp->word);
str = tmp->word;
k = 0;
for (j = i; j < i + strlen(str); j++)
{
data[j] = str[k];
k++;
}
i += strlen(str);
data[i] = ' ';
i++;
sorted++;


}
tmp = tmp->next;
if (tmp == NULL)
{
tmp = tmp1;
flag++;
}
}
data[i] = '\0';
if (sorted != els)
{
ERROR("ERROR: lines are wrong.");
return;
}
printf("%s", data);
free(data);
}

int main()
{
list_t list;
FILE * file = NULL;
int size_f = 0;
char * data = NULL;
int is_done;



//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF);
data = read_data(file, &size_f);

/*printf("size of file: %i\n", size_f);
printf("data:\n");
printf("%s\n", data);
printf("************************\n" );*/
is_done = create(&list, data, size_f);
if (is_done == -1)
return 0;
printlist(&list);

sort(&list, size_f);

/*printf("%i\n", size_f);
printf("%s\n", data);*/
destroy(&list);
return 0;
}

Пример данных:
input.txt
a b c d e f
a b
d c
b d

output.txt
a b e d c f
Но заклинаю я самым чистым и святым - ни мира, ни любви у сильных не проси!...
(однако помощи то у знающих просить не запрещается! )
Pblcb вне форума Ответить с цитированием
Старый 23.11.2011, 19:09   #3
Pblcb
Пользователь
 
Регистрация: 22.10.2010
Сообщений: 14
По умолчанию

Подскажите пожалуйста, ЧТО и КАК надо изменить в программе? Буду благодарна за пример, надеюсь, что понятно написала условие.
Просьба не посылать в гугл
Но заклинаю я самым чистым и святым - ни мира, ни любви у сильных не проси!...
(однако помощи то у знающих просить не запрещается! )
Pblcb вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
доделать немного программу на СИ++ с функциями Наталько Помощь студентам 1 21.05.2011 08:40
нужно немного переписать программу на Delphi dizWOLV Фриланс 6 15.05.2011 13:29
Топологическая сортировка. amsask Помощь студентам 0 05.05.2010 20:05
Немного изменить программу в Delphi Console. (Массивы) QuadroX Помощь студентам 1 14.10.2009 17:42
Помогите переделать программу немного. texcel Общие вопросы C/C++ 1 16.02.2009 19:42