Optimal Symmetric Paths
Optimal Symmetric Paths |
You have a grid of n rows and n columns. Each of the unit squares contains a non-zero digit. You walk from the top-left square to the bottom-right square. Each step, you can move left, right, up or down to the adjacent square (you cannot move diagonally), but you cannot visit a square more than once. There is another interesting rule: your path must be symmetric about the line connecting the bottom-left square and top-right square. Below is a symmetric path in a 6 x 6 grid.
Your task is to find out, among all valid paths, how many of them have the minimal sum of digits?
Input
There will be at most 25 test cases. Each test case begins with an integer n ( 2n100). Each of the next n lines contains n non-zero digits (i.e. one of 1, 2, 3, ..., 9). These n2 integers are the digits in the grid. The input is terminated by a test case with n = 0, you should not process it.Output
For each test case, print the number of optimal symmetric paths, modulo 1,000,000,009.Sample Input
2 1 1 1 1 3 1 1 1 1 1 1 2 1 1 0
Sample Output
2 3
求从坐上角到右下角的所有路中,权值最小的路有多少条
要求路径必须与图中所示对角线对称
#include<stdio.h>
#include<string.h>
#include<set>
#include<algorithm>
#define M 105
#define INF 0xfffffff
#define MOD 1000000009
using namespace std;
struct node
{
int no,dis;
bool operator <(const node &A)const
{
if (dis!=A.dis)
return dis<A.dis;
else return no<A.no;
}
}tmp;
struct edge
{
int to,v,next;
}edge[M*M*10];
int n,tot;
int dis[M*M],cnt[M*M];
bool v[M*M];
int map[M][M];
int head[M*M];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
void add(int a,int b,int c)
{
edge[tot].to=b; edge[tot].v=c;
edge[tot].next=head[a]; head[a]=tot++;
}
set<node> st;
void SPFA()
{
int i,p;
st.clear();
memset(v,false,sizeof(v));
memset(dis,-1,sizeof(dis));
memset(cnt,0,sizeof(cnt));
dis[0]=map[0][0];
tmp.dis=map[0][0];
tmp.no=0;
cnt[0]=1;
st.insert(tmp);
while(!st.empty())
{
tmp= *st.begin();
st.erase(st.begin());
p=tmp.no;
if(v[p]) continue;
v[p]=true;
for(i=head[p];i!=-1;i=edge[i].next)
{
int u=edge[i].to;
if(dis[u]==-1||dis[p]+edge[i].v<dis[u])
{
dis[u]=dis[p]+edge[i].v;
cnt[u]=cnt[p];
tmp.no=u;
tmp.dis=dis[u];
st.insert(tmp);
}
else if(dis[p]+edge[i].v==dis[u])
{
cnt[u]+=cnt[p];
cnt[u]=cnt[u]%MOD;
}
}
}
}
int Isin(int x,int y)
{
return x>=0&&x<n&&y>=0&&y<n;
}
int main()
{
int i,j,k;
int x,y,mn,ans;
while(scanf("%d",&n)&&n)
{
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&map[i][j]);
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
map[i][j]+=map[n-j-1][n-i-1];
memset(head,-1,sizeof(head));
tot=0;
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
for(k=0;k<4;k++)
{
x=i+dir[k][0];
y=j+dir[k][1];
if(Isin(x,y))
add(i*n+j,x*n+y,map[x][y]);
}
SPFA();
mn=INF;
ans=0;
for(i=0;i<n;i++)
{
x=i;
y=n-i-1;
if(dis[x*n+y]<mn)
mn=dis[x*n+y];
}
for(i=0;i<n;i++)
{
x=i;
y=n-i-1;
if(dis[x*n+y]==mn)
{
ans+=cnt[x*n+y];
ans=ans%MOD;
}
}
printf("%d\n",ans);
}
return 0;
}