Codeforces Round #586 (Div. 1 + Div. 2) E. Tourism

link:

https://codeforces.com/contest/1220/problem/E

Meaning of the questions:

Alex decided to go on a touristic trip over the country.

For simplicity let's assume that the country has n cities and m bidirectional roads connecting them. Alex lives in city s and initially located in it. To compare different cities Alex assigned each city a score wi which is as high as interesting city seems to Alex.

Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city v from city u, he may choose as the next city in the trip any city connected with v by the road, except for the city u.

Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.

Ideas:

Meaning of the title is not immediately backtrack, but look around you can backtrack .. I thought it was every edge can only go once.
In this case the code to see other people, consider Dfs, a record exists or not there is no chain of the bottom ring exist If there can be up to return, it points to the cumulative value of the answer.
If not, it can not return the longest chain of value recorded separately and then kept up to update, update a maximum value chain can be.

Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 2e5+10;

vector<int> G[MAXN];
LL Other[MAXN], Val[MAXN], res = 0;
int Vis[MAXN];
int n, m, s;

bool Dfs(int u, int fa)
{
    Vis[u] = 1;
    bool flag = false;
    for (int i = 0;i < G[u].size();i++)
    {
        int node = G[u][i];
        if (node == fa)
            continue;
        if (Vis[node] == 1)
        {
            flag = true;
            continue;
        }
        bool Tmp = Dfs(node, u);
        if (Tmp)
            flag = true;
        Other[u] = max(Other[u], Other[node]);
    }
    if (flag)
    {
        res += Val[u];
        return true;
    }
    else
    {
        Other[u] += Val[u];
        return false;
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n >> m;
    for (int i = 1;i <= n;i++)
        cin >> Val[i];
    int u, v;
    for (int i = 1;i <= m;i++)
    {
        cin >> u >> v;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    cin >> s;
    Dfs(s, 0);
    cout << res+Other[s] << endl;

    return 0;
}

Guess you like

Origin www.cnblogs.com/YDDDD/p/11627536.html