Graph Algorithm Summary

Source: Internet
Author: User
Tags array definition

One: Cause

(1) on the graph of the algorithm is generally more complex, their own in this area is relatively weak, the first is the graph of storage problems and traversal problems:

The storage is divided into two kinds, adjacency matrix and Street table, the traversal is divided into DFS and BFS two kinds, very similar to the binary tree of the first followed traversal and hierarchical traversal.

(2) The figure in the practical application is very extensive, this and all things in one, the theory of everything connected to the same, the two objects have inextricably linked, we become such a link to establish the network for the map (with weight map); The strength of the link is the weight of the edge.

(3) Some of the complex algorithms of the graph are based on the thought of two kinds of ergodic graphs, so let's start with a brief discussion.


Two: code example

(1) The simplest graph traversal problem

Lake Counting

Sample Input

Ten
W ..... WW.
. WWW.....WWW
.... Ww... WW.
......... WW.
......... W..
.. W...... W..
. W.W ..... WW.
W.w.w ..... W.
. w.w. W.
.. W....... W.
Sample Output

3

Requires the number of connected branches in the output graph, the simplest graph traversal problem.

There are two common ways to traverse graphs: depth-first traversal and breadth-first traversal, whose role is to access each point in the diagram, but in a different order.

If each side of the graph is equal (for example, 1), the depth-first traversal process is as deep as possible to access the nodes, as follows:

1. Arbitrarily select a point p0 as the starting point for the traversal

2. When access to a node P1, if P1 below has not been traversed sub-nodes, we then access to one of the P1 is not traversed child nodes, and marked the child node has been visited,

3. If the P1 does not have an unreachable child node, we go back to the parent node of P1 and perform the 2nd step

4. Perform steps 2nd, 3, until all nodes have been accessed.

We also see that the depth of the first traversal is a recursive process, so it is easy to think of the use of the data structure of the stack, the implementation of the time can be recursive, can also use the stack. Look at the personal habits.
The breadth-first traversal implementation is going to use the queue. Here is the code for different implementations of poj2386

#include <iostream> #include <string>using namespace std;const int max_size = 102;string strs[max_size];int n , m;int dir[8][2] = {{ -1,0},{-1,-1},{0,-1},{1,-1},{1,0},{1,1},{0,1},{-1,1}};inline bool Isbound (int x,int y) {return (x& lt;0 | | X>=m | | y<0 | | Y>=n);}    void Dfs (int xindex,int yindex) {Strs[xindex][yindex] = '. ';    int i,x,y;        for (i=0; i<8; ++i) {x = xindex+dir[i][0];        y = yindex+dir[i][1];        if (!isbound (x, y) && strs[x][y]== ' W ') {dfs (x, y);    }}}int Main () {int i,j;    CIN >> m >> N;        Getline (Cin,strs[0]);//¿õðð¹ýâëfor (i=0; i<m; ++i) {getline (cin,strs[i]);    cout << strs[i] << "i=" << i << Endl;    } int ans = 0;                For (i=0, i<m; ++i) {for (j=0; j<n; ++j) {if (strs[i][j]== ' W ') {                cout << Strs[i][j];                Ans + +;            DFS (I,J); }       }} cout << ans << endl;    CIN >> N; return 0;}

(2) Minimum spanning tree

Test instructions: There are villages in the Arctic that need to establish communications between these villages, with s satellite channels, and any two villages with satellite channels can communicate directly through satellites, ignoring distances, villages without satellites communicating by radio, and the distances of these two villages cannot exceed D, The D value depends on the power of the radio transceiver, the greater the power, the greater the D value, but the higher the price, for the purchase cost and maintenance cost considerations, all village radios are the same, that is the same D value, it is required to ensure that any two villages can communicate directly or indirectly, and the minimum D value, output this minimum value. Is the weight of the maximum edge of the output minimum spanning tree, but the satellite channel is an uncertain factor. This problem has a very good solution and proof.
In fact, the title means to convert a minimal spanning tree into a forest with s tree, each tree with a satellite channel, and the longest edge of all sides in the forest is the smallest
In fact, it means you can delete the S-1 in the smallest spanning tree, and ask what's the longest in the remaining edges.
Since the construction of every two points between the edge, is a dense map, it is better to use prim method----Some of the problems are slightly more complex, first of all to determine whether to connect, and then to find the minimum spanning tree

#include <iostream> #include <cmath> #include <algorithm>using namespace std;const int INF = 1000000; const int max_size = 501;double Map[max_size][max_size];d ouble path[max_size];struct node{int x;int y;}    point[max_size];//records the auxiliary array definition struct{int Adjvex from the vertex set U to the least expensive edge of v-u; Double lowcost;} Closedge[max_size];bool CMP (double a,double b)//from large to small partial order {return a>b;} Ask for the distance inline double caldist (struct node &a, struct node &b) {double xx = (a.x-b.x);d ouble yy = (a.y-b.y); return sq RT (xx*xx + yy*yy);}    The graph void Prim (int k,int n) {int i,j) of the minimum production tree t,n vertices of the construction net G from the K-vertex Primm algorithm;            for (j=1;j<=n;j++)//auxiliary array initialization {if (j!=k) {closedge[j].adjvex=k;        CLOSEDGE[J].LOWCOST=MAP[K][J]; }}closedge[k].lowcost=0; Initial, U={u}, here will be 0 as the visited flag int l=0;for (i=1;i<n;i++)//Select the remaining n-1 vertices, this I not without any practical significance, just select n-1 points, record the number of times {double min=inf;for ( j=1;j<=n;j++)//Find the next node of T: K Vertex, smallest, non-ring (i.e. not visited) {if (closedge[j].lowcost!=0&&min>closedge[j].lowcost) {K=j;min=closedge[j].lowCost;}} closedge[k].lowcost=0; The k vertex is incorporated into the U-set Path[l++]=map[k][closedge[k].adjvex]; Save this edge, if the cost of the minimum spanning tree, you have to change to add and, if the minimum spanning tree to maximize the edge weight, you have to compare the maximum value for (j=1;j<=n;j++)//new vertex after merging U re-select the minimum edge {if (map[k][j]< Closedge[j].lowcost) {closedge[j].adjvex=k;closedge[j].lowcost=map[k][j];}}    End of for}//end of For}int main () {int t,m,n;int i,j;    cin>>t; while (t--) {cin>>m>>n;//input for (i=1;i<=n;i++) {Cin>>point[i].x>&gt ;p Oint[i].y;} Init dist for (i=1;i<=n;i++)//Find the distance between each two vertices {for (j=1;j<i;j++) {map[i][j]=map[j][i ]=caldist (Point[i],point[j]);//cout << map[i][j] << Endl;}} for (i=1;i<=n;i++) {map[i][i]=inf;} Primeprim (1,n); sort (path,path+n-1,cmp); The n-1 of the smallest spanning tree is sorted from large to small cout.setf (ios::fixed);//reserved Two decimal places cout.precision (2); cout<<path[m-1]<<endl;// Array d is stored starting with subscript 0, which is the M-side} return 0;


(3)

Graph Algorithm Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.