您的位置:首页 > 其它

HDU 4707 Pet 图的遍历(BFS和DFS)

2016-08-03 19:28 387 查看
题目的链接如下:

http://acm.hdu.edu.cn/showproblem.php?pid=4707

Pet

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2544 Accepted Submission(s): 1258

Problem Description

One day, Lin Ji wake up in the morning and found that his pethamster escaped. He searched in the room but didn’t find the hamster. He tried to use some cheese to trap the hamster. He put the cheese trap in his room and waited for three days. Nothing but cockroaches was caught. He got the map of the school and foundthat there is no cyclic path and every location in the school can be reached from his room. The trap’s manual mention that the pet will always come back if it still in somewhere nearer than distance D. Your task is to help Lin Ji to find out how many possible locations the hamster may found given the map of the school. Assume that the hamster is still hiding in somewhere in the school and distance between each adjacent locations is always one distance unit.

Input

The input contains multiple test cases. Thefirst line is a positive integer T (0

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>

using namespace std;

int ans;
int T;
vector<int>G[100010];
int n, m;
int a, b;
int dis[100010];

void init(int x)
{
for (int i = 0; i <= x; i++)
{
G[i].clear();
}
}

void bfs()
{
queue<int >Q;
dis[0] = 0;
Q.push(0);
while (!Q.empty())
{
int now = Q.front();
Q.pop();
for (int i = 0; i < G[now].size(); i++)
{
dis[G[now][i]] = dis[now] + 1;
if (dis[G[now][i]] > m)
ans++;
Q.push(G[now][i]);
}
}
}

int main(void)
{
scanf("%d", &T);
while (T--)
{

scanf("%d %d", &n, &m);
init(n);
for (int i = 1; i < n; i++)
{
scanf("%d %d", &a, &b);
G[a].push_back(b);
}
ans = 0;
bfs();
printf("%d\n", ans);
}
return 0;
}


第二种解法DFS:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;
#define mem(a,x) memset(a,x,sizeof(a))
const int maxn = 100000 + 10;
bool vis[maxn];
int n,d;
int ans = 0;
vector<int>G[maxn];
void dfs(int x,int dep){
for(int i=0;i<G[x].size();i++){
int v = G[x][i];
if(!vis[v]){
vis[v] = 1;
if(dep + 1> d) ans++;
dfs(v,dep+1);
}
}
}
void init(int n){
ans = 0;
memset(vis,0,sizeof(vis));
for(int i=0;i<=n;i++) G[i].clear();
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&d);
init(n);
for(int i=0;i<n-1;i++){
//cout<<"tt"<<endl;
int a,b;
scanf("%d%d",&a,&b);
G[a].push_back(b);
G[b].push_back(a);
}
vis[0] = 1;
dfs(0,0);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  遍历 bfs dfs 图论