图的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, );
}
}
}

图的遍历题型实战:

              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 ;
}
上一篇:重新整理数据结构与算法(c#)—— 图的深度遍历和广度遍历[十一]


下一篇:解决ubuntu中zip解压的中文乱码问题