The city where Vasya lives has a park with n lawns connected by m
paths. One can walk in both directions along each path. The lawns connected by the path are called neighbors.
The entrance to the park is near the lawn number one which will be called the entrance lawn. Vasya's parents are very concerned about his safety, so they allow him to play only on the lawn that is a neighbor to the entrance lawn. Entrance lawn is usually overcrowded, so Vasya can't play on it.
Vasya finds it boring to simply walk along the path to the neighbor lawn. Instead, he starts at the entrance lawn, and walks along exactly three different paths. After that he plays on the lawn where he ends his walk. Vasya does not break the rules set by the parents, so he always ends his walk on the lawn neighboring to the entrance lawn.
Every day Vasya wants to choose a new walk he hasn't taken before. Help him to determine how many ways are to begin his journey at the entrance lawn, follow exactly three different paths, and find himself on the lawn neighboring to the entrance lawn.
Input
The first line of input contains two integers n
and m — the number of lawns and the number of paths, respectively (1≤n≤100000, 1≤m≤200000
).
The next m
lines contain pairs of lawns connected by paths. Any two lawns are connected by no more than one path. There are no paths connecting a lawn to itself.
Output
Print the number of walks that Vasya can take.
ac代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define ll long long
using namespace std;
const int N = 1e5+10;
int n,m,num;
vector<int>g[N];
int mp[101000];
int vis[N];
void dfs(int pos,int k)
{
if(k==0)
{
if(mp[pos])
{
num++;
}
return;
}
int len=g[pos].size();
for(int i=0; i<len; i++)
{
if(vis[g[pos][i]]==0)
{
vis[g[pos][i]] = 1;
dfs(g[pos][i],k-1);
vis[g[pos][i]] = 0;
}
}
return;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1; i<=m; i++)
{
int u,v;
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
if(u==1)
mp[v] = 1;
if(v==1)
mp[u] = 1;
}
vis[1] = 1;
dfs(1,3);
printf("%d\n",num);
return 0;
}
昨天训练赛的一道题,,,,,,打了7、8次硬是超时,以为是剪枝还不够,午觉起来。。。。又敲,,把map容器改为了数组存储,ac!!!!难道stl里的函数还没有数组寸的更优秀吗。。
该博客讨论了一道关于图论的算法题,题目涉及一个公园内的草坪和路径。Vasya只能在与入口草坪相邻的草坪上玩耍,他每天要选择一条之前未走过的、包含三条不同路径的新路线。作者通过编写AC代码,将map容器改为数组以优化性能,最终解决了超时问题。博客主要探讨了如何利用深度优先搜索(DFS)来计算所有可能的路径,并强调了STL中某些操作可能不如数组高效。
3543

被折叠的 条评论
为什么被折叠?



