zoukankan      html  css  js  c++  java
  • Graph I

    Graph

    There are two standard ways to represent a graph G=(V,E)G=(V,E), where VV is a set of vertices and EE is a set of edges; Adjacency list representation and Adjacency matrix representation.

    An adjacency-list representation consists of an array Adj[|V|]Adj[|V|] of |V||V| lists, one for each vertex in VV. For each uVu∈V, the adjacency list Adj[u]Adj[u] contains all vertices vv such that there is an edge (u,v)E(u,v)∈E. That is, Adj[u]Adj[u] consists of all vertices adjacent to uu in GG.

    An adjacency-matrix representation consists of |V|×|V||V|×|V| matrix A=aijA=aij such that aij=1aij=1 if (i,j)E(i,j)∈E, aij=0aij=0 otherwise.

    Write a program which reads a directed graph GG represented by the adjacency list, and prints its adjacency-matrix representation. GG consists of n(=|V|)n(=|V|) vertices identified by their IDs 1,2,..,n1,2,..,nrespectively.

    Input

    In the first line, an integer nn is given. In the next nn lines, an adjacency list Adj[u]Adj[u] for vertex uu are given in the following format:

    ukv1v1 v2v2 ... vkvk

    uu is vertex ID and kk denotes its degree. vivi are IDs of vertices adjacent to uu.

    Output

    As shown in the following sample output, print the adjacent-matrix representation of GG. Put a single space character between aijaij.

    Constraints

    • 1n1001≤n≤100

    Sample Input

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

    Sample Output

    0 1 0 1
    0 0 0 1
    0 0 0 0
    0 0 1 0

    #include <iostream>
    using namespace std;
    const int N = 100;
    
    int main()
    {
    	int M[N][N];	// 0 0起点的邻接矩阵
    	int n, u, k, v;
    	
    	cin >> n;
    	for(int i = 0; i < n; ++ i)
    	{
    		for(int j = 0; j < n; ++ j)
    		{
    			M[i][j] = 0;
    		}
    	} 
    	
    	for(int i = 0; i < n; ++ i)
    	{
    		cin >> u >> k;
    		u --;	// 转换为0起点 
    		for(int j = 0; j < k; ++ j)
    		{
    			cin >> v;
    			v --;	// 转换为0起点 
    			M[u][v] = 1;	// 在u和v之间画出一条边 
    		}
    	}
    	
    	for(int i = 0; i < n; ++ i)
    	{
    		for(int j = 0; j < n; ++ j)
    		{
    			if(j)	cout << " ";
    			cout << M[i][j];
    		}
    		cout << endl;
    	}
    	
    	return 0;
    } 
    

      

  • 相关阅读:
    永续债的会计处理
    python基于粒子群优化的投资组合优化研究
    R语言使用Metropolis- Hasting抽样算法进行逻辑回归
    R语言使用K-Means聚类可视化WiFi访问
    R语言实现拟合神经网络预测和结果可视化
    Python Monte Carlo K-Means聚类实战研究
    R语言: GARCH模型股票交易量的研究道琼斯股票市场指数
    R语言stan泊松回归Poisson regression
    R语言旅行推销员问题TSP
    在R语言和Stan中估计截断泊松分布
  • 原文地址:https://www.cnblogs.com/mjn1/p/10796757.html
Copyright © 2011-2022 走看看