Chinaunix首页 | 论坛 | 博客
  • 博客访问: 984579
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: C/C++

2012-12-28 10:17:12

有一个课程表,有课程名和编号,还有一些课程的先导课信息,参数是vector,例如
A:B C D
B:C
C:
D:
表示有4门课,课程名分别为A,B,C,D,然后再上A课程之前必须先上B,C,D,上B之前必须先上C,求出一个上课的顺序。
 
以前没做过这类。是简单的拓扑排序。
根据百度百科,基本解法如下:
 (1)从有向图中选择一个没有前驱(即入度为0)的顶点并且输出它.
 (2)从网中删去该顶点,并且删去从该顶点发出的全部有向边.
 (3)重复上述两步,直到剩余的网中不再存在没有前趋的顶点为止.
 
代码codepad.org已验证

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>


  3. void cover(int matrix[][4], int size){
  4.     int row = 0;
  5.     int column = 0;
  6.     int count = 0;
  7.     char record[size];
  8.     int i = 0;
  9.     for(;i<size;i++){
  10.         record[i] = 0;
  11.     }

  12.     while(count!=size){
  13.                 row = 0;
  14.         for(;row<size && record[row]!=1;row++){
  15.             int sum = 0;
  16.             column = 0;
  17.             for(;column<size;column++){
  18.                 sum|=matrix[row][column];
  19.             }
  20.             if(sum == 0){
  21.                 printf("%d->",row);
  22.                 //remove the node;
  23.                 record[row] = 1;
  24.                 int d;
  25.                 for(d= 0;d<size;d++){
  26.                     matrix[d][row] = 0;
  27.                 }
  28.                                 count++;
  29.             }
  30.         }
  31.     }
  32. }

  33. int main(){
  34.     int matrix[4][4]={{0}};
  35.     matrix[0][1] = 1;
  36.     matrix[0][3] = 1;
  37.     matrix[1][2] = 1;
  38.     matrix[3][2] = 1;
  39.     cover(matrix,4);

  40.     return 0;
  41. }

阅读(1391) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~