算法训练 关联矩阵

版权声明:菜鸟一枚~~ 有想法可在下面评论, 转载标明出处即可。 https://blog.csdn.net/KLFTESPACE/article/details/82592320

问题描述

  有一个n个结点m条边的有向图,请输出他的关联矩阵。

输入格式

  第一行两个整数n、m,表示图中结点和边的数目。n<=100,m<=1000。
  接下来m行,每行两个整数a、b,表示图中有(a,b)边。
  注意图中可能含有重边,但不会有自环。

输出格式

  输出该图的关联矩阵,注意请勿改变边和结点的顺序。

样例输入

5 9
1 2
3 1
1 5
2 5
2 3
2 3
3 2
4 3
5 4

样例输出

1 -1 1 0 0 0 0 0 0
-1 0 0 1 1 1 -1 0 0
0 1 0 0 -1 -1 1 -1 0
0 0 0 0 0 0 0 1 -1
0 0 -1 -1 0 0 0 0 1

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    int m, n, i, j, p, q;

    cin >> n >> m;
    int map[n+5][m+5];
        memset(map, 0, sizeof(map));
    for(i=1; i<=m; i++)
    {
        cin >> p >> q;
        map[p][i]=1;
        map[q][i]=-1;
    }

    for(i=1; i<=n; i++)
    {
        for(j=1; j<=m; j++)
        {
            cout << map[i][j] << " ";
        }
        cout<<endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/KLFTESPACE/article/details/82592320