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;
}


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