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

    service password-encryption 将会把所有password用思科私有方式加密, 标记是 7,show run 查看密码时,5为md5加密结果即secret, no servic ...

  2. IO流学习之字符流(三)

    IO流之字符流缓冲区: 概念: 流中的缓冲区:是先把程序需要操作的数据保存在内存中,然后我们的程序读写数据的时候,不直接和持久设备之间交互,而改成和内存中的数据进行交互. 缓冲区:它就是临时存储数据, ...

  3. latex技巧:弧AB

    \usepackage{yhmath} $\wideparen{ABCDEFG}$

  4. defender 月考总结

    今天是2019年5月28日,昨天月考了,也是C**生日.昨天考完之后,还是那种考完试的释然感.目前,已经批出来了数学.英语.物理三门学科的成绩,语文还没有批出来.应该明天就能够批出来吧.现在趁着休息, ...

  5. Linux shell 只删除目录下所有(不知道文件名字)文件,只删除文件夹

    #!/bin/sh RM="rm -rf" function delete_all_dir() { for i in `ls` do if [ -d $i ];then $RM $ ...

  6. python基础(1):第一个python程序的编写

    1.第一个python编程 1.1 python的安装 1> https://www.python.org/  进入python官网,选择目标版本进行download 2> 点击setup ...

  7. Python调用百度地图API实现批量经纬度转换为实际省市地点(api调用,json解析,excel读取与写入)

    1.获取秘钥 调用百度地图API实现得申请百度账号或者登陆百度账号,然后申请自己的ak秘钥.链接如下:http://lbsyun.baidu.com/apiconsole/key?applicatio ...

  8. 斜率优化 DP

    CF311B Cats Transport 暑假到现在终于过了这道题

  9. Git 版本回退的几种操作方法

    1, 结合使用 git reset --hard <commit id> , git reset --hard HEAD^,  git reflog , git log 1) 使用 git ...

  10. IDEA please configure web facet first