邻接表存储图,然后询问的时候依次输出某个head[]中的元素就行了.....
用矩阵的话会爆内存;
不过题目描述和题目....
///ACcode
#include <bits/stdc++.h> using namespace std; const int maxn=100010; typedef struct node { int data; node *next; } node,*Node; ///有序的邻接表插入函数...头指针的数据域代表"后面"一共有多少个元素 void Insert(Node &head,int x) { Node q,a,tail; ///a是q的前驱节点 tail是要插入的节点 tail=new node; tail->data=x; if (head==NULL) { head=new node; head->data=1; ///初始为 1 head->next=tail; tail->next=NULL; } else if (head!=NULL) { head->data++; ///链的 数据个数++ a=head; ///前驱 q=head->next; while (q) { if (q->data > x) { a->next=tail; tail->next=q; break; ///从小到大排序 遇到大的就插入 然后一定要跳出while } a=a->next; q=q->next; } if (q==NULL) ///没找到比x大的 所以把x放在最后 { a->next=tail; tail->next=NULL; } } } int main() { int n,m,i; int u,v; int key; int t; Node head[maxn],tail; cin>>t; while (t--) { cin>>n>>m; for (i=1; i<=n; i++) ///初始化 { head[i]=NULL; } for (i=1; i<=m; i++) { cin>>u>>v; Insert(head[v],u); ///将u的数据插入到v的节点中 } int q; cin>>q; for (i=1; i<=q; i++) { cin>>key; if (head[key]==NULL) { cout<<"0"<<endl; } else { cout<<head[key]->data<<endl; tail=head[key]->next; while (tail) { cout<<tail->data; if (tail->next!=NULL) { cout<<" "; } tail=tail->next; } cout<<endl; } } } return 0; } 有关的邻接表传送门 http://blog.csdn.net/gentle_guan/article/details/52214869
