#include#include #include #include using namespace std;#define MAX 100struct Node{ int value; struct Node* nextNode;};struct LGraph{ struct Node vertexs[MAX]; int ids[MAX]; int vexnum; int edgenum;} lg;void create_lg(){ int u,v; int i; struct Node *pi; for(i = 0; i < lg.edgenum; i++){ scanf("%d%d", &u, &v); u --; v --; pi = (struct Node*)malloc(sizeof(struct Node)); pi->value = v; pi->nextNode = lg.vertexs[u].nextNode; lg.vertexs[u].nextNode = pi; lg.ids[v] ++; }}void sort() { int i; int index = 0; int count[MAX]; memset(count, 0, sizeof(count)); queue Q; for(i = 0; i < lg.vexnum; i++){ if(0 == lg.ids[i]){ Q.push(i); } } while(!Q.empty()){ int node; struct Node * pi; struct Node * tmp; node = Q.front(); count[index++] = node; Q.pop(); pi = lg.vertexs[node].nextNode; while(pi){ int v = pi->value; lg.ids[v] --; if(lg.ids[v] == 0) { Q.push(v); } tmp = pi; pi = pi->nextNode; free(tmp); lg.edgenum --; } } if(index == lg.vexnum){ for(i = 0; i < index; i++){ if(i == 0){ printf("%d", count[i] + 1); } else{ printf(" %d", count[i] + 1); } } printf("\n"); } else{ printf("Network has a cycle!\n"); } }void delete_lg(){ int i; struct Node * pi; for( i = 0; i < lg.vexnum; i++){ pi = lg.vertexs[i].nextNode; while(pi) { pi = pi->nextNode; free(pi); } } }void init_lg(){ lg.vexnum = 0; lg.edgenum = 0; memset(lg.vertexs, 0, sizeof(lg.vertexs)); memset(lg.ids, 0, sizeof(lg.ids)); delete_lg();}int N, M;int main() { int i; while(1) { scanf("%d%d", &N, &M); if( 0 == N && 0 == M) { break; } init_lg(); lg.vexnum = N; lg.edgenum = M; create_lg(); sort(); } init_lg(); return 0;}
假设输入文件中有向图的格式为:首先是顶点个数 n 和边数 m;然后是每条边,每条边的数
据占一行,格式为 u v,表示从顶点 u 到顶点 v 的一条有向边,顶点序号从 1 开始计起。输入文件最后一行为 0 0,表示输入数据结束。 样例输入: 6 8 1 2 1 4 2 6 3 2 3 6 5 1 5 2 5 6 6 8 1 3 1 2 2 5 3 4 4 2 4 6 5 4 5 6 0 0样例输出:
3 5 1 4 2 6
Network has a cycle!