二分 + 判环 + DAGDP
- 最大值最小化可以想到二分答案
- check过程为只给小于等于答案的点之间连边,虽然 k 很大,但如果存在环则一定可以,不存在环就求当前图的最长路,如果最长路 <= k - 1 则可以
- 判环和求最长路都可用拓扑排序完成
- 注意 k == 1 时要特判
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 2e5 + 10;
int n, m;
ll k;
int a[N], din[N];
pair<int, int> Edge[N];
vector<int> G[N];
int dist[N];
void init()
{
for (int i = 1; i <= n; i++)
G[i].clear();
memset(dist, 0, sizeof dist);
memset(din, 0, sizeof din);
}
void add(int a, int b)
{
G[a].push_back(b);
din[b]++;
}
bool topsort()
{
queue<int> q;
for (int i = 1; i <= n; i++)
if (!din[i]) q.push(i);
vector<int> ans;
while(!q.empty())
{
int u = q.front();
q.pop();
ans.push_back(u);
for (int v : G[u])
{
din[v]--;
dist[v] = max(dist[v], dist[u] + 1);
if (!din[v])
q.push(v);
}
}
return ans.size() < n || *max_element(dist + 1, dist + n + 1) >= k - 1;
}
bool check(int x)
{
init();
for (int i = 1; i <= m; i++)
if (a[Edge[i].first] <= x && a[Edge[i].second] <= x)
add(Edge[i].first, Edge[i].second);
return topsort();
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m >> k;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= m; i++)
cin >> Edge[i].first >> Edge[i].second;
if (k == 1)
{
cout << *max_element(a + 1, a + n + 1) << endl;
return 0;
}
int l = 0, r = 1e9 + 1;
while(l + 1 != r)
{
int mid = l + r >> 1;
if (check(mid))
r = mid;
else
l = mid;
}
cout << (r == (int)1e9 + 1 ? -1 : r) << endl;
return 0;
}