Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

BFS无限跪,改成DFS就1A了,这是什么原理……

Posted by ccxx2c2 at 2017-04-02 19:14:25 on Problem 1694
跪掉的BFS:
#include<cstdio>
#include<cstring>
#include<algorithm>
struct NODE{
    int fa,sons,cnts;
    int pp;
    int peak[256];
}node[256];
NODE q[256];
bool cmp(int a,int b)
{
    return a>b;
}
int main(){
    int ans=0;
    int m,n,qh,qe;
    for(scanf("%d",&m);m;m--){
        scanf("%d",&n);
        qh=qe=0;
        ans=0;
        memset(node,0,sizeof(node));
        memset(q,0,sizeof(q));
        for(int i=0;i<n;i++)
        {
            int p,r,son;
            scanf("%d %d",&p,&r);
            node[p].sons=r;
            if(!r){node[p].pp=1;q[qe]=node[p];qe++;}
            for(int j=0;j<r;j++){
                scanf("%d",&son);
                node[son].fa=p;
            }
        }
        while(qh<qe){            
            for(int i=0;i<q[qh].cnts;i++)
                q[qh].pp=q[qh].pp>(q[qh].peak[i]+i)?q[qh].pp:(q[qh].peak[i]+i);
            if(q[qh].pp>ans)ans=q[qh].pp;
            
            node[q[qh].fa].peak[node[q[qh].fa].cnts]=q[qh].pp;
            node[q[qh].fa].cnts++;
            if(node[q[qh].fa].cnts==node[q[qh].fa].sons){
                std::sort(node[q[qh].fa].peak,node[q[qh].fa].peak+node[q[qh].fa].sons,cmp);
                q[qe]=node[q[qh].fa];
                qe++;
            }
            qh++;
        }
        printf("%d\n",ans);
    }
    return 0;
}
起来的DFS:
#include<cstdio>
#include<cstring>
#include<algorithm>
struct NODE{
    int fa,cnt;
    int pp;
    int sons[1024];
}node[1024];
NODE q[1024];
bool cmp(int a,int b)
{
    return a>b;
}
int dfs(int a){
    if(node[a].cnt==0) return 1;
    int peak[1024];
    int ret=0;
    for(int j=0;j<node[a].cnt;j++)
        peak[j]=dfs(node[a].sons[j]);
    std::sort(peak,peak+node[a].cnt,cmp);
    for(int j=0;j<node[a].cnt;j++)
        if(ret<peak[j]+j)ret=peak[j]+j;
    return ret;
}
int main(){
    int ans=0;
    int m,n,qh,qe;
    for(scanf("%d",&m);m;m--){
        scanf("%d",&n);
        qh=qe=0;
        ans=0;
        memset(node,0,sizeof(node));
        memset(q,0,sizeof(q));
        
        for(int i=0;i<n;i++)
        {
            int p,r,son;
            scanf("%d%d",&p,&r);
            node[p].cnt=r;
            for(int j=0;j<r;j++){
                scanf("%d",&node[p].sons[j]);
            }
        }
        
        printf("%d\n",dfs(1));
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator