1 条题解

  • 0
    @ 2024-12-24 10:06:03

    C++ :

    #include<cstdio>
    #include<cstring>
    #include<map>
    #include<vector>
    #include<cmath>
    #include<cstdlib>
    #include<stack>
    #include<queue>
    #include <iomanip>
    #include<iostream>
    #include<algorithm>
    using namespace std ;
    const int N=10005 ;
    struct node
    {
        int data ;
        struct node *next ;
    }tab[N];
    int vist[N];
    int cnt ;
    
    void add(int a,int b)
    {
          struct node *q=&tab[a];     //去头结点地址
          while( q->next != NULL)
          {
               q = q->next ;
          }                            //找到链尾,就连上去
          struct node *s ;
          s = (struct node *)malloc(sizeof(struct node)) ;
          q->next =s ;
          s->data =b;
          s->next =NULL ;
    }
    
    void dfs(int x,int n,int s)
    {
            vist[x]=1;
            struct node *q=&tab[x];    //搜到点x,取点x的链表地址,坐标往下搜
            if(n>=3)                   //一条路径有四个点,从起点s开始搜到第四次就满足一条路径
            {
                cnt++;
                return ;
            }
            while( (q=q->next) !=NULL) //往下一个点找
            {
                   int w=q->data;  //下一个点的序号
              if( vist[w]!=1 ||( w == s && n==2 ))//下一个点没访问过,或者下一个点就是起点了
                   {
                        dfs(w,n+1,s);      //可以接着往下搜
                        if( w != s )      //退栈置0 ;
                            vist[w]=0;   //当w==s时,不用 置0,因为总是从s为起点,s一直标记为访问过
                   }
            }
    }
    
    int main()
    {
          int n,m,a,b;
          scanf("%d%d",&n,&m);
          for(int i = 1 ; i <= n ; i++ )    //初始化每个头结点的值
          {
                tab[i].data = i ;
                tab[i].next = NULL ;
          }
          while(m--)
          {
                  scanf("%d%d",&a,&b);      //建图,双向图
                  add(a,b);                 //b与a相连,b连在a的链表上
                  add(b,a);                 //a与b相连,a连在b的链表上
          }
          cnt = 0 ;
          for(int i = 1 ; i <= n ; i++)    //从n条链表上深搜
          {
                 memset(vist,0,sizeof(vist));
                 dfs(i,0,i);              //(当前搜到的点,搜到的是第几个点,起点位置 )
          }
          printf("%d\n",cnt);
          return 0;
    }
    
    
    • 1

    信息

    ID
    1830
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者