HDU 4707 Pet(搜索+乱搞,两种做法)

来源:互联网 发布:招商银行数据分析 编辑:程序博客网 时间:2024/04/30 19:53

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4707

题意要求寻找所有距离家(也就是位置0)大于d的场所(location)个数。

看到题第一反应就是到搜索题,A了之后才知道队友是乱搞做出来的,表示佩服= =、

一、搜索法(这里采用了DFS,当然BFS也可以)

首先构造一棵树,以0点作为树的父亲节点(树的第1层),将所有大于d层的节点数取和得出结果。

代码没用到STL,写的比较水。

#include<cstdio>#include<iostream>#include<cstring>using namespace std;int n,d,x,y;int ans,num;int b[100010];struct tree{    int to;//下一个点的名称    int find;//寻找该节点的其他路    int step;//所在树的层数}a[100010];void dfs(int x,int step){    if(b[x]!=-1)    for(int i=b[x];i!=0;i=a[i].find)//遍历路    {        a[i].step=step;        if(a[i].step>=d)        ans++;        dfs(a[i].to,step+1);    }}int main(){    int T;    while(~scanf("%d",&T))    {        while(T--)        {            memset(a,0,sizeof(a));            memset(b,0,sizeof(b));            ans=0,num=0;            scanf("%d%d",&n,&d);            for(int i=1;i<n;i++)            {                scanf("%d%d",&x,&y);                a[i].to=y;                a[i].find=b[x];                b[x]=i;            }            dfs(0,0);            printf("%d\n",ans);        }    }    return 0;}

二、乱搞

用一个一维数组a[]。a[i]表示走到i位置所需的step数,若大于d,则给计数器+1。

因为此题题目要求位置的编号都是小于n的,所以最后统计时可以遍历一次0~n-1的所有位置;

又因为此题所构造的路线中不会有任何的环,所以此题用如下方法可解。。

以下为队友代码:

#include<iostream>#include<string.h>#include<cstdio>using namespace std;int a[100005];int main(){    int t;    cin>>t;    while(t--)    {        int n,k,p,q;        cin>>n>>k;        a[0]=0;        memset(a,0,sizeof(a));        for(int i=0;i<n-1;i++)        {            scanf("%d%d",&p,&q);            a[q]=a[p]+1;        }        int count=0;        for(int i=0;i<n;i++)            if(a[i]>k)                count++;        cout<<count<<endl;    }    return 0;}




0 0