AcWing 算法基础课 图论

图可以用邻接表存储,

邻接表为n个链表,

链表可以用数组模拟(比vector速度快)。

const int N;

int h[N],e[N],ne[N],idx;//分别表示,h[i]:图中编号i的头结点,e[i]:节点i的值(编号),ne[i]节点i在链表中的下一个节点的idx。

void add(int a,int b)//增加一个链表结点,而非图中点

{

  e[idx]=b;

  ne[idx]=h[a];

  h[a]=idx++;

 

}

 

(不同链表的节点可以有相同的值,表示点的编号,找当前点的下一个邻接点用ne[idx],找邻接点的邻接点用h[e[idx]])

 

DFS可以返回子树的结点个数

 

返回子树结点个数的dfs代码示例:

846 树的重心

const int N = 100010;

int h[N], e[2 * N], ne[2 * N],idx=0;
bool vis[N];
int res = INT_MAX;
int n;
void Insert(int a, int b)
{
idx++;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx;
}

int DFS(int i)
{
vis[i] = true;
int cur_res = 0;
int node = 0;
for (int ii = h[i]; ii != 0; ii = ne[ii])
{
if (!vis[e[ii]])
{
int sub_num = DFS(e[ii]);
cur_res = max(cur_res, sub_num);
node += sub_num;
}
}
node++;
cur_res = max(cur_res, n - node);
res = min(res, cur_res);
return node;


}
int main()
{

cin >> n;
for (int i = 1; i <= n - 1; i++)
{
int a, b;
cin >> a >> b;
Insert(a, b);
Insert(b, a);
}
DFS(1);


}

 

848 有向图的拓扑序列

可以通过BFS生成有向图的拓扑序列,通过维护节点的入度,每次在队列中放入入度为0的节点

const int N = 100010;

int h[N], e[ N], ne[ N],in_degree[N],idx=0;
bool vis[N];
int n,m;
vector<int> res;
void Insert(int a, int b)
{
idx++;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx;
in_degree[b]++;
}

void BFS()
{
queue<int> que;
for (int i = 1; i <= n; i++)
{
if (in_degree[i] == 0)
{
que.push(i);
res.push_back(i);
}
}
while (que.size())
{
int cur = que.front();
que.pop();
for (int i = h[cur]; i != 0; i = ne[i])
{
in_degree[e[i]]--;
if (in_degree[e[i]] == 0)
{
que.push(e[i]);
res.push_back(e[i]);
in_degree[e[i]]--;
}
}
}

}
int main()
{

cin >> n>>m;
while (m--)
{
int x, y;
cin >> x >> y;
Insert(x, y);
}
BFS();
if (res.size() == n)
{
for (auto node : res)
cout << node << ' ';
}
else
cout << -1;
return 0;

}

posted @   80k  阅读(218)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示