Poj3013 big Christmas tree --- Shortest Path

Source: Internet
Author: User

I'm sorry to write it on the title. This is the shortest path.

This question is quite interesting. The key is to convert the question quantity into the shortest path.


Question:

For an undirected graph, each node has the right value p [I], and each edge has the right value W [I].

The minimum cost for connecting all vertices of the tree to the root node 1,

Minimum Cost = Σ W [I] × Σ p [I]

The first Σ is all edges, and the second Σ is the weight and

Ideas:

Through derivation, we can find that for each node, the cost of calculation is P [I] * d [I],

D [I] indicates the distance from the node to the root node.

So it suddenly becomes clear .. Question 1

The only pitfall is int64, and INF is large enough.


# Include <cstdio> # include <cstring> # include <queue> # include <iostream> using namespace STD; const ll INF = 1ll <60; // pitfall! This question INF must be large enough # define n 50010 # define M 100010 struct node {int V, next; ll W;} e [m]; int vis [N], n, m, head [N], H; ll d [N], p [N]; void addedge (int A, int B, ll c) {e [H]. V = B; E [H]. W = C; E [H]. next = head [a]; head [a] = H ++;} int spfa (INT st) {memset (VIS, 0, sizeof vis ); for (INT I = 0; I <= N; I ++) d [I] = inf; d [st] = 0; vis [st] = 1; queue <int> q; q. push (ST); int X, I, V; while (! Q. Empty () {x = Q. Front (); q. Pop (); vis [x] = 0; for (I = head [X]; I! =-1; I = E [I]. next) {v = E [I]. v; If (d [v]> d [x] + E [I]. w) {d [v] = d [x] + E [I]. w; If (! Vis [v]) {vis [v] = 1; q. push (v) ;}}}} void Init () {memset (Head,-1, sizeof head); H = 0 ;}int main () {int t, a, B, I; ll ans, C; scanf ("% d", & T); While (t --) {Init (); scanf ("% d", & N, & M); for (I = 1; I <= N; I ++) CIN> P [I]; while (M --) {scanf ("% d", & A, & B); CIN> C; addedge (A, B, C); addedge (B, a, c) ;}spfa (1); ans = 0; int flag = 1; for (I = 2; I <= N; I ++) {If (d [I] = inf) {flag = 0; break;} ans + = (d [I] * P [I]);} If (! Flag) printf ("No answer \ n"); else cout <ans <Endl;} return 0 ;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.