题目描述
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
一开始有点糊涂,感觉dfs可能超时,就写了并查集,结果发现它不符合对称性,然后又想了想dfs,才知道时间复杂度为O(n+n),这才写了,还真是,唉!分析的能力有待提升
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<cmath>
#include<vector>
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define inf 0x0f0f0f0f
using namespace std;
const int maxn=10000+10;vector<int>tree[maxn];
bool vis[maxn];
int ans;void init(int n)
{
for (int i=0;i<=n;i++)
{
vis[i]=0;
tree[i].clear();
}
}void dfs(int u)
{
ans++;
vis[u]=true;
for (int i=0;i<tree[u].size();i++)
{
int v=tree[u][i];
if (!vis[v])
{
dfs(v);
}
}
}int main()
{
int n,m,l,t,x,y;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&l);
init(n);
while(m--)
{
scanf("%d%d",&x,&y);
tree[x].push_back(y);
}
ans=0;
while(l--)
{
scanf("%d",&x);
if (!vis[x]) dfs(x);
}
printf("%d\n",ans);
}
return 0;
}
作者 chensunrise
hust 1511 Dominos 2,布布扣,bubuko.com