Pagini recente » Borderou de evaluare (job #2342692) | Monitorul de evaluare | Cod sursa (job #548469) | Cod sursa (job #452907) | Cod sursa (job #3302655)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("cerere.in");
ofstream fout("cerere.out");
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2")
const int MAXN = 100005;
const int BUFSIZE = 16384;
int n, step[MAXN], output[MAXN], parent[MAXN], stack1[MAXN], depth;
vector<int> children[MAXN];
// Input buffer
char buf[BUFSIZE], outBuf[BUFSIZE + 10];
int bufPos = 0, outPos = 0;
inline void advance() {
if (++bufPos == BUFSIZE)
fin.read(buf, BUFSIZE), bufPos = 0;
}
inline void readInt(int &x) {
x = 0;
while (!isdigit(buf[bufPos])) advance();
while (isdigit(buf[bufPos])) x = x * 10 + buf[bufPos] - '0', advance();
}
inline void writeInt(int x) {
if (x == 0) outBuf[outPos++] = '0';
else {
int start = outPos;
while (x) outBuf[outPos++] = x % 10 + '0', x /= 10;
reverse(outBuf + start, outBuf + outPos);
}
outBuf[outPos++] = ' ';
if (outPos >= BUFSIZE) fout.write(outBuf, outPos), outPos = 0;
}
// DFS that computes result for each node
inline void process(int node) {
stack1[++depth] = node;
if (step[node])
output[node] = output[stack1[depth - step[node]]] + 1;
for (int child : children[node])
process(child);
--depth;
}
int main() {
fin.read(buf, BUFSIZE);
readInt(n);
for (int i = 1; i <= n; ++i)
readInt(step[i]);
for (int i = 1; i < n; ++i) {
int u, v;
readInt(u), readInt(v);
children[u].push_back(v);
parent[v] = u;
}
int root = 1;
while (parent[root]) ++root;
process(root);
for (int i = 1; i <= n; ++i)
writeInt(output[i]);
fout.write(outBuf, outPos);
return 0;
}