博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CF 17B Hierarchy
阅读量:5879 次
发布时间:2019-06-19

本文共 2648 字,大约阅读时间需要 8 分钟。

Nick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi at extra cost ci». The qualification qj of each employee is known, and for each application the following is true: qai > qbi.

Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.

Input

The first input line contains integer n (1 ≤ n ≤ 1000) — amount of employees in the company. The following line contains n space-separated numbers qj (0 ≤ qj ≤ 106)— the employees' qualifications. The following line contains number m (0 ≤ m ≤ 10000) — amount of received applications. The following mlines contain the applications themselves, each of them in the form of three space-separated numbers: ai,bi and ci (1 ≤ ai, bi ≤ n0 ≤ ci ≤ 106). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai > qbi.

Output

Output the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.

Sample test(s)
input
47 2 3 141 2 52 4 13 4 11 3 5
output
11
input
31 2 323 1 23 1 3
output
-1
Note

In the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1.

预处理+贪心就能够了,由于根仅仅有一个,所以在输入的时候预处理子节点的最小值贪心就好了=。=
#include
#include
#include
#include
#include
using namespace std;const int INF=0x3ffffff;int f[1100];int main(){ int n,m; int temp,u,v,w; while(cin>>n) { for(int i=1;i<=n;i++) { cin>>temp; f[i]=INF; } cin>>m; for(int i=1;i<=m;i++) { cin>>u>>v>>w; if(f[v]>w)//预处理最小值 f[v]=w; } int flag=1,k=1; int ans=0; for(int i=1;i<=n;i++)//仅仅能有一个INF,即根节点 { if(f[i]==INF&&k) { ans-=INF; k=0; } else if(f[i]==INF) { flag=0; break; } ans+=f[i]; } if(flag) cout<
<

转载地址:http://kndix.baihongyu.com/

你可能感兴趣的文章
纸上谈兵: 栈 (stack)
查看>>
Windows phone8 基础篇(三) 常用控件开发
查看>>
Oracle学习笔记之五,Oracle 11g的PL/SQL入门
查看>>
PHP安全编程:register_globals的安全性 全局变量注册(转)
查看>>
工程技巧Linux上建立工程项目
查看>>
Linux php 中文乱码解决
查看>>
pjsip视频通信开发(上层应用)之拨号键盘下部份拨号和删除功能
查看>>
SAP-GR/IR的理解
查看>>
Web自动化测试 Selenium 3/3 https的配置
查看>>
.NET 常用加密、解密& 数字签名算法
查看>>
“解析包时出现问题”
查看>>
Google地图之OverlayView使用(自定义叠加层)
查看>>
Android面试,与Service交互方式
查看>>
CFileDialog的使用方法简单介绍
查看>>
c#语言-高阶函数
查看>>
sql server 小技巧(4) Sql server 排序时让空值排在最后
查看>>
【BZOJ】1043: [HAOI2008]下落的圆盘(计算几何基础+贪心)
查看>>
设计模式的3个常用原则
查看>>
公司梦想讨论
查看>>
clearRect清除html5画布
查看>>