poj 2404 Jogging Trails 求走最少距离使得所有边至少都遍历一次并回到原点(即sum+加上最少多少距离使得原图变成欧拉回路) FLOYD+状态压缩DP

Description

Gord is training for a marathon. Behind his house is a park with a large network of jogging trails connecting water stations. Gord wants to find the shortest jogging route that travels along every trail at least once.

Input

Input consists of several test cases. The first line of input for each case contains two positive integers: n <= 15, the number of water stations, and m < 1000, the number of trails. For each trail, there is one subsequent line of input containing three positive integers: the first two, between 1 and n, indicating the water stations at the end points of the trail; the third indicates the length of the trail, in cubits. There may be more than one trail between any two stations; each different trail is given only once in the input; each trail can be travelled in either direction. It is possible to reach any trail from any other trail by visiting a sequence of water stations connected by trails. Gord's route may start at any water station, and must end at the same station. A single line containing 0 follows the last test case.

Output

For each case, there should be one line of output giving the length of Gord's jogging route.

Sample Input

4 5
1 2 3
2 3 4
3 4 5
1 4 10
1 3 12
0

Sample Output

41

//

用floyd求两点间最短路,由欧拉回路可知,度为奇数的点之间互相匹配(即连一条边),选这些边之和最小值加上
          所有边及答案,匹配时可用记忆搜(即状态压缩优化dfs)。。。。

#include
#include
#include
#include
using namespace std;
const int N=50;
const int inf=(1<<28);
const int maxn=1<<20;
int dp[maxn];
int mat[N][N];
int n,m;
int du[N];
int dfs(int state)
{
    if(state==0) return 0;
    if(dp[state]!=-1) return dp[state];
    int l=0;
    while((state&(1<     int _min=inf;
    for(int j=l+1;j<=n;j++)
    {
        if(state&(1<         {
            int sts=state-(1<             _min=min(_min,dfs(sts)+mat[l][j]);
        }
    }
    return dp[state]=_min;
}
int main()
{
    while(scanf("%d",&n)==1&&n)
    {
        scanf("%d",&m);
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++) mat[i][j]=inf;
            mat[i][i]=0;
        }
        int sum=0;
        memset(du,0,sizeof(du));
        for(int i=0;i         {
            int x,y,z;scanf("%d%d%d",&x,&y,&z);
            sum+=z;
            mat[x][y]=mat[y][x]=min(mat[x][y],z);
            du[x]++,du[y]++;
        }
        int state=0;
        for(int i=1;i<=n;i++)
        {
            if(du[i]&1)
            {
                state|=(1<             }
        }
        for(int k=1;k<=n;k++)
        {
            for(int i=1;i<=n;i++)
            {
                for(int j=1;j<=n;j++)
                {
                    mat[i][j]=min(mat[i][j],mat[i][k]+mat[k][j]);
                }
            }
        }
        memset(dp,-1,sizeof(dp));
        int cnt=dfs(state);
        printf("%d\n",sum+cnt);
    }
    return 0;
}

你可能感兴趣的:(acm_图论,acm_动态规划)