时间限制:
1000ms
单点时限:
1000ms
内存限制:
256MB
-
2 7 1 2 1 3 2 4 2 5 3 6 3 7 3 3 7 2 7 1 2 1 3 2 4 2 5 3 6 3 7 3 3 2 7
样例输出
-
YES NO
描述
小Hi和小Ho准备国庆期间去A国旅游。A国的城际交通比较有特色:它共有n座城市(编号1-n);城市之间恰好有n-1条公路相连,形成一个树形公路网。小Hi计划从A国首都(1号城市)出发,自驾遍历所有城市,并且经过每一条公路恰好两次——来回各一次——这样公路两旁的景色都不会错过。
令小Hi苦恼的是他的小伙伴小Ho希望能以某种特定的顺序游历其中m个城市。例如按3-2-5的顺序游历这3座城市。(具体来讲是要求:第一次到达3号城市比第一次到达2号城市早,并且第一次到达2号城市比第一次到达5号城市早)。
小Hi想知道是否有一种自驾顺序满足小Ho的要求。
输入
输入第一行是一个整数T(1<=T<=20),代表测试数据的数量。
每组数据第一行是一个整数n(1 <= n <= 100),代表城市数目。
之后n-1行每行两个整数a和b (1 <= a, b <= n),表示ab之间有公路相连。
之后一行包含一个整数m (1 <= m <= n)
最后一行包含m个整数,表示小Ho希望的游历顺序。
输出
YES或者NO,表示是否有一种自驾顺序满足小Ho的要求。
看似简单的一题,但姿势不好很容易T
用了STL中的bitset,发现很好用。
一个发现:只要搜出规定顺序的路径即可,不必搜所有。
代码,参考了cxlove比赛提交的代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <functional>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
//typedef pair<int,int> pii;
#define INF 1e9
#define MAXN 10000
#define MAXM 100
const int maxn = 105;
const int mod = 1000003;
#define eps 1e-6
#define pi 3.1415926535897932384626433
#define rep(i,n) for(int i=0;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define scan(n) scanf("%d",&n)
#define scan2(n,m) scanf("%d%d",&n,&m)
#define scans(s) scanf("%s",s);
#define ini(a) memset(a,0,sizeof(a))
#define FILL(a,n) fill(a,a+maxn,n)
#define out(n) printf("%d\n",n)
//ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b);}
#define mk(n,m) make_pair(n,m)
using namespace std;
vector<int> G[maxn];
bitset<maxn> f[maxn]; //学会了bitset的用法,发现很好用
bool cango[maxn][maxn];
int a[maxn];
int n,m;
int now;
void dfs(int u,int fa)
{
f[u][u] = 1;
rep(i,(int)G[u].size())
{
int v = G[u][i];
if(v == fa) continue;
dfs(v,u);
f[u] |= f[v];
}
}
int c;
bool ok;
void solve(int u,int fa)
{
if(c < m && a[c] == u ) c++;
if(c == m) {
ok = 1;
return;
}
while(c < m){ //这个看似没用的循环很重要,充分利用了递归的性质
int nex = a[c];
int cur = c;
rep(i,(int)G[u].size())
{
int v = G[u][i];
if(v == fa) continue;
if(f[v][nex] && cango[u][v])
{
cango[u][v] = 0;
solve(v,u);
break;
}
}
if(c == cur) break; //表示以该节点为根的子树不存在目标点,跳出循环,(然后返回递归上一层)
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
#endif
int T;
cin>>T;
while(T--)
{
cin>>n;
ini(cango);
rep1(i,n)
{
f[i].reset();
G[i].clear();
}
rep(i,n-1)
{
int u,v;
scan2(u,v);
G[u].push_back(v);
G[v].push_back(u);
cango[u][v] = cango[v][u] = 1;
}
cin>>m;
rep(i,m) scan(a[i]);
dfs(1,-1);
c = 0;
ok = 0;
solve(1,-1);
if(ok) puts("YES");
else puts("NO");
}
return 0;
}