HDU 3001 (triplicate)

Source: Internet
Author: User
Question

Solution

When we see this question, we will think of the traveling salesman problem. However, each vertex can go through a maximum of two times, so we can use a three-digit representation.

Code
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <algorithm>#include <cctype>#include <vector>#define INF 2139062143#define MAX 0x7ffffffffffffff#define del(a,b) memset(a,b,sizeof(a))using namespace std;typedef long long ll;template<typename T>inline void read(T&x){    x=0;T k=1;char c=getchar();    while(!isdigit(c)){if(c==‘-‘)k=-1;c=getchar();}    while(isdigit(c)){x=x*10+c-‘0‘;c=getchar();}x*=k;}const int maxn=15;int dis[maxn][maxn];int dp[60000][maxn];int poww[15];void _init() {    poww[0]=1;    for(int i=1;i<=10;i++) poww[i]=poww[i-1]*3;    return;}int query(int s,int k) {    return s/poww[k]%3;}int add(int x,int k) {    return x+poww[k];}int n,m;bool check(int x) {    for(int i=0;i<n;i++) if(!query(x,i)) return 0;    return 1;}int main(){    _init();    while(~scanf("%d %d",&n,&m)) {        del(dis,127);del(dp,127);        for(int i=1,u,v,w;i<=m;i++) {            read(u),read(v),read(w);--u,--v;            dis[u][v]=min(dis[u][v],w);            dis[v][u]=min(dis[v][u],w);        }                for(int i=0;i<n;i++) dp[add(0,i)][i]=0;                int ans=INF;        for(int s=0;s<poww[n];s++) {            for(int i=0;i<n;i++) {                if(!query(s,i)) continue;                for(int j=0;j<n;j++) {                    if(j==i||query(s,j)==2||dis[i][j]==INF) continue;                    dp[add(s,j)][j]=min(dp[s][i]+dis[i][j],dp[add(s,j)][j]);                }                if(check(s)) ans=min(ans,dp[s][i]);            }        }        if(ans==INF) printf("-1\n");        else printf("%d\n",ans);    }    return 0;}
View code

 

HDU 3001 (triplicate)

Related Keywords:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.