拓扑排序-图8 How Long Does It Take
2017-05-31 17:23
357 查看
题目
08-图8 How Long Does It Take (25分)
分析
典型的拓扑排序问题。大致的解法如下:
我的代码
08-图8 How Long Does It Take (25分)
分析
典型的拓扑排序问题。大致的解法如下:
我的代码
#include <stdio.h> #define MAXN 100 #define INF 1234567 int graph[MAXN][MAXN]; int inDegree[MAXN] = {0}; int earliest[MAXN]; struct Queue{ int front; int end; int arrays[MAXN]; }que; void queInit(){ que.front = -1; que.end = 0; } int quePop(){ return que.arrays[++que.front]; } void quePush(int x){ que.arrays[que.end++] = x; } int queEmpty(){ return que.end-que.front == 1; } int topSort(int N){ int cnt = 0; queInit(); for (int i=0; i<N; i++) { if(inDegree[i] == 0) { quePush(i); earliest[i] = 0; } } while (!queEmpty()) { int p = quePop(); cnt++; for (int i=0; i<N; i++) { if(graph[p][i]!=0 && graph[p][i]!=INF){ inDegree[i]--; if(earliest[p]+graph[p][i] > earliest[i]){ earliest[i] = earliest[p]+graph[p][i]; } if (inDegree[i] == 0) { quePush(i); } } } } if(cnt < N) return 0; return 1; } int main(int argc, const char * argv[]) { int N, M; scanf("%d%d", &N, &M); //init graph for(int i=0; i<N; i++){ for (int j=0; j<N; j++) { if (i == j) { graph[i][j] = 0; }else{ graph[i][j] = INF; } } } //read data int x,y,weight; for(int i=0; i<M; i++){ scanf("%d%d%d", &x, &y, &weight); graph[x][y] = weight;//有向图 } //init inDegree[] for(int i=0; i<N; i++){ for (int j=0; j<N; j++) { if(graph[i][j]!=0 && graph[i][j]!=INF) inDegree[j]++; } } //init earliest[] for(int i=0; i<N; i++) earliest[i] = -1; int ans = topSort(N); int max = 0; if(ans == 0) printf("Impossible\n"); else{ for(int i=0; i<N; i++) { // printf("%d\n", earliest[i]); if(earliest[i] > max) max = earliest[i]; } printf("%d\n", max); } return 0; }
相关文章推荐
- 08-图8 How Long Does It Take(25 point(s)) 拓扑排序
- 06-4. How Long Does It Take (25)拓扑排序 求关键路径的最长的长度
- PAT 数据结构 06-图7. 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-
- 08-图8 How Long Does It Take
- How long does it take to make a context switch?
- 陈越何欣铭老师数据结构PTA08-图8 How Long Does It Take
- 08-图8 How Long Does It Take
- mooc -- 06-4 How Long Does It Take
- 08-图8 How Long Does It Take
- 7-11 How Long Does It Take(25 分)(toposort)
- 08-图8 How Long Does It Take
- 06-图7. How Long Does It Take (25)
- 08-图8 How Long Does It Take
- 08-图8 How Long Does It Take(25 分)
- 06-图7. How Long Does It Take (25)
- PAT--How Long Does It Take (25)
- 中国大学MOOC-数据结构基础习题集、06-4、How Long Does It Take
- MOOC PTA 08-图8 How Long Does It Take
- 06-图7. How Long Does It Take (25)