#include<iostream>
#include<string.h>
using namespace std;
struct mapList {
int data;
mapList* next;
};
struct map {
// 单链表尾指针
mapList* tail;
// 单链表头指针
mapList* list;
};
// 单链表存储图
void dispatch(map* ma, int x, int y) {
if (ma[x - 1].tail == NULL) {
ma[x - 1].tail = ma[x - 1].list = new mapList();
} else {
/* auto p = ma[x - 1].list;
while (p != NULL) {
if (p->data == y - 1) {
return;
}
p = p->next;
}*/
ma[x - 1].tail = ma[x - 1].tail->next = new mapList();
}
ma[x - 1].tail->data = y - 1;
}
int DFS(map* ma, bool* visited, int s, int max) {
visited[s] = true;
mapList* p = ma[s].list;
while (p != NULL) {
int w = p->data;
if (max < w) {
max = w;
}
if (!visited[w]) {
int next = DFS(ma, visited, w, max);
if (max < next) {
max = next;
}
}
p = p->next;
}
return max;
}
int main() {
int m, n, x, y;
cin >> n >> m;
map* ma = new map[n]();
bool* visited = new bool[n]();
// 读入数据
for (int i = 0; i < m; i++) {
cin >> x >> y;
dispatch(ma, x, y);
}
for (int i = 0; i < n; i++) {
cout << DFS(ma, visited, i, i) + 1<< " ";
memset(visited, 0, sizeof(bool) * n);
}
return 0;
}
两个点超时,