bzoj 1706: [usaco2007 Nov]relays cows relay run [matrix multiplication + Floyd]

Well, I don't know how to say it... Probably the core is to turn the multiplication part of the fast power of the matrix into something like Floyd. The very god
first discretizes the points, there are at most 200, and then establishes an adjacency matrix, a[u][v ] is the distance between (u, v), no road is inf,
and then pay attention to the part of overloading the multiplication sign. Note that this multiplication is equivalent to changing the adjacency matrix that originally stored the shortest path through k roads into a storage The adjacency matrix of the shortest path passing through k+1 roads
seems to be enough to multiply n times. Here, we use the matrix fast power
.

#include<iostream>
#include<cstdio>
using namespace std;
const int N=1005;
const long long inf=1e15;
int n,m,s,t,id[N],tot;
struct qwe
{
    long long a[205][205];
    qwe operator * (const qwe &b) const
    {
        qwe c;
        for(int i=1;i<=tot;i++)
            for(int j=1;j<=tot;j++)
                c.a[i][j]=inf;
        for(int k=1;k<=tot;k++) 
            for(int i=1;i<=tot;i++)
                for(int j=1;j<=tot;j++)
                    c.a[i][j]=min(c.a[i][j],a[i][k]+b.a[k][j]);
        return c;
    }
}a,r;
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
int main()
{
    n=read(),m=read(),s=read(),t=read();
    for(int i=1;i<=m;i++)
    {
        int z=read(),x=read(),y=read();
        x=(id[x]!=0)?id[x]:(id[x]=++tot);
        y=(id[y]!=0)?id[y]:(id[y]=++tot);//cerr<<x<<" "<<y<<endl;
        a.a[x][y]=a.a[y][x]=z;
    }
    for(int i=1;i<=tot;i++)
        for(int j=1;j<=tot;j++)
            if(!a.a[i][j])
                a.a[i][j]=inf;
    int x=n-1;
    r=a;
    while(x)
    {
        if(x&1)
            r=r*a;
        a=a*a;
        x>>=1;
    }
    printf("%lld\n",r.a[id[s]][id[t]]);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339435&siteId=291194637