1220E - Tourism - CodeForces Solution


dfs and similar dp dsu graphs greedy trees *2200

Please click on ads to support us..

Python Code:

import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

n, m = map(int, input().split())
w = [0] + list(map(int, input().split()))
G = [[] for _ in range(n + 1)]
for _ in range(m):
    u, v = map(int, input().split())
    G[u].append(v)
    G[v].append(u)
s = int(input())
cnt = [len(g) for g in G]
q, k = [], 0
dp = [0] * (n + 1)
for i in range(1, n + 1):
    if cnt[i] == 1 and i ^ s:
        q.append(i)
ans = sum(w)
while len(q) ^ k:
    i = q[k]
    ma = 0
    for j in G[i]:
        ma = max(ma, dp[j])
    dp[i] = w[i] + ma
    ans -= w[i]
    for j in G[i]:
        cnt[j] -= 1
        if cnt[j] == 1 and j ^ s:
            q.append(j)
    k += 1
ans += max(dp)
print(ans)

C++ Code:

// [ нvмegy ]
// OLPCHUYENTIN2023 GOTOHUE
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
 
#define int long long
#define all(c) c.begin(), c.end()
#ifdef hvmegy
#define dbg(...) logger(#__VA_ARGS__, __VA_ARGS__)
template<typename ...Args>
void logger(string vars, Args&&... values) {
	cerr << "[" << vars << " : ";
	string delim = "";
	(..., (cerr << delim << values, delim = ", "));
	cerr << "]" << '\n'; 
}
#else
#define dbg(...)
#endif
 
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());
 
int GOTOHUE();
 
int32_t main()
{
        cin.tie(0) -> sync_with_stdio(0); 
        cout << fixed << setprecision(15);
	#ifdef hvmegy
		freopen("input.txt", "r", stdin); 
		freopen("output.txt", "w", stdout); 
		freopen("log.txt", "w", stderr);
	#endif
        bool MULTITEST = 0; 
        int OLPCHUYENTIN2023 = 1; 
        if (MULTITEST) cin >> OLPCHUYENTIN2023; 
	for (int i = 1; i <= OLPCHUYENTIN2023; i++) {
		if (GOTOHUE()) break;
		#ifdef hvmegy
			cout << "--ENDTEST--" << '\n';
		#endif
	}
	#ifdef hvmegy
		cerr << '\n' << clock() * 1000.0 / CLOCKS_PER_SEC << "ms" << '\n';
	#endif
        return 0;
}

int GOTOHUE() {
	
	int n, m; 
	cin >> n >> m; 
	vector<int> a(n + 1); 
	for (int i = 1; i <= n; i++) { 
		cin >> a[i]; 
	}

	vector<vector<int>> adj(n + 1); 
	for (int i = 1; i <= m; i++) { 
		int u, v; 
		cin >> u >> v; 
		adj[u].push_back(v); 
		adj[v].push_back(u); 
	}

	int s; 
	cin >> s; 

	vector<bool> vis(n + 1); 
	int ans = 0; 
	auto dfs = [&](auto self, int u, int p) -> bool { 
		int res = 0; 
		vis[u] = true; 
		for (int v : adj[u]) { 
			if (v == p) continue; 
			if (vis[v]) { 
				res |= 1; 
			}
			else { 
				res |= self(self, v, u); 
			}
		}
		if (res) { 
			ans += a[u]; 
			a[u] = 0; 
		}
		return res; 
	};

	dfs(dfs, s, s); 

	vector<int> dp(n + 1); 
	for (int i = 1; i <= n; i++) { 
		vis[i] = false; 
	}
	
	auto dfsdp = [&](auto self, int u, int p) -> void { 
		vis[u] = true; 
		dp[u] = a[u]; 
		for (int v : adj[u]) { 
			if (v == p) continue; 
			if (vis[v]) continue; 
			self(self, v, u); 
			dp[u] = max(dp[u], a[u] + dp[v]); 
		}
	};

	dfsdp(dfsdp, s, s); 

	cout << ans + dp[s]; 
	return 0; 
}


Comments

Submit
0 Comments
More Questions

878. Nth Magical Number
2099. Find Subsequence of Length K With the Largest Sum
1608A - Find Array
416. Partition Equal Subset Sum
1446. Consecutive Characters
1618A - Polycarp and Sums of Subsequences
1618B - Missing Bigram
938. Range Sum of BST
147. Insertion Sort List
310. Minimum Height Trees
2110. Number of Smooth Descent Periods of a Stock
2109. Adding Spaces to a String
2108. Find First Palindromic String in the Array
394. Decode String
902. Numbers At Most N Given Digit Set
221. Maximal Square
1200. Minimum Absolute Difference
1619B - Squares and Cubes
1619A - Square String
1629B - GCD Arrays
1629A - Download More RAM
1629C - Meximum Array
1629D - Peculiar Movie Preferences
1629E - Grid Xor
1629F1 - Game on Sum (Easy Version)
2148. Count Elements With Strictly Smaller and Greater Elements
2149. Rearrange Array Elements by Sign
2150. Find All Lonely Numbers in the Array
2151. Maximum Good People Based on Statements
2144. Minimum Cost of Buying Candies With Discount