The 15th UESTC Programming Contest Preliminary B - B0n0 Path cdoj1559
地址:http://acm.uestc.edu.cn/#/problem/show/1559
题目:
B0n0 Path
Time Limit: 1500/500MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
There is a country with NN cities, there are roads between some pairs of cities.
For every pair of cities, there is exactly one path between them, on which there are no cities passed more than once.
So it is obvious that there are N−1N−1 roads and N(N−1)2N(N−1)2 paths.
The cities number from 11 to NN, and the ithith city has one number AiAi.
A path is Bono if and only if the numbers AiAi on the path are non-strictly increasing or decreasing.
i.e., if the numbers are Ab1,Ab2,…,AbmAb1,Ab2,…,Abm,
How many Bono paths in the country?
Input
The first line contains one integer NN.
The second line contains NN integers, where the ithith indicates AiAi.
For the next N−1N−1 lines, each line contains two integers u,vu,v, meaning that there is a road between uthuth city and vthvth city.
1≤N≤105,1≤u,v≤N,1≤Ai≤1091≤N≤105,1≤u,v≤N,1≤Ai≤109
Output
One integer indicating the number of bono paths in the country.
Sample input and output
Sample Input | Sample Output |
---|---|
4
1 7 1 9
1 3
1 4
2 1
|
5
|
6
1 1 2 2 3 3
1 2
2 3
3 4
4 5
5 6
|
15
|
Hint
For sample 1:
The format of the text on ithith node is (i:Ai)(i:Ai).
There are 5 bono paths: (1,2),(1,3),(1,4),(2,1,3),(3,1,4)(1,2),(1,3),(1,4),(2,1,3),(3,1,4), while path (2,1,4)(2,1,4) is not bono path.
For sample 2:
All path are bono paths.
Source
1 #include <bits/stdc++.h>
2
3 using namespace std;
4
5 #define MP make_pair
6 #define PB push_back
7 typedef long long LL;
8 typedef pair<int,int> PII;
9 const double eps=1e-8;
10 const double pi=acos(-1.0);
11 const int K=1e6+7;
12 const int mod=1e9+7;
13 vector<int>mp[K];
14 int n,val[K];
15 LL dp[K][3];
16 LL ans;
17
18 void dfs(int x,int f)
19 {
20 for(int i=0;i<mp[x].size();i++)
21 {
22 int v=mp[x][i];
23 if(v==f) continue;
24 dfs(v,x);
25 if(val[v]<val[x])
26 {
27 ans+=(dp[x][2]+dp[x][0])*(dp[v][1]+dp[v][0]+1);
28 dp[x][1]+=dp[v][1]+dp[v][0]+1;
29 }
30 else if(val[v]>val[x])
31 {
32 ans+=(dp[x][1]+dp[x][0])*(dp[v][2]+dp[v][0]+1);
33 dp[x][2]+=dp[v][2]+dp[v][0]+1;
34 }
35 else
36 {
37 ans+=dp[x][0]*(dp[v][1]+dp[v][2]+dp[v][0]+1)+dp[x][1]*(dp[v][2]+dp[v][0]+1)+dp[x][2]*(dp[v][1]+dp[v][0]+1);
38 dp[x][0]+=dp[v][0]+1;
39 dp[x][1]+=dp[v][1];
40 dp[x][2]+=dp[v][2];
41 }
42 }
43 ans+=dp[x][0]+dp[x][1]+dp[x][2];
44 //cout<<"x="<<x<<" "<<dp[x][0]<<" "<<dp[x][1]<<" "<<dp[x][2]<<" "<<ans<<endl;
45 //printf("x=%I64d %I64d %I64d %I64d\n",x,dp[x][0],dp[x][1],dp[x][2]);
46 }
47
48 int main(void)
49 {
50 cin>>n;
51 for(int i=1;i<=n;i++)
52 scanf("%d",val+i);
53 for(int i=1,x,y;i<n;i++)
54 scanf("%d%d",&x,&y),mp[x].PB(y),mp[y].PB(x);
55 dfs(1,0);
56 cout<<ans<<endl;
57 return 0;
58 }
作者:weeping
出处:www.cnblogs.com/weeping/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。