E. Gardener and Tree(拓扑)

Gardener and Tree
题意:k次操作,每次删去叶子节点,问最后剩的节点
思路:拓扑,度为1的就是叶子结点

//#pragma GCC optimize(2)
//#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
#define int long long
#define fi first
#define se second
#define pb push_back
#define pii pair<int,int>
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int inf=2e18+100;
const int maxn=4e5+100;
vector<int>g[maxn];
int in[maxn];
bool vis[maxn];
signed main()
{
	IOS
	int tt;
	cin>>tt;
	while(tt--)
	{
		queue<pii>q;
		int n,k;
		cin>>n>>k;
		memset(vis,0,sizeof(bool)*(n+10));
		memset(in,0,sizeof(int)*(n+10));
		for(int i=1;i<=n;i++)g[i].clear();
		for(int i=1;i<n;i++)
		{
			int u,v;
			cin>>u>>v;
			g[u].pb(v);
			g[v].pb(u);
			in[u]++;
			in[v]++;
		}
		if(n==1)
		{
			if(k>=1)cout<<"0"<<"\n";
			else cout<<"1"<<"\n";
			continue;
		}
		for(int i=1;i<=n;i++)
		{
			if(in[i]==1)
			{
				q.push({i,1});
				vis[i]=1;
			}
		}
		while(!q.empty())
		{
			auto now=q.front();
			if(now.se>k)break;
			vis[now.fi]=1;
			q.pop();
			for(auto it:g[now.fi])
			{
				in[it]--;
				if(in[it]==1)
				{
					if(now.se+1<=k)
					{
						q.push({it,now.se+1});
					}
				}
			}
		}
		int ans=0;
		for(int i=1;i<=n;i++)
		{
			if(!vis[i])ans++;
		}
		cout<<ans<<"\n";
	}
}
上一篇:DFS(深度优先搜索)模板


下一篇:(剑指offer)合并两个排序的链表