题解【洛谷P2853】[USACO06DEC]牛的野餐Cow Picnic

题目描述

The cows are having a picnic! Each of Farmer John's (K (1 ≤ K ≤ 100)) cows is grazing in one of (N (1 ≤ N ≤ 1,000)) pastures, conveniently numbered (1...N). The pastures are connected by (M (1 ≤ M ≤ 10,000)) one-way paths (no path connects a pasture to itself).

The cows want to gather in the same pasture for their picnic, but (because of the one-way paths) some cows may only be able to get to some pastures. Help the cows out by figuring out how many pastures are reachable by all cows, and hence are possible picnic locations.

(K(1≤K≤100))只奶牛分散在(N(1≤N≤1000))个牧场.现在她们要集中起来进餐.牧场之间有(M(1≤M≤10000))条有向路连接,而且不存在起点和终点相同的有向路.她们进餐的地点必须是所有奶牛都可到达的地方.那么,有多少这样的牧场呢?

输入输出格式

输入格式

Line (1): Three space-separated integers, respectively: (K), (N), and (M)

Lines (2..K+1): Line (i+1) contains a single integer ((1..N)) which is the number of the pasture in which cow (i) is grazing.

Lines (K+2..M+K+1): Each line contains two space-separated integers, respectively (A) and (B) (both (1..N) and (A != B)), representing a one-way path from pasture (A) to pasture (B).

输出格式

Line 1: The single integer that is the number of pastures that are reachable by all cows via the one-way paths.

输入输出样例

输入样例#1

2 4 4
2
3
1 2
1 4
2 3
3 4

输出样例#1

2

说明

The cows can meet in pastures (3) or (4).

题解

这是一道对图进行深度优先遍历的一道很好的练习题。

从题面中,我们可以知道,这道题目是让我们对每只奶牛所在的点进行深度优先遍历,找到遍历的次数正好等于奶牛数的点,最后输出这样的点的数量。

我们使用一个数组(s[x])表示点(x)被遍历的次数,如果遍历到了点(x),那么(s[x])就加(1)

注意:每次遍历之前都需要将判断点是否已经访问过的(vis[])数组清空,并且每次在遍历下一个点的时候都需要判断点是否已经访问,因为每一个点在每次遍历中都是最多访问(1)次。

另外,本题中(n)的范围并不大,因此我们可以使用邻接矩阵来存图。

不难得出(AC)代码。

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cctype>//头文件准备

using namespace std;//使用标准名字空间

//以下为快速读入
inline int gi()
{
	int f = 1, x = 0; char c = getchar();
	while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar();}
	while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar();}
	return f * x;
}

int n, m, k, ans, g[1003][1003], c[1003], s[1003], vis[1003];
//n,m,k的含义如题面,ans为最终答案,g数组为邻接矩阵,c数组存储牛的位置,s数组为每个点被遍历的次数,vis数组用来判断点是否已经被访问过

void dfs(int x)//进行图的深度优先遍历
{
    vis[x] = 1;//将现在访问的点标记为已遍历
    ++s[x];//将这个点遍历的次数+1
    for (int i = 1; i <= n; i++)//枚举节点编号
    {
        if (!vis[i] && g[x][i]) //如果当前节点没有被访问过并且与当前节点有边连接
            dfs(i);//就遍历i号节点
    }
}

int main()
{
    k = gi(), n = gi(), m = gi();//分别输入k,m,n(注意顺序)
    for (int i = 1; i <= k; i++) c[i] = gi();//输入每只奶牛的顺序
    for (int i = 1; i <= m; i++)
    {
        int u = gi(), v = gi(); //输入边两端的点的编号
        g[u][v] = 1;//连接两边(注意不是双向边,是单向边)
    }
    for (int i = 1; i <= k; i++)//对奶牛的位置进行枚举
    {
        dfs(c[i]);//从每一只奶牛的位置开始遍历
        memset(vis, 0, sizeof(vis));//记得每次遍历完都需要清空标记数组
    }
    for (int i = 1; i <= n; i++)
    {
        if (s[i] == k) ++ans;//统计答案,如果当前节点被访问的次数恰好为奶牛的只数
    }
    printf("%d
", ans);//输出最后答案
    return 0;//完美结束
}

完结撒花~

原文地址:https://www.cnblogs.com/xsl19/p/11116740.html