Dominos 2(dfs)

描述

Dominos are lots of fun. Children like to stand the tiles on their side in long lines. When one domino falls, it knocks down the next one, which knocks down the one after that, all the way down the line. However, sometimes a domino fails to knock the next one down. In that case, we have to knock it down by hand to get the dominos falling again.

Given a set of dominos that are knocked down by hand, your task is to determine the total number of dominos that fall.

输入

The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing three integers n, m, l no larger than 10 000, followed by m+l additional lines. The first integer n is the number of domino tiles. The domino tiles are numbered from 1 to n. Each of the m lines after the first line contains two integers x and y indicating that if domino number x falls, it will cause domino number y to fall as well. Each of the following l lines contains a single integer z indicating that the domino numbered z is knocked over by hand.

输出

For each test case, output a line containing one integer, the total number of dominos that fall over.

样例输入

1
3 2 1
1 2
2 3
2

样例输出

2

题意

多米诺骨牌,每次推倒一张牌,问你最后总共推倒几张牌
没看清题意就写了…以为每次推牌就输出推倒了几张牌,还需要注意连着推牌的时候是叠加在上一次操作上的…
用vector储存能直接影响的牌,并用vis数组标记这个牌有没有倒了
dfs搜索一下就可以了

#include 
using namespace std;
const int N=10005;
vector<int>G[N];
int vis[N],fa[N];
int n,m,t,l;
int ss;
int f(int k){
    int flag=0,sum=0;
    if(vis[k]==0){
        sum=1;
        vis[k]=1;
    }

    int num=G[k].size();

    for(int i=0;i<num;i++){
        if(vis[G[k][i]]==0){
            sum+=f(G[k][i]);
        }
    }
    return sum;
}


int main()
{
    int x,y;
    scanf("%d",&t);
    while(t--){
        ss=0;
        memset(vis,0,sizeof(vis));
        scanf("%d%d%d",&n,&m,&l);
        for(int i=0;i<=n;i++) G[i].clear();

        for(int i=1;i<=m;i++){
            scanf("%d%d",&x,&y);
            G[x].push_back(y);
        }
        for(int i=0;i<l;i++){
            scanf("%d",&y);
            ss+=f(y);
        }
        printf("%d\n",ss);
    }
    return 0;
}

你可能感兴趣的:(C++)