I.graph
#include <iostream> #include <vector> using namespace std; vector<vector<int>> graph={{-1,0,3,0,0},{2,-1,4,0,0},{0,0,-1,2,7},{0,0,0,-1,3},{0,0,0,0,-1}}; vector<int> toposort(vector<vector<int>> graph){ vector<int> res; auto n=graph.size(),k=n; vector<int> rudu(n,0); vector<int> visited(n,0); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(graph[i][j]>0) rudu[j]++; } } while (k--) { for(int i=0;i<n;i++){ if(rudu[i]==0&&visited[i]==0){ res.push_back(i); visited[i]=1; for(int j=0;j<n;j++){ if(graph[i][j]>0) rudu[j]--; } break; } } } return res; } vector<int> dijkstra(vector<vector<int>> graph,int t){ auto n=graph.size(),k=n; vector<int> dist(n,INT32_MAX); vector<int> visited(n,0); dist[t]=0; visited[t]=1; int cur=INT32_MAX; while(k--){ cur=INT32_MAX; for(int i=0;i<n;i++){ if(visited[i]==0 && dist[i]<cur){ cur=dist[i]; t=i; } } for(int i=0;i<n;i++){ if(visited[i]==0 && graph[t][i]>0){ dist[i]=min(dist[i],graph[t][i]+dist[t]); } } visited[t]=1; } return dist; } int main(){ //1.DFS,BFS 类似树的非递归DFS和BFS,区别是需要一个list来标记哪些节点访问过,用来避免回路。 //2.拓扑排序(有向图),出度入度逐渐剪枝思想,可以用来检查图是否有环(无向图总是减去度为1的),检查是否完全联通或有几个联通子图 vector<int> topolist=toposort(graph); //3.最短路径 Dijkstra 该算法要求图中不存在负权边 vector<int> dist=dijkstra(graph,1); }
II.binary search
重在边界上:
- begin=mid; vs begin=mid+1;
- end=mid; vs end=mid-1;
- if(begin<end) vs if(begin<=end)
- mid=(begin+end)/2 vs mid=(begin+end+1)/2