PAT甲级——A1146 TopologicalOrder【25】
This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topological order obtained from the given directed graph? Now you are supposed to write a program to test each of the options.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers N (≤ 1,000), the number of vertices in the graph, and M (≤ 10,000), the number of directed edges. Then M lines follow, each gives the start and the end vertices of an edge. The vertices are numbered from 1 to N. After the graph, there is another positive integer K (≤ 100). Then K lines of query follow, each gives a permutation of all the vertices. All the numbers in a line are separated by a space.
Output Specification:
Print in a line all the indices of queries which correspond to "NOT a topological order". The indices start from zero. All the numbers are separated by a space, and there must no extra space at the beginning or the end of the line. It is graranteed that there is at least one answer.
Sample Input:
6 8
1 2
1 3
5 2
5 4
2 3
2 6
3 4
6 4
5
1 5 2 3 6 4
5 1 2 6 3 4
5 1 2 3 6 4
5 2 1 6 3 4
1 2 3 4 5 6
Sample Output:
3 4
Solution:
使用邻接矩阵来保存这个有向矩阵,并且把每个节点的入度计算,遍历判断的序列,每经过一个节点就判断该节点入度是不是为0,若不是,说明不是拓扑序列
每经过一个节点,将其指向节点的入度-1,表明指向节点的父节点遍历完毕,从而保证了整个序列是个拓扑序列
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std; int main()
{
int n, m, k;
cin >> n >> m;
vector<vector<int>>v(n + );
vector<int>in(n + , ), temp, res;//节点的入度
for (int i = ; i < m; ++i)
{
int a, b;
cin >> a >> b;
v[a].push_back(b);
in[b]++;
}
cin >> k;
for (int i = ; i < k; ++i)
{
bool flag = true;
temp = in;
for (int j = ; j < n; ++j)
{
int x;
cin >> x;
if (temp[x] != )flag = false;
for (auto a : v[x])--temp[a];//出现一次入度减一
}
if (!flag)
res.push_back(i);
}
for (int i = ; i < res.size(); ++i)
cout << (i == ? "" : " ") << res[i];
return ;
}
最新文章
- Spring基础学习笔记-Bean的基础知识
- CentOS-7下安装MySQL5.6.22
- [WPF]DataGridHyperlinkColumn网址过长TextTrimming无效
- 关于Python中的文件操作(转)
- hdu4975 A simple Gaussian elimination problem.(正确解法 最大流+删边判环)(Updated 2014-10-16)
- tomcat架构
- MASS批量维护
- MongoDB驱动特性检查列表
- 01-08-01【Nhibernate (版本3.3.1.4000) 出入江湖】NHibernate中的三种状态
- LabVIEW设计模式系列——移位寄存器
- LCD显示的一些基本概念以及DSI的一些clock解释
- shell timeout
- Linux下安装Perl和Perl的DBI模块
- FCKeditor
- POJ1274_The Perfect Stall(二部图最大匹配)
- 长话短说 之 js的原型和闭包
- 【一天一道LeetCode】#31. Next Permutation
- node项目自动化部署--基于Jenkins,Docker,Github(1)安装Jenkins
- HDU-魔咒词典(字符串hash)
- [android] fragment的动态创建