1. 程式人生 > 實用技巧 >模板和彙總

模板和彙總

10.14 topsort

核心:模擬佇列,切進入佇列時候已經就是答案了,直接按照佇列輸出就可

注意while迴圈用輸入量來作為終止

#include <stdio.h>
#include <algorithm>
#include <cstring>

using namespace std;

const int maxn=200020;

int head[maxn],nex[maxn],ver[maxn],tot;
int q[maxn];
int du[maxn];
int n;

void topsort()
{
    int hh=0,tt=-1;
    
for(int i=1;i<=n;i++) if(du[i]==0) q[++tt]=i; while(hh<=tt) { int x=q[hh++]; for(int i=head[x];i;i=nex[i]) { int y=ver[i]; if(--du[y]==0) q[++tt]=y; } } } void add(int x,int y) { ver[++tot]=y; nex[tot]=head[x]; head[x]
=tot; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { int a; while(scanf("%d",&a)!=0) { add(i,a); du[a]++; } } topsort(); for(int i=1;i<=n;i++) printf("%d ",q[i]); return 0; }
View Code