uva208 dfs+Floyd

经历:
用链表做了一次,又用邻接矩阵做了,都tle
百度查知用floyd来判断能否到达终点,实现剪枝。
使用floyd后依然tle,先是发现是floy的某个地方自己写错了,最后发现memset的使用方法自己一直都不会。

把数组中的每个数变为无穷大时,用memset(all,0x3f,sizeof(all));
用0x3f即把每个数变为0x3f3f3f3f,如此无穷大+无穷大依然为无穷大,防止了溢出。
具体看这个网站 https://blog.csdn.net/jolinxia/article/details/39324061

floyd看这个网站
(http://www.cnblogs.com/biyeymyhjob/archive/2012/07/31/2615833.html)

ac代码如下

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=30;
bool mp[maxn][maxn],vi[maxn];
int flo[maxn][maxn];
int fin;
const int wuq=0x3f3f3f3f;
int ans[maxn],cnt;
void dfs(int cu,int th,int lim)
{
    if(cu==fin)
{printf("1");
    for(int i=2;i<th;i++)printf(" %d",ans[i]);printf("\n");cnt++;return;}
    for(int i=1;i<=lim;i++)
    {
        if(!vi[i]&&flo[i][fin]!=wuq&&mp[cu][i])
        {
            vi[i]=1;
            ans[th]=i;
            dfs(i,th+1,lim);
            vi[i]=0;
        }
    }
}
int main(void)
{ans[1]=1;
vi[1]=1;
int time=0;
    while(scanf("%d",&fin)!=EOF)
    {memset(mp,0,sizeof(mp));

        int fr,to,most=-1;
        memset(flo,0x3f,sizeof(flo));
        while(1)
        {
            scanf("%d%d",&fr,&to);
            if(fr==0)break;
            mp[fr][to]=mp[to][fr]=1;
            flo[fr][to]=flo[to][fr]=1;
            most=max(max(fr,to),most);
        }

        int i,d,k;
        for(k=1;k<=most;k++)
            for(i=1;i<=most;i++)
            for(d=1;d<=most;d++)
            flo[i][d]=min(flo[i][d],flo[i][k]+flo[k][d]);

        cnt=0;
         printf("CASE %d:\n",++time);
        dfs(1,2,most);
          printf("There are %d routes from the firestation to streetcorner %d.\n",cnt,fin);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43235540/article/details/86656751
今日推荐