bzoj3252: 攻略 优先队列 并查集 贪心
考场上自己yy出来的做法.....
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | #include<cstdio> #include<algorithm> #include<queue> #include<vector> #include<string> using namespace std; void setIO(string a){ freopen ((a+ ".in" ).c_str(), "r" ,stdin); freopen ((a+ ".out" ).c_str(), "w" ,stdout); } void shutIO(){ fclose (stdin); fclose (stdout); } #define ll long long #define maxn 200009 struct Node{ ll dist; int u; Node(ll dist=0, int u=0):dist(dist),u(u){} bool operator<(Node a) const { return a.dist>dist; } }; priority_queue<Node>Q; int p[maxn], tag[maxn],n,m,k,cnt,val[maxn],head[maxn],to[maxn<<1],nex[maxn<<1]; ll sumv[maxn]; int find( int x){ return p[x]==x?x:p[x]=find(p[x]); } void merge( int a, int b){ int x=find(a),y=find(b); if (x==y) return ; p[x]=y; } void addedge( int u, int v){ nex[++cnt]=head[u],head[u]=cnt,to[cnt]=v; } bool check( int a){ int x=find(a); if (tag[x]) return false ; tag[x]=1; return true ; } void dfs( int u, int fa){ sumv[u]=(ll)val[u]; int flag=0; ll MAX=0; for ( int v=head[u];v;v=nex[v]){ if (to[v]==fa) continue ; dfs(to[v],u); if (sumv[to[v]]>MAX) MAX=sumv[to[v]], flag=to[v]; } if (flag){ sumv[u]+=MAX, merge(u,flag); for ( int v=head[u];v;v=nex[v]){ if (to[v]==fa) continue ; if (to[v]!=flag) Q.push(Node(sumv[to[v]],to[v])); } } } int main(){ //setIO("game"); scanf ( "%d%d" ,&n,&k); for ( int i=1;i<=n;++i) scanf ( "%d" ,&val[i]); for ( int i=1;i<=n;++i) p[i]=i; for ( int i=1;i<n;++i){ int a,b; scanf ( "%d%d" ,&a,&b); addedge(a,b),addedge(b,a); } dfs(1,0); Q.push(Node(sumv[1],1)); int cur=0; ll fin=0; while (!Q.empty()&&cur<k){ Node a=Q.top();Q.pop(); if (check(a.u))fin+=a.dist,cur+=1; } printf ( "%lld" ,fin); //shutIO(); return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步