首页 > 代码库 > hdu 1428 漫步校园

hdu 1428 漫步校园

http://acm.hdu.edu.cn/showproblem.php?pid=1428

dijstra+dp;

 1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 #include <algorithm> 5 #define maxn 100 6 #define ll __int64 7 using namespace std; 8 const int inf=1<<29; 9 10 int g[maxn][maxn];11 bool vis[maxn][maxn];12 ll dis[maxn][maxn];13 ll dp[maxn][maxn];14 int n;15 int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};16 struct node17 {18     int x,y,w;19     bool friend operator <(node a,node b)20     {21         return a.w>b.w;22     }23 }st1,st;24 25 void dijstra(int x,int y)26 {27     memset(vis,false,sizeof(vis));28     for(int i=0; i<=n; i++)29     {30         for(int j=0; j<=n; j++)31         {32             dis[i][j]=inf;33         }34     }35     priority_queue<node>q;36     st.x=x;37     st.y=y;38     st.w=g[x][y];39     dis[x][y]=g[x][y];40     q.push(st);41     while(!q.empty())42     {43         st1=q.top();q.pop();44         if(vis[st1.x][st1.y]) continue;45         vis[st1.x][st1.y]=true;46         for(int i=0; i<4; i++)47         {48             int xx=st1.x+dir[i][0];49             int yy=st1.y+dir[i][1];50             if(xx>=0&&xx<n&&yy>=0&&yy<n&&!vis[xx][yy])51             {52                 if(dis[st1.x][st1.y]+g[xx][yy]<dis[xx][yy])53                 {54                     dis[xx][yy]=dis[st1.x][st1.y]+g[xx][yy];55                     st.x=xx;56                     st.y=yy;57                     st.w=dis[xx][yy];58                     q.push(st);59                 }60             }61         }62     }63 }64 65 ll dfs(int x,int y)66 {67     if(dp[x][y]) return dp[x][y];68     for(int i=0; i<4; i++)69     {70         int x1=x+dir[i][0];71         int y1=y+dir[i][1];72         if(x1>=0&&x1<n&&y1>=0&&y1<n&&dis[x1][y1]<dis[x][y])73         dp[x][y]+=dfs(x1,y1);74     }75     return dp[x][y];76 }77 int main()78 {79      while(scanf("%d",&n)!=EOF)80      {81          memset(g,0,sizeof(g));82          for(int i=0; i<n; i++)83          {84              for(int j=0; j<n; j++)85              {86                  scanf("%d",&g[i][j]);87              }88          }89          dijstra(n-1,n-1);90          memset(dp,0,sizeof(dp));91          dp[n-1][n-1]=1;92          printf("%I64d\n",dfs(0,0));93      }94      return 0;95 }
View Code