1 solutions
-
0
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; }Java :
import java.util.ArrayList; import java.util.Scanner; public class Main { public static int N, M; public static ArrayList<Integer> temp; public static ArrayList<Integer>[] list; public static long count = 0; public void dfs(int start, int father, int step) { if(step == 3) { if(temp.get(0) != temp.get(2) && temp.get(1) != temp.get(3)) count++; return; } else { for(int i = 0;i < list[start].size();i++) { if(list[start].get(i) == father) continue; temp.add(list[start].get(i)); dfs(list[start].get(i), start, step + 1); temp.remove(temp.size() - 1); } } } @SuppressWarnings("unchecked") public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); N = in.nextInt(); M = in.nextInt(); list = new ArrayList[N + 1]; for(int i = 1;i <= N;i++) list[i] = new ArrayList<Integer>(); for(int i = 1;i <= M;i++) { int u = in.nextInt(); int v = in.nextInt(); list[u].add(v); list[v].add(u); } for(int i = 1;i <= N;i++) { temp = new ArrayList<Integer>(); temp.add(i); test.dfs(i, -1, 0); } System.out.println(count); } }
- 1
Information
- ID
- 16285
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- (None)
- Tags
- # Submissions
- 0
- Accepted
- 0
- Uploaded By