我们给出了不同的数字对。现在我们必须创建一个链,如果pair1的任何元素等于pair2的任何元素,那么它们属于同一个集合。
实施例: -
给出对:
(0,1)
(2,3)
(5,4)
(3,5)
(7,6)
(8,7)
所以这一切都是
{0,1}, {2,3,4,5}, {6,7,8}
我们如何实现这一目标。我对此并不在意。任何帮助将不胜感激。
解决方案 C代码 #include
#define SIZE 100100
int visited[SIZE];
struct adjListNode{
int dest;
struct adjListNode* next;
};
struct adjList{
struct adjListNode* head;
};
struct Graph{
int V;
struct adjList* array;
};
struct adjListNode* newAdjListNode(int dest){
struct adjListNode* newNode = (struct adjListNode*)malloc(sizeof(struct adjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int V){
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->array = (struct adjList*)malloc(V * sizeof(struct adjList));
int i;
for(i = 0; i < V; i++){
graph->array[i].head = NULL;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest){
struct adjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
void printGraph(struct Graph* graph)
{
int v;
for (v = 0; v < graph->V; ++v)
{
struct adjListNode* pCrawl = graph->array[v].head;
printf("\n Adjacency list of vertex %d\n head ", v);
while (pCrawl)
{
printf("-> %d", pCrawl->dest);
pCrawl = pCrawl->next;
}
printf("\n");
}
}
void DFS(struct Graph* graph, int v){
if(visited[v] == 0){
visited[v] = 1;
printf("%d --> ", v);
struct adjListNode *pCrawl = graph->array[v].head;
while(pCrawl){
if(visited[pCrawl->dest] == 0){
DFS(graph, pCrawl->dest);
}
pCrawl = pCrawl->next;
}
}
}
int main(void) {
int V = 5, I, src, dest, i, count = 0;
scanf("%d %d", &V, &I);
memset(visited, 0, SIZE);
struct Graph* graph = createGraph(V);
while(I--){
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
}
for(i = 0; i < V; i++){
if(visited[i] == 0){
count++;
DFS(graph, i);
printf("\n");
}
}
// print the adjacency list representation of the above graph
printGraph(graph);
printf("Countries :- %d", count);
return 0;
}
输入
10 8
0 1
2 3
1 4
5 6
7 8
9 7
1 7
3 5
输出
SET :: 0 --> 1 --> 7 --> 9 --> 8 --> 4 -->
SET :: 2 --> 3 --> 5 --> 6 -->
Adjacency list of vertex 0
head -> 1
Adjacency list of vertex 1
head -> 7-> 4-> 0
Adjacency list of vertex 2
head -> 3
Adjacency list of vertex 3
head -> 5-> 2
Adjacency list of vertex 4
head -> 1
Adjacency list of vertex 5
head -> 3-> 6
Adjacency list of vertex 6
head -> 5
Adjacency list of vertex 7
head -> 1-> 9-> 8
Adjacency list of vertex 8
head -> 7
Adjacency list of vertex 9
head -> 7
Sets :- 2
答案 0 :(得分:0)
您可以将数字表示为图形顶点。这对是边缘。现在您需要做的就是运行bfs来计算连接的部分。
答案 1 :(得分:0)
Union-find algorithm对解决这个问题非常有效(你的例子不构建链,只有集合)