题目四 艺术品
Dr.Kong設計了一件藝術品,該藝術品由N個構件堆疊而成,N個構件從高到低按層編號依次為1,2,……,N。藝術品展出后,引起了強烈的反映。Dr.Kong觀察到,人們尤其對作品的高端部分評價甚多。
?
狂熱的Dr.Kong一激動,對組成該藝術品的N個構件重新組合,比如:把第6層到第12層的構件搬下來,想一想,然后整體放到剩下構件的第7層下面;過一會兒,又把第2層到第9層的構件搬下來,整體放到剩下構件的第1層下面等等。于是,Dr.Kong在進行了連續若干次“搬來搬去”后,還是這N個構件,又誕生了一件新的藝術品。
?
編程:請輸出新的藝術品最高十層構件的編號。
【標準輸入】
第一行: N K?????? 表示構件的總數和“搬來搬去”的總次數
第2~K+1行:A B C????? 表示要搬動的構件(即從第A層到第B層)整個放在第C層下面;
如果C等于0,則要搬動的構件將放到最高層。
【標準輸出】
由十行組成,分別為組成新藝術品的第一層到第十層構件的編號。
【約束條件】
(1)?? 10≤N≤20000??? 1≤k≤1000
(2)?? 1≤A≤B≤N,????? 0≤C≤N-(B-A+1)
【 樣? 例 】
?
| 標準輸入 | 標準輸出 |
| 13 3 6 12 1 2 9 0 10 13 8 ? | 6 7 8 9 10 11 12 2 3 4 |
?
數據結構的作業,我用的方法算是很笨的了,并且我也沒經歷過算法訓練,所以代碼寫的很差,僅供參考。
整體思路就是用鏈表保存藝術品,節點定義為:
typedef struct Lnode{ int num;Lnode* next; }node,*LinkList;
num表示藝術品編號。
整體代碼如下:
1 /* 2 zp 3 zzti 4 2012/10/06 5 */ 6 #include<iostream> 7 using namespace std; 8 typedef struct Lnode{ 9 int num; //藝術品編號 10 Lnode* next; 11 }node,*LinkList; 12 void CreatList(LinkList& l,int n) //初始化鏈表,給所有節點賦值 13 { 14 node* p=new node; 15 p->next=NULL; 16 p->num=0; 17 l=p; 18 for(int i=0;i<n;i++) 19 { 20 node* q=new node; 21 q->num=i+1; 22 q->next=NULL; 23 p->next=q; 24 p=p->next; 25 } 26 } 27 28 void Move(LinkList& l,int a ,int b,int c){ 29 node* p=l; 30 node* headpre,*tailpre; //a的前一個位置和b的前一個位置 31 int i=0; 32 //第一次遍歷,找出ab的位置 33 while(p->next!=NULL) 34 { 35 i++; 36 if(i==a) 37 { 38 headpre=p; 39 } 40 if(i==b) 41 { 42 tailpre=p;; 43 } 44 p=p->next; 45 } 46 node* head=headpre->next; //a的位置 47 node* tail=tailpre->next; //b的位置 48 headpre->next=tail->next; 49 50 //第二次遍歷,將抽出的鏈表重新插入到合適的位置 51 p=l;i=0; 52 while(p->next) 53 { 54 if(i==c) 55 { 56 node* q=p->next; //將鏈表插入 57 p->next=head; 58 tail->next=q; 59 } 60 i++;p=p->next; 61 } 62 } 63 64 void PrRes(LinkList l) { //PrintResult 65 int i=0; 66 node* p=l->next; 67 while(i<10) 68 { 69 cout<<p->num<<endl; 70 i++; 71 p=p->next; 72 } 73 } 74 75 76 int main() 77 { 78 79 int n,k,a,b,c,t1,t2,t3; 80 cout<<"請輸入n,k:"<<endl; 81 do{ 82 cin>>t1>>t2; 83 if(t1<10||t1>20000||t2<1||t2>>1000) 84 { 85 cout<<"輸入數據超過規定范圍,請重新輸入!"<<endl; 86 } 87 else break; 88 89 }while(1); 90 n=t1;k=t2; 91 LinkList l; 92 CreatList(l,n); 93 for(int i=0;i<k;i++) 94 { 95 cout<<"請輸入要搬運的范圍以及放置位置:"<<endl; 96 do{ 97 cin>>t1>>t2>>t3; 98 if(t1<1||t1>n||t2<1||t2>n||t1>t2||t3<0||t3>(n-(t2-t1+1))) 99 { 100 cout<<"輸入數據有誤,請重新輸入!"<<endl; 101 } 102 else break; 103 }while(1); 104 a=t1,b=t2,c=t3; 105 Move(l,a,b,c); 106 } 107 PrRes(l); 108 return 0; 109 } 110?
?
轉載于:https://www.cnblogs.com/csonezp/archive/2012/10/06/2712685.html
總結
- 上一篇: 怎样配置键盘最方便,以及一些设计的思考
- 下一篇: C# 类(14) 事件