题目描述
输入
输出
示例输入
1 10 9 2 1 3 2 4 3 5 3 6 3 7 3 8 3 9 3 10 5 10 7 6 3 7 1 2 8 1 2 5
示例输出
0 0 6 4 5 6 7 8 9 0 1 2 1 3 0 1 2 1 3 110
#include<stdio.h> #include<string.h> #include<stdlib.h> #define max 100000 typedef struct node { int data; node *next; }node,*Bnode; void Insert(Bnode &head,int x)//有序的邻接表插入函数...头指针的数据域代表"后面"共有多少个元素对这些元素进行数组存储; { Bnode tail,p,q;//p是q的前驱节点 tail是要插入的节点 tail=new node; tail->data=x; tail->next=NULL; if(head==NULL) { head=new node; head->next=tail; // tail->next=NULL; head->data=1;//元素个数为1; } else { head->data++;//链的数据个数++ p=head; q=head->next; while(q) { if(q->data>x) { p->next=tail; tail->next=q; break;//从小到大排序 遇到大的就插入 然后一定要跳出while } p=p->next; q=q->next; } if(q==NULL) //没找到比x大的 所以把x放在最后 { p->next=tail; //tail->next=NULL; } } } int main() { int i,t,n,m,a,b; scanf("%d",&t); Bnode head[max],tail; while(t--) { scanf("%d%d",&n,&m); for(i=1;i<=n;i++) head[i]=NULL;//初始化 for(i=0;i<m;i++) { scanf("%d%d",&a,&b); Insert(head[b],a);//将a的数据插入到b的节点中 } int q; scanf("%d",&q); for(i=0;i<q;i++) { int key; scanf("%d",&key); if(head[key]==NULL)//key值元素个数为空; printf("0\n"); else { printf("%d\n",head[key]->data);//key值元素的总个数; tail=head[key]->next; while(tail) { printf("%d",tail->data); if(tail->next!=NULL) printf(" "); tail=tail->next; } printf("\n"); } } } }
#include <iostream> #include<cstring> #include<vector> #include<algorithm> #include<cstdio> using namespace std; const int Maxn=100001; vector<int>G[Maxn]; int t,m,n,q; int main() { cin>>t; while(t--) { cin>>n>>m; int i; for(i=1;i<=n;i++) G[i].clear(); while(m--) { int u,v; cin>>u>>v; G[v].push_back(u); } cin>>q; while(q--) { int num; cin>>num; int l=G[num].size(); if(l==0) cout<<"0\n"; else { cout<<l<<endl; sort(G[num].begin(),G[num].end()); vector<int>::iterator it; for(it=G[num].begin();it<G[num].end();it++) printf("%d ",*it); cout<<endl; //printf("%d\n",G[num][G[num].size()-1]); } } } //cout << "Hello world!" << endl; return 0; }