zoukankan      html  css  js  c++  java
  • c++实现洗牌

    输入描述:
    第一行一个数T(T ≤ 100),表示数据组数。对于每组数据,第一行两个数n,k(1 ≤ n,k ≤ 100),接下来一行有2n个数a1,a2,...,a2n(1 ≤ ai ≤ 1000000000)。表示原始牌组从上到下的序列。




    输出描述:
    对于每组数据,输出一行,最终的序列。数字之间用空格隔开,不要在行末输出多余的空格。


    输入例子1:
    3
    3 1
    1 2 3 4 5 6
    3 2
    1 2 3 4 5 6
    2 2
    1 1 1 1


    输出例子1:
    1 4 2 5 3 6

    1 5 4 3 2 6


    该代码实现了一次性连续输入多组纸牌顺序,最后一次性把每个组洗牌结果输出 。而不是输入一组纸牌,立马输出洗牌后的结果。关键是用到了vector再二维数组的使用。

    #include <iostream>
    #include <vector>
    using namespace std;
    int main()
    {
    	void ShuffleCards(vector<int>&cardArray,int k,vector<vector<int> >&outArray,int &t);
    	int T,x;
    	cin>>T;
    	vector<int> xArray;
    	int n,k;
    
    	vector<vector<int> >outArray(T);//定义T行的二维数组,不同行可以不等长
    	int t=0;
    	while (T--)
    	{
    		cin>>n>>k;
    		vector<int> cardArray(2*n);//一组牌
    		for (int i=0;i<2*n;i++)
    			cin>>cardArray[i];
    		ShuffleCards(cardArray,k,outArray,t);
    		t++;
    	}
    	for (int outi=0;outi<t;outi++)
    	{
    		for(vector<int>::const_iterator p=outArray[outi].begin();p!=outArray[outi].end();p++)
    		{
    			if (p==outArray[outi].end()-1)
    				cout<<*p;
    			else
    				cout<<*p<<" ";
    		}
    		if (outi<t-1)
    			cout<<endl;
    	}
    	return 0;
    }
    void ShuffleCards(vector<int>&cardArray,int k,vector<vector<int> >&outArray,int&t)
    {
    	int len=cardArray.size();
    	vector<int>a(len);
    	while (k--)
    	{
    		for (int j=len-1,i=len/2;j>0;j=j-2,i--)
    		{
    			a[j]=cardArray[i+len/2-1];
    			a[j-1]=cardArray[i-1];
    
    		}
    		for (int j=0;j<len;j++)
    			cardArray[j]=a[j];
    	}
    	outArray[t].resize(len);
    	for (int j=0;j<len;j++)
    		outArray[t][j]=cardArray[j];
    }


  • 相关阅读:
    I.MX6 Surfaceflinger 机制
    理解 Android Fragment
    RPi 2B DDNS 动态域名
    RPi 2B IPC webcam server
    理解 Android MVP 开发模式
    I.MX6 system.img unpack repack
    can't set android permissions
    VMware Ubuntu 共享文件夹
    解决oracle数据库连接不上的问题
    perfect-scrollbar示例
  • 原文地址:https://www.cnblogs.com/fushuixin/p/7413206.html
Copyright © 2011-2022 走看看