第十八天PAT-A1146 Topological Order判定拓扑序列

博客分析了PAT考试中的A1146题,探讨如何判断给定序列是否为有向图的拓扑序列。关键在于通过检查序列中每个节点的入度是否为零来实现。
摘要由CSDN通过智能技术生成

A1146

Description:

给出有向图及序列,判断该序列是否为拓扑序列;

思路:

  • 根据拓扑序列构造方法,检查序列依次出栈的节点入度是否为零即可;
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 1e3+5;
const int maxm = 1e4+5;
struct Node{
    int d;  //入度,当该点为终点时+1
    vector<int>to;  //该节点指向的节点下标
}node[maxn];
int n, m, k;
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    scanf("%d%d", &n ,&m);
    int u, v;
    for(int i = 0; i < m; i++){
        scanf("%d%d", &u, &v);
        node[u].to.push_back(v);    //将终点加入当前节点指向节点序列
        node[v].d++;    //终点的入度++
    }
    bool flag = false;  //用于标记是否为首个输出的元素,false为首个元素
    int du[maxn], t;    //du数组用于复制所有节点的入度信息
    scanf("%d", &k);
    for(int i = 0 ; i < k ; i++){
        for(int j = 1; j <= n; j++){
            du[j] = node[j].d;  //每次问询拷贝入读信息
        }
        bool istpo = true;  //初始化当前为拓扑序列
        for(int j = 0; j < n; j++){
            scanf("%d", &t);
            if(istpo){
                if(du[t]!=0) istpo = false;
                else for(auto it:node[t].to){
                    du[it]--;
                }
            }
        }
        if(!istpo){ //非拓扑序列
            if(!flag) flag = true;  //首次输出
            else printf(" ");
            printf("%d", i);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值