poj2387 深搜算法或dijstra算法

dijkstra算法

#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
struct re
{
    int e,d;
    re (int b=0,int c=0)
    {
        e=b;d=c;
    }
    bool operator<(const re it)const
    {
        return d<it.d;
    }
};
const int maxn=1e3+10;
re all[maxn];
vector<re>road[maxn];
priority_queue<re>have;
int best[maxn],n,vis[maxn];
void dijkstra()
{
    have.push(re(n,0));
    memset(best,0x3f3f3f3f,sizeof(best));
    while(!have.empty())
    {
        re get=have.top();
        have.pop();
        for(int i=road[get.e].size()-1;i>=0;--i)
        {
            re a=road[get.e][i];
            int new_d=a.d+get.d;
            if(new_d<best[a.e])
            {
                have.push(re(a.e, new_d));
                best[a.e]=new_d;
            }

        }
    }
}
int main(void)
{
    int t;
    scanf("%d %d",&t,&n);
    for(int i=1;i<=t;++i)
    {
        int a,b,c;
        scanf("%d %d %d",&a,&b,&c);
        road[a].push_back(re(b,c));
        road[b].push_back(re(a,c));
    }
    dijkstra();
    printf("%d",best[1]);
}

深搜算法

include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
struct re
{
    int e,d;
};
const int maxn=2e3+10;
vector<re>all[maxn];
int best[maxn],n;
void dfs(int now,int val)
{
    if(best[now]<=val)return;
    best[now]=val;
    if(now==1)return;
    for(int i=all[now].size()-1;i>=0;--i)
    {
        re tem;
        tem=all[now][i];
        dfs(tem.e,val+tem.d);
    }
}
int main(void)
{
    int t;
    scanf("%d %d",&t,&n);
     for(int i=1;i<=t;++i)
    {
        int a,b,c;
        re tem;
        scanf("%d %d %d",&a,&b,&c);
        tem.d=c;
        tem.e=b;
        all[a].push_back(tem);
        tem.e=a;
        all[b].push_back(tem);
    }
    memset(best,0x3f3f3f3f,sizeof(best));
    dfs(n,0);
    printf("%d",best[1]);
    return 0;
}
发布了114 篇原创文章 · 获赞 22 · 访问量 7007

猜你喜欢

转载自blog.csdn.net/qq_43235540/article/details/104000801