poj2367拓扑排序模版题
程序员文章站
2022-03-14 19:49:56
...
方法一:
采用二位数组的形式(也可以用邻接表形式)
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int maxx=1e3+10;
const int inf=0x3f3f3f3f;
int n;
int indegree[maxx];
int vis[maxx][maxx];
int flag[maxx];
int a[maxx][maxx];
int q[maxx];
int main(){
while(cin>>n){
queue<int>Q;
memset(q,0,sizeof(q));
memset(vis,0,sizeof(vis));
memset(a,0,sizeof(a));
memset(indegree,0,sizeof(indegree));
memset(flag,0,sizeof(flag));
for(int i=1;i<=n;i++){
int index;
int k=0;
cin>>index;
while(index!=0){
indegree[index]++;
vis[i][index]=1;
cin>>index;
}
flag[i]=k;
}
for(int i=1;i<=n;i++){
if(indegree[i]==0){
Q.push(i);
}
}
while(!Q.empty()){
int u=Q.front();
Q.pop();
cout<<u<<" ";
for(int i=1;i<=n;i++){
if(vis[u][i]==1){
indegree[i]--;
if(indegree[i]==0){
Q.push(i);
}
}
}
}
cout<<endl;
}
return 0;
}
方法二:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int maxx=1e3+10;
const int inf=0x3f3f3f3f;
int n;
int indegree[maxx];
int vis[maxx][maxx];
int flag[maxx];
int a[maxx][maxx];
int q[maxx];
void TopoSort(int n) {
int c=1,index,m;
for(int i=1;i<=n;i++){
m=0;
for(int j=1;j<=n;j++){
if(indegree[j]==0){
m++;
index=j;
}
}
q[c++]=index;
indegree[index]=-1;
for(int j=1;j<=n;j++){
if(vis[index][j]==1){
indegree[j]--;
}
}
}
}
int main(){
while(cin>>n){
queue<int>Q;
memset(q,0,sizeof(q));
memset(vis,0,sizeof(vis));
memset(a,0,sizeof(a));
memset(indegree,0,sizeof(indegree));
memset(flag,0,sizeof(flag));
for(int i=1;i<=n;i++){
int index;
int k=0;
cin>>index;
while(index!=0){
indegree[index]++;
vis[i][index]=1;
cin>>index;
}
flag[i]=k;
}
TopoSort(n);
for(int i=1;i<=n;i++){
cout<<q[i]<<" ";
}
cout<<endl;
}
return 0;
}
上一篇: MD5加密