PAT甲级1146 Topological Order (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

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

二、解题思路

一个有向无环图的拓扑序列,即对于这个序列中的每个结点,它的前驱结点一定在它之前。由于数据量不大,我们这道题可以使用邻接矩阵存储,G[tmp1][tmp2]=1表示从结点tmp1指向tmp2,即前一个结点是后一个结点的前驱结点,同时将G[tmp2][tmp1]设置为-1。那么对于输入的数据,我们只需要用一个简单的二重循环,看一看有没有两个点的邻接矩阵对应值为-1的,如果有,那么就不是一个拓扑序列,将标号存入ans中,最后打印输出即可,详情可见代码注释。

三、AC代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 1010;
int G[maxn][maxn] = {
    
    0};    //邻接矩阵
int main()
{
    
    
  int N, M, K, tmp1, tmp2;
  scanf("%d%d", &N, &M);
  for(int i=0; i<M; i++)
  {
    
    
    scanf("%d%d", &tmp1, &tmp2);
    G[tmp1][tmp2] = 1;  //tmp1是tmp2的前驱
    G[tmp2][tmp1] = -1;
  }
  vector<int> ans;
  scanf("%d", &K);
  for(int i=0; i<K; i++)
  {
    
    
    vector<int> test;
    bool flag = true;
    for(int j=0; j<N; j++)
    {
    
    
      scanf("%d", &tmp1);
      test.push_back(tmp1);
    }
    for(int j=0; j<N; j++)
    {
    
    
      for(int k=j+1; k<N; k++)
      {
    
    
        if(G[test[j]][test[k]] == -1)   //结点test[k]是G[test[j]的前驱结点,但却排在它的后面
        {
    
    
          flag = false;
          break;
        }
      }
      if(!flag) //flag为false,存入ans中
      {
    
    
        ans.push_back(i);
        break;
      }
    }
  }
  for(int i=0; i<ans.size(); i++)
  {
    
    
    if(i==0)	printf("%d", ans[i]);
    else	printf(" %d", ans[i]);
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/109091391
今日推荐