来补补图论。
前言
本文章适合具有一定图论基础的人食用。
图的存储遍历
B3613 图的存储与出边的排序
首先建图,这道题我使用了链式前向星,然后遍历每个点的每条出边,将它们统计入一个数组中,排序后输出即可。
- 坑点:对于每一组数据,
head数组和统计出边的数组不能将全部空间都初始化,分别初始化至 和 即可,不然会 T;
时间复杂度:( 的时间复杂度为排序带来)。
#include <bits/stdc++.h>
using namespace std;
int n,m,head[500010],cnt,t;
struct Edge{
int next,to = -1;
}edge[500010];
void add(int from,int to){
edge[cnt].to = to;
edge[cnt].next = head[from];
head[from] = cnt ++;
return;
}
int main(){
ios::sync_with_stdio(0);cin.tie(0);
cin >> t;
while(t --){
int tp = 0;
int q[500010];
cin >> n >> m;
for(int i = 1;i <= n + 5;i ++) head[i] = -1;
for(int i = 1;i <= m + 5;i ++) q[i] = 0;
for(int i = 1;i <= m;i ++){
int a,b;
cin >> a >> b;
add(a,b);
}
for(int i = 1;i <= n;i ++){
for(int j = head[i];j != -1;j = edge[j].next)
q[++ tp] = edge[j].to;
sort(q + 1,q + tp + 1);
for(int j = 1;j <= tp;j ++)
cout << q[j] << " ";
cout << '\n';
tp = 0;
}
}
}P3916 图的遍历
60pts 做法
发现对于 的数据,有 ,于是考虑暴力。这时我们可以对于每一个点 dfs 找最远能到达的点,时间复杂度 ,这正是其弱化版 B3862 的做法。
100pts 做法
与其考虑每个点最远能到达哪个点,不如去想编号大的点最远能到达每个点。所以我们建反向边,循环从大到小遍历每个点,dfs 它所能到达的点。因为是从大到小遍历,所以每次搜到的点不会能到达编号更远的点。于是我们给每个点打标记,每搜到一次就不再搜。
时间复杂度 。
//code by xxt0218
#include <bits/stdc++.h>
using namespace std;
int n,m,head[100010],cnt = 1,in[100010],anss[100010],vis[100010];
struct Edge{
int to,next;
}edge[100010];
void add(int from,int to){
edge[cnt].to = to;
edge[cnt].next = head[from];
head[from] = cnt ++;
in[to] ++;
}
void dfs(int start,int now){
if(vis[now]) return;
vis[now] = 1;
for(int i = head[now];i != -1;i = edge[i].next){
int u = edge[i].to;
anss[u] = max(anss[u],start);
dfs(start,u);
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
memset(head,-1,sizeof(head));
cin >> n >> m;
for(int i = 1;i <= m;i ++){
int a,b;
cin >> a >> b;
add(b,a);
}
for(int i = 1;i <= n;i ++) anss[i] = i;
for(int i = n;i > 0;i --) dfs(i,i);
for(int i = 1;i <= n;i ++) cout << anss[i] << ' ';
return 0;
}最短路
P4779 【模板】单源最短路径(标准版)
Dijkstra 是一个神奇的算法,可以以 的时间复杂度内解决无负权边的单元最短路问题。
重载运算符
先引入一个叫重载运算符的东西,其中常用的是 函数调用运算符。
通俗的说,就是一个