hdu 4396 spfa

2513 단어 cstruct
http://acm.hdu.edu.cn/showproblem.php?pid=4396
제목:
한 점 s 에서 e 까지 적어도 k 개의 변 을 거 쳐 가장 짧 은 값 을 구 하 는 것 은?(무 거 운 쪽으로 갈 수 있다);
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<memory.h>
using namespace std;
const int maxn=6002;
const int maxm=100002;
const int inf=1<<29;
int n,m,s,t,k,NE,f[52][maxn],in[52][maxn],head[maxn];
struct node
{
    int u,v,w,next;
} Edge[maxm<<2];
void addEdge(int u,int v,int w)
{
    Edge[NE].u=u;
    Edge[NE].v=v;
    Edge[NE].w=w;
    Edge[NE].next=head[u];
    head[u]=NE++;
}
struct Link
{
    int step,pos;
} p;
void init()
{
    // k=(k+9)/10;
    if(k % 10) k = k/10 +1;
    else k = k / 10;

    for(int i=0; i<=50; i++)
    {
        for(int j=0; j<=n; j++)
        {
            f[i][j]=inf;
        }
    }
}
void SPFA(int st,int ed)
{
    queue<Link>q;
    p.step=0,p.pos=st;
    q.push(p);
    in[0][st]=1;
    f[0][st]=0;
    while(!q.empty())
    {
        Link tmp=q.front();
        q.pop();
        int step=tmp.step;
        int u=tmp.pos;
        in[step][u]=0;
        for(int i=head[u]; i!=-1; i=Edge[i].next)
        {
            int v=Edge[i].v;
            int w=Edge[i].w;
            int next=step+1;
            if(step==k) next--;
            if(f[next][v]>f[step][u]+w)
            {
                f[next][v]=f[step][u]+w;
                if(!in[next][v])
                {
                    Link tmp;
                    tmp.step=next,tmp.pos=v;
                    in[next][v]=1;
                    q.push(tmp);
                }

            }
        }
    }
    if(f[k][ed]==inf)cout<<-1<<endl;
    else cout<<f[k][ed]<<endl;
}
int main()
{
    //freopen("C:\\Documents and Settings\\Administrator\\  \\ 10         +    +  \\(1006-1008)DLUT\\1007-More lumber is required\\data.in","r",stdin);
   // freopen("C:\\Documents and Settings\\Administrator\\  \\ 10         +    +  \\(1006-1008)DLUT\\1007-More lumber is required\\ans.txt","w",stdout);
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int u,v,c,i,j;
        NE=0;
        memset(head,-1,sizeof(head));
        for(i=1; i<=m; i++)
        {
            scanf("%d%d%d",&u,&v,&c);
            addEdge(u,v,c);
            addEdge(v,u,c);
        }
        scanf("%d%d%d",&s,&t,&k);
        init();
        SPFA(s,t);
    }
    return 0;
}

좋은 웹페이지 즐겨찾기