我们做算法题的目的是解决问题,完成任务,而不是创造算法,解题的过程是利用算法的过程而不是创造算法的过程,我们不能不能陷入这样的认识误区。而想要快速高效的利用算法解决算法题,积累算法模板就很重要,利用模板可以使我们编码更高效,思路更清晰,不容易出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, );
}
}
}

图的遍历题型实战:

              1034 Head of a Gang (30分)

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遍历模板(邻接表和邻接矩阵存储)的更多相关文章

  1. 图的bfs遍历模板(邻接矩阵存储和邻接表存储)

    bfs遍历图模板伪代码: bfs(u){ //遍历u所在的连通块 queue q; //将u入队 inq[u] = true; while (q非空){ //取出q的队首元素u进行访问 for (从u ...

  2. 《数据结构》C++代码 邻接表与邻接矩阵

    上一篇“BFS与DFS”写完,突然意识到这个可能偏离了“数据结构”的主题,所以回来介绍一下图的存储:邻接表和邻接矩阵. 存图有两种方式,邻接矩阵严格说就是一个bool型的二维数组,map[i][j]表 ...

  3. 邻接表存储图,DFS遍历图的java代码实现

    import java.util.*; public class Main{ static int MAX_VERTEXNUM = 100; static int [] visited = new i ...

  4. 图的基本操作(基于邻接表):图的构造,深搜(DFS),广搜(BFS)

    #include <iostream> #include <string> #include <queue> using namespace std; //表结点 ...

  5. 数据结构与算法之PHP用邻接表、邻接矩阵实现图的广度优先遍历(BFS)

    一.基本思想 1)从图中的某个顶点V出发访问并记录: 2)依次访问V的所有邻接顶点: 3)分别从这些邻接点出发,依次访问它们的未被访问过的邻接点,直到图中所有已被访问过的顶点的邻接点都被访问到. 4) ...

  6. hdu 4707 Pet(DFS &amp;&amp; 邻接表)

    Pet Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submis ...

  7. 数据结构——图的深度优先遍历(邻接矩阵表示+java版本)

    ​1.深度优先遍历(DFS) 图的深度优先遍历本质上是一棵树的前序遍历(即先遍历自身,然后遍历其左子树,再遍历右子树),总之图的深度优先遍历是一个递归的过程. 如下图所示,左图是一个图,右图是图的深度 ...

  8. 【数据结构】【图文】【oj习题】 图的拓扑排序(邻接表)

    拓扑排序: 按照有向图给出的次序关系,将图中顶点排成一个线性序列,对于有向图中没有限定次序关系的顶点,则可以人为加上任意的次序关系,由此所得顶点的线性序列称之为拓扑有序序列.显然对于有回路的有向图得不 ...

  9. c++邻接表存储图(无向),并用广度优先和深度优先遍历(实验)

    一开始我是用c写的,后面才发现广搜要用到队列,所以我就直接使用c++的STL队列来写, 因为不想再写多一个队列了.这次实验写了两个多钟,因为要边写边思考,太菜了哈哈. 主要参考<大话数据结构&g ...

随机推荐

  1. 【1】Logistic回归

    Logistic回归  在Logistic回归中,损失函数L定义为 成本函数 J  损失函数是单个训练样本的误差,而成本函数是所有训练样本误差的平均值. 之所以选择这个损失函数,是因为该损失函数L与w ...

  2. Winpcap学习笔记

    ————————————————版权声明:本文为CSDN博主「Ezioooooo」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明.原文链接:https://blo ...

  3. 判断合同金额是否可以转整形和sql语句中添加条件语句

    主要用到sqlserver语句中的判断语法 if (min_hetonge.Length > 0 && int.TryParse(min_hetonge, out min)) s ...

  4. 剑指offer 14. 链表中倒数第 k 个结点

    14. 链表中倒数第 k 个结点 题目描述 输入一个链表,输出该链表中倒数第k个结点 法一:快慢指针 快指针先走 k 步,等快指针到达尾部时,慢指针所指结点即是倒数第 k 个结点 public cla ...

  5. layui的跳转链接实现分页low

    layui.use(['laypage', 'layer'], function(){ var laypage = layui.laypage ,layer = layui.layer; laypag ...

  6. Python获取时间范围

    import datetime def dateRange(beginDate, endDate): dates = [] dt = datetime.datetime.strptime(beginD ...

  7. [Code+#4] 最短路 - 建图优化,最短路

    最短路问题,然而对于任意\(i,j\),从\(i\)到\(j\)可以只花费\((i xor j) \cdot C\) 对每个点\(i\),只考虑到\(j\)满足\(j=i xor 2^k, j \le ...

  8. arm9特点

    ARM9主要特点 ARM 处理器凭借它的低功耗.高性能等特点,被广泛应用于个人通信等嵌入式领域,而ARM7 也曾在中低端手持设备中占据了一席之地.然而,ARM7 的处理性能逐渐无法满足人们日益增长的高 ...

  9. 题解 AT4170 【[ABC103A] Task Scheduling Problem】

    翻译 有 \(3\) 个正整数 \(a\).\(b\).\(c\),请你输出这 \(3\) 个数中的最大值 \(-\) 最小值的差. 分析 求最大值 \(-\) 最小值的差,我们自然可以使用 for ...

  10. C++常用字符串操作和UTF-8和GBK之间的转换以及判定(转)

    编码转换原文地址:https://www.cnblogs.com/Toney-01-22/p/9935297.html C++字符串常用操作:C++ 中字符串查找.字符串截取.字符串替换