标签:style blog color io os 使用 for div sp
手写邻接表很麻烦。。。。所以写了一个邻接表模板,方便用
vector实现,使用时看看代码注释即可
#include <iostream> #include <vector> #include <cstdio> #include <malloc.h> #define INF 99999999; #define max_point 1000000 ////定义总共的节点数目 using namespace std; struct node { int u, v, w;//分别代表一条边的起点,终点,权值 }; vector<node> mymap[max_point]; //储存图 //插入一条边 void insertnode(int u, int v, int w, bool isdirection)//参数分别表示起点,终点,权值,还有是否为有向图 { node temp1 = {u, v, w}; node temp2 = {v, u, w}; if( isdirection ) { mymap[u].push_back(temp1); } else { mymap[u].push_back(temp1); mymap[v].push_back(temp2); } } //删除一条边 //返回0表示删除失败 //返回大于0的整数表示删除了多少条边 int deletenode(int u, int v, bool isdirection)//参数分别表示起点,终点,权值,还有是否为有向图 { int flag = 0; if( isdirection ) { for(vector<node>::iterator iter = mymap[u].begin(); iter != mymap[u].end(); ) { if((*iter).v == v) { mymap[u].erase(iter); iter = mymap[u].begin(); flag ++; } else { iter++; } } } else { for(vector<node>::iterator iter = mymap[u].begin(); iter != mymap[u].end(); ) { if((*iter).v == v) { mymap[u].erase(iter); iter = mymap[u].begin(); flag++; } else { iter++; } } for(vector<node>::iterator iter = mymap[v].begin(); iter != mymap[v].end(); ) { if((*iter).v == u) { mymap[v].erase(iter); iter = mymap[v].begin(); flag++; } else { iter++; } } } return flag; } //更新一条边 更新起点为u,终点为v的边权值为w bool updatenode(int u, int v, int w, bool isdirection) { bool flag = false; if( isdirection ) { for(vector<node>::iterator iter = mymap[u].begin(); iter != mymap[u].end(); iter++) { if((*iter).v == v) { (*iter).w = w; flag = true; break; } } } else { for(vector<node>::iterator iter = mymap[u].begin(); iter != mymap[u].end(); iter++) { if((*iter).v == v) { (*iter).w = w; flag++; break; } } for(vector<node>::iterator iter = mymap[v].begin(); iter != mymap[v].end(); iter++) { if((*iter).v == u) { (*iter).w = w; flag++; break; } } } return flag; } //查找在u为起点的边中权值最大或者权值最小的顶点和权值 // choose等于1时表示查找最大值,等于2时表示查找最小值 //接收的结果要free!!!!!!!!!!!!!!!!!! int * serachnode(int u, int choose) { int * res = (int *) malloc(sizeof(int)*2); int max = -INF; int flag; int min = INF; if(choose == 1) { for(vector<node>::iterator iter = mymap[u].begin(); iter != mymap[u].end(); iter++) { if( (*iter).w > max) { max = (*iter).w; flag = (*iter).v; } } res[0] = flag; res[1] = max; } else if(choose == 2) { for(vector<node>::iterator iter = mymap[u].begin(); iter != mymap[u].end(); iter++) { if( (*iter).w < min) { min = (*iter).w; flag = (*iter).v; } } res[0] = flag; res[1] = min; } return res; }
标签:style blog color io os 使用 for div sp
原文地址:http://www.cnblogs.com/ltwy/p/3991357.html