【題解】CSES 1690 Hamiltonian Flights

【題目敘述】https://cses.fi/problemset/task/1690/

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
 
int n, m, a, b, dp[(1<<20)][20], mod = 1e9+7;
vector <int> v[25];
 
int f(int mask, int pos){
    if (~dp[mask][pos]) return dp[mask][pos];
    int ans = 0;
    for (int &i:v[pos]){
        if (mask&(1<<i)){
            ans += f(mask^(1<<pos), i);
            ans %= mod;
        }
    }
    return dp[mask][pos] = ans;
}
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> m;
    memset(dp, -1, sizeof(dp));
    for (int i = 0; i < m; i++){
        cin >> a >> b;
        a--;
        b--;
        if (a == b) continue;
        v[b].push_back(a);
    }
    dp[1][0] = 1;
    for (int i = 1; i < n; i++){
        dp[(1<<i)][i] = 0;
    }
    cout << f((1<<n)-1, n-1) << "\n";
}
分享本文 Share with friends