写在前面
- 思路分析
- 邻接表v存储有向图,并将每个节点入度保存在indeg数组中。
- 对每1个要判断是否是拓扑序列的结点遍历,当前结点入度不为0则表示不是拓拓扑序列列,每次选中某个点后要将它所指向的所有结点的入度减去1
- 根据是否出现过入度不为0的点决定是否要输出当前的编号i
- flag变量用来判断是否输出空格的
- judge变量用来判断是否拓扑序列
- 题目简单,存储、对比序列是否符合拓扑性质
- 25分钟a题
测试用例
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
output:
3 4
ac代码
- 参考链接
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, m, a, b, k, flag = 0, indeg[1010];
vector<int> v[1010];
scanf("%d%d", &n, &m);
for(int i=0; i<m; i++)
{
scanf("%d %d", &a, &b);
v[a].push_back(b);
// 入度加1
indeg[b]++;
}
scanf("%d", &k);
for(int i=0; i<k; i++)
{
int judge = 1;
// 复制数组
vector<int> tin(indeg,indeg+n+1);
for(int j=0; j<n; j++)
{
scanf("%d", &a);
// 入度不为0,非拓扑排序
if(tin[a] != 0) judge = 0;
// 当前结点,所有子节点入度减1
for(int it: v[a]) tin[it]--;
}
if(judge == 1) continue;
printf("%s%d", flag == 1 ? " " : "", i);
flag = 1;
}
return 0;
}
知识点小结
- 复制数组至容器变量
int a[4]={0,10,22,3};
std::vector<int> array(a, a + 4);