• Day23:算法之分支定界


    一、分支定界思想

    分支定界思想:一般用来解决寻路问题(最短路径)   广度寻路  A星寻路
        ①常用广度优先或者以最小耗费(最大收益)优先的方式搜索问题的解空间树。
            
        ②在分支定界算法思想中,

            每一个活节点(坐标节点)只有一次机会成为拓展节点
                  一旦成为拓展节点,就一次性生成其所有孩子节点。
                在这些孩子节点中,导致不可行解或者非最优解的孩子节点被舍弃(剪枝)
                其余孩子节点被加入活节点表中(存放,记录,保存)
             此后,从活节点表中获取下一节点成为当前拓展节点,并重复上述节点拓展过程。
        这个过程一直到找到需要的解(找到终点)或者活节点表(buff)为空。

        ③分支定界法常用的两个数据结构:
                1. 队列式分支定界法
                    按照队列原则选取下一个节点成为拓展节点。(广度寻路)
                2. 优先队列式分支定界法
                    按照优先队列中规定的优先级选取优先级最高的节点成为当前拓展节点(A星寻路)

    二、案例一:爬虫

    算法流程:

            给一个网址 
                解析网址:
                连上网页的服务器
                发送请求到网页服务器,获取网页源码
                源码中就有很多的图片链接和网址链接
                把网址链接存到队列中
                循环从队列中一个个取出 取出后

    1. /*
    2. 爬虫原理:
    3. 要求用户输入一个网址
    4. 获取到这个网址代表的网页的源代码
    5. 分析源代码:
    6. 得到 网址
    7. 得到 网络图片地址
    8. 网络图片地址 --> 下载图片到本地
    9. 循环连新的网址
    10. 去重
    11. http协议:客户端连接网页服务器
    12. 客户端发送信息给网页服务器,服务器收到后 反馈 传输完数据
    13. 断开连接
    14. 基于tcp协议
    15. Get Post
    16. 服务器的ip地址和服务器的端口号
    17. www.baidu.com
    18. http://www.netbian.com/s/meinvmm/
    19. http:// //前缀 说明了 协议类型
    20. www.netbian.com //域名
    21. /s/meinvmm/ //路径
    22. */
    23. #include //正则表达式头文件
    24. #include //文件操作头文件
    25. #include
    26. #include
    27. #include //队列容器
    28. #include //解决网址重复问题
    29. #include
    30. #pragma comment(lib, "ws2_32.lib")//加载动态库 把源代码弄过来
    31. #include
    32. using namespace std;
    33. //网址 数据
    34. mapint> g_map;//解决网址重复问题
    35. //存放主机名
    36. char g_zhuji[256] = { 0 };
    37. //存放主机后的路径
    38. char g_path[256] = { 0 };
    39. //服务器socket
    40. SOCKET g_socket;
    41. //存放图片地址的容器
    42. vector photoAddr;
    43. //存放网页地址的容器
    44. vector htmlAddr;
    45. //爬jpg图片
    46. void snapJpg(const char* addr);
    47. //解析网址
    48. void jiexiAddr(char* buff);
    49. //连接服务器
    50. void connectAddr();
    51. //得到源代码
    52. void getHtml();
    53. //下载图片
    54. void saveImage(string str);
    55. //从网页源代码中获取图片链接
    56. void getImage(string& allHtml);
    57. //从网页源代码中获取网址链接
    58. void getAddr(string& allHtml);
    59. int main(){
    60. string begAddr;
    61. cout << "请输入起始网址:";
    62. cin >> begAddr;
    63. //创建一个文件夹
    64. CreateDirectory(".\\images", NULL);
    65. snapJpg(begAddr.c_str());
    66. while (1);
    67. return 0;
    68. }
    69. //爬jpg图片
    70. void snapJpg(const char* addr){
    71. queue q;//存网址
    72. q.push(addr);//把起始网址放进去
    73. while (!q.empty()){
    74. //从q中拿出一个
    75. string currentAddr = q.front();
    76. //删掉
    77. q.pop();
    78. //解决网址重复问题
    79. g_map[currentAddr]++;
    80. //解析网址 拿到域名
    81. char buff[256] = { 0 };
    82. strcpy(buff, currentAddr.c_str());
    83. //解析网址
    84. jiexiAddr(buff);
    85. //连接服务器
    86. connectAddr();
    87. //得到源代码
    88. getHtml();
    89. //从源代码中解析出网址和图片地址 存入对应容器中
    90. //把网址存放到队列q中
    91. vector::iterator it;
    92. for (it = htmlAddr.begin(); it != htmlAddr.end(); it++){
    93. if (0 == g_map[*it]){//没有连接过
    94. q.push(*it);//放到队列中
    95. }
    96. }
    97. htmlAddr.clear();//清空容器
    98. //下载图片
    99. for (it = photoAddr.begin(); it != photoAddr.end(); it++){
    100. saveImage(*it);
    101. }
    102. photoAddr.clear();//清空容器
    103. }
    104. }
    105. //解析网址
    106. void jiexiAddr(char* buff){
    107. char temp[256] = { 0 };
    108. strcpy(temp, buff);
    109. //略过前面七个 http://
    110. char* p = strstr(buff,"http://");//buff中找子串 "http://" 找到返回子串首地址
    111. if (NULL == p) return;
    112. else
    113. p += 7;//往后挪七个
    114. sscanf(p, "%[^/]%s", g_zhuji, g_path);
    115. printf("主机:%s\n", g_zhuji);
    116. printf("路径:%s\n", g_path);
    117. }
    118. //连接服务器
    119. void connectAddr(){
    120. //1 获取协议版本号
    121. WSADATA wsaData;
    122. WSAStartup(MAKEWORD(2, 2), &wsaData);
    123. if (LOBYTE(wsaData.wVersion) != 2 ||
    124. HIBYTE(wsaData.wVersion) != 2){
    125. printf("请求版本号失败!\n");
    126. return;
    127. }
    128. printf("请求版本号成功!\n");
    129. //2 创建socket
    130. g_socket = socket(AF_INET, SOCK_STREAM, 0);
    131. if (SOCKET_ERROR == g_socket){
    132. printf("创建socket失败!\n");
    133. return;
    134. }
    135. printf("创建socket成功!\n");
    136. //3 创建协议地址族
    137. SOCKADDR_IN addr = { 0 };
    138. addr.sin_family = AF_INET; //必须和socket函数第一个参数一致
    139. //4 绑定
    140. int r = bind(g_socket, (sockaddr*)&addr, sizeof addr);
    141. if (-1 == r){
    142. printf("绑定失败!\n");
    143. return;
    144. }
    145. printf("绑定成功!\n");
    146. //5 拿到主机ip地址
    147. struct hostent* p = gethostbyname(g_zhuji);//192.168.0.44 ipv4
    148. if (NULL == p){
    149. printf("获取主机地址失败!\n");
    150. return;
    151. }
    152. printf("获取主机地址成功!\n");
    153. memcpy(&addr.sin_addr, p->h_addr, 4); //把主机地址放入协议地址族中
    154. addr.sin_port = htons(80); //设置主机端口号 浏览器端口号一般为80
    155. //6 连接服务器
    156. r = connect(g_socket, (sockaddr*)&addr, sizeof addr);
    157. if (-1 == r){
    158. printf("连接服务器失败!\n");
    159. return;
    160. }
    161. printf("连接服务器成功!\n");
    162. //7 通信:发送获取源代码请求
    163. //请求信息
    164. string reqInfo = "GET " + (string)g_path + " HTTP/1.1\r\nHost:" +
    165. (string)g_zhuji + "\r\nConnection:Close\r\n\r\n";
    166. //发送请求信息到服务器
    167. r = send(g_socket, reqInfo.c_str(), reqInfo.size(), NULL);
    168. if (r > 0){
    169. printf("发送请求信息成功!\n");
    170. }
    171. else{
    172. printf("发送请求信息失败,失败原因:%d\n", WSAGetLastError());
    173. }
    174. }
    175. //得到源代码
    176. void getHtml(){
    177. string allHtml;
    178. char buff[1024];
    179. int r;
    180. while (1){
    181. r = recv(g_socket, buff, 1023, NULL);
    182. if (r > 0){
    183. buff[r] = 0;
    184. allHtml += buff;
    185. }
    186. else{
    187. break;
    188. }
    189. }
    190. //cout << allHtml << endl;
    191. //从网页源代码中获取图片链接
    192. getImage(allHtml);
    193. //从网页源代码中获取网址链接
    194. getAddr(allHtml);
    195. }
    196. //下载图片
    197. void saveImage(string str){
    198. //1 解析图片地址
    199. char buff[256];
    200. memset(buff, 0, 256);
    201. strcpy(buff, str.c_str());
    202. jiexiAddr(buff);
    203. //2 连接服务器
    204. //3 发送下载图片请求
    205. connectAddr();
    206. //4 本地创建图片文件
    207. //4.1 得到图片文件名
    208. string photoName;
    209. photoName.resize(str.size());
    210. char ch;
    211. int j = 0;
    212. for (int i = 0; i < str.length(); i++){
    213. ch = str[i];
    214. // '\0' '\n' '\t' '\r' '\\' '\"'
    215. if (ch != '\\' && ch != '/' && ch != ':' && ch != '*' && ch != '?' &&
    216. ch != '"' && ch != '<' && ch != '>' && ch != '|'){
    217. photoName[j++] = ch;
    218. }
    219. }
    220. photoName = "./images/" + photoName.substr(0, j);
    221. //4.2 创建图片文件
    222. fstream file;
    223. file.open(photoName, ios::out | ios::binary);//二进制写
    224. //5 接收发送过来的图片信息并写入图片文件中
    225. int r;
    226. char tempBuff[1024] = { 0 };
    227. //排除掉文件头的"\r\n\r\n"
    228. r = recv(g_socket, tempBuff, 1023, NULL);
    229. char* p = strstr(tempBuff, "\r\n\r\n");
    230. file.write(p + strlen("\r\n\r\n"), r - (p - tempBuff) - strlen("\r\n\r\n"));
    231. while (1){
    232. r = recv(g_socket, tempBuff, 1023, NULL);
    233. if (r > 0){
    234. file.write(tempBuff, r);
    235. }
    236. else{
    237. break;
    238. }
    239. }
    240. //6 保存关闭
    241. file.close();
    242. }
    243. //从网页源代码中获取图片链接
    244. void getImage(string& allHtml){
    245. smatch mat;//用作匹配的对象
    246. regex pattren("src=\"(.*?\\.jpg)\"");
    247. string::const_iterator start = allHtml.begin();//起始位置
    248. string::const_iterator end = allHtml.end();//结束位置
    249. while (regex_search(start, end, mat, pattren)){
    250. string msg(mat[1].first, mat[1].second);
    251. photoAddr.push_back(msg);
    252. cout << "找到图片:" << msg << endl;
    253. start = mat[0].second;//改变起始位置
    254. }
    255. }
    256. //从网页源代码中获取网址链接
    257. void getAddr(string& allHtml){
    258. smatch mat;//用作匹配的对象
    259. regex pattren("href=\"(http://[^\\s,\"]+)\"");
    260. string::const_iterator start = allHtml.begin();//起始位置
    261. string::const_iterator end = allHtml.end();//结束位置
    262. while (regex_search(start, end, mat, pattren)){
    263. string msg(mat[1].first, mat[1].second);
    264. htmlAddr.push_back(msg);
    265. cout << "找到网址:" << msg << endl;
    266. start = mat[0].second;//改变起始位置
    267. }
    268. }

     三、案例二:图的A*寻路算法

    1. #include
    2. #include
    3. #include //numeric_limits
    4. #include
    5. using namespace std;
    6. //节点类
    7. class Node {
    8. public://属性 一般应该是 private 或者 protected
    9. int index; //序号
    10. int weight; //权重
    11. public://功能
    12. //构造
    13. Node(int index = 0, int weight = 0) :index(index), weight(weight) {}
    14. //拷贝构造
    15. Node(const Node& object) :index(object.index), weight(object.weight) {}
    16. //重载小于运算符 为了比较 剪枝
    17. friend bool operator<(const Node& one, const Node& two) {
    18. return (one.weight > two.weight);
    19. }
    20. };
    21. //路径类 节点类是边 路径类其实是很多节点相加
    22. class Path {
    23. public://属性 一般应该是 private 或者 protected
    24. int index; //序号
    25. int weight; //权重
    26. public://功能
    27. Path() :index(0), weight(numeric_limits<int>::max()) {}
    28. };
    29. class shortTestPath {
    30. public://属性
    31. vectorint>> graph; //图
    32. int nodeCount; //节点统计
    33. const int edge; //起始
    34. const int end; //结束
    35. vector<int> pathIndex; //存储最短路径的容器
    36. int shortPath; //最短路径值
    37. public://功能
    38. //构造函数
    39. shortTestPath(const vectorint>>& object, int end) :edge(-1), end(end),
    40. nodeCount(object.size()), graph(object) {}
    41. //打印
    42. void printPath() {
    43. cout << "最短路径值:" << shortPath << endl;
    44. cout << "路径:";
    45. //反向打印
    46. copy(pathIndex.rbegin(), pathIndex.rend(),
    47. ostream_iterator<int>(cout, " "));
    48. cout << endl;
    49. }
    50. void getShortTestPath() {
    51. vector myPath(nodeCount);//初始化路径容器大小
    52. priority_queue> minHeap;//准备一个优先队列(小顶堆)
    53. minHeap.push(Node(0, 0));//入口入堆
    54. while (1) {
    55. Node top = minHeap.top();
    56. minHeap.pop();
    57. //如果是终点,结束循环
    58. if (top.index == end) break;
    59. for (int i = 0; i < nodeCount; i++) {//剪枝过程
    60. if (graph[top.index][i] != edge &&
    61. top.weight + graph[top.index][i] < myPath[i].weight) {
    62. minHeap.push(Node(i, top.weight + graph[top.index][i]));
    63. myPath[i].index = top.index;
    64. myPath[i].weight = top.weight + graph[top.index][i];
    65. }
    66. }
    67. //最终堆空了,还没找到终点
    68. if (minHeap.empty()) break;
    69. }//end of while (1)
    70. //求路径和
    71. shortPath = myPath[end].weight;
    72. //求路径
    73. int index = end;
    74. pathIndex.push_back(index);
    75. while (1) {
    76. index = myPath[index].index;
    77. pathIndex.push_back(index);
    78. if (0 == index) break;
    79. }
    80. }
    81. };
    82. int main() {
    83. //准备图结构
    84. const int size = 11;//顶点个数
    85. vectorint>> graph(size);
    86. for (int i = 0; i < size; i++) {
    87. graph[i].resize(size);//重置大小 开空间
    88. }
    89. //赋值
    90. for (int i = 0; i < size; i++) {
    91. for (int j = 0; j < size; j++) {
    92. graph[i][j] = -1;
    93. }
    94. }
    95. graph[0][1] = 2;
    96. graph[0][2] = 3;
    97. graph[0][3] = 4;
    98. graph[1][2] = 3;
    99. graph[1][4] = 7;
    100. graph[1][5] = 2;
    101. graph[2][6] = 2;
    102. graph[2][5] = 9;
    103. graph[3][6] = 2;
    104. graph[4][7] = 3;
    105. graph[4][8] = 3;
    106. graph[5][6] = 1;
    107. graph[5][8] = 3;
    108. graph[6][9] = 1;
    109. graph[6][8] = 5;
    110. graph[7][10] = 3;
    111. graph[8][10] = 2;
    112. graph[9][8] = 2;
    113. graph[9][10] = 2;
    114. //创建shortTestPath对象
    115. shortTestPath sPath(graph, 10);
    116. sPath.getShortTestPath();
    117. sPath.printPath();
    118. while (1);
    119. return 0;
    120. }

  • 相关阅读:
    Mysql系列(一) - Mysql的架构体系
    【机试题】两个链表相减,并以相同形式返回一个表示相减结果的链表
    基于黑马程序员瑞吉外卖开发的瑞吉外卖cloud项目
    我开始使用了Typescript
    64 ---- 两直线的位置关系
    第七章 字符串
    2022-纯css3飞翔的小鸟
    QT day3
    博客园商业化之路-开发任务众包平台:召集早期合作开发者
    Linux 信号
  • 原文地址:https://blog.csdn.net/zjjaibc/article/details/126682603