图的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 ...
随机推荐
- [SDOI2010]粟粟的书架 [主席树]
[SDOI2010]粟粟的书架 考虑暴力怎么做 显然是提取出来 (x2-x1+1)*(y2-y1+1) 个数字拿出来 然后从大到小排序 然后就可以按次取数了- 然而接下来看数据范围 \(50\%\ r ...
- 使用Python爬虫整理小说网资源-自学
第一次接触python,原本C语言的习惯使得我还不是很适应python的语法风格.希望读者能够给出建议. 相关的入门指导来自以下的网址:https://blog.csdn.net/c406495762 ...
- WPF-命令-基础知识
命令模型的主要元素: 1.命令 2.命令绑定:命令连接到相关的应用程序逻辑 3.命令源:命令源触发命令, 4.命令目标:应用程序逻辑. -------------------------------- ...
- Extreme Learning Machine
Extreme Learning Machine 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 1. ELM 2004年南洋理工大学黄广斌提出了ELM ...
- vue踩坑:vue+ element ui 表单验证有值但验证失败。
一.如图:有值但是验证失败 二. <el-form :model="form" :rules="rules"> <el-form-item l ...
- [POI2015]PUS [线段树优化建图]
problem 线段树优化建图,拓扑,没了. #include <bits/stdc++.h> #define ls(x) ch[x][0] #define rs(x) ch[x][1] ...
- 跨域请求问题:CORS
1.编写过滤器类:需要实现Filter接口,并重写三个方法: (1)先设置字符编码: request.setCharacterEncoding("utf-8"); response ...
- LaTeX绘图
http://math.uchicago.edu/~weinan/programs/tex_diagrams/diagrams.html 给大家分享下这个,用鼠标画diagrams,然后可以一键复制l ...
- MongoDB地理空间(2d)索引创建与查询
LBS(Location Based Services)定位服务,即根据用户位置查询用户附近相关信息,这一功能在很多应用上都有所使用.基于用户位置进行查询时,需要提供用户位置的经纬度.为了提高查询速度 ...
- [POI2010] GRA-The Minima Game - 贪心,dp,博弈论
给出N个正整数,AB两个人轮流取数,A先取.每次可以取任意多个数,直到N个数都被取走.每次获得的得分为取的数中的最小值,A和B的策略都是尽可能使得自己的得分减去对手的得分更大.在这样的情况下,最终A的 ...