XTU2016CCPC中南邀请赛C
Hamiltonian Path |
||
Accepted : 74 | Submit : 189 | |
Time Limit : 2000 MS | Memory Limit : 65536 KB |
Hamiltonian PathIn ICPCCamp, there are Bobo wants to make big news by solving the famous Hamiltonian Path problem. That is, he would like to visit all the Formally, Bobo likes to find InputThe input contains at most The first line contains The 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 |
注意条件ai是小于bi!这意味着什么?意味着只能1到2,2到3的来走,任何一个跳着城市编号的道路都是无用条件,只需要把最小的相邻城市的路加起来就行了。。。mp[i]表示i到i+1的城市路径,只要条件中缺少一个mp[i]就不能满足,只能输出-1
#include <bits/stdc++.h> typedef long long ll; using namespace std; const int maxn = 1e4; int mp[maxn+10]; ll ans; int main() { // freopen("in.txt","r",stdin); int n,m; int flag = 0; while(~scanf("%d%d",&n,&m)) { ans = 0LL; for(int i = 1; i <= maxn; i++) mp[i] = maxn; // cout<<ans; while(m--) { int a,b,c; cin>>a>>b>>c; if(a==b-1) { if(mp[a]>c) { mp[a] = c; } } } for(int i = 1; i < n; i++) { if(mp[i]!=maxn) { ans += mp[i]; } else { puts("-1"); flag = 1; break; } } if(!flag) cout<<ans<<endl; } }