简单的一道深搜:
思路:让每个有奶牛的农场沿着道路跑下去,跑到的农场加上root地方的奶牛数量,最后统计能有k头奶牛的农场数量就是答案
代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
#include<fstream>
#include<stack>
typedef long long ll;
using namespace std;
const int N = 1e3 + 10;
ll hascow[N];
ll numofcow[N];
bool vis[N];
ll ans = 0;
vector<int>G[N];
void dfs(ll u,ll root)
{
vis[u] = 1;
for (int i = 0; i < G[u].size(); i++)
{
if(!vis[G[u][i]])
{
numofcow[G[u][i]] += hascow[root];
dfs(G[u][i], root);
}
}
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0), cout.tie(0);
ll k, n, m; cin >> k >> n >> m;
queue<ll>qid;
for (int i = 0; i < k; i++)
{
ll x; cin >> x;
if(!hascow[x])qid.push(x);
hascow[x] += 1;
numofcow[x] = hascow[x];
}
for (int i = 0; i < m; i++)
{
ll u, v; cin >> u >> v;
G[u].push_back(v);
}
//思路:从有牛的节点找起,然后给所有这个牛能到的节点加1,统计满的节点数量
while (!qid.empty())
{
dfs(qid.front(),qid.front());
qid.pop();
memset(vis, 0, sizeof(vis));
}
for (int i = 1; i <= n; i++)
if (numofcow[i] == k)
ans++;
cout << ans;
return 0;
}
很神奇:那个一段如果改为以下:
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
#include<fstream>
#include<stack>
typedef long long ll;
using namespace std;
const int N = 1e3 + 10;
ll hascow[N];
ll numofcow[N];
bool vis[N];
ll ans = 0;
vector<int>G[N];
void dfs(ll u,ll root)
{
vis[u] = 1;
for (int i = 0; i < G[u].size(); i++)
{
if(!vis[G[u][i]])
{
numofcow[G[u][i]] += hascow[root];
dfs(G[u][i], root);
}
}
vis[u] = 0;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0), cout.tie(0);
ll k, n, m; cin >> k >> n >> m;
queue<ll>qid;
for (int i = 0; i < k; i++)
{
ll x; cin >> x;
if(!hascow[x])qid.push(x);
hascow[x] += 1;
numofcow[x] = hascow[x];
}
for (int i = 0; i < m; i++)
{
ll u, v; cin >> u >> v;
G[u].push_back(v);
}
//思路:从有牛的节点找起,然后给所有这个牛能到的节点加1,统计满的节点数量
while (!qid.empty())
{
dfs(qid.front(),qid.front());
qid.pop();
}
for (int i = 1; i <= n; i++)
if (numofcow[i] == k)
ans++;
cout << ans;
return 0;
}
就过不了
待查为什么...