单点时限: 2.0 sec
内存限制: 256 MB
华师大是一个巨大的学校,众所周知,华师大的地图是一棵树,有 n 座教学楼,这些教学楼之间由 n−1 条道路相连,每条道路的长度都是一千米。
现在华师大投资建设一个「三千米健身步道」。为了让同学们不带喘气的跑(走)完这个健身步道,这个健身步道必须有一个起点,一个终点,中间是一段连续的三千米的跑道。华师大决定利用现有的 n−1 条道路建设这一个健身步道。问总共有多少种方案?
注意,起点和终点交换算同一种方案。
输入格式
第一行为 n (2≤n≤1000),表示教学楼数量,教学楼编号从 1 到 n。
接下来 n−1 行,每行为 ui,vi (1≤ui,vi≤n,ui≠vi),表示 ui,vi 之间有道路相连。
输出格式
输出方案数。如果不存在,输出 0。
样例
input
6 1 2 2 3 3 4 4 5 4 6
output
3
题意:已知有n个节点,n-1个节点之间有连接,连续的三个连接为一个方案,求有多少种方案。
思路:深度搜索,以每一个节点为起点,以其所连接的节点作为下一步的起点,当深度到3时结束。以vector数组node[i]表示节点i所连接的节点编号。
注意:①i与j之间有连接,则需要同时向node[i]中加入j,向node[j]中加入i,其目的是防止如三元环的出现(否则将被误认为仅有两条路径而不作为答案)
②应将尝试的节点设置为used,尝试后取消,为防止如仅有两个节点时,两个节点之间反复计算。
1 #include<cstdio> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 vector<int>node[1010]; 6 int used[1010]; 7 int ans,n; 8 void dfs(int index,int a) { 9 if (index == 3) { 10 ans++; 11 return; 12 } 13 vector<int>::iterator it; 14 if (!node[a].empty()) { 15 for (it = node[a].begin(); it != node[a].end(); it++) { 16 if (!used[*it]) { 17 used[*it] = 1; 18 dfs(index + 1, *it); 19 used[*it] = 0; 20 } 21 } 22 } 23 } 24 int main() { 25 int u,v; 26 fill(used, used + 1010, 0); 27 scanf("%d", &n); 28 for (int i = 0; i < n - 1; i++) { 29 scanf("%d%d", &u, &v); 30 node[u].push_back(v); 31 node[v].push_back(u); 32 } 33 for (int i = 1; i <= n; i++) { 34 used[i] = 1; 35 dfs(0, i); 36 used[i] = 0; 37 } 38 printf("%d", ans/2); 39 return 0; 40 }