这题问给出一个有向图,问走k步,每次费用为路径上的最大值,最大值最小是多少
这种minmax问题,首先想到二分,然后我们可以对这个答案进行二分
然后观察一下,如果能走k步,那么说明去除所有大于mid的点的影响之后,要么最长路长度是大于等于k,要么存在环
可以用拓扑排序一次求出,重新建图,然后判断入队点数等不等于有效点数或者最长路大于等于k
#include <bits/stdc++.h>
using namespace std;
constexpr int limit = (200000 + 5);//防止溢出
#define INF 0x3f3f3f3f
#define inf 0x3f3f3f3f3f3f3f
#define lowbit(i) i&(-i)//一步两步
#define EPS 1e-9
#define FASTIO ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
#define ff(a) printf("%d\n",a );
#define pi(a, b) pair<a,b>
#define rep(i, a, b) for(ll i = a; i <= b ; ++i)
#define per(i, a, b) for(ll i = b ; i >= a ; --i)
#define MOD 998244353
#define traverse(u) for(int i = head[u]; ~i ; i = edge[i].nxt)
#define FOPEN freopen("C:\\Users\\tiany\\CLionProjects\\akioi\\data.txt", "rt", stdin)
#define FOUT freopen("C:\\Users\\tiany\\CLionProjects\\akioi\\dabiao.txt", "wt", stdout)
typedef long long ll;
typedef unsigned long long ull;
char buf[1 << 23], *p1 = buf, *p2 = buf, obuf[1 << 23], *O = obuf;
inline ll read() {
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
ll sign = 1, x = 0;
char s = getchar();
while (s > '9' || s < '0') {
if (s == '-')sign = -1;
s = getchar();
}
while (s >= '0' && s <= '9') {
x = (x << 3) + (x << 1) + s - '0';
s = getchar();
}
return x * sign;
#undef getchar
}//快读
void print(ll x) {
if (x / 10) print(x / 10);
*O++ = x % 10 + '0';
}
void write(ll x, char c = 't') {
if (x < 0)putchar('-'), x = -x;
print(x);
if (!isalpha(c))*O++ = c;
fwrite(obuf, O - obuf, 1, stdout);
O = obuf;
}
int n,m;
int a[limit];
vector<int>g[limit], g2[limit];
int deg[limit];
int deg2[limit];
int dp[limit];
void solve(){
ll k;
cin>>n;
cin>>m;
cin>>k;
priority_queue<pi(int, int)>q;
rep(i,1,n){
cin>>a[i];
}
rep(i,1,m){
int u,v;
cin>>u>>v;
deg[v]++;
g[u].push_back(v);
}
auto check = [&](ll x)->bool{
queue<int>q;
int tot = 0;
rep(i,1,n){
deg2[i] = 0;
g2[i].clear();
dp[i] = -1;
}
rep(i,1,n){
tot += (a[i] <= x);
for(auto && v : g[i]){
if(a[i] <= x and a[v] <= x){
g2[i].push_back(v);
deg2[v]++;
}
}
}
rep(i,1,n){
if(!deg2[i] and a[i] <= x){
q.push(i);
dp[i] = 0;
// dp[i] = 0;
}
}
int inq = 0;
while(!q.empty()){
int u = q.front();
q.pop();
// cout<<u<<" f"<<endl;
inq++;
for(auto v : g2[u]){
deg2[v]--;
dp[v] = max(dp[v], dp[u] + 1);
if(deg2[v] == 0){
q.push(v);
}else{
// cout<<v<<" "<<deg2[v]<<endl;
}
}
}
// cout<<"inqueue "<<inq<<endl;
// cout<<"tot "<<tot<<endl;
int flag = *max_element(dp + 1, dp + 1 + n) >= k - 1 or inq != tot;
return flag;
};
ll ans = -1;
// cout<<check(5<<1)<<endl;
for(ll l = 1, r = 2e9; l <= r; ){
ll mid = l + (r - l) / 2;
if(check(mid)){
r = mid - 1;
ans = mid;
}else{
l = mid + 1;
}
}
cout<<ans<<endl;
};
int32_t main() {
#ifdef LOCAL
FOPEN;
// FOUT;
#endif
FASTIO
// int kase;
// cin>>kase;
// while (kase--)
invoke(solve);
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << "s\n";
return 0;
}
标签:...,int,Graph,ll,cin,cf791,limit,rep,define
From: https://www.cnblogs.com/tiany7/p/17087910.html