Pagini recente » Monitorul de evaluare | Cod sursa (job #804316) | Cod sursa (job #1458525) | Cod sursa (job #907641) | Cod sursa (job #2902745)
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
typedef struct nod {
int id;
int numNeihgbors;
int *neighbors;
}nod;
int numComponents;
int* nodComponents;
void dfs(nod* graph, int n, int source)
{
nodComponents[source] = numComponents;
for (int i = 0; i < graph[source].numNeihgbors; i++)
if (nodComponents[graph[source].neighbors[i] - 1] == 0)
dfs(graph, n, graph[source].neighbors[i] - 1);
}
int main(int argc, char **argv)
{
int n, m;
if (argc < 2)
exit(-1);
FILE* f = fopen(argv[1], "r");
fscanf(f, "%d%d", &n, &m);
nodComponents = (int*)malloc(n * sizeof(int));
for (int k = 0; k < n; k++)
nodComponents[k] = 0;
nod* graph = (nod*)malloc(n * sizeof(nod));
int i;
for (i = 0; i < n; i++)
{
graph[i].id = i + 1;
graph[i].numNeihgbors = 0;
graph[i].neighbors = (int*)malloc((n - 1) * sizeof(int));
}
int x, y;
for (i = 0; i < m; i++)
{
fscanf(f, "%d%d", &x, &y);
graph[x - 1].neighbors[graph[x - 1].numNeihgbors] = y;
graph[x - 1].numNeihgbors++;
graph[y - 1].neighbors[graph[y - 1].numNeihgbors] = x;
graph[y - 1].numNeihgbors++;
}
fclose(f);
for (i = 0; i < n; i++)
if (nodComponents[i] == 0)
{
numComponents++;
dfs(graph, n, i);
}
FILE* g = fopen(argv[2], "w");
fprintf(g, "%d", numComponents);
fclose(g);
return 0;
}