2017 ACM/ICPC 沈阳 L题 Tree
Consider a un-rooted tree T which is not the biological significance of tree or plant, but a tree as an undirected graph in graph theory with n nodes, labelled from 1 to n. If you cannot understand the concept of a tree here, please omit this problem.
Now we decide to colour its nodes with k distinct colours, labelled from 1 to k. Then for each colour i = 1, 2, · · · , k, define Ei as the minimum subset of edges connecting all nodes coloured by i. If there is no node of the tree coloured by a specified colour i, Ei will be empty.
Try to decide a colour scheme to maximize the size of E1 ∩ E2 · · · ∩ Ek, and output its size.
Now we decide to colour its nodes with k distinct colours, labelled from 1 to k. Then for each colour i = 1, 2, · · · , k, define Ei as the minimum subset of edges connecting all nodes coloured by i. If there is no node of the tree coloured by a specified colour i, Ei will be empty.
Try to decide a colour scheme to maximize the size of E1 ∩ E2 · · · ∩ Ek, and output its size.
InputThe first line of input contains an integer T (1 ≤ T ≤ 1000), indicating the total number of test cases.
For each case, the first line contains two positive integers n which is the size of the tree and k (k ≤ 500) which is the number of colours. Each of the following n - 1 lines contains two integers x and y describing an edge between them. We are sure that the given graph is a tree.
The summation of n in input is smaller than or equal to 200000.
OutputFor each test case, output the maximum size of E1 ∩ E1 ... ∩ Ek.Sample Input
3 4 2 1 2 2 3 3 4 4 2 1 2 1 3 1 4 6 3 1 2 2 3 3 4 3 5 6 2
Sample Output
1 0 1
题解:考虑某条边,则只要两边的2个顶点都大于等于k,则连边时一定会经过这条边,ans++;
参看代码:

1 #include<bits/stdc++.h> 2 using namespace std; 3 #define clr(a,b,n) memset((a),(b),sizeof(int)*n) 4 typedef long long ll; 5 const int maxn = 2e5+10; 6 int n,k,ans,num[maxn]; 7 vector<int> vec[maxn]; 8 9 void dfs(int u,int fa) 10 { 11 num[u]=1; 12 for(int i=0;i<vec[u].size();i++) 13 { 14 int v=vec[u][i]; 15 if(v==fa) continue; 16 dfs(v,u); 17 num[u]+=num[v]; 18 if(num[v]>=k&&n-num[v]>=k) ans++; 19 } 20 } 21 22 int main() 23 { 24 int T,u,v; 25 scanf("%d",&T); 26 while(T--) 27 { 28 scanf("%d%d",&n,&k); 29 clr(num,0,n+1); ans=0; 30 for(int i=1;i<=n;i++) vec[i].clear(); 31 for(int i=1;i<n;i++) 32 { 33 scanf("%d%d",&u,&v); 34 vec[u].push_back(v); 35 vec[v].push_back(u); 36 } 37 dfs(1,-1); 38 //for(int i=1;i<=n;++i) cout<<num[i]<<endl; 39 printf("%d\n",ans); 40 } 41 return 0; 42 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· C# 13 中的新增功能实操
· Supergateway:MCP服务器的远程调试与集成工具
· Vue3封装支持Base64导出的电子签名组件