判断给定森林中有多少棵树特别版
題目描述
眾人皆知,在編程領域中,C++是一門非常重要的語言,不僅僅因為其強大的功能,還因為它是很多其他面向對象語言的祖先和典范。不過這世上幾乎沒什么東 西是完美的,C++也不例外,多繼承結構在帶來強大功能的同時也給軟件設計和維護帶來了很多困難。為此,在java語言中,只允許單繼承結構,并采用接口 來模擬多繼承。KK最近獲得了一份java編寫的迷你游戲的源代碼,他對這份代碼非常感興趣。這份java代碼是由n個類組成的(本題不考慮接口),n個類分別用數字1..n表示。現在給你n個類之間的關系,有q次詢問,每次詢問某一個有多少個直接繼承的子類。輸入子類的個數和標號(標號按照字典序大小輸出)。輸入
首先輸入一個整數T,表示數據的組數。每組數據格式如下。 第一行包含兩個整數n,m,表示該份代碼中的n個類和m個單繼承關系(1<=m<n<=10^5)輸出
對于每組輸入。輸出詢問類的子類的數量和編號。示例輸入
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; }
總結
以上是生活随笔為你收集整理的判断给定森林中有多少棵树特别版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: url类型
- 下一篇: HDU3534 给你一个树让你找出其中最