HDU 1224 Free DIY Tour DAG最長路

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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章