Pagini recente » Cod sursa (job #1689314) | infoarena - te ajutam sa devii olimpic! | Cod sursa (job #2467544) | Cod sursa (job #1689465) | Cod sursa (job #2740449)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct graph {
int name;
int numNeighbours;
int* neighbours;
} graph;
int N, M;
int visited[100001];
graph* read(const char* filename)
{
FILE* f = fopen(filename, "r");
if (f == NULL) {
return NULL;
}
fscanf(f, "%d %d", &N, &M);
graph* newGraph = (graph*)malloc(sizeof(graph) * (N + 1));
for (int i = 1; i <= N; i++) {
newGraph[i].name = i;
newGraph[i].numNeighbours = 0;
newGraph[i].neighbours = NULL;
}
int left, right;
for (int i = 0; i < M; i++) {
fscanf(f, "%d %d", &left, &right);
newGraph[left].numNeighbours++;
newGraph[left].neighbours = (int*)realloc(newGraph[left].neighbours, sizeof(int) * newGraph[left].numNeighbours);
newGraph[left].neighbours[newGraph[left].numNeighbours - 1] = right;
}
fclose(f);
return newGraph;
}
void DFS(graph* list, int current)
{
visited[current] = 1;
for (int i = 0; i < list[current].numNeighbours; i++) {
if (visited[list[current].neighbours[i]] == 0)
DFS(list, list[current].neighbours[i]);
}
}
int main()
{
graph* graphV = read("dfs.in");
int count = 0;
for (int i = 1; i <= N; i++) {
if (visited[i] != 1) {
count++;
DFS(graphV, i);
}
}
FILE* f = fopen("dfs.out", "w");
fprintf(f, "%d", count);
fclose(f);
return 0;
}