欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HDU 1224 Free DIY Tour DAG最长路

程序员文章站 2024-02-24 17:47:16
...

DAG最长路可以用动态规划或者spfa的方法求。逛了一圈论坛,看见有人说dijkstra也可以,但我自己写了个dijkstra却WA了,还是太菜了呀。

#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<stack>
using namespace std;

int t,n,cas,m,point[105],mapp[105][105],dist[105],fa[105];

int main()
{
    cas=0;
    scanf("%d",&t);
    while (t--)
    {
        cas++;
        stack<int> stacks;
        if (cas>1) cout<<endl;
        cout<<"CASE "<<cas<<"#"<<endl;
        scanf("%d",&n);
        n++;
        for (int i=1; i<n; i++)
        {
            scanf("%d",&point[i]);
        }
        point[n]=0;
        for(int i=1; i<=n; i++)
        {
            for (int j=1; j<=n; j++)
            {
                mapp[i][j]=0;
            }
        }
        for (int i=1; i<=n; i++)
        {
            dist[i]=0; fa[i]=-1;
        }
        scanf("%d",&m);
        for (int i=1; i<=m; i++)
        {
            int a,b; scanf("%d%d",&a,&b);
            mapp[a][b]=1;
        }
        for (int i=1; i<=n; i++)
        {
            for (int j=1; j<=n; j++)
            {
                //cout<<"i="<<i<<" j="<<j<<" disti="<<dist[i]<<" pi="<<point[i]<<" dj"<<dist[j]<<endl;
                if (mapp[i][j] && dist[i]+point[i]>dist[j])
                {
                    dist[j]=dist[i]+point[i];
                    fa[j]=i;
                    //cout<<"j="<<j<<" i="<<i<<endl;
                }
            }
        }
        cout<<"points : "<<dist[n]<<endl;
        cout<<"circuit : 1->";
        int tmp=n;
        stacks.push(1);
        while (fa[tmp]!=-1)
        {
            tmp=fa[tmp];
            stacks.push(tmp);
        }
        int first=true;
        while (!stacks.empty())
        {
            if (first)
            {
                cout<<stacks.top();
                first=false;
            }
            else
            {
                cout<<"->"<<stacks.top();
            }
            stacks.pop();
        }
        cout<<endl;
    }
    return 0;
}