HDU-3001 TSP + ternary DP

Meaning of the questions: given an undirected graph, each point can not be more than twice after selecting a starting point for all points asked the shortest path through at least once.

Solution: Note that this problem is not through each point more than twice, and the general problem of TSP different. But did not make this problem has become very complex and original state that we are represented by binary compression, this time is not good enough, we have to express through 0, 1, 2 times. What think? Yes that is ternary representation can, TSP and other similar issues. DP [S] [x] represents the passage to state S is now complete path length of the target in the x-point distance. As usual dp can be.

#include<bits/stdc++.h>
using namespace std;
const int M=10*10;
const int INF=0x3f3f3f3f; 
int n,m;

int cnt,head[M<<1],nxt[M<<1],to[M<<1],len[M<<1];
void add_edge(int x,int y,int z) {
    nxt[++cnt]=head[x]; to[cnt]=y; len[cnt]=z; head[x]=cnt;
}

int inc(int S,int x) {
    int p=1; for (;x>1;x--) p*=3;
    return S+p;
}
int get(int S,int x) {
    int t=1;
    while (t<=n) {
        if (t==x) return S%3;
        S/=3; t++;
    }
}
bool check(int S) {
    int t=1;
    while (t<=n) {
        if (S%3==0) return 0;
        S/=3; t++;
    }
    return 1;
}

int dp[200000][12];
int dfs(int S,int x) {
    if (check(S)) return 0;
    if (dp[S][x]!=-1) return dp[S][x];
    int ret=INF;
    for (int i=head[x];i;i=nxt[i]) {
        int y=to[i];
        if (get(S,y)<2) ret=min(ret,dfs(inc(S,y),y)+len[i]);
    }
    return dp[S][x]=ret;
}

int main()
{
    while (scanf("%d%d",&n,&m)==2) {
        cnt=1,memset(head,0,sizeof(head));
        for (int i=1;i<=m;i++) {
            int x,y,z; scanf("%d%d%d",&x,&y,&z);
            add_edge(x,y,z);
            add_edge(y,x,z);
        }
        memset(dp,-1,sizeof(dp));
        int ans=INF;
        for (int i=1;i<=n;i++) ans=min(ans,dfs(inc(0,i),i));
        if (ans==INF) puts("-1"); else printf("%d\n",ans);
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/clno1/p/10943666.html