传送门
题目描述
给定n 个点m 条边的有向图,可能不连通,可能有重边,也可能会有自环。求最长的路径(可以经过重复节点),使得这条路径的编号和权值都严格单调递增,其中编号指输入的顺序。路径的长度是指经过边的数量。
分析
一开始的思路是按边的顺序建图,后来发现不好去维护,后来发现我们可以在主席树上做DP
我们首先把每一个点建一颗权值线段树,每棵树的叶子结点表示到这个点,最后一段距离是j的最大链为多少,然后合并为主席树,用DP搞一搞就出来了
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 10;
struct Node{
int l,r;
int res;
}tr[N * 20];
int n,m;
int root[N],idx;
int query(int u,int l,int r,int L,int R){
if(L > R) return 0;
if(l >= L && r <= R) return tr[u].res;
int ans = 0;
int mid = l + r >> 1;
if(L <= mid) ans = query(tr[u].l,l,mid,L,R);
if(mid < R) ans = max(ans,query(tr[u].r,mid + 1,r,L,R));
return ans;
}
int insert(int u,int l,int r,int x,int z){
int q = ++idx;
tr[q] = tr[u];
if(l == r){
tr[q].res = max(tr[q].res,z);
return q;
}
int mid = l + r >> 1;
if(x <= mid) tr[q].l = insert(tr[u].l,l,mid,x,z);
else tr[q].r = insert(tr[u].r,mid + 1,r,x,z);
tr[q].res = max(tr[tr[q].l].res,tr[tr[q].r].res);
return q;
}
int main(){
scanf("%d%d",&n,&m);
int ans = 0;
while(m--){
int x,y,z,p;
scanf("%d%d%d",&x,&y,&z);
p = query(root[x],0,N,0,z - 1);
root[y] = insert(root[y],0,N,z,p + 1);
ans = max(ans,p + 1);
}
printf("%d\n",ans);
return 0;
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/