You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
1.7 KiB
76 lines
1.7 KiB
6 years ago
|
#include <stdlib.h>
|
||
|
#include <stdio.h>
|
||
|
|
||
|
#include <glib.h>
|
||
|
|
||
|
/*
|
||
|
* Apparently using a hash table for this is much faster...
|
||
|
*
|
||
|
* $ time ./main
|
||
|
* 69285
|
||
|
* ./main 271,27s user 0,11s system 99% cpu 4:33,04 total
|
||
|
* $ time ./main_hash
|
||
|
* 69285
|
||
|
* ./main_hash 0,13s user 0,02s system 98% cpu 0,156 total
|
||
|
*/
|
||
|
|
||
|
#ifndef USE_HASH
|
||
|
gpointer g_array_lookup(GArray *array, gpointer item, guint size)
|
||
|
{
|
||
|
for (gchar *i = array->data; i < array->data + array->len * size; i += size) {
|
||
|
if (memcmp(i, item, size) == 0) {
|
||
|
return i;
|
||
|
}
|
||
|
}
|
||
|
return NULL;
|
||
|
}
|
||
|
#endif
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
long value = 0;
|
||
|
char *line = NULL;
|
||
|
size_t line_len = 0;
|
||
|
FILE *f = fopen("input", "r");
|
||
|
if (!f) {
|
||
|
perror("input");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
#ifdef USE_HASH
|
||
|
GHashTable *hash = g_hash_table_new(g_direct_hash, g_direct_equal);
|
||
|
g_hash_table_insert(hash, GINT_TO_POINTER(value), GINT_TO_POINTER(TRUE));
|
||
|
#else
|
||
|
GArray *array = g_array_new(FALSE, FALSE, sizeof(long));
|
||
|
g_array_append_val(array, value);
|
||
|
#endif
|
||
|
|
||
|
while (1) {
|
||
|
rewind(f);
|
||
|
while (getline(&line, &line_len, f) != -1) {
|
||
|
long number = strtol(line, NULL, 0);
|
||
|
value += number;
|
||
|
|
||
|
#ifdef USE_HASH
|
||
|
if (g_hash_table_lookup(hash, GINT_TO_POINTER(value))) goto found;
|
||
|
g_hash_table_insert(hash, GINT_TO_POINTER(value), GINT_TO_POINTER(TRUE));
|
||
|
#else
|
||
|
if (g_array_lookup(array, &value, sizeof(long))) goto found;
|
||
|
g_array_append_val(array, value);
|
||
|
#endif
|
||
|
}
|
||
|
}
|
||
|
found:
|
||
|
|
||
|
printf("%ld\n", value);
|
||
|
|
||
|
#ifdef USE_HASH
|
||
|
g_hash_table_destroy(hash);
|
||
|
#else
|
||
|
g_array_free(array, TRUE);
|
||
|
#endif
|
||
|
free(line);
|
||
|
fclose(f);
|
||
|
return 0;
|
||
|
}
|