hdu4849 Wow! Such City!

最短路算法.    照他说的 把x,y,z三个数组处理出来,之后就是裸的最短路了.   最后注意下取模就好.

#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
#define ll __int64
const int N = 1150;
ll INF = 0x3f3f3f3f;


ll y[N*N],x[N*N],z[N*N];
ll n,m;
ll map[N][N], dist[N];
bool visit[N];


void turn()
{
int i,j;
for(i=0;i<=1;i++)
z[i]=(x[i]*90123+y[i])%8475871+1;
for(i=2;i<n*n;i++)
{
x[i] = (12345+x[i-1]*23456+x[i-2]*34567+x[i-1]*x[i-2]*45678)%5837501;
   y[i] = (56789+y[i-1]*67890+y[i-2]*78901+y[i-1]*y[i-2]*89012)%9860381; 
   z[i]=(x[i]*90123+y[i])%8475871+1;

}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
map[i+1][j+1]=0;
else
map[i+1][j+1]=z[i*n+j];
}
}
}


void dijk()     //Dijkstra算法
{
    int i, j, next;
    ll MIN;
    memset(visit, false, sizeof(visit));
    for(i = 1; i <= n; i++) dist[i] = INF;
    dist[1] = 0;
    for(i = 1; i <= n; i++)
    {
        MIN = INF;
        for(j = 1; j <= n; j++)
            if(!visit[j] && dist[j] <= MIN)
                MIN = dist[next=j];
        if(MIN == INF) break;
        visit[next] = true;
        for(j = 1; j <= n; j++)
            if(!visit[j] && dist[j] > dist[next] + map[next][j])
                dist[j] = dist[next] + map[next][j];
    }
}


void spfa()     //SPFA算法
{
    int i, now;
    memset(visit, false, sizeof(visit));
    for(i = 1; i <= n; i++) dist[i] = INF;
    dist[1] = 0;
    queue<int> Q;
    Q.push(1);
    visit[1] = true;
    while(!Q.empty())
    {
        now = Q.front();
        Q.pop();
        visit[now] = false;
        for(i = 1; i <= n; i++)
        {
            if(dist[i] > dist[now] + map[now][i])
            {
                dist[i] = dist[now] + map[now][i];
                if(visit[i] == 0)
                {
                    Q.push(i);
                    visit[i] = true;
                }
            }
        }
    }
}
int main()
{
int i;
    while(scanf("%I64d%I64d%I64d%I64d%I64d%I64d",&n,&m,&x[0],&x[1],&y[0],&y[1])!=EOF)
{
turn();
spfa();//也可以用 dijk();
   ll min=INF;
ll ans;
        for(i=2;i<=n;i++)
        {
ans=dist[i]%m;
            if(min>ans)
                min=ans;
        }
        printf("%I64d\n",min);
}
return 0;
}

你可能感兴趣的:(C++,算法,最短路)