Test instructions
Nick ' s company employedNPeople. Now Nick needs to build a tree hierarchy of«supervisor-surbodinate»relations in the company (this is to say so each EM Ployee, except one, has exactly one supervisor). There is m applications written in the following form: «employee a i is ready to become a supervisor of Employee b i at extra cost C i ». The Qualification q J of each Employee is known, and for each application the following are True: q a i > q b Span class= "Lower-index" > i .
Would you help Nick calculate the minimum cost of such a hierarchy, or find off that it's impossible to build it.
Ideas:
Implementation, "to find the root first"
Code:
intn,m;intq[1005];intg[1005][1005];intans[1005];intfa[1005];intMain () {CIN>>N; Rep (I,1, N) cin>>Q[i]; CIN>>m; inttemp=-inf; intHead; Rep (I,1, N) { if(q[i]>temp) {Temp=Q[i]; Head=i; }} mem (G,inf); MEM (Ans,inf); Rep (I,1, M) { intA,b,c; CIN>>a>>b>>C; G[A][B]=min (g[a][b],c); } Rep (I,1, N) {Rep (J,1, N) { if(g[j][i]<Ans[i]) {Ans[i]=G[j][i]; Fa[i]=J; } } } intres=0; Rep (I,1, N) { if(I==head)Continue; if(ans[i]==inf) {Puts ("-1"); RET0; } Res+=G[fa[i]][i]; } Print ("%d\n", RES); return 0;}
cf17b Hierarchy (amount,, water)