poj 3159 Candies

http://poj.org/problem?id=3159

经过我不断的尝试 老天重要显灵了

终于来个个 1400+ms  伤不起呀

用 queue 过不了 得用 stack

可能对于后台数据 queue 会有一些多余的搜索

也可能时 stack 本身比 queue 用快一些

anyway 我的代码就得用 stack

还有就是题目描述有点问题

 它是让我们求 flymouse 最多比 snoopy 多得多少 candy

#include<iostream>

#include<cstdio>

#include<string>

#include<queue>

#include<stack>

#include<cstring>



using namespace std;



const int N=30005;

stack<int>str;//需要用 stack 不能用 queue

struct node

{

    struct tt *next;

}mem[N];//需要用邻接表

int dis[N];

bool in[N];

struct tt

{

    struct tt *next;

    int j;

    int x;

};

inline void build(int i,int j,int x)

{

    struct tt *t=new tt;

    t->j=j;

    t->x=x;

    t->next=mem[i].next;

    mem[i].next=t;

}

int n;

void findans()

{

   memset(dis,-1,sizeof(dis));//距离

   memset(in,false,sizeof(in));//是否在栈 中

   dis[1]=0;

   in[1]=true;

   str.push(1);//1 入栈

   int k;

   struct tt *t;

   while(!str.empty())

   {

       k=str.top();

       str.pop();

       in[k]=false;

       t=mem[k].next;

       while(t!=NULL)

       {

           if(dis[t->j]>dis[k]+t->x||dis[t->j]==-1)//无论 t->j 在不在栈中 可更新时就更新

           {

               dis[t->j]=dis[k]+t->x;

               if(!in[t->j]&&t->j!=n)//但只有 不在栈中时 才 入栈 防止重复搜索

               {str.push(t->j);in[t->j]=true;}

           }

           t=t->next;

       }

   }

}

int main()

{

    int m,i,j,x;

    scanf("%d %d",&n,&m);

    while(m--)

    {

        scanf("%d %d %d",&i,&j,&x);

        if(i!=n&&j!=1)//剪掉无意义的边

        build(i,j,x);

    };

    findans();

    printf("%d\n",dis[n]);

    return 0;

}

 

你可能感兴趣的:(poj)