简体   繁体   中英

WA in SPOJ SCAVHUNT

I am getting wrong answer in this question although the code works fun on all test cases. Can somebody help with what might my code be missing ?? I am using stl map and simple dfs to print the route as asked in the question.

#include<cstdio>
#include<iostream>
#include<map>
#include<list>
#include<cstring>
#define tr(c,it) for(typeof(c.begin()) it=c.begin();it!=c.end();++it)
using namespace std;
map<int,string> city;
list<int> *adj;
bool *visited;
void dfs(int s) {
    visited[s]=true;
    cout<<city[s]<<endl;
    tr(adj[s],it) {
        if(!visited[*it])
            dfs(*it);
    }
}   
main() {
    int t;
    scanf("%d",&t);
    for(int i=1;i<=t;++i) {
        map<string,int> mymap;
        int n;
        scanf("%d",&n); 
        visited=new bool[n+1];
        memset(visited,false,sizeof(visited));
        adj=new list<int>[n+1];
        int indegree[n+1];
        for(int j=0;j<=n;++j) indegree[j]=0;
        int index=1;
        for(int j=0;j<n-1;++j) {
            string n1,n2;
            cin>>n1>>n2;
            if(!mymap[n1]) {
                mymap[n1]=index++;
                city[index-1]=n1;
            }
            if(!mymap[n2]) {
                mymap[n2]=index++;
                city[index-1]=n2;
            }
            adj[mymap[n1]].push_back(mymap[n2]);
            indegree[mymap[n2]]++;
        }
        int start;
        for(int j=1;j<=n;++j) {
            if(indegree[j]==0) {
                start=j;
                break;
            }
        }
        printf("Scenario #%d:\n",i);
        dfs(start);
        printf("\n");
        city.clear();
    }
    return 0;
}

If I comment out if(!visited[*it]) your code passes all the test cases. Why do you need the visited array anyway? Each adjacency list will have exactly one child, except that last leaf node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM