# 2016长城信息杯中国大学生程序设计竞赛中南邀请赛 xtu 1245 Hamiltonian Path

878人阅读 评论(0)

In ICPCCamp, there arencities andmdirected roads between cities. Thei-th road going from theai-th city to thebi-th city iscikilometers long. For each pair of cities(u,v), there can be more than one roads fromutov.

Bobo wants to make big news by solving the famous Hamiltonian Path problem. That is, he would like to visit all thencities one by one so that the total distance travelled is minimized.

Formally, Bobo likes to findndistinct integersp1,p2,,pnto minimizew(p1,p2)+w(p2,p3)++w(pn1,pn)wherew(x,y)is the length of road from thex-th city to they-th city.

## Input

The input contains at most30sets. For each set:

The first line contains2integersn,m(2n105,0m105).

Thei-th of the followingmlines contains3integersai,bi,c        i1ai<bin,1ci104).

## 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

2
-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;
}

个人资料
等级：
访问量： 6万+
积分： 2274
排名： 2万+
最新评论