[Luogu 3128] USACO15DEC Max Flow
最近跟 LCA 干上了…
树剖好啊,我再也不想写倍增了。
以及似乎成功转成了空格选手 qwq。
对于每两个点 S and T,求一下 LCA 顺便树上差分,最后求差分数组的前缀和并找出最大值输出就行了。
(PS:最近考前训练不开 C++11,所以如果看见我写了奇怪的 define 请自动无视QAQ!)
#include <algorithm>
#include <cstdio>
#define nullptr NULL
const int MAXN = 50010;
int n, m;
namespace HLD
{
int num, qwq[MAXN];
struct Node
{
int depth, father, son, top, size, DFN;
}s[MAXN];
class Graph
{
private:
struct Edge
{
int to;
Edge *next;
Edge(int to, Edge* next): to(to), next(next) {}
~Edge(void)
{
if(next != nullptr)
delete next;
}
}*head[MAXN];
void AddEdges(int u, int v)
{
head[u] = new Edge(v, head[u]);
head[v] = new Edge(u, head[v]);
}
void DFS1(int u, int k)
{
s[u].depth = k;
s[u].size = 1;
int v;
for(Edge *i = head[u]; i != nullptr; i = i -> next)
if(!s[v = i -> to].size)
{
DFS1(v, k + 1);
s[u].size += s[v].size;
s[v].father = u;
if(s[v].size > s[s[u].son].size)
s[u].son = v;
}
}
void DFS2(int u, int top)
{
s[u].top = top;
s[u].DFN = ++num;
if(s[u].son)
DFS2(s[u].son, top);
int v;
for(Edge *i = head[u]; i != nullptr; i = i -> next)
if(!s[v = i -> to].top)
DFS2(v, v);
}
void Modify(int x, int y)
{
++qwq[s[x].DFN];
--qwq[s[y].DFN + 1];
}
public:
Graph(int n)
{
std :: fill(head + 1, head + n + 1, (Edge*)nullptr);
for(int i = 1, x, y; i < n; ++i)
{
scanf("%d %d", &x, &y);
AddEdges(x, y);
}
DFS1(1, 1);
DFS2(1, 1);
}
~Graph(void)
{
for(int i = 1; i <= n; ++i)
delete head[i];
}
void Run(int x, int y)
{
int a, b;
while((a = s[x].top) ^ (b = s[y].top))
if(s[a].depth > s[b].depth)
{
Modify(a, x);
x = s[a].father;
}
else
{
Modify(b, y);
y = s[b].father;
}
if(s[x].depth < s[y].depth)
Modify(x, y);
else
Modify(y, x);
}
int Answer(void)
{
int ans = qwq[1];
for(int i = 2; i <= n; ++i)
ans = std :: max(ans, qwq[i] += qwq[i-1]);
return ans;
}
}*G;
}
int main(void)
{
scanf("%d %d", &n, &m);
HLD :: G = new HLD :: Graph(n);
for(int i = 1, x, y; i <= m; ++i)
{
scanf("%d %d", &x, &y);
HLD :: G -> Run(x, y);
}
printf("%d
", HLD :: G -> Answer());
return 0;
}
谢谢阅读。