洛谷_P13099 [FJCPC 2025] VERTeX
题目链接:P13099 [FJCPC 2025] VERTeX - 洛谷
题目大意:
给定一棵树,边权等于两端点权之和,已知边权
判断是否存在正整数点权并构造。
思路:
首先,如果某个节点的权值确定,那么所有节点的权值也都确定
我们从某个节点入手,假设该节点的权值为1,
得出所有节点权值,若该方案合法,直接输出即可
若不合法,说明必定存在某个节点的权值是非正数,
我们调整该节点的权值,让所有节点权值变为正数
再次判断即可
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<bitset>
#include<tuple>
#include<array>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;
const int N = 400086, mod = 998244353;
int n, m;
int h[N], ne[N], e[N], w[N], idx;
int res[N];
void add(int a, int b, int c) {
w[idx] = c, e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u, int fa) {
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
res[j] = w[i] - res[u];
dfs(j, u);
}
}
void solve() {
mst(h, -1);
cin >> n;
for (int i = 1; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
res[1] = 1;
dfs(1, 0);
int mn = *min_element(res + 1, res + n + 1);
if (mn <= 0) {
fill(res, res + n + 1, 0), res[1] = 2 - mn;
dfs(1, 0);
mn = *min_element(res + 1, res + n + 1);
cout << (mn <= 0 ? "NO" : "YES") << endl;
} else cout << "YES" << endl;
if (mn > 0) for (int i = 1; i <= n; i++) cout << res[i] << ' ';
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int T = 1;
// cin >> T;
while (T--) solve();
return 0;
}

浙公网安备 33010602011771号