Tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 530 Accepted Submission(s): 337
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.
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.
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
1 0 1
题意:
给你一个图,途中有n个结点,在给你k种颜色,要你对结点染色,每个结点对应一个集合,这个集合的值为连接所有被颜色i染色的结点的最小边的集合,
问每个结点所对应的集合的最大交集
题解:
题目实在很难读懂,把题目提取一下,就是求满足在一条边的两端(将树分成两部分),结点数均大于k(包含自身)的这种边的条数
一开始我使用stack和queue来写的们也是用vector但是一直超时,说实话这种递归我很难想到
,很巧妙
#include<iostream>
#include<cstring>
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
const int inf = 2e5+5;
int n,k;
int sum[inf];
int ans=0;
vector<int>s[inf];
void dfs(int u,int pre)
{
sum[u]=1;
int i;
for(i=0;i<s[u].size();i++){
if(s[u][i]!=pre){
dfs(s[u][i],u);
sum[u]+=sum[s[u][i]];
}
}
if(sum[u]>=k&&n-sum[u]>=k)
ans++;
}
int main()
{
int i;
int num;
scanf(“%d”,&num);
while(num–){
ans=0;
memset(sum,0,sizeof(sum));
scanf(“%d %d”,&n,&k);
//建立邻接表
for(i=0;i<n-1;i++){
int st,ed;
scanf(“%d %d”,&st,&ed);
s[st].push_back(ed);
s[ed].push_back(st);
}
dfs(1,-1);
printf(“%d\n”,ans);
for(i=1;i<=n;i++) s[i].clear();
}
return 0;
}