判断是否是一个堆,把树构造好遍历一遍就OK了
#include<stdio.h> #include<iostream> #include<stack> #include<queue> #include<math.h> #include<stdlib.h> #include<cstring> #include<algorithm> using namespace std; #define Max(a,b) (a>b?a:b) #define Min(a,b) (a<b?a:b) #define INF 0xfffffff #define maxn 410 int Tree[maxn][maxn], n, flag, Value[maxn], vis[maxn]; void DFS(int k) { vis[k] = 1; for(int i=1; i<=n; i++) { if(Tree[k][i] && !vis[i]) { if(Value[k] <= Value[i]) DFS(i); else flag = 1; } } } int main() { int T, i, a, b; cin >> T; while(T--) { cin >> n; flag = 0; memset(Tree, 0, sizeof(Tree)); memset(vis, 0, sizeof(vis)); for(i=1; i<=n; i++) cin >> Value[i]; for(i=1; i<n; i++) { cin >> a >> b; Tree[a][b] = 1;
Tree[b][a] = 1;//谢谢提醒! } DFS(1); if(flag) printf("No "); else printf("Yes "); } return 0; }