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;
#define int long long
/***
N equations and M unknowns - can only have a unique solution if M <= N
Since M >= N - 1 =>
* the graph is a tree, in wich case we can solve the problem
* the graph is a tree with a simple cycle (N edges). Solve the problem for leafs and solve from a cycle
Solve for a cycle:
* even length: multiple solution (for each node do +1 on one edge and -1 on the other)
* odd length: unique solution, do some math stuff and deduce first edge
N = the number of nodes that are left are the process
sum(1) = W(n, 1) + W(1, 2)
sum(2) = W(1, 2) + W(2, 3)
sum(1) = W(n, 1) + sum(2) - W(2, 3)
sum(1) = W(n, 1) + sum(2) - sum(3) + sum(4) - ... - sum(N) + W(n, 1)
2 * W(n, 1) = sum(1) - sum(2) + sum(3) - sum(4) + .... + sum(N)
***/
const int MAXN = 1000 * 100;
int n, m;
set<int> g[MAXN + 1];
pair<int, int> edges[MAXN + 1];
map<pair<int, int>, int> edgeId;
int weight[MAXN + 1], sum[MAXN + 1];
bool visited[MAXN + 1];
vector<int> cycle;
void dfs(int u, int dad = -1) {
visited[u] = true;
cycle.push_back(u);
for (const int &v : g[u]) {
if (v == dad || visited[v]) {
continue;
}
dfs(v, u);
}
}
signed main() {
cin >> n >> m;
if (m > n) {
cout << "0\n";
return 0;
}
for (int i = 1; i <= n; i++) {
cin >> sum[i];
}
for (int i = 0; i < m; i++) {
int u, v; cin >> u >> v;
edgeId[make_pair(u, v)] = edgeId[make_pair(v, u)] = i;
g[u].insert(v);
g[v].insert(u);
}
queue<int> q;
for (int i = 1; i <= n; i++) {
if ((int)g[i].size() == 1) {
q.push(i);
}
}
while (!q.empty()) {
int u = q.front();
q.pop();
if ((int)g[u].size() > 0) {
int v = *g[u].begin();
int id = edgeId[make_pair(u, v)];
weight[id] = sum[u];
sum[v] -= weight[id];
g[u].erase(v);
g[v].erase(u);
if ((int)g[v].size() == 1) {
q.push(v);
}
}
}
for (int i = 1; i <= n; i++) {
if ((int)g[i].size() > 0) {
dfs(i);
break;
}
}
if ((int)cycle.size() > 0 && (int)cycle.size() % 2 == 0) {
cout << "0\n";
return 0;
}
if ((int)cycle.size() > 0) {
int s = 0;
for (int i = 0; i < (int)cycle.size(); i++) {
if (i % 2 == 0) {
s += sum[cycle[i]];
} else {
s -= sum[cycle[i]];
}
}
int id = edgeId[make_pair(cycle[0], cycle.back())];
weight[id] = s / 2;
g[cycle[0]].erase(cycle.back());
g[cycle.back()].erase(cycle[0]);
sum[cycle[0]] -= weight[id];
sum[cycle.back()] -= weight[id];
q.push(cycle[0]);
// q.push(cycle.back());
while (!q.empty()) {
int u = q.front();
q.pop();
int v = *g[u].begin();
int id = edgeId[make_pair(u, v)];
weight[id] = sum[u];
sum[v] -= weight[id];
g[u].erase(v);
g[v].erase(u);
if ((int)g[v].size() == 1) {
q.push(v);
}
}
}
for (int i = 0; i < m; i++) {
cout << 2 * weight[i] << " ";
}
cout << "\n";
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |