PAT(MOOC-数据结构) 06-4. How long does it take (25)
2015-02-09 10:16
495 查看
#include<cstring> #include<iostream> #include<fstream> using namespace std; //ifstream fin("06-4.txt"); //#define cin fin #define MAX 101 typedef struct edge *ed; struct edge{ int weight; }edge[MAX][MAX]; int n, m; int start, end1; bool vst[MAX];//此题是因为要判定环路 才设定vst数组的 否则是不用的 int path = 0, max_path = -1; bool dfs(int v){ if (path > max_path){ end1 = v; max_path = path; } for (int i = 0; i < n; i++){ if (edge[v][i].weight > 0){ if (vst[i]){ return false; } path += edge[v][i].weight; vst[i] = true; if (!dfs(i)) return false; path -= edge[v][i].weight; vst[i] = false; } } return true; } void dfs_re(int v){ if (path > max_path){ end1 = v; max_path = path; } for (int i = 0; i < n; i++){ if (edge[i][v].weight > 0){ path += edge[i][v].weight; dfs_re(i); path -= edge[i][v].weight; } } } int main(){ cin >> n >> m; memset(edge, -1, sizeof(edge)); int c1, c2, w; for (int i = 0; i < m; i++){ cin >> c1 >> c2 >> w; edge[c1][c2].weight = w; } int i, j; for (j = 0; j < n; j++){ for (i = 0; i < n;i++) if (edge[i][j].weight != -1) break; if (i == n) break; } if (j == n){ printf("Impossible\n"); return 0; } start = j; /* 从这个入度为0的点开始沿正向深度遍历,找到那最远的点 */ vst[start] = true; if (!dfs(start)){ printf("Impossible\n"); return 0; } vst[start] = false; start = end1;/* 再从最远点逆序遍历 找最远点- - 只要求得max_path值即可 */ path = 0; dfs_re(start); printf("%d\n", max_path); return 0; }
相关文章推荐
- 中国大学MOOC-数据结构基础习题集、06-4、How Long Does It Take
- PAT 数据结构 06-图7. How Long Does It Take (25) 拓扑排序 最早开始时间
- PAT--How Long Does It Take (25)
- 06-图7. How Long Does It Take (25)
- mooc -- 06-4 How Long Does It Take
- 06-图7. How Long Does It Take (25)
- 06-图7. How Long Does It Take (25)
- 06-4. How Long Does It Take (25)拓扑排序 求关键路径的最长的长度
- 08-图8 How Long Does It Take(25 分)
- 7-11 How Long Does It Take(25 分)(toposort)
- MOOC PTA 08-图8 How Long Does It Take
- 08-图8 How Long Does It Take(25 point(s)) 拓扑排序
- 08-图8 How Long Does It Take
- 08-图8 How Long Does It Take
- 拓扑排序-图8 How Long Does It Take
- How Long Does It Take
- 08-图8 How Long Does It Take
- 关键路径算法(PAT How Long Does It Take (25))
- Apache Logs: how long does it take to serve a request?(apache配置access.Log记录响应时间)http://www.ducea.com/2008/02/06/apache-logs-how-
- How long does it take to make a context switch?