拓扑排序 / dp
前置
priority_queue与sort恰好相反,若重载小于符号,则sort表从小到大,而priority_queue表从大到小,反之亦然。
struct po{
int ru,pos;
friend bool operator <(struct po a,struct po b){
return a.ru>b.ru; //对于优先队列来说表从小到大,与sort正好相反
}
};
priority_queue<struct po> q;
题意
给定一张无向图,求一组点,使得两个相邻的点在图中邻接且该组点的入度(出度)呈严格递增,要使点的数量尽可能多,问该组点的数量最多是多少?
分析
- 所选的点必须在图中邻接,且使入度(出度)递增,则只要算出每个点的入度,进行dp即可
- 转移方程:
i f ( r u [ u ] < r u [ v ] ) if (ru[u]<ru[v]) if(ru[u]<ru[v])
d p [ u ] = m a x ( d p [ u ] , d p [ v ] + 1 ) dp[u]=max(dp[u],dp[v]+1) dp[u]=max(dp[u],dp[v]+1) - 由于从权值小的向权值大的转移,故需先更新权值小的,再更新权值大的,故考虑拓扑排序
Code
#include<bits/stdc++.h>
using namespace std;
const int maxn=3e5+5;
const int mod=998244353;
const long long inf=1e18;
const int base=131;
const double pi=3.1415926;
#define ll long long
#define int long long
#define ull unsigned long long
#define maxx(a,b) (a>b?a:b)
#define minx(a,b) (a<b?a:b)
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define debug(...) fprintf(stderr, __VA_ARGS__)
inline ll qpow(ll base, ll n) { assert(n >= 0); ll res = 1; while (n) { if (n & 1) res = res * base % mod; base = base * base % mod; n >>= 1; } return res; }
ll gcd(ll a,ll b) {return b==0?a:gcd(b,a%b);}
ll lcm(ll a,ll b) { return a*b/gcd(a,b); }
ll inv(ll a) {return a == 1 ? 1 : (ll)(mod - mod / a) * inv(mod % a) % mod;}
ll C(ll n,ll m){if (m>n) return 0;ll ans = 1;for (int i = 1; i <= m; ++i) ans=ans*inv(i)%mod*(n-i+1)%mod;return ans%mod;}
ll A(ll n,ll m){ll sum=1; for(int i=n;i>=n-m+1;i--) sum=(sum*i)%mod; return sum%mod;}
ll GetSum(ll L, ll R) {return (R - L + 1ll) * (L + R) / 2ll;} //等差数列求和
/************/
int n,m,ru[maxn],dp[maxn],ans;
vector<int> ve[maxn];
struct po{
int ru,pos;
friend bool operator <(struct po a,struct po b){
return a.ru>b.ru;
}
};
priority_queue<struct po> q;
signed main()
{
IOS;
cin>>n>>m;
for(int i=0;i<m;i++){
int u,v;
cin>>u>>v;
ve[u].push_back(v);
ve[v].push_back(u);
ru[u]++;
ru[v]++;
}
for(int i=0;i<n;i++){
struct po a;
a.ru=ru[i];
a.pos=i;
q.push(a);
}
while(!q.empty()){
int u=q.top().pos;
q.pop();
int len=ve[u].size();
for(int i=0;i<len;i++){
int v=ve[u][i];
if(ru[u]>ru[v]) dp[u]=max(dp[u],dp[v]+1);
}
ans=max(ans,dp[u]);
}
cout<<ans+1;
return 0;
}