Tree of Life (easy)
Heidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.
On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection ofn points (called vertices), some of which are connected using n - 1 line segments (edges) so that each pair of vertices is connected by apath (a sequence of one or more edges).
To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree – these are paths of length 2, i.e., consisting of two edges. Help her!
The first line of the input contains a single integer n – the number of vertices in the tree (1 ≤ n ≤ 10000). The vertices are labeled with the numbers from 1 to n. Then n - 1 lines follow, each describing one edge using two space-separated numbers a b – the labels of the vertices connected by the edge (1 ≤ a < b ≤ n). It is guaranteed that the input represents a tree.
Print one integer – the number of lifelines in the tree.
4
1 2
1 3
1 4
3
5
1 2
2 3
3 4
3 5
4
In the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5.
分析:长度为2的路的个数;
代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <algorithm> #include <climits> #include <cstring> #include <string> #include <set> #include <map> #include <queue> #include <stack> #include <vector> #include <list> #include <ext/rope> #define rep(i,m,n) for(i=m;i<=n;i++) #define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++) #define vi vector<int> #define pii pair<int,int> #define mod 1000000007 #define inf 0x3f3f3f3f #define pb push_back #define mp make_pair #define fi first #define se second #define ll long long #define pi acos(-1.0) const int maxn=1e4+10; const int dis[4][2]={{0,1},{-1,0},{0,-1},{1,0}}; using namespace std; using namespace __gnu_cxx; ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);} ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}return f;} int n,m,vis[maxn],cnt; vi a[maxn]; void dfs(int p) { for(int x:a[p])for(int y:a[x])if(!vis[y])cnt++; } int main() { int i,j,k,t; scanf("%d",&n); rep(i,1,n-1)scanf("%d%d",&j,&k),a[j].pb(k),a[k].pb(j); rep(i,1,n)vis[i]=1,dfs(i); printf("%d\n",cnt); //system ("pause"); return 0; }