Luogu1137 旅行计划 (拓扑排序)

2022-10-15,,,

每次入队时DP : \(f[v] = \max \{f[u] + 1\}\)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long //#define ON_DEBUG #ifdef ON_DEBUG #define D_e_Line printf("\n\n----------\n\n")
#define D_e(x) cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin); #else #define D_e_Line ;
#define D_e(x) ;
#define Pause() ;
#define FileOpen() ; #endif struct ios{
template<typename ATP>ios& operator >> (ATP &x){
x = 0; int f = 1; char c;
for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
x*= f;
return *this;
}
}io;
using namespace std; const int N = 100007; struct Edge{
int nxt, pre;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v){
e[++cntEdge] = (Edge){ head[u], v}, head[u] = cntEdge;
} int ans[N];
int in[N];
int q[N], top;
int main(){
FileOpen(); int n, m;
io >> n >> m;
R(i,1,m){
int u, v;
io >> u >> v;
add(u, v);
++in[v];
} R(i,1,n){
if(!in[i]){
ans[i] = 1;
q[++top] = i;
} }
while(top){
int u = q[top--];
for(register int i = head[u]; i; i = e[i].nxt){
int v = e[i].pre;
--in[v];
ans[v] = Max(ans[v], ans[u] + 1);
if(!in[v]){
q[++top] = v;
}
}
} R(i,1,n){
printf("%d\n", ans[i]);
} return 0;
}

Luogu1137 旅行计划拓扑排序)的相关教程结束。

《Luogu1137 旅行计划 (拓扑排序).doc》

下载本文的Word格式文档,以方便收藏与打印。