标准的拓扑排序
2024-04-21 11:58:27
发布于:广东
19阅读
0回复
0点赞
#include <stdio.h>
#include <queue>
#include <vector>
#include <algorithm>
#define N 1020
using namespace std;
int n, m;
int indegree[N], a[N], b[N], books[N][N];
vector<int>e[N];
struct edge {
int start;
int temp;
};
queue<edge>q;
int bfs()
{
int i, v, s, ans = 1;
for(i=1; i<=n; i++)
if (indegree[i] == 0)
q.push(edge{ i, 1 });
while (!q.empty())
{
edge u = q.front();
q.pop();
s = u.start;
ans = max(ans, u.temp);
for (i = 0; i < e[s].size(); i++)
{
v = e[s][i];
indegree[v]--;
if (indegree[v] == 0)
q.push(edge{ v, u.temp + 1 });
}
}
return ans;
}
int main()
{
int i, j, k, l, len;
scanf("%d%d", &n, &m);
while (m--)
{
scanf("%d", &k);
for (i = 0; i < k; i++)
scanf("%d", &a[i]);
l = 1;
len = 0;
for (j = a[0] + 1; j < a[k - 1]; j++)
{
if (j == a[l])
{
l++;
continue;
}
b[len++] = j;
}
for (i = 0; i < k; i++)
{
for (j = 0; j < len; j++)
{
if (books[a[i]][b[j]])
continue;
e[a[i]].push_back(b[j]);
indegree[b[j]]++;
books[a[i]][b[j]] = 1;
}
}
}
printf("%d\n", bfs());
return 0;
}
这里空空如也
有帮助,赞一个