拓扑排序

https://en.wikipedia.org/wiki/Topological_sorting

 1 struct pointtype
 2 {
 3     vector<int> next;
 4     int in;
 5 }point[1000001];
 6 int n,m;
 7 queue<int> q;
 8 list<int> res;
 9 void init()
10 {
11     scanf("%d%d",&n,&m);
12     for(int i=1;i<=n;i++)
13     {
14         point[i].in=0;
15         point[i].next.clear();
16     }
17     for(int i=1;i<=m;i++)
18     {
19         int x,y;
20         scanf("%d%d",&x,&y);
21         point[x].next.push_back(y);
22         point[y].in+=1;
23     }
24     for(int i=1;i<=n;i++)
25     {
26         if(point[i].in==0)
27         {
28             q.push(i);
29         }
30     }
31     return;
32 }
33 bool topological_sorting()//是否存在拓扑序及其解 
34 {
35     while(!q.empty())
36     {
37         int now=q.front();
38         q.pop();
39         res.push_back(now);
40         vector<int>::iterator it;
41         for(it=point[now].next.begin();it!=point[now].next.end();it++)
42         {
43             point[*it].in-=1;
44             if(point[*it].in==0)
45             {
46                 q.push(*it);
47             }
48         }
49         point[now].next.clear();
50     }
51     bool flag=true;
52     for(int i=1;i<=n;i++)
53     {
54         if(!point[i].next.empty())
55         {
56             flag=false;
57             break;
58         }
59     }
60     return flag;
61 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值