NOIP 2014 联合权值
生活随笔
收集整理的這篇文章主要介紹了
NOIP 2014 联合权值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:
https://www.luogu.org/problemnew/show/P1351
參考洛谷題解:
使用鏈式前向星儲存圖。如果使用深度優先搜索的話,是會超時的,如果遍歷中間的點,雖然比直接遍歷快一點,但是也會超時,畫一個有三個頂點一個中心的菊花圖,題目就是要求三個頂點兩兩相乘的和,找規律可得到:結果為三個頂點的和的平方減去三個頂點的平方和,推廣到n個頂點也是一樣的。由此得出代碼:
#include <iostream> #include <cstring> #include <stdio.h> using namespace std; typedef long long ll; const int inf=1e6+7; struct node {int from,to,next; }themap[inf]; int head[inf],thevalue[inf],thenow[inf]; int cnt=0; int themax=-1,theans=0;void addedge(int u,int v) //遠不如直接在用一個來的好。 {themap[cnt].from=u;themap[cnt].to=v;themap[cnt].next=head[u];head[u]=cnt++;themap[cnt].from=v;themap[cnt].to=u;themap[cnt].next=head[v];head[v]=cnt++; }int main() {int n,u,v;memset(head,-1,sizeof(head));scanf("%d",&n);for(int i=1;i<n;i++){scanf("%d %d",&u,&v);addedge(u,v);}for(int i=1;i<=n;i++)scanf("%d",&thevalue[i]);for(int i=1;i<=n;i++){int flag=0;ll one=-1,two=-1; //最大值和次大值。ll temp1=0;ll temp2=0;for(int j=head[i];j!=-1;j=themap[j].next){//thenow[flag++]=themap[j].to;int now=themap[j].to; //是其中的值啊.if(thevalue[now]>one){two=one;one=thevalue[now];}else if(thevalue[now]>two)two=thevalue[now];temp1+=thevalue[now];temp1=temp1%10007;temp2+=(thevalue[now]*thevalue[now])%10007;temp2=temp2%10007; flag++;}if(flag==1){}else{if(one*two>themax){themax=one*two; }temp1=(temp1*temp1)%10007;theans+=(temp1-temp2+10007); //防止theans成為負的。theans=theans%10007; }}printf("%d %d\n",themax,theans%10007);return 0; }?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的NOIP 2014 联合权值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Traveling on the Axi
- 下一篇: noip 2017棋盘