Pagini recente » Cod sursa (job #3129132) | Monitorul de evaluare | Cod sursa (job #20413) | Cod sursa (job #3234872) | Cod sursa (job #3298163)
#include <stdio.h>
#include <stdlib.h>
#define FIN "hashuri.in"
#define FOUT "hashuri.out"
#define MOD 700000
#define INS 1
#define DEL 2
#define SEARCH_OP 3
#define MAX_CHAIN_SIZE 1000
// Node structure for chaining in hash table
typedef struct Node {
long value;
struct Node* next;
} Node;
// Hash table as array of linked lists
Node* Hash[MOD];
// Function to create a new node
Node* createNode(long value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->value = value;
newNode->next = NULL;
return newNode;
}
// Function to find a value in the hash table (equivalent to seek)
Node* seek(long value) {
long key = value % MOD;
Node* current = Hash[key];
while (current != NULL) {
if (current->value == value) {
return current;
}
current = current->next;
}
return NULL;
}
// Insert function
void insert(long value) {
long key = value % MOD;
Node* found = seek(value);
// If value doesn't exist, insert it
if (found == NULL) {
Node* newNode = createNode(value);
newNode->next = Hash[key];
Hash[key] = newNode;
}
}
// Search function
int search(long value) {
Node* found = seek(value);
return (found != NULL) ? 1 : 0;
}
// Remove function
void removeValue(long value) {
long key = value % MOD;
Node* current = Hash[key];
Node* prev = NULL;
while (current != NULL) {
if (current->value == value) {
if (prev == NULL) {
// Remove first node
Hash[key] = current->next;
} else {
// Remove middle/end node
prev->next = current->next;
}
free(current);
return;
}
prev = current;
current = current->next;
}
}
// Research function (same as search)
int research(long value) {
Node* found = seek(value);
return (found != NULL) ? 1 : 0;
}
// Initialize hash table
void initHashTable() {
for (int i = 0; i < MOD; i++) {
Hash[i] = NULL;
}
}
// Free hash table memory
void freeHashTable() {
for (int i = 0; i < MOD; i++) {
Node* current = Hash[i];
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
}
}
int main() {
FILE* fin = fopen(FIN, "r");
FILE* fout = fopen(FOUT, "w");
if (fin == NULL || fout == NULL) {
printf("Error opening files!\n");
return 1;
}
// Initialize hash table
initHashTable();
int N; // number of operations
int op, el;
fscanf(fin, "%d", &N);
for (; N; N--) {
fscanf(fin, "%d %ld", &op, &el);
if (op == INS) {
insert(el);
} else if (op == DEL) {
removeValue(el);
} else if (op == SEARCH_OP) {
int ans = research(el);
if (ans == 1) {
fprintf(fout, "1\n");
} else {
fprintf(fout, "0\n");
}
}
}
// Clean up
fclose(fin);
fclose(fout);
freeHashTable();
return 0;
}