poj3256 Cow Picnic

本文详细解析了CowPicnic算法问题,介绍了如何通过深度优先搜索(DFS)算法确定所有奶牛能够到达的牧场数量,以选择合适的野餐地点。算法涉及图论中的一次遍历和计数技巧。
Cow Picnic
Time Limit:2000MSMemory Limit:65536K
Total Submissions:5811Accepted:2388

Description

The cows are having a picnic! Each of Farmer John'sK(1 ≤K≤ 100) cows is grazing in one ofN(1 ≤N≤ 1,000) pastures, conveniently numbered 1...N. The pastures are connected byM(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.

Input

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 iis grazing.
Lines K+2.. M+ K+1: Each line contains two space-separated integers, respectively Aand B(both 1.. Nand A!= B), representing a one-way path from pasture Ato pasture B.

Output

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

Sample Input

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

Sample Output

2

Hint

The cows can meet in pastures 3 or 4.

Source

从每头牛开始的地方dfs一下。。。经过的点x全部cnt[x]++。。。然后看一下那些点的cnt值等于k。。。
用到了一个小trick。。。vis[i][j]表示点i是否第j头牛曾经经过。。。 (空间换时间。。。)
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <cmath>
#include <cctype>
#include <string>
#include <cfloat>
#include <stack>
#include <cassert>

using namespace std;

int k, n, m, val[1010], cow[110], head[10010], rest[10010], to[10010], tot, vis[10010][110], ans;

void add(int u, int v) {
    tot ++;
    to[tot] = v;
    rest[tot] = head[u];
    head[u] = tot;
}

void dfs(int u, int ext) {
    vis[u][ext] = 1;
    val[u] ++;
    for(int i = head[u] ; i ; i = rest[i]) {
        int v = to[i];
        if(vis[v][ext]) continue;
        dfs(to[i], ext);
    }
}

int main() {
    scanf("%d%d%d", &k, &n, &m);
    for(int i = 1 ; i <= k ; i ++) {
        scanf("%d", &cow[i]);
    }
    for(int i = 1, a, b ; i <= m ; i ++) {
        scanf("%d%d", &a, &b);
        add(a, b);
    }
    for(int i = 1 ; i <= k ; i ++) {
        dfs(cow[k], i);
    }
    for(int i = 1 ; i <= n ; i ++) {
        if(val[i] == k) {
            ans ++;
        }
    }
    printf("%d\n", ans);
}

  

转载于:https://www.cnblogs.com/KingSann/articles/7502098.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值