Hamiltonian Path | ||
Accepted : 41 | Submit : 96 | |
Time Limit : 2000 MS | Memory Limit : 65536 KB |
Hamiltonian PathIn 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. InputThe 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,ci ( 1≤ai<bi≤n,1≤ci≤104 ). OutputFor each set, an integer denotes the minimum total distance. If there exists no plan, output Sample Input3 3 1 2 1 1 3 1 2 3 1 3 2 1 2 1 1 3 2 Sample Output2 -1 |
这题……神坑;现场做的时候大部分队伍都应该以为是曼哈顿路径,160个队伍只有10来个队伍过了,大家真是都狠狠的被郭晓旭同学玩了一把。闭幕式上讲题的时候,只说了一句Pi = i,现场啊声一片,醉了;
关键是叉姐把一个题目的一个重要条件不着痕迹的放在了一个很阴险的地方:
The
i
-th of the following
m
lines contains
3
integers
ai,bi,ci
(
1≤ai<bi≤n,1≤ci≤104
).
竟然:ai<bi。
这样一来直接就变成大水题了,pi必须等于i,否则不可能符合题目要求。但是现场有10个题目可以选择,这题看似真不容易,过的人也极少。。于是大部分队伍包括竟然都没发现这题。
【代码】
</pre><pre name="code" class="cpp">/* ***********************************************
Author :angon
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define REP(i,k,n) for(int i=k;i<n;i++)
#define REPP(i,k,n) for(int i=k;i<=n;i++)
#define scan(d) scanf("%d",&d)
#define scann(n,m) scanf("%d%d",&n,&m)
#define mst(a,k) memset(a,k,sizeof(a));
#define LL long long
#define maxn 1005
#define mod 100000007
/*
inline int read()
{
int s=0;
char ch=getchar();
for(; ch<'0'||ch>'9'; ch=getchar());
for(; ch>='0'&&ch<='9'; ch=getchar())s=s*10+ch-'0';
return s;
}
inline void print(int x)
{
if(!x)return;
print(x/10);
putchar(x%10+'0');
}
*/
int p[100005];
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int m,n,a,b,c;
while(~scann(n,m))
{
for(int i=1;i<=n;i++) p[i]=10005;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&a,&b,&c);
if(a==b-1)
{
if(p[a]>c)
p[a]=c;
}
}
LL ans=0;
bool flag=false;
for(int i=1;i<n;i++)
{
if(p[i]==10005)
{
flag=true;
break;
}
ans+=p[i];
}
if(!flag)
printf("%lld\n",ans);
else
printf("-1\n");
}
return 0;
}