题解 P3942 【将军令】
___new2zy___ · · 题解
题解 P3942
【将军令】
题面翻译:
给你一个图,共有1~n个点,编号分别为1~n,告诉你第ui个点与第vi个点有一条长度为1的边,每个小队(可以放在任意点上)最多有k的覆盖长度,问最多要放置多少个小队才能把整张图全部覆盖?
------------------------我是分隔线----------------------------------------------------------------------------------------------
本题真的是高效率(O^2优化)题目,
本人交了3次,前两次都是90分,其中有两个点数据吓人,
总是TLE,心态大崩。。。。。所以我发现:不加优化会死人的-------------
好了,不多说,直接上代码,自己的做法都写在代码里了233~~~
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
//#include<cstring>
//#include<vector>
//#include<map>
//#include<string>
//#include<stdlib.h>
using namespace std;
typedef long long ll;
const int inf=1e9+7;
inline int read()//拙劣的快读
{
int p=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9'){p=p*10+c-'0';c=getchar();}
return f*p;}
struct Node
{
int p,depth;
}node[100009];//定义节点:顺序p和深度depth
int n,t,k,cnt,next[200020],last[200005],to[200005],vis[100009],ans;
//next[],last[],to[]是链式前向星存边
//vis[]用来判断放置小队后该点能否被控制
bool arrive[100009];//这里优化:在dfs时看该点是否被便历过(便历过就直接跳过,降低时间复杂度)
bool cmp(Node x,Node y)//用于排序(按深度由远及近)
{return x.depth>y.depth;}
inline void add_edge(int u,int t)//链式前向星存边
{
cnt++;
to[cnt]=t;
next[cnt]=last[u];
last[u]=cnt;
}
inline void bfs(int x)//bfs处理出每个节点的深度(便于排序)
{
for(int i=last[x];i;i=next[i])
{
int y=to[i];
if(!node[y].depth)
{node[y].de pth=1+node[x].depth;//更新子节点深度
bfs(y);}
}
}
inline void dfs(int x,int depth)//与下面的check()有关,用来查看放置小队后的影响范围
{
vis[x]=1;
arrive[x]=true;
for(int i=last[x];i;i=next[i])
{
int t=to[i];
if(!arrive[t]&&depth>0)//arrive数组优化
dfs(t,depth-1);
}
arrive[x]=false;
}
inline void check()//开始设置小队位置
{
sort(node+1,node+1+n,cmp);
for(int i=1;i<=n;i++)
if(!vis[node[i].p])//如果还没控制
{
ans++;//放置小队
dfs(node[i].p,k+k);//开始深搜(查看放置小队后的影响)
}
}
int main()
{
n=read(),k=read(),t=read();
for(int i=1;i<n;i++)
{
int ui=read(),vi=read();
add_edge(ui,vi);
add_edge(vi,ui);
node[i].p=i;
}
node[n].p=n;//初始化最远节点(序号为n,深度为1)
node[1].depth=1;
bfs(1);//处理节点深度
check();//求解
printf("%d",ans);
return 0;
}
小提示:别想着抄代码,我可是加了一大堆全角空格哦~~~