Pagini recente » Cod sursa (job #2780408) | Cod sursa (job #2517699) | Cod sursa (job #1615304) | Cod sursa (job #2182894) | Cod sursa (job #634003)
Cod sursa(job #634003)
#include <cstring>
#include <fstream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
const int INF = 0x3f3f3f3f;
const int SIZE = 200002;
typedef vector<int> VI;
int N, result;
VI V[SIZE], Term[SIZE], aux;
int val[SIZE], P[SIZE], pos[SIZE], pose[SIZE], where[SIZE], pnow;
int up[SIZE], down[SIZE];
bool S[SIZE];
class set_compare
{
public:
bool operator () (const int& i1, const int& i2)
{
return i1 < i2;
}
};
set<int, set_compare> Set;
inline bool compare(const int& i1, const int& i2)
{
return val[i1] < val[i2];
}
inline bool compare_euler(const int& i1, const int& i2)
{
return pos[i1] < pos[i2];
}
void compM(int x)
{
S[x] = true;
pos[x] = ++pnow;
set<int, set_compare>::iterator Aval = Set.lower_bound(val[x]);
int value = P[(Aval == Set.end() ? 0 : *Aval)];
where[x] = value;
if (value != 0) Term[value].push_back(x);
Set.insert(val[x]);
for (VI::iterator it = V[x].begin(); it != V[x].end(); ++it)
if (!S[*it])
compM(*it);
Set.erase(Set.find(val[x]));
pose[x] = ++pnow;
}
void dfsUp(int x)
{
S[x] = true;
if (where[x] != 0)
up[x] = up[where[x]] + 1;
for (VI::iterator it = V[x].begin(); it != V[x].end(); ++it)
if (!S[*it])
dfsUp(*it);
}
void dfsDown(int x)
{
S[x] = true;
for (VI::iterator it = V[x].begin(); it != V[x].end(); ++it)
if (!S[*it])
dfsDown(*it);
sort(Term[x].begin(), Term[x].end(), compare_euler);
sort(V[x].begin(), V[x].end(), compare_euler);
down[x] = 1;
VI::iterator aux = Term[x].begin();
for (VI::iterator it = V[x].begin(); it != V[x].end(); ++it)
if (pos[*it] >= pos[x])
{
int maxnow = 0;
while (aux != Term[x].end() && pos[*aux] >= pos[*it] && pose[*aux] <= pose[*it])
{
maxnow = max(maxnow, down[*aux]);
++aux;
}
down[x] += maxnow;
}
}
int main()
{
ifstream fin("guvern.in");
ofstream fout("guvern.out");
fin >> N;
for (int i = 1, nod1, nod2; i < N; ++i)
{
fin >> nod1 >> nod2;
V[nod1].push_back(nod2);
V[nod2].push_back(nod1);
}
for (int i = 1; i <= N; ++i)
{
fin >> val[i];
P[i] = i;
}
// I. Normalizare + realizarea muchiilor obligatorii + euler
sort(P + 1, P + N + 1, compare);
for (int i = 1; i <= N; ++i)
val[P[i]] = i;
compM(1);
/* verificare
for (int i = 1; i <= N; ++i) fout << where[i] << '\n';
*/
// II. Dfs - construirea up[x]
memset(S, 0, sizeof(S));
dfsUp(1);
/* verificare
for (int i = 1; i <= N; ++i) fout << up[i] << ' ';
*/
// III. Dfs - construirea down[x]
memset(S, 0, sizeof(S));
dfsDown(1);
// IV. Result
for (int i = 1; i <= N; ++i)
result = max(result, down[i] + up[i]);
fout << result << '\n';
fin.close();
fout.close();
}