hdu4707 Pet 2013 ACM/ICPC Asia Regional Online —— Warmup

One day, Lin Ji wake up in the morning and found that his pethamster escaped. He searched in the room but didn’t find the hamster. He tried to use some cheese to trap the hamster. He put the cheese trap in his room and waited for three days. Nothing but cockroaches was caught. He got the map of the school and foundthat there is no cyclic path and every location in the school can be reached from his room. The trap’s manual mention that the pet will always come back if it still in somewhere nearer than distance D. Your task is to help Lin Ji to find out how many possible locations the hamster may found given the map of the school. Assume that the hamster is still hiding in somewhere in the school and distance between each adjacent locations is always one distance unit.
题意:说的是Lin Ji丢失了一个宠物,他在房间放了一些cheess陷阱等了3天都没有抓到。现在他拿到了一份学校地图,有n个房间,n-1条边,从0开始,也就是Lin Ji的房间号。还给你一个distance D,表示最远能抓到宠物的距离。现在问有多少个宠物可能在的地方。(在小于D的距离内,宠物是会跑回来陷入陷阱的)。
题解:看题意可知宠物一定是在比D大的地方,也就是到0房间的距离大于D。统计个数就可以了。最开始想的是求单源的最短路径,然后统计路径大于D的个数,发现bellman,SPFA什么的都是TLE..- -.. 换了n个建图的方式。。然后我重写,直接定义一个全部为0的数组,输入x,y表示x到y是可达的,我就将a[y]=a[x]+1,表示x到y的距离是a[x]的值加1。并且同时统计大于D的个数。(再开一个for循环统计个数也是会TLE的。。)
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<queue>
#define maxn 100005
using namespace std;
int a[maxn];
int main()
{
    int T,n,d,ans;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&d);
        ans=0;
        memset(a,0,sizeof(a));
        for(int i=0;i<n-1;i++)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            a[y]=a[x]+1;
            if(a[y]>d||a[x]>d)
                ans++;
        }
        printf("%d\n",ans);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章