This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 5;
vector<pair<int, int>> G[MAX_N];
int color[MAX_N];
vector<int> comp, path, path_edges, cycle, cycle_edges;
bool visited[MAX_N] = {};
long double A[MAX_N];
void DFS(int u) {
comp.push_back(u);
for (auto [v, c] : G[u]) {
if (color[v] == -1) {
color[v] = !color[u];
DFS(v);
}
}
}
bool find_cycle(int u) {
visited[u] = true;
path.push_back(u);
for (auto [v, c] : G[u]) {
if (!visited[v]) {
path_edges.push_back(c);
if (find_cycle(v)) {
return true;
}
path_edges.pop_back();
} else if (color[u] == color[v]) {
path_edges.push_back(c);
while (path.back() != v) {
cycle.push_back(path.back());
cycle_edges.push_back(path_edges.back());
path.pop_back();
path_edges.pop_back();
}
cycle.push_back(path.back());
cycle_edges.push_back(path_edges.back());
return true;
}
}
path.pop_back();
return false;
}
long double check(int s, long double value) {
for (int v : comp) {
visited[v] = false;
}
A[s] = value;
queue<int> Q;
Q.push(s);
visited[s] = true;
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (auto [v, c] : G[u]) {
if (!visited[v]) {
A[v] = c - A[u];
visited[v] = true;
Q.push(v);
} else if (abs(A[u] + A[v] - c) > 1e-15l) {
cout << "NO\n";
exit(0);
}
}
}
long double ans = 0;
for (int v : comp) {
ans += abs(A[v]);
}
return ans;
}
void solve(int u) {
cycle = cycle_edges = path = path_edges = vector<int>();
if (find_cycle(u)) {
long double sum = 0;
rotate(cycle_edges.begin(), cycle_edges.begin() + 1, cycle_edges.end());
for (int i = 0; i < (int)cycle_edges.size(); i++) {
sum += cycle_edges[i] * (i % 2 ? -1 : +1);
}
check(cycle[0], sum /= 2);
} else {
long double l = -1e6, r = 1e6;
for (int i = 0; i < 60; i++) {
long double m1 = l + (r - l) / 2.1;
long double m2 = r - (r - l) / 2.1;
if (check(u, m1) < check(u, m2)) {
r = m2;
} else {
l = m1;
}
}
check(u, (l + r) / 2);
}
}
int main() {
cout << fixed << setprecision(9);
cin.tie(nullptr)->sync_with_stdio(false);
int N, M;
cin >> N >> M;
for (int i = 0; i < M; i++) {
int a, b, c;
cin >> a >> b >> c;
a--, b--;
G[a].push_back(pair {b, c});
G[b].push_back(pair {a, c});
}
memset(color, -1, sizeof color);
for (int i = 0; i < N; i++) {
if (color[i] == -1) {
comp = vector<int>();
color[i] = 0;
DFS(i);
solve(i);
}
}
cout << "YES\n";
for (int i = 0; i < N; i++) {
cout << A[i] << " \n"[i + 1 == N];
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |