hdu5469 Antonidas(DFS)

来源:互联网 发布:mac 六维空间 编辑:程序博客网 时间:2024/05/16 13:49

思路:直接找到开头的那个结点,然后往子树搜或者父亲结点搜...一个可行的剪枝是如果子树剩下的最大高度小于需要匹配的字符数目的话就肯定没有解了...然后就水过去了...


#include<bits/stdc++.h>using namespace std;const int maxn = 1e4+7;vector<int>e[maxn];int n,tarlen;int dep[maxn],vis[maxn],f[maxn];char s[maxn];char tar[maxn];void dfs(int u,int fa){    int d = 0;//    dep[u]=d;    f[u]=fa;    for(int i = 0;i<e[u].size();i++)    {        int v = e[u][i];        if(v!=fa)        {                dfs(v,u);            d = max(d,dep[v]);        }    }    dep[u]=d+1;}bool dfs1(int now,int len){    vis[now]=1;    if(len==tarlen)        return true;    for(int i = 0;i<e[now].size();i++)    {        int v = e[now][i];        if(!vis[v] && f[now]!=v && s[v]==tar[len] && (tarlen-len<=dep[v]))            if(dfs1(v,len+1))return true;    }    int fa = f[now];    if(!vis[fa] && s[fa]==tar[len])        if (dfs1(fa,len+1))return true;    return false;}int main(){    int T,cas=1;    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        for(int i= 0;i<=n;i++)            e[i].clear();        memset(dep,0,sizeof(dep));        for(int i = 1;i<=n-1;i++)        {            int u,v;            scanf("%d%d",&u,&v);            e[u].push_back(v);            e[v].push_back(u);        }        dfs(1,0);        scanf("%s",s+1);        scanf("%s",tar);        tarlen = strlen(tar);        bool flag = false;        for(int i = 1;i<=n;i++)        {            if(s[i]==tar[0])            {                memset(vis,0,sizeof(vis));                flag = dfs1(i,1);                if(flag)                    break;            }        }        printf("Case #%d: ",cas++);        if(flag)            printf("Find\n");        else            printf("Impossible\n");    }}


Problem Description
Given a tree with N vertices and N1 edges. Each vertex has a single letter Ci. Given a string S, you are to choose two vertices A and B, and make sure the letters catenated on the shortest path from A to B is exactly S. Now, would you mind telling me whether the path exists?
 

Input
The first line is an integer T, the number of test cases.
For each case, the first line is an integer N. Following N1 lines contains two integers a and b, meaning there is an edge connect vertex a and vertex b.
Next line contains a string C, the length of C is exactly N. String C represents the letter on each vertex.
Next line contains a string S.
1T2001N1041a,bNab|C|=N1|S|104. String C and S both only contain lower case letters.
 

Output
First, please output "Case #k: ", k is the number of test case. See sample output for more detail.
If the path exists, please output “Find”. Otherwise, please output “Impossible”.
 

Sample Input
271 22 32 41 55 66 7abcdefgdbaefg51 22 32 44 5abcxyyxbac
 

Sample Output
Case #1: FindCase #2: Impossible
 

Source
2015 ACM/ICPC Asia Regional Shanghai Online
 

0 0