A : A DS图_传递信息

Description

小明在和他的小伙伴们玩传消息游戏,游戏规则如下:

  1. 有n名玩家,所有玩家编号分别为0~n-1,其中小明编号为0;
  2. 每个玩家都有固定的若干个可传信息的其他玩家(也可能没有)。传消息的关系是单向的(即,有向边)。
  3. 每轮信息必须传递给另一个人,且信息可重复经过同一个人。
    给定总玩家数n,以及按[玩家编号,对应可传递玩家编号]关系组成的二维数组relation。输出信息从小明(编号0)经过k轮传递到编号为n-1的小伙伴处的方案数;若不能到达,则输出0。
    例如,对于n = 5, len = 7, relation = [[0,2],[2,1],[3,4],[2,3],[1,4],[2,0],[0,4]], k = 3,信息从编号0处开始,经3轮传递,到达编号4,共有3种方案:分别是0->2->0->4,0->2->1->4,0->2->3->4。

Input

第一行输入t,表示有t个测试样例。
接着,首先输入n,表示有n名玩家,接着输入len,表示接下来要输入的二维数组的长度,接着依次输入relation数组,接着输入k。
以此类推,共输入t个测试样例。

Output

每一行输出当前测试样例的方案数量。
以此类推共输出t行。

Sample

Input

3

5
7
0 2
2 1
3 4
2 3
1 4
2 0
0 4
3

3
2
0 2
2 1
2

4
6
0 1
0 2
0 3
1 2
1 3
2 3
3

Output

3
0
1

Hint

2 <= n <= 10
1 <= k <= 5
len == relation.length
1 <= len <= 90
relation[i] == 2
0 <= relation[i][0], relation[i][1] < n
elation[i][0] != relation[i][1]

AC代码

#include<iostream>
using namespace std;
#define INFINITY
//DFS 深度搜索
//有向图
// 信息可重复经过同一个人
int totalWays;//方案数量
class Graph{
public:
    int **matrix;
    int numVertexes,numEdges;
    Graph(int v,int e):numVertexes(v),numEdges(e){
        matrix=new int*[numVertexes];
        for(int i=0;i<numVertexes;i++){
            matrix[i]=new int[numVertexes];
        }
        for(int i=0;i<numVertexes;i++){
            for(int j=0;j<numVertexes;j++){
                matrix[i][j]=0;
            }
        }
        int v1,v2;
        for(int i=0;i<numEdges;i++){
            cin>>v1>>v2;
            matrix[v1][v2]=1;
        }
    }
    ~Graph(){
        for(int i=0;i<numVertexes;i++){
            delete[] matrix[i];
        }
        delete[] matrix;
    }
};
void DFS(Graph &G,int remainrounds,int currenplays){
    if(currenplays==G.numVertexes-1&&remainrounds==0){
        totalWays++;
        return;
    }
    for(int i=0;i<G.numVertexes;i++){
        if(G.matrix[currenplays][i]==1&&remainrounds>0){//击鼓传花
            DFS(G,remainrounds-1,i);
        }
    }
}
int main(){
    int t;
    cin>>t;
    while(t--){
        totalWays=0;//初始化
        int numVertexes,numEdges;
        cin>>numVertexes>>numEdges;//玩家个数 二维数组长度
        Graph G(numVertexes,numEdges);
        int rounds;
        cin>>rounds;
        DFS(G,rounds,0);
        cout<<totalWays<<endl;
    }
    // system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值