图的dfs遍历模板(邻接表和邻接矩阵存储)
我们做算法题的目的是解决问题,完成任务,而不是创造算法,解题的过程是利用算法的过程而不是创造算法的过程,我们不能不能陷入这样的认识误区。而想要快速高效的利用算法解决算法题,积累算法模板就很重要,利用模板可以使我们编码更高效,思路更清晰,不容易出bug.下面是利用DFS算法思想遍历图的模板。
邻接矩阵版:
//邻接矩阵版
int n, G[MAXV][MAXV]; //n为顶点数
bool vis[MAXV] = { false }; //入股顶点i已经被访问,则vis[i] = true, 初值为false void dfs(int u, int depth){ //u为当前访问的顶点标号,depth为深度
vis[u] = true; //设置u已经被访问 //如果需要对u进行一些操作,可以在这里进行
//下面对所有从u出发能到达的分治顶点进行枚举
for (int v = ; v < n; v++){
if (vis[v] == false && G[u][v] != INF){ //如果v未被访问,且u可到达v
dfs(v, depth + ); //访问v, 深度加一
}
}
} void dfsTrave(){
for (int u = ; u < n; u++){
if (vis[u] == false){
dfs(u, ); //访问u和u所在的连通块,1表示初识为第一层
}
}
}
邻接表版(顶点类型为结构体):
struct Node{
int v;
int w;
};
//邻接表版
vector<Node> Adj[MAXV]; //图G的邻接表
int n; //n为顶点数,MAXV最大顶点数
bool vis[MAXV] = { false };
void dfs(int u, int depth){
vis[u] = true;
/*如果需要对u进行一些操作可以在此处进行*/
for (int i = ; i < Adj[u].size(); i++){
int v = Adj[u][i].v;
if (vis[v] == false){
dfs(v, depth + );
}
}
}
void dfsTrave(){
for (int u = ; u < n; u++){
if (vis[u] == false){
dfs(u, );
}
}
}
图的遍历题型实战:
One way that the police finds the head of a gang is to check people's phone calls. If there is a phone call between A and B, we say that A and B is related. The weight of a relation is defined to be the total time length of all the phone calls made between the two persons. A "Gang" is a cluster of more than 2 persons who are related to each other with total relation weight being greater than a given threshold K. In each gang, the one with maximum total weight is the head. Now given a list of phone calls, you are supposed to find the gangs and the heads.
Input Specification:
Each input file contains one test case. For each case, the first line contains two positive numbers N and K (both less than or equal to 1000), the number of phone calls and the weight threthold, respectively. Then N lines follow, each in the following format:
Name1 Name2 Time
where Name1 and Name2 are the names of people at the two ends of the call, and Time is the length of the call. A name is a string of three capital letters chosen from A-Z. A time length is a positive integer which is no more than 1000 minutes.
Output Specification:
For each test case, first print in a line the total number of gangs. Then for each gang, print in a line the name of the head and the total number of the members. It is guaranteed that the head is unique for each gang. The output must be sorted according to the alphabetical order of the names of the heads.
Sample Input 1:
8 59
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10
Sample Output 1:
2
AAA 3
GGG 3
Sample Input 2:
8 70
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10
Sample Output 2:
0
题目要求大意:找出每个连通分量中总边权最大的点,并统计相应连通分量中点的数量
代码:
#include <stdio.h>
#include <iostream>
#include <string>
#include <map> using namespace std; const int maxn = ;
const int INF = ; map<string, int> stringToInt; // 将名字转换成数字
map<int,string> intToString; // 将编号转换成名字
map<string, int> gang; // 每个团伙的头目以及人数 int G[maxn][maxn] = { }, weight[maxn] = { }; // 矩阵以及点权
int n, k, numPerson = ; // 边数,下限数,总人数numperson
bool vis[maxn] = { false }; // 标记是否被访问 // DFS函数访问单个连通块
// nowVisit为当前访问的编号
// head为头目的编号
void DFS(int visNow, int& head, int& numMember, int& totalValue){
vis[visNow] = true;
numMember++;
if (weight[head] < weight[visNow]){
head = visNow;
} // 访问当前顶点的所有邻接点
for (int i = ; i < numPerson; i++){
if (G[visNow][i] > ){
totalValue += G[visNow][i];
G[visNow][i] = G[i][visNow] = ;
if (vis[i] == false){
DFS(i, head, numMember, totalValue);
} }
} } void DFSTrave(){
for (int i = ; i < numPerson; i++){
if (vis[i] == false){
int head = i, numMember = , totalValue = ;
DFS(i, head, numMember, totalValue);
if (numMember > && totalValue > k){
gang[intToString[head]] = numMember;
}
}
}
} // 根据名字获取名字的编号
int change(string str){
if (stringToInt.find(str) != stringToInt.end()){ // 如果str已经存在
return stringToInt[str];
}
else{
stringToInt[str] = numPerson; // 编号
intToString[numPerson] = str;
return numPerson++;
}
} int main()
{
// 读取输入
// freopen("in.txt", "r", stdin);
int w;
string str1, str2;
cin >> n >> k;
for (int i = ; i < n; i++){
cin >> str1 >> str2 >> w;
// 读入每个名字都转化成编号
int id1 = change(str1);
int id2 = change(str2);
// 存入对称矩阵
weight[id1] += w;
weight[id2] += w;
G[id1][id2] += w;
G[id2][id1] += w; }
// 遍历矩阵,统计数据
DFSTrave(); // 遍历map,输入结果
cout << gang.size() << endl;
for (map<string, int>::iterator it = gang.begin(); it != gang.end(); it++){
cout << it->first << " " << it->second << endl;
} // fclose(stdin);
return ;
}
图的dfs遍历模板(邻接表和邻接矩阵存储)的更多相关文章
- 图的bfs遍历模板(邻接矩阵存储和邻接表存储)
bfs遍历图模板伪代码: bfs(u){ //遍历u所在的连通块 queue q; //将u入队 inq[u] = true; while (q非空){ //取出q的队首元素u进行访问 for (从u ...
- 《数据结构》C++代码 邻接表与邻接矩阵
上一篇“BFS与DFS”写完,突然意识到这个可能偏离了“数据结构”的主题,所以回来介绍一下图的存储:邻接表和邻接矩阵. 存图有两种方式,邻接矩阵严格说就是一个bool型的二维数组,map[i][j]表 ...
- 邻接表存储图,DFS遍历图的java代码实现
import java.util.*; public class Main{ static int MAX_VERTEXNUM = 100; static int [] visited = new i ...
- 图的基本操作(基于邻接表):图的构造,深搜(DFS),广搜(BFS)
#include <iostream> #include <string> #include <queue> using namespace std; //表结点 ...
- 数据结构与算法之PHP用邻接表、邻接矩阵实现图的广度优先遍历(BFS)
一.基本思想 1)从图中的某个顶点V出发访问并记录: 2)依次访问V的所有邻接顶点: 3)分别从这些邻接点出发,依次访问它们的未被访问过的邻接点,直到图中所有已被访问过的顶点的邻接点都被访问到. 4) ...
- hdu 4707 Pet(DFS && 邻接表)
Pet Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submis ...
- 数据结构——图的深度优先遍历(邻接矩阵表示+java版本)
1.深度优先遍历(DFS) 图的深度优先遍历本质上是一棵树的前序遍历(即先遍历自身,然后遍历其左子树,再遍历右子树),总之图的深度优先遍历是一个递归的过程. 如下图所示,左图是一个图,右图是图的深度 ...
- 【数据结构】【图文】【oj习题】 图的拓扑排序(邻接表)
拓扑排序: 按照有向图给出的次序关系,将图中顶点排成一个线性序列,对于有向图中没有限定次序关系的顶点,则可以人为加上任意的次序关系,由此所得顶点的线性序列称之为拓扑有序序列.显然对于有回路的有向图得不 ...
- c++邻接表存储图(无向),并用广度优先和深度优先遍历(实验)
一开始我是用c写的,后面才发现广搜要用到队列,所以我就直接使用c++的STL队列来写, 因为不想再写多一个队列了.这次实验写了两个多钟,因为要边写边思考,太菜了哈哈. 主要参考<大话数据结构&g ...
随机推荐
- 【整理】IC失效机理(持续更新)
IC 四种常见失效机理如下: EM -- electron migration,电子迁移)TDDB -- time dependent dielectric breakdown,与时间相关电 ...
- P2048 [NOI2010]超级钢琴 [堆+st表]
考虑只能取长度为 [L,R] 的,然后不难想到用堆搞. 搞个前缀和的st表,里面维护的是一个 最大值的位置 struct rmq { int mx[N][20] ; void qwq(int n) { ...
- vue 学习3
在 2.5.0 及以上版本中,如果你使用了单文件组件 $children,$slots,$attrs .... $attrs 可以透传props 注意.模板标签上有:属性="a", ...
- 在mac下初次使用pygame踩坑纪实(卡死)
初次使用pygame实现绘图功能就踩坑 直接上代码 import pygame pygame.init() # 创建游戏的窗口 480 * 700screen = pygame.display.set ...
- 500kuai
https://www.bilibili.com/bangumi/media/md11653495/?spm_id_from=666.10.b_62616e67756d695f64657461696c ...
- Go-结构体,结构体指针和方法
https://cloud.tencent.com/developer/article/1482382 4.1.结构体 结构体:讲一个或多个变量组合到一起形成新的类型,这个类型就是结构体,结构体是值类 ...
- 《深入理解java虚拟机》读书笔记九——第十章
第十章 早期(编译期)优化 1.Javac的源码与调试 编译期的分类: 前端编译期:把*.java文件转换为*.class文件的过程.例如sun的javac.eclipseJDT中的增量编译器. JI ...
- cmd 下sql语句及结果
Microsoft Windows [版本 10.0.14393](c) 2016 Microsoft Corporation.保留所有权利. C:\Users\李长青>mysql -uroot ...
- Ubuntu系统Apache2部署SSL证书
参考链接: https://help.aliyun.com/document_detail/102450.html?spm=a2c4g.11186623.6.582.17b74c07mBaXWS
- <软件工程基础>
我是JX_Z,学习信息安全方向 //(怎么在这头不头尾不尾的地方弄个自我介绍这么尴尬呢) 之前也写过一些随笔记录自己的学习过程 软件工程基础课程中遇到的问题和学习心得都会记录在这篇文章中不断更新. 谢 ...