zoukankan      html  css  js  c++  java
  • 图的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 = 0; v < n; v++){
            if (vis[v] == false && G[u][v] != INF){        //如果v未被访问,且u可到达v
                dfs(v, depth + 1);        //访问v, 深度加一
            }
        }
    }
    
    void dfsTrave(){
        for (int u = 0; u < n; u++){
            if (vis[u] == false){
                dfs(u, 1);                    //访问u和u所在的连通块,1表示初识为第一层
            }
        }
    }

    邻接表版(顶点类型为结构体):

     1 struct Node{
     2     int v;
     3     int w;
     4 };
     5 
     6 //邻接表版
     7 vector<Node> Adj[MAXV];            //图G的邻接表
     8 int n;                    //n为顶点数,MAXV最大顶点数
     9 bool vis[MAXV] = { false };
    10 
    11 void dfs(int u, int depth){
    12     vis[u] = true;
    13 
    14     /*如果需要对u进行一些操作可以在此处进行*/
    15     for (int i = 0; i < Adj[u].size(); i++){
    16         int v = Adj[u][i].v;
    17         if (vis[v] == false){
    18             dfs(v, depth + 1);
    19         }
    20     }
    21 }
    22 
    23 void dfsTrave(){
    24     for (int u = 0; u < n; u++){
    25         if (vis[u] == false){
    26             dfs(u, 1);
    27         }
    28     }
    29 }

    图的遍历题型实战:

                  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

    题目要求大意:找出每个连通分量中总边权最大的点,并统计相应连通分量中点的数量

    代码:

     1 #include <stdio.h>
     2 #include <iostream>
     3 #include <string>
     4 #include <map>
     5 
     6 using namespace std;
     7 
     8 const int maxn = 2010;
     9 const int INF = 1000000000;
    10 
    11 map<string, int> stringToInt;            // 将名字转换成数字
    12 map<int,string> intToString;        // 将编号转换成名字
    13 map<string, int> gang;                // 每个团伙的头目以及人数
    14 
    15 int G[maxn][maxn] = { 0 }, weight[maxn] = { 0 };    // 矩阵以及点权
    16 int n, k, numPerson = 0;            // 边数,下限数,总人数numperson
    17 bool vis[maxn] = { false };            // 标记是否被访问
    18 
    19 // DFS函数访问单个连通块
    20 // nowVisit为当前访问的编号
    21 // head为头目的编号
    22 void DFS(int visNow, int& head, int& numMember, int& totalValue){
    23     vis[visNow] = true;
    24     numMember++;
    25     if (weight[head] < weight[visNow]){
    26         head = visNow;
    27     }
    28 
    29     // 访问当前顶点的所有邻接点
    30     for (int i = 0; i < numPerson; i++){
    31         if (G[visNow][i] > 0){
    32             totalValue += G[visNow][i];
    33             G[visNow][i] = G[i][visNow] = 0;
    34             if (vis[i] == false){
    35                 DFS(i, head, numMember, totalValue);
    36             }
    37 
    38         }
    39     }
    40 
    41 }
    42 
    44 void DFSTrave(){
    45     for (int i = 0; i < numPerson; i++){
    46         if (vis[i] == false){
    47             int head = i, numMember = 0, totalValue = 0;
    48             DFS(i, head, numMember, totalValue);
    49             if (numMember > 2 && totalValue > k){
    50                 gang[intToString[head]] = numMember;
    51             }
    52         }
    53     }
    54 }
    55 
    56 // 根据名字获取名字的编号
    57 int change(string str){
    58     if (stringToInt.find(str) != stringToInt.end()){    // 如果str已经存在
    59         return stringToInt[str];
    60     }
    61     else{
    62         stringToInt[str] = numPerson;    // 编号
    63         intToString[numPerson] = str;
    64         return numPerson++;
    65     }
    66 }
    67 
    68 int main()
    69 {
    70     // 读取输入
    71     // freopen("in.txt", "r", stdin);
    72     int w;
    73     string str1, str2;
    74     cin >> n >> k;
    75     for (int i = 0; i < n; i++){
    76         cin >> str1 >> str2 >> w;
    77         // 读入每个名字都转化成编号
    78         int id1 = change(str1);
    79         int id2 = change(str2);
    80         // 存入对称矩阵
    81         weight[id1] += w;
    82         weight[id2] += w;
    83         G[id1][id2] += w;
    84         G[id2][id1] += w;
    85 
    86     }
    87     // 遍历矩阵,统计数据
    88     DFSTrave();
    89 
    90     // 遍历map,输入结果
    91     cout << gang.size() << endl;
    92     for (map<string, int>::iterator it = gang.begin(); it != gang.end(); it++){
    93         cout << it->first << " " << it->second << endl;
    94     }
    95 
    96     // fclose(stdin);
    97     return 0;
    98 }
  • 相关阅读:
    澳门两日游之续一
    记澳门两日游0516
    [原创]北大ACM POJ 1050题解
    [原创]百度之星低频词过滤题解
    [原创]百度之星题解之重叠区间大小
    澳门两日游之续三
    澳门两日游之续二
    [原创]LZW网页判重的题解
    [原创]北大ACM POJ 1032题解
    创建产品列表控件时触发自定义DataUpated事件时,设置MultiView.ActiveViewIndex无效
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/11481017.html
Copyright © 2011-2022 走看看