第十天PAT-A1154 Vertex Coloring邻接表做法

A1154

Description:

求所给颜色序列是否为所给图的合适着色,即相邻两点颜色不同。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 1e4+5;
struct edge{
   
    int v;
    int next;
}e[maxn*maxn/2];
int p[maxn], eid
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用邻接创建无向图的示例代码,具体实现思路如下: 1. 定义一个结构体作为邻接中的节点,该节点包含两个成员变量:顶点编号和指向下一个节点的指针。 2. 创建一个大小为n的邻接数组adjList,其中n为顶点个数。 3. 遍历边数组edges,将每条边的两个顶点分别添加到对方的邻接中。 4. 为每个节点的邻接添加一个哨兵节点,以方便遍历。 ```c #include <stdio.h> #include <stdlib.h> // 邻接中的节点 typedef struct Node { int vertex; // 顶点编号 struct Node* next; // 指向下一个节点的指针 } Node; // 创建无向图的邻接 void createGraph(Node** adjList, int n, int m, int* edges[]) { // 初始化邻接 for (int i = 0; i < n; i++) { adjList[i] = (Node*)malloc(sizeof(Node)); adjList[i]->vertex = i; adjList[i]->next = NULL; } // 添加边到邻接中 for (int i = 0; i < m; i++) { int u = edges[i][0]; int v = edges[i][1]; // 添加v到u的邻接中 Node* node = (Node*)malloc(sizeof(Node)); node->vertex = v; node->next = adjList[u]->next; adjList[u]->next = node; // 添加u到v的邻接中 node = (Node*)malloc(sizeof(Node)); node->vertex = u; node->next = adjList[v]->next; adjList[v]->next = node; } // 为每个节点的邻接添加哨兵节点 for (int i = 0; i < n; i++) { Node* sentinel = (Node*)malloc(sizeof(Node)); sentinel->vertex = -1; sentinel->next = adjList[i]->next; adjList[i]->next = sentinel; } } // 输出邻接 void printGraph(Node** adjList, int n) { for (int i = 0; i < n; i++) { printf("Node %d:", i); Node* p = adjList[i]->next; while (p != NULL) { printf(" %d", p->vertex); p = p->next; } printf("\n"); } } int main() { int n = 5; // 顶点个数 int m = 7; // 边数 int* edges[7] = {{0, 1}, {0, 4}, {1, 2}, {1, 3}, {1, 4}, {2, 3}, {3, 4}}; // 边数组 // 创建邻接 Node** adjList = (Node**)malloc(n * sizeof(Node*)); createGraph(adjList, n, m, edges); // 输出邻接 printGraph(adjList, n); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值