Defined
There's a whole lot of things.
Things a need to do something B (or more) to get it done.
And then sort!
(with direction-free diagram)
Ideas
An online figure for easy comprehension (The following process takes this diagram as an example)
- Record the penetration and the degree of all points
- Find a point with a degree of 0 added to the stack as a
- The top element output of the stack is deleted and the input of the point connected to the top of the stack is reduced by one
- If there are zero-degree points in the removal process, they are also added to the stack
- Until the number of outputs equals n finish sorting
PS: If the number of outputs is less than n indicates that the graph has a ring
Examples
Family tree
"Title description"
There is a large family, generational relationship is very confusing, please help to tidy up this relationship.
Give a message to everyone's children.
Enter a sequence so that everyone's descendants are listed later than that person.
Input
The first line is an integer (1<=n<=100) that represents the number of families.
Next n lines, line I represents the son of the first person.
The end of each line is 0, which means the description is complete.
Output
Output a sequence so that everyone's descendants are listed later than that person.
If there is more than one solution to output any solution.
"Input Sample"
5
0
4 5 1 0
1 0
5 3
0
3 0
"Output Example"
2 4 5) 3 1
Code
#include<iostream>using namespace std;int a[101][101];//每个点连接的下一个点int c[101];//出度int r[101];//入度int ans[101];//栈int i,j,tot,temp,num,n;int main(){ cin>>n; for(i=1;i<=n;i++) { do { cin>>j; if(j!=0) { c[i]++;//i的入度加一 a[i][c[i]]=j;//i的第c[i]个连接点为j r[j]++;//j的入度加一 } } while(j!=0); } for(i=1;i<=n;i++) if(r[i]==0) ans[++tot]=i;//如果有点入度为0 加入栈中 while(num!=n)//当输出的数不为n是循环 { temp=ans[tot];//temp等于栈顶的点 cout<<temp;//输出 tot--;//栈中元素减一 num++;//输出数加一 for(i=1;i<=c[temp];i++)//循环与栈顶元素相连的点 { r[a[temp][i]]--;//入度减一 if(r[a[temp][i]]==0)//如果入度为0 加入栈中 ans[++tot]=a[temp][i]; } }}
"Algorithm" doesn't know what sort of topology to use.