国庆出游

代码链接:https://hihocoder.com/problemset/problem/1041
参考链接:

  1. http://blog.csdn.net/u010535824/article/details/40652865
  2. http://blog.csdn.net/u013076044/article/details/45795939

思路:
(1)从根节点开始利用bitset求出每个节点的所有子孙节点;
(2)对于长度为total的目标序列seq,从根节点开始深搜。

  • 若当前节点等于seq[cur_index],则++cur_index;
  • 若cur_index==total,置ok=1,返回;
  • 当cur_index小于total时,对当前节点的每一个满足条件的子孙节点进行深搜(条件:该子节点可达seq[cur_index]&&未曾访问);
  • 若深搜后cur_index大小未变说明没有可达序列,函数返回。
#include
#include
#include
#include 
#include 
using namespace std;
const int limited = 101;
vector<int> u[limited];
vector<int> seq(limited,0);
int no_visited[limited][limited];
bitset reach[limited];
int ok = 0, total = 0,cur_index=0;
void can_reach(int v) {
    reach[v][v] = 1;
    for (int i = 0;i < u[v].size();++i) {
        int child = u[v][i];
        can_reach(child);
        reach[v] |= reach[child];
    }
}
int judge(int v) {
    if (v == seq[cur_index])
        ++cur_index;
    if (cur_index >= total) {
        ok = 1;
        return 0;
    }
    while (cur_index < total) {
        int mark = cur_index,c=seq[cur_index];
        for (int i = 0;i < u[v].size();++i) {
            int node = u[v][i];
            if (reach[node][c] && no_visited[v][node]) {
                no_visited[v][node] = 0;
                judge(node);
            }
        }
        if (mark == cur_index)
            return 1;
    }
}
int main() {
    int test = 0;
    scanf("%d", &test);
    memset(no_visited, 0, sizeof(no_visited));
    while (test--) {
        ok = 0;cur_index = 0;
        for (int i = 0;i < limited;++i) {
            u[i].clear();
            reach[i].reset();
        }
        int n,f,c;
        scanf("%d", &n);
        for (int i = 1;i < n;++i) {
            scanf("%d%d", &f, &c);
            u[f].push_back(c);
            no_visited[f][c] = 1;
        }
        scanf("%d", &total);
        for (int i = 0;i < total;++i)
            scanf("%d", &seq[i]);
        can_reach(1);
        judge(1);
        printf("%s\n", ok == 1 ? "YES" : "NO");
    }
    return 0;
}

你可能感兴趣的:(hiho刷题日记,bitset,算法)