C++之数组转换

题目如下:

 

 这道题经过好久的思考也没找到能一次性输入两组数的方法,只能一次性处理一组数,所以就把代码放上来,欢迎交流留言一起讨论可以放两组数的方法~(QQ 841587906)

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <string.h>
 5 #include <sstream>
 6 using namespace std;
 7 
 8 int swapNum(int length,vector<int>,vector<int>);
 9 
10 int main()
11 {
12     /*先接收数列的长度 创建原数组
13     //接收转换数组 遍历转换数组 交换原数组的数据 再跟目标数组比较是否相等
14     //接收目标数组*/
15 
16 
17 
18 
19     vector<int> trans_vec,aim_vec;
20     //数组长度
21     int length;
22     cin >> length;
23 
24     //给两个数组分配空间
25     trans_vec.reserve(length);
26     aim_vec.reserve(length);
27 
28     //接收的数值
29     int number;
30     //数组的索引值
31     int index = 0;
32 
33     //给转换数组和目标数组赋值
34     while(index < length && cin >> number ){
35         trans_vec.insert(trans_vec.begin()+index,number);
36         index ++;
37     }
38     index = 0;
39     while(index < length && cin >> number){
40         aim_vec.insert(aim_vec.begin()+index,number);
41         index ++;
42     }
43 
44     //跳出循环的两个条件:time超过次数;经过time转换变成目标数组
45     int time = swapNum(length,trans_vec,aim_vec);
46     if(time < 50){
47         cout << time << endl;
48     }else{
49         cout << "impossible" << endl;
50     }
51 
52 
53 
54     return 0;
55 
56 }
57 
58 
59 int swapNum(int length,vector<int> trans_vec,vector<int> aim_vec){
60     //创建一个经过变化的目标数组 和 原数组
61     int supposeaim_vec[length],orig_array[length];
62     for(int i = 0;i <length;i++){
63         orig_array[i] = i;
64     }
65 
66     //读取转换数列中的值 来操作原数组
67     //记录执行转换数组的次数
68     int time = 0;
69     bool flag = false;
70     while(time < 50 && !flag){//当超过50就不再继续操作
71         for(int i = 0;i < length; i++){
72             int j = trans_vec[i];
73             //将原数组的第i个元素放到目标数组的第j个位置
74             supposeaim_vec[j] = orig_array[i];
75         }
76         //运行完将原数组
77         memcpy(orig_array,supposeaim_vec,length*sizeof(int));
78         //完成一次就次数+1
79         time++;
80         flag = true;
81         for(int i = 0;i < length;i++){
82             if(supposeaim_vec[i] != aim_vec[i]){
83                 flag = false;
84             }
85         }
86     }
87 
88 
89      return time;
90 
91 }

 

posted on 2020-03-27 19:47  秃头女孩今夜也不睡觉  阅读(749)  评论(0编辑  收藏  举报

导航