【NOIP2014 Day1 T2】联合权值
Time Limit:10000MS Memory Limit:131072K
Total Submit:87 Accepted:38
Case Time Limit:1000MS
Description
Input
Output
Sample Input
5
1 2
2 3
3 4
4 5
1 5 2 3 10
Sample Output
20 74
Hint
这题BFS明显比DFS快一些,之前不知道DFS怎么优化,后来BFS过了才想起来
#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxn=2e6+5,mod=10007;
int n,last[maxn],w[maxn],ans1,ans2;
int depth[maxn],sum[maxn],curm[maxn],fa[maxn];
bool vis[maxn];
queue<int>q;
inline void _read(int &x){
char t=getchar();bool sign=true;
while(t<'0'||t>'9')
{if(t=='-')sign=false;t=getchar();}
for(x=0;t>='0'&&t<='9';t=getchar())x=x*10+t-'0';
if(!sign)x=-x;
}
struct wr{
int a,b,c,NEXT;
wr(int a,int b,int c,int NEXT):a(a),b(b),c(c),NEXT(NEXT){}
};
vector<wr>s;
void insert(int a,int b){
s.push_back(wr(a,b,1,last[a]));
last[a]=s.size()-1;
s.push_back(wr(b,a,1,last[b]));
last[b]=s.size()-1;
}
void bfs(){
q.push(1);vis[1]=1;
int lastfa=0,i;
while(q.size()){
int x=q.front();q.pop();
if(fa[x]!=lastfa)sum[depth[x]]=curm[depth[x]]=0;
lastfa=fa[x];
if(depth[x]>=2)ans1=max(ans1,w[x]*w[fa[fa[x]]]),ans2=(ans2+(w[x]*w[fa[fa[x]]])%mod)%mod;
ans1=max(ans1,curm[depth[x]]*w[x]),ans2=(ans2+(sum[depth[x]]*w[x])%mod)%mod;
sum[depth[x]]=(sum[depth[x]]+w[x])%mod,curm[depth[x]]=max(curm[depth[x]],w[x]);
for(i=last[x];i>=0;i=s[i].NEXT)
if(!vis[s[i].b]){
fa[s[i].b]=x;
depth[s[i].b]=depth[x]+1;
q.push(s[i].b);
vis[s[i].b]=1;
}
}
}
int main(){
memset(last,-1,sizeof(last));
_read(n);
int i,j,x,y;
for(i=1;i<n;i++){
_read(x);_read(y);
insert(x,y);
}
for(i=1;i<=n;i++)_read(w[i]);
bfs();
printf("%d %d",ans1,(ans2*2)%mod);
}