版权声明:原创文章,转载要注明作者哦 https://blog.csdn.net/DYT_B/article/details/81489655
题目描述:戳这里
题解:
树上贪心。对于每一个路径,肯定是一个折线型的。那么我们找出两个端点的lca,然后按lca的深度排序,从深到浅,能加入就加入,否则就不加入。
证明可以口胡一下:我们会发现如果这个路径能加却不加,而是加一个深度更浅的路径,那么肯定肯定会使后面的点的限制更加紧,后面能加的路径更少,所以必然更加不优秀。
那么代码如下:
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100005;
int n,m,tot,ans,lnk[maxn],son[2*maxn],nxt[2*maxn],dep[maxn],f[maxn][21];
bool vis[maxn];
struct dyt{
int x,y,z;
bool operator <(const dyt &b) const{return dep[z]>dep[b.z];}
}a[maxn];
void add(int x,int y){
son[++tot]=y,nxt[tot]=lnk[x],lnk[x]=tot;
}
void dfs(int x){
for (int j=lnk[x];j;j=nxt[j])
if (!dep[son[j]]) {
dep[son[j]]=dep[x]+1; f[son[j]][0]=x; dfs(son[j]);
}
}
void make_(){
for (int j=1;j<=20;j++)
for (int i=1;i<=n;i++)
f[i][j]=f[f[i][j-1]][j-1];
}
int lca(int x,int y){
if (dep[x]<dep[y]) swap(x,y);
for (int j=20;j>=0;j--)
if (dep[f[x][j]]>=dep[y]) x=f[x][j];
if (x==y) return y;
for (int j=20;j>=0;j--)
if (f[x][j]!=f[y][j]) x=f[x][j],y=f[y][j];
return f[x][0];
}
void make_(int p){
int grand=a[p].z,x=a[p].x,y=a[p].y;
while (x!=grand) {if (vis[x]) return; x=f[x][0];}
while (y!=grand) {if (vis[y]) return; y=f[y][0];}
if (vis[grand]) return;
x=a[p].x,y=a[p].y; ans++;
while (x!=grand) {vis[x]=1; x=f[x][0];}
while (y!=grand) {vis[y]=1; y=f[y][0];}
vis[grand]=1;
}
int main(){
while (~scanf("%d %d",&n,&m)){
tot=ans=0;
memset(lnk,0,sizeof(lnk));
memset(f,0,sizeof(f));
memset(vis,0,sizeof(vis));
memset(dep,0,sizeof(dep));
for (int i=1;i<n;i++) {
int x,y; scanf("%d %d",&x,&y);
add(x,y); add(y,x);
}
dep[1]=1; dfs(1); make_();
for (int i=1;i<=m;i++) {
scanf("%d %d",&a[i].x,&a[i].y);
a[i].z=lca(a[i].x,a[i].y);
}
sort(a+1,a+1+m);
for (int i=1;i<=m;i++) make_(i);
printf("%d\n",ans);
}
return 0;
}