486D - Valid Sets - CodeForces Solution


dfs and similar dp math trees *2100

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
long long MOD;
int a[2005];
long long dp[2005];
int visited[2005];
int d;
vector<int> graph[2005] ;

void dfs(int current, int root){
    visited[current] = 1;
    for(auto u: graph[current]){
        if(visited[u] == 1){
            continue;
        }
        if(a[u] < a[root] || a[u] > a[root]+d){
            continue;
        }
        if((a[u] == a[root]) && u < root){
            continue;
        }
        dfs(u, root);
        dp[current] = dp[current]*(dp[u] + 1);
        dp[current] %= MOD;
    }
}

int main()
{
    // freopen("input.txt", "r", stdin);
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    MOD = 1e9+7;
    int n;
    cin>>d>>n;
    for(int i=1; i<=n; i++){
        cin>>a[i];
    }
    for(int i=1; i<n; i++){
        int u, v;
        cin>>u>>v;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    
    long long res = 0;
    
    for(int i=1; i<=n; i++){
        for(int j=1; j<=n; j++){
            visited[j] = 0;
            dp[j] = 1;
        }
        dfs(i, i);
        res += dp[i];
        res %= MOD;
    }
    cout<<res;
    return 0;
}


Comments

Submit
0 Comments
More Questions

1194C - From S To T
110B - Lucky String
1114A - Got Any Grapes
224B - Array
125B - Simple XML
567B - Berland National Library
431B - Shower Line
282C - XOR and OR
1582B - Luntik and Subsequences
609A - Флеш-карты
1207A - There Are Two Types Of Burgers
371C - Hamburgers
343B - Alternating Current
758B - Blown Garland
1681B - Card Trick
1592A - Gamer Hemose
493D - Vasya and Chess
1485A - Add and Divide
337B - Routine Problem
1392D - Omkar and Bed Wars
76E - Points
762C - Two strings
802M - April Fools' Problem (easy)
577B - Modulo Sum
1555B - Two Tables
1686A - Everything Everywhere All But One
1469B - Red and Blue
1257B - Magic Stick
18C - Stripe
1203B - Equal Rectangles