時間限制: 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;
}