1. 程式人生 > 其它 >CodeForces-1679D Toss a Coin to Your Graph...

CodeForces-1679D Toss a Coin to Your Graph...

Toss a Coin to Your Graph...

二分 + 記憶化搜尋

答案是單調的,所以直接二分答案,然後檢查的時候就記憶化搜尋,看看在限制當前最高值的情況下,能不能走 k 步,如果走的發現是個環,則直接返回可以走 k 步就行

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <deque>
#include <stack>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
const ll maxn = 2e5 + 10;
const ll inf = 1e17 + 10;
int num[maxn];
int a[maxn], vis[maxn];
ll dp[maxn];
vector<int>gra[maxn];
ll n, m, k;

ll dps(int now, int x)
{
    if(dp[now]) return dp[now] == -1 ? 0 : dp[now];
    if(num[now] > x) {dp[now] = -1; return 0;}
    vis[now] = 1;
    ll ans = 0;
    for(int i=0; i<gra[now].size() && ans < k; i++)
    {
        int nex = gra[now][i];
        if(vis[nex]) ans = k;
        else
            ans = max(ans, dps(nex, x));
    }
    vis[now] = 0;
    return dp[now] = ans + 1;
}

bool judge(int x)
{
    for(int i=1; i<=n; i++) dp[i] = vis[i] = 0;
    ll ans = 0;
    for(int i=1; i<=n && ans < k; i++)
        ans = max(ans, dps(i, x));
    return ans >= k;
}

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 >> num[i]; a[i] = num[i];}
    while(m--)
    {
        int a, b;
        cin >> a >> b;
        gra[a].push_back(b);
    }
    sort(a + 1, a + n + 1);
    int l = 1, r = n;
    while(l < r)
    {
        int mid = l + r >> 1;
        if(judge(a[mid]))
            r = mid;
        else
            l = mid + 1;
    }
    if(judge(a[l]))
        cout << a[l] << endl;
    else
        cout << -1 << endl;

    return 0;
}