https://i-blog.csdnimg.cn/blog_migrate/c2e146bf6dfb26cc009c356f5ce25183.png
In ICPCCamp, there are
n
cities and
m
directed roads between cities. The
i
-th road going from the
ai
-th city to the
bi
-th city is
ci
kilometers long. For each pair of cities
(u,v)
, there can be more than one roads from
u
to
v
.
Bobo wants to make big news by solving the famous Hamiltonian Path problem. That is, he would like to visit all the
n
cities one by one so that the total distance travelled is minimized.
Formally, Bobo likes to find
n
distinct integers
p1,p2,…,pn
to minimize
w(p1,p2)+w(p2,p3)+⋯+w(pn−1,pn)
where
w(x,y)
is the length of road from the
x
-th city to the
y
-th city.
Input
The input contains at most
30
sets. For each set:
The first line contains
2
integers
n,m
(
2≤n≤105,0≤m≤105
).
The
i
-th of the following
m
lines contains
3
integers
ai,bi,c i
(
1≤ai<bi≤n,1≤ci≤104
).
Output
For each set, an integer denotes the minimum total distance. If there exists no plan, output -1
instead.
Sample Input
3 3
1 2 1
1 3 1
2 3 1
3 2
1 2 1
1 3 2
Sample Output
首先 题目是求某人想遍历n个点所需要的时间最少 刚开始以为是最小生成树~~~然后看一下题意,看清楚,就是求w(p1,p2)+w(p2,p3)....然后输入的是有向图,ai<bi就是说不能回去了 尼玛。。所以你想遍历所有图 只能从1去2去3...如果有一处断了 输出-1 好吧 大水题 比赛的时候题目都没看 英语爆炸
#include<iostream>
#include<stdio.h>
#include<cmath>
#include<string.h>
using namespace std;
int main()
{
int t,n,m,a,b,c;
int d[100005];
long long ans;
while(~scanf("%d %d",&n,&m))
{
memset(d,0x3f,sizeof d);
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&a,&b,&c);
if(a==b-1)
d[a]=min(d[a],c);
}
t=1;
ans=0;
for(int i=1;i<n;i++)
{
if(d[i]==0x3f3f3f3f)
{
t=0;break;
}
ans+=d[i];
}
if(!t) printf("-1\n");
else printf("%lld\n",ans);
}
return 0;
}