程序设计与算法(三)

001:简单一点的swap

#include <iostream>
using namespace std;
class A
{
	public:
	int x;
	int getX() { return x; }	
};
void swap(A &a,A &b)
{
	int  tmp = a.x;
	a.x = b.x;
	b.x = tmp;
}
int main()
{
	A a,b;
	a.x = 3;
	b.x = 5;
	swap(a,b);
	cout << a.getX() << "," << b.getX();
	return 0;
}

002:难一点的swap

#include <iostream>
using namespace std;

void swap(int *&a,int *&b)
{
	int * tmp = a;
	a = b;
	b = tmp;
}
int main()
{
	int a = 3,b = 5;
	int * pa = & a;
	int * pb = & b;
	swap(pa,pb);
	cout << *pa << "," << * pb;
	return 0;
}

003:好怪异的返回值

#include <iostream>
using namespace std;
int & getElement(int * a, int i)
{
	return a[i];
}
int main()
{
	int a[] = {1,2,3};
	getElement(a,1) = 10;
	cout << a[1] ;
	return 0;
}

004:神秘的数组初始化

#include <iostream>
using namespace std;

int main()
{
	int * a[] = {NULL,NULL,new int,new int[6]};
	
	*a[2] = 123;
	a[3][5] = 456;
	if(! a[0] ) {
		cout << * a[2] << "," << a[3][5];
	}
	return 0;
}

005:编程填空:学生信息处理程序

#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <cstdlib>
using namespace std;
class Student {
	private:
		char name[20];
		int id,age;
		float a,b,c,d;
		char ch;
	public:
		void input()
		{
			cin.get(name,21,',');
			cin >> ch >> age >> ch >> id >> ch >> a >> ch >> b >> ch >> c >> ch >> d;
		}
		float calculate()
		{
			float sum = a + b + c + d;
			return sum / 4;
		}
		bool t()
		{
			float sum = (a + b + c + d) / 4;
			int a = sum;
			if(a == sum)
			return true;
			else return false;
		}
		void output()
		{
			float mid = calculate();
			cout << name << "," << age << "," << id << ",";
			if(t() == false)
			{
				printf("%.1f",mid);
			}
			else
			printf("%.0f",mid);
		}
};
int main() {
	Student student;        // 定义类的对象
	student.input();        // 输入数据
	student.calculate();    // 计算平均成绩
	student.output();       // 输出数据
}

006:奇怪的类复制

#include <iostream>
using namespace std;
class Sample {
public:
	int v;
	Sample(int n = 0)
	{
		v = n;
	 } 
	 Sample(const Sample &x)
	{
		v = x.v + 2;
	}
};
void PrintAndDouble(Sample o)
{
	cout << o.v;
	cout << endl;
}
int main()
{
	Sample a(5);
	Sample b = a;
	PrintAndDouble(b);
	Sample c = 20;
	PrintAndDouble(c);
	Sample d;
	d = a;
	cout << d.v;
	return 0;
}

007:返回什么才好呢

#include <iostream>
using namespace std;
class A {
public:
	int val;

	A(int m)
	{
		val = m;
	}
	A()
	{
		val = 123;
	}
	A & GetObj()
	{
		return *this;
	}
};
int main()
{
	int m,n;
	A a;
	cout << a.val << endl;
	while(cin >> m >> n) {
		a.GetObj() = m;
		cout << a.val << endl;
		a.GetObj() = A(n);
		cout << a.val<< endl;
	}
	return 0;
}

008:超简单的复数类

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
    double r,i;
public:
    void Print() {
        cout << r << "+" << i << "i" << endl;
    }
    Complex &operator = (const char *s)
    {
    	string str = s;
    	int pos = str.find("+",0);
    	string strReal = str.substr(0,pos);
    	r = atof(strReal.c_str());
    	string strImaginary = str.substr(pos + 1,str.length() - pos - 2);
    	i = atof(strImaginary.c_str());
    	return *this;
	}
};
int main() {
    Complex a;
    a = "3+4i"; a.Print();
    a = "5+6i"; a.Print();
    return 0;
}

009:哪来的输出

#include <iostream>
using namespace std;
class A {
	public:
		int i;
		A(int x) { i = x; }
		~A(){
			cout << i <<endl;
		}
};
int main()
{
	A a(1);
	A * pa = new A(2);
	delete pa;
	return 0;
}

010:返回什么才好呢

#include <iostream>
using namespace std;
class A {
public:
	int val;

	A(int m)
	{
		val = m;
	}
	A()
	{
		val = 123;
	}
	A & GetObj()
	{
		return * this;
	}
};
int main()
{
	int m,n;
	A a;
	cout << a.val << endl;
	while(cin >> m >> n) {
		a.GetObj() = m;
		cout << a.val << endl;
		a.GetObj() = A(n);
		cout << a.val<< endl;
	}
	return 0;
}

011:Big & Base 封闭类问题

#include <iostream>
#include <string>
using namespace std;
class Base {
public:
	int k;
	Base(int n) :k(n) { }
};
class Big
{
public:
	int v;
	Base b;
	// 在此处补充你的代码
	Big(int n) :b(n)
	{
		v = n;
	}
};
int main()
{
	int n;
	while (cin >> n) {
		Big a1(n);
		Big a2 = a1;
		cout << a1.v << "," << a1.b.k << endl;
		cout << a2.v << "," << a2.b.k << endl;
	}
}

012:这个指针哪来的

#include <iostream>
using namespace std;

struct A
{
	int v;
	A(int vv) :v(vv) { }
	const A* getPointer() const{
		return this;
	}
};

int main()
{
	const A a(10);
	const A* p = a.getPointer();
	cout << p->v << endl;
	return 0;
}

013:魔兽世界之一:备战

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
const int  WARRIOR_NUM = 5;
/*
string Warrior::names[WARRIOR_NUM] = { "dragon","ninja","iceman","lion","wolf" };
红方司令部按照 iceman、lion、wolf、ninja、dragon 的顺序制造武士。
蓝方司令部按照 lion、dragon、ninja、iceman、wolf 的顺序制造武士。
*/
 
class Headquarter;
class Warrior
{
	private:
		Headquarter * pHeadquarter;
		int kindNo; //武士的种类编号 0 dragon 1 ninja 2 iceman 3 lion 4 wolf
		int no;
	public:
		static string names[WARRIOR_NUM];
		static int initialLifeValue [WARRIOR_NUM];
		Warrior( Headquarter * p,int no_,int kindNo_ );
		void PrintResult(int nTime);
};
 
class Headquarter
{
	private:
		int totalLifeValue;
		bool stopped;
		int totalWarriorNum;
		int color;
		int curMakingSeqIdx; //当前要制造的武士是制造序列中的第几个
		int warriorNum[WARRIOR_NUM]; //存放每种武士的数量
		Warrior * pWarriors[1000];
	public:
		friend class Warrior;//为啥要定义友元?   方便访问私有成员 
		static int makingSeq[2][WARRIOR_NUM]; //武士的制作顺序序列
		void Init(int color_, int lv);
		~Headquarter () ;
		int Produce(int nTime);
		string GetColor();
 
};
 
 
Warrior::Warrior( Headquarter * p,int no_,int kindNo_ ) {
	no = no_;
	kindNo = kindNo_;
	pHeadquarter = p;
}
 
void Warrior::PrintResult(int nTime)
{
    string color =  pHeadquarter->GetColor();
    printf("%03d %s %s %d born with strength %d,%d %s in %s headquarter\n"	,
        nTime, color.c_str(), names[kindNo].c_str(), no, initialLifeValue[kindNo],
        pHeadquarter->warriorNum[kindNo],names[kindNo].c_str(),color.c_str());// string 在printf中输出的函数调用c_str() 
}
 
void Headquarter::Init(int color_, int lv)
{
	color = color_;
	totalLifeValue = lv;
	totalWarriorNum = 0;
	stopped = false;
	curMakingSeqIdx = 0;
	for( int i = 0;i < WARRIOR_NUM;i++ )
		warriorNum[i] = 0;
}
 
Headquarter::~Headquarter () {
	for( int i = 0;i < totalWarriorNum;i++ )
		delete pWarriors[i];
}
 
int Headquarter::Produce(int nTime)
{
 
	if( stopped )
		return 0;
	int searchingTimes = 0;
	while( Warrior::initialLifeValue[makingSeq[color][curMakingSeqIdx]] > totalLifeValue &&
		searchingTimes < WARRIOR_NUM ) {
		curMakingSeqIdx = ( curMakingSeqIdx + 1 ) % WARRIOR_NUM;
		searchingTimes++;
	}
	int kindNo = makingSeq[color][curMakingSeqIdx];
	if( Warrior::initialLifeValue[kindNo] > totalLifeValue ) {
		stopped = true;
		if( color == 0)
			printf("%03d red headquarter stops making warriors\n",nTime);
		else
			printf("%03d blue headquarter stops making warriors\n",nTime);
		return 0;
	}
	//制作士兵:
	totalLifeValue -= Warrior::initialLifeValue[kindNo];
	curMakingSeqIdx = ( curMakingSeqIdx + 1 ) % WARRIOR_NUM;
	pWarriors[totalWarriorNum] = new Warrior( this,totalWarriorNum+1,kindNo);
	warriorNum[kindNo]++;
	pWarriors[totalWarriorNum]->PrintResult(nTime);
	totalWarriorNum++;
	return 1;
}
 
string Headquarter::GetColor()
{
	if( color == 0)
		return "red";
	else
		return "blue";
}
 
string Warrior::names[WARRIOR_NUM] = { "dragon","ninja","iceman","lion","wolf" };
int Warrior::initialLifeValue [WARRIOR_NUM];
int Headquarter::makingSeq[2][WARRIOR_NUM] = { { 2,3,4,1,0 },{3,0,1,2,4} }; //两个司令部武士的制作顺序序列
 
int main()
{
	int t;
	int m;
	Headquarter RedHead,BlueHead;
	scanf("%d",&t);
	int nCaseNo = 1;
	while ( t-- ) {
		printf("Case:%d\n",nCaseNo++);
		scanf("%d",&m);
		for( int i = 0;i < WARRIOR_NUM;i++ )
		scanf("%d", & Warrior::initialLifeValue[i]);
		RedHead.Init(0,m);
		BlueHead.Init(1,m);
		int nTime = 0;
		while(true) {
			int tmp1 = RedHead.Produce(nTime);
			int tmp2 = BlueHead.Produce(nTime);
			if( tmp1 == 0 && tmp2 == 0)
				break;
			nTime++;
		}
	}
	return 0;
}

014:MyString

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class MyString {
	char * p;
public:
	MyString(const char * s) {
		if (s) {
			p = new char[strlen(s) + 1];
			strcpy(p, s);
		}
		else
			p = NULL;
	}
	~MyString() { 
		if (p) delete[] p;
	}
 
	// 在此处补充你的代码
	void Copy(char* s) {
		p = new char[strlen(s) + 1];
		strcpy(p, s);
	}
	friend ostream& operator<< (ostream& o, const MyString& s)
	{
		o << s.p;
		return o;
	}
	MyString& operator =(char * w) {
		p = new char[strlen(w) + 1];
		strcpy(p, w);
		return *this;
	}
	MyString& operator =(MyString& s) {
		p = new char[strlen(s.p) + 1];
		strcpy(p, s.p);
		return *this;
	}
	//补充代码结束
};
 
int main()
{
	char w1[200], w2[100];
	while (cin >> w1 >> w2) {
		MyString s1(w1), s2 = s1;
		MyString s3(NULL);
		s3.Copy(w1);
		cout << s1 << "," << s2 << "," << s3 << endl;
 
		s2 = w2;
		s3 = s2;
		s1 = s3;
		cout << s1 << "," << s2 << "," << s3 << endl;
	}
}

015:看上去好坑的运算符重载

#include <iostream> 
using namespace std;
class MyInt 
{ 
	int nVal; 
	public: 
	MyInt( int n) { nVal = n ;}
 
MyInt& operator -(int a){
        nVal-=a;
        return *this;
    }
    operator int () {
    return nVal;
    }
}; 
int Inc(int n) {
	return n + 1;
}
int main () { 
	int n;
	while(cin >>n) {
		MyInt objInt(n); 
		objInt-2-1-3; 
		cout << Inc(objInt);
		cout <<","; 
		objInt-2-1; 
		cout << Inc(objInt) << endl;
	}
	return 0;
}

016:惊呆!Point竟然能这样输入输出

#include <iostream> 
using namespace std;
class Point { 
	private: 
		int x; 
		int y; 
	public: 
		Point() { };
friend istream &operator >>(istream &in, Point &a)
	{
		in >> a.x >> a.y;
		return in;
	}
	friend ostream &operator <<(ostream &o,const Point &a)
	{
		o << a.x <<"," << a.y;
		return o;
	}

}; 
int main() 
{ 
 	Point p;
 	while(cin >> p) {
 		cout << p << endl;
	 }
	return 0;
}

017:二维数组类

#include <iostream>
#include <cstring>
using namespace std;
 
class Array2 {
// 在此处补充你的代码
private:
    int ** p;//数组指针的指针,关键!
    int col,row;
public:
    //构造函数
    Array2(int x = 0, int y = 0):col(x),row(y){
        if( x && y == 0 ) p = NULL;
        else{
            p = new int*[col];
            for(int i = 0; i < col; i++){
                p[i] = new int[row];
            }
        }
    }
    //复制构造函数
    Array2(const Array2 & array2_){
        col = array2_.col;
        row = array2_.row;
        p = new int*[col];
        for(int i = 0; i < col; i++){
            p[i] = new int[row];
        }
        memcpy(p,array2_.p,sizeof(int) * col * row);
    }
 
    //重载"="实现深拷贝
    Array2 & operator=(const Array2 & array2_){
        if(p) delete []p;
        col = array2_.col;
        row = array2_.row;
        p = new int*[col];
        for(int i = 0; i < col; i++){
            p[i] = new int[row];
        }
        memcpy(p,array2_.p,sizeof(int) * col * row);
        return *this;
    }
 
    //析构函数
    ~Array2(){
        if(p) delete []p;
    }
 
    //重载"[]"
    int * operator[](int i){
        return p[i];
        //重载的是 a[][]的第一个[] ,因为返回的是p[x],则第二个[]相当于取p[x]的第y个。
    }
 
    //重载"()"
    int & operator()(int x, int y){ //重载()
        return p[x][y];
    }
 
};
 
int main() {
    Array2 a(3,4); //构造函数,两int型参数,Array2是二维数组形式。
    int i,j;
    for(  i = 0;i < 3; ++i )
        for(  j = 0; j < 4; j ++ )
            a[i][j] = i * 4 + j;
            //a[i][j] 在C++里相当于:a,operator[](i).operator[](j)
    for(  i = 0;i < 3; ++i ) {
        for(  j = 0; j < 4; j ++ ) {
            cout << a(i,j) << ","; //重载"()"
        }
        cout << endl;
    }
    cout << "next" << endl;
    Array2 b;
    b = a; //重载 "=",实现深拷贝。
    for(  i = 0;i < 3; ++i ) {
        for(  j = 0; j < 4; j ++ ) {
            cout << b[i][j] << ",";
        }
        cout << endl;
    }
    return 0;
}

018:别叫,这个大整数已经很简化了!

#include <iostream> 
#include <cstring> 
#include <cstdlib> 
#include <cstdio> 
using namespace std;
const int MAX = 110; 
class CHugeInt {
	private:
		char buf[220];//固定一个220位大小的数组,便于进行对齐
	public:
		void reverse(char *p)//将存储数据的数组进行逆序操作,符合竖式计算从低位向高位进行的原理
		{
			int len=strlen(p)	;
			int i=0,j=len-1;
			while(i<j)
			{
				swap(p[i],p[j]);
				++i;
				--j;	
			}
		}
		CHugeInt(char *p)
		{
			memset(buf,0,sizeof(buf));//将buf初始化
			strcpy(buf,p);
			reverse(buf);
		}
		CHugeInt(int n)
		{
			memset(buf,0,sizeof(buf));
			sprintf(buf,"%d",n);
			reverse(buf);	
		}
		CHugeInt operator+(int n)
		{
			return *this+CHugeInt(n);//可以直接利用后面写的重载运算符	
		}
		CHugeInt operator+(const CHugeInt & n) const
		{
			CHugeInt tmp(0);
			int carry =0;//进位
			for(int i=0;i<210;i++)
			{
					char c1=buf[i];
					char c2=n.buf[i];
					if(c1==0&&c2==0&&carry==0)
						break;
					if(c1==0)
						c1='0';
					if(c2==0)
						c2='0';
					int k=c1-'0'+c2-'0'+carry;
					if(k>=10)//相加大于10则进位
					{
						carry=1;//进位位置1
						tmp.buf[i]=k-10+'0';
					}
					else
					{
						carry=0;
						tmp.buf[i]=k+'0';	
					}
			}
			return tmp;
		}
		friend CHugeInt operator+(int n,const CHugeInt & h)
		{
			return h+n;	
		}
		friend ostream & operator<<(ostream & o,const CHugeInt &h)//输出运算符重载
		{
			int len=strlen(h.buf);
			for(int i=len-1;i>=0;--i)
			cout<<h.buf[i];
			return o;	
		}
		CHugeInt &operator++()
		{
			*this=*this+1;
			return *this;	
		}
		CHugeInt operator++(int)
		{
			CHugeInt tmp(*this);
			*this=*this+1;
			return tmp;
		}
		CHugeInt &operator+=(int n)
		{
			*this=*this+n;
			return *this;	
		}
};
int  main() 
{ 
	char s[210];
	int n;
 
	while (cin >> s >> n) {
		CHugeInt a(s);
		CHugeInt b(n);
 
		cout << a + b << endl;
		cout << n + a << endl;
		cout << a + n << endl;
		b += n;
		cout  << ++ b << endl;
		cout << b++ << endl;
		cout << b << endl;
	}
	system("pause");
	return 0;
}

019:全面的MyString

#define  _CRT_SECURE_NO_WARNINGS
#include <cstdlib>
#include <iostream>
using namespace std;
/*
int strlen(const char * s)
{
	int i = 0;
	for (; s[i]; ++i);
	return i;
}
void strcpy(char * d, const char * s)
{
	int i = 0;
	for (i = 0; s[i]; ++i)
		d[i] = s[i];
	d[i] = 0;
}
int strcmp(const char * s1, const char * s2)
{
	for (int i = 0; s1[i] && s2[i]; ++i) {
		if (s1[i] < s2[i])
			return -1;
		else if (s1[i] > s2[i])
			return 1;
	}
	return 0;
}
void strcat(char * d, const char * s)
{
	int len = strlen(d);
	strcpy(d + len, s);
}*/
 
class MyString
{
private:
	char *p;
 
public:
 
 
	MyString(const char * s = NULL)
	{
		if (s)
		{
			p = new char[strlen(s) + 1];
			strcpy(p, s);
		}
		else
		{
			p = new char[1];
			p[0] = '\0';
		}
 
 
	}
	~MyString()
	{
		if (p) delete[] p;
	}
	// 在此处补充你的代码
 
	MyString(const MyString &s)
	{
		if (s.p)
		{
			p = new char[strlen(s.p) + 1];
			strcpy(p, s.p);
		}
		else
		{
			p = new char[1];
			p[0] = '\0';
		}
	}
 
	MyString & operator=(const char * s)
	{
		if (p == s)
			return *this;
		delete[] p;
		if (s)
		{
			p = new char[strlen(s) + 1];
			strcpy(p, s);
		}
		else
		{
			p = new char[1];
			p[0] = '\0';
		}
		return *this;
	}
 
	MyString & operator=(const MyString & s)
	{
		if (p == s.p)
			return *this;
		delete[] p;
		if (s.p)
		{
			p = new char[strlen(s.p) + 1];
			strcpy(p, s.p);
		}
		else
		{
			p = new char[1];
			p[0] = '\0';
		}
		return *this;
	}
 
 
	friend MyString  operator+(MyString &a, MyString &b)
	{
		char *temp = new char[strlen(a.p) + strlen(b.p)];
		strcpy(temp, a.p);
		strcat(temp, b.p);
		return MyString(temp);
	}
 
 
	friend ostream & operator<<(ostream &os, MyString & s)
	{
		os << s.p;
		return os;
	}
 
	char & operator[](int i)
	{
		return p[i];
	}
 
	MyString & operator+=(const char *s)
	{
		char* temp = new char[strlen(p)+1];
		strcpy(temp, p);
		delete[] p;
		p = new char[strlen(temp) + strlen(s)+1];
		strcpy(p, temp);
		strcat(p, s);
		return *this;
	}
 
	friend MyString  operator+(const char * str, MyString s )
	{
		char *temp = new char[strlen(str) + strlen(s.p)+1];
		strcpy(temp,str);
		strcat(temp, s.p);
 
		return MyString(temp);
 
	}
 
	friend MyString operator+(MyString s, const char *str)
	{
		char *temp = new char[strlen(s.p) + strlen(str) + 1];
		strcpy(temp, s.p);
		strcat(temp, str);
		return MyString(temp);
	}
 
	friend bool operator<(MyString &s1, MyString &s2)
	{
		if (strcmp(s1.p, s2.p) < 0)
			return true;
		else
			return false;
	}
 
	friend bool operator>(MyString &s1, MyString &s2)
	{
		if (strcmp(s1.p, s2.p) > 0)
			return true;
		else
			return false;
	}
 
	friend bool operator==(MyString &s1, MyString &s2)
	{
		if (strcmp(s1.p, s2.p) == 0)
			return true;
		else
			return false;
	}
 
	char * operator () (int start, int length)
	{
		char * temp = new char[length+1];
		for (int i = start; i < start+length; i++)
		{
			temp[i - start] = p[i];
		}
		temp[length] = '\0';
		return temp;
	}
 
 
};
 
 
int CompareString(const void * e1, const void * e2)
{
	MyString * s1 = (MyString *)e1;
	MyString * s2 = (MyString *)e2;
	if (*s1 < *s2)
		return -1;
	else if (*s1 == *s2)
		return 0;
	else if (*s1 > *s2)
		return 1;
}
 
int main()
{
	MyString s1("abcd-"), s2, s3("efgh-"), s4(s1);
	MyString SArray[4] = { "big","me","about","take" };
	cout << "1. " << s1 << s2 << s3 << s4 << endl;
	s4 = s3;
	s3 = s1 + s3;
	cout << "2. " << s1 << endl;
	cout << "3. " << s2 << endl;
	cout << "4. " << s3 << endl;
	cout << "5. " << s4 << endl;
	cout << "6. " << s1[2] << endl;
	s2 = s1;
	s1 = "ijkl-";
	s1[2] = 'A';
	cout << "7. " << s2 << endl;
	cout << "8. " << s1 << endl;
	s1 += "mnop";
	cout << "9. " << s1 << endl;
	s4 = "qrst-" + s2;
	cout << "10. " << s4 << endl;
	s1 = s2 + s4 + " uvw " + "xyz";
	cout << "11. " << s1 << endl;
	qsort(SArray, 4, sizeof(MyString), CompareString);
	for (int i = 0; i < 4; i++)
		cout << SArray[i] << endl;
	//s1的从下标0开始长度为4的子串
	cout << s1(0, 4) << endl;
	//s1的从下标5开始长度为10的子串
	cout << s1(5, 10) << endl;
	system("pause");
	return 0;
}

020:继承string的MyString

#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class MyString :public string
{
public:
	MyString(const string& str) :string(str) {}
	MyString(const MyString& str) :string(str) {}
	MyString(const char* str) :string(str) {}
	MyString() :string() {}
	string operator() (int x, int y) {
		return string::substr(x, y);
	}
};


int main()
{
	MyString s1("abcd-"), s2, s3("efgh-"), s4(s1);
	MyString SArray[4] = { "big","me","about","take" };
	cout << "1. " << s1 << s2 << s3 << s4 << endl;
	s4 = s3;
	s3 = s1 + s3;
	cout << "2. " << s1 << endl;
	cout << "3. " << s2 << endl;
	cout << "4. " << s3 << endl;
	cout << "5. " << s4 << endl;
	cout << "6. " << s1[2] << endl;
	s2 = s1;
	s1 = "ijkl-";
	s1[2] = 'A';
	cout << "7. " << s2 << endl;
	cout << "8. " << s1 << endl;
	s1 += "mnop";
	cout << "9. " << s1 << endl;
	s4 = "qrst-" + s2;
	cout << "10. " << s4 << endl;
	s1 = s2 + s4 + " uvw " + "xyz";
	cout << "11. " << s1 << endl;
	sort(SArray, SArray + 4);
	for (int i = 0; i < 4; i++)
		cout << SArray[i] << endl;
	//s1的从下标0开始长度为4的子串
	cout << s1(0, 4) << endl;
	//s1的从下标5开始长度为10的子串
	cout << s1(5, 10) << endl;
	return 0;
}

021:魔兽世界之二:装备

#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const char TIME_FILL = '0';
const int TIME_W = 3;
const int WAR_NUM = 5;
class Warrior
{
public:
	Warrior() { };
	Warrior(int hp_, int id_) : hp(hp_), id(id_) { };
private:
	int hp;
	int id;
};
class Lion : public Warrior
{
public:
	Lion() { };
	Lion(int hp_, int id_, int loy_) : Warrior(hp_, id_), loyalty(loy_) { };
private:
	int loyalty;
};
class Ninja : public Warrior
{
public:
	Ninja() { };
	Ninja(int hp_, int id_) : Warrior(hp_, id_) { };
	void* weapon_1;
	void* weapon_2;
private:
};
class Dragon : public Warrior
{
public:
	Dragon() { };
	Dragon(int hp_, int id_, double morale_) : Warrior(hp_, id_), morale(morale_) { };
	void* weapon;
private:
	double morale;
	
};
class Iceman : public Warrior
{
public:
	Iceman() { };
	Iceman(int hp_, int id_) : Warrior(hp_, id_) { };
	void* weapon;
private:
};
class Wolf : public Warrior
{
public:
	Wolf() { };
	Wolf(int hp_, int id_) : Warrior(hp_, id_) { };
};
class Sword
{
public:
	Sword() { };
};
class Bomb
{
public:
	Bomb() { };
};
class Arrow
{
public:
	Arrow() { };
};
class GameTime
{
public:
	GameTime();
	bool Tick();
	bool Disp();
	bool Init();
private:
	unsigned int nTime;
}Clock;
class HeadQuarter
{
public:
	HeadQuarter(string, int);
	bool ProWar();
	unsigned int nElement;
	string strFaction;
	bool bProEnd;
private:
	int nFaction;
	int nMark;
	int nNinja;  
    int nIceman;  
    int nWolf;  
    int nLion;  
    int nDragon;
	int nWarrior;
	bool ProMark(int);
    bool ProIceman();
    bool ProNinja();
    bool ProDragon();
    bool ProLion();
    bool ProWolf();
	vector<Dragon> vDragon;
	vector<Lion> vLion;
	vector<Ninja> vNinja;
	vector<Iceman> vIceman;
	vector<Wolf> vWolf;
};
unsigned int dHP, nHP, iHP, lHP, wHP;
int main()  
{  
    int nTest;  
    cin >> nTest;  
    for(int test = 1; test <= nTest; test++)  
    {  
        Clock.Init();  
        int nElement;  
        cin >> nElement;  
        cin >> dHP >> nHP >> iHP >> lHP >> wHP;  
        HeadQuarter red("red", nElement);  
        HeadQuarter blue("blue", nElement);  
        cout << "Case:" << test << endl;  
        while(true)  
        {  
            if(red.bProEnd && blue.bProEnd)
            {  
                break;  
            }  
            if(!red.bProEnd)                           
            {  
                red.ProWar();  
            }  
            if(!blue.bProEnd)  
            {  
                blue.ProWar();  
            }  
            Clock.Tick(); 
        }  
    }  
    return 0;  
}  
GameTime::GameTime()
{
	nTime = 0;
}
bool GameTime::Tick()
{
	nTime++;
	return true;
}
bool GameTime::Disp()
{
	cout << setfill(TIME_FILL) << setw(TIME_W)
		 << nTime;
	return true;
}
bool GameTime::Init()
{
	nTime = 0;
	return true;
}
HeadQuarter::HeadQuarter(string faction_, int element_)
{
	strFaction = faction_;
	nElement = element_;
	nMark = 0;
	bProEnd = false;
	nDragon = 0;
	nNinja = 0;
	nIceman = 0;
	nLion = 0;
	nWolf = 0;
	nWarrior = 0;
}
bool HeadQuarter::ProWar()
{
	int i;
	bool bProFlag = false;
	for(i = nMark; i < WAR_NUM; ++i)
	{
		bProFlag = ProMark(i);
		if(bProFlag)                  
        {  
            nMark = i + 1;  
            break;  
        }  
	}
	if(!bProFlag)
    {  
        for(i = 0; i < nMark; i++)  
        {  
            bProFlag = ProMark(i);  
            if(bProFlag)  
            {  
                nMark = i + 1;  
                break;  
            }  
        }  
    }
	if(!bProFlag)
    {  
        bProEnd = true;  
        Clock.Disp();  
        cout << " " << strFaction << " headquarter stops making warriors" << endl;  
    }
	else 
    {  
        if(nMark >= 5)  
        {
			nMark = 0;  
		}
    }
	return true;
}
bool HeadQuarter::ProMark(int mark_)  
{  
    if(strFaction == "red")
    {  
        switch(mark_)  
        {  
            case 0: return ProIceman();  
            case 1: return ProLion();  
            case 2: return ProWolf();  
            case 3: return ProNinja();  
            case 4: return ProDragon();  
            default: return false;  
        }  
    }  
    if(strFaction == "blue")  
    {  
        switch(mark_)  
        {  
            case 0: return ProLion();  
            case 1: return ProDragon();  
            case 2: return ProNinja();  
            case 3: return ProIceman();  
            case 4: return ProWolf();  
            default: return false;  
        }  
    }  
	return false;
}  
bool HeadQuarter::ProIceman()  
{  
    if(nElement >= iHP)  
    {  
        nWarrior++;  
        nIceman++;  
        nElement -= iHP;  
        Clock.Disp();  
        cout << " " << strFaction << " iceman "  << nWarrior   
        <<  " born with strength " << iHP << "," << nIceman 
		<< " iceman in " << strFaction << " headquarter" << endl;
		cout << "It has a ";
		Iceman tmp(iHP, nWarrior);
		switch(nWarrior % 3)
		{
		case 0:
			tmp.weapon = new Sword;
			cout << "sword" << endl;
			break;
		case 1:
			tmp.weapon = new Bomb;
			cout << "bomb" << endl;
			break;
		case 2:
			tmp.weapon = new Arrow;
			cout << "arrow" << endl;
			break;
		}
		vIceman.push_back(tmp);
        return true;  
    }  
    else return false;  
}  
bool HeadQuarter::ProDragon()  
{  
    if(nElement >= dHP)  
    {  
        nWarrior++;  
        nDragon++;  
        nElement -= dHP;  
        Clock.Disp();  
        cout << " " << strFaction << " dragon "  << nWarrior   
        <<  " born with strength " << dHP << "," << nDragon 
		<< " dragon in " << strFaction << " headquarter" << endl;  
		Dragon tmp(dHP, nWarrior, ((double)nElement / (double)dHP));
		cout << "It has a ";
		switch(nWarrior % 3)
		{
		case 0:
			tmp.weapon = new Sword;
			cout << "sword";
			break;
		case 1:
			tmp.weapon = new Bomb;
			cout << "bomb";
			break;
		case 2:
			tmp.weapon = new Arrow;
			cout << "arrow";
			break;
		}
		cout.setf(ios::fixed | ios::showpoint);
		cout.precision(2);
		cout << ",and it's morale is " << ((double)nElement / (double)dHP) << endl;
		vDragon.push_back(tmp);
        return true;  
    }  
    else return false;  
}  
bool HeadQuarter::ProNinja()  
{  
    if(nElement >= nHP)  
    {  
        nWarrior++;  
        nNinja++;  
        nElement -= nHP;  
        Clock.Disp();  
        cout << " " << strFaction << " ninja "  << nWarrior   
        <<  " born with strength " << nHP << "," << nNinja 
		<< " ninja in " << strFaction << " headquarter" << endl;  
		Ninja tmp(nHP, nWarrior);
		cout << "It has a ";
		switch(nWarrior % 3)
		{
		case 0:
			tmp.weapon_1 = new Sword;
			cout << "sword";
			break;
		case 1:
			tmp.weapon_1 = new Bomb;
			cout << "bomb";
			break;
		case 2:
			tmp.weapon_1 = new Arrow;
			cout << "arrow";
			break;
		}
		cout << " and a ";
		switch((nWarrior + 1) % 3)
		{
		case 0:
			tmp.weapon_2 = new Sword;
			cout << "sword" << endl;
			break;
		case 1:
			tmp.weapon_2 = new Bomb;
			cout << "bomb" << endl;
			break;
		case 2:
			tmp.weapon_2 = new Arrow;
			cout << "arrow" << endl;
			break;
		}
		vNinja.push_back(tmp);
        return true;  
    }  
    else return false;  
}  
bool HeadQuarter::ProLion()  
{  
    if(nElement >= lHP)  
    {  
        nWarrior++;  
        nLion++;  
        nElement -= lHP;  
        Clock.Disp();  
        cout << " " << strFaction << " lion "  << nWarrior   
        <<  " born with strength " << lHP << "," << nLion 
		<< " lion in " << strFaction << " headquarter" << endl;  
		Lion tmp(lHP, nWarrior, nElement);
		cout << "It's loyalty is " << nElement << endl;
		vLion.push_back(tmp);
        return true;  
    }  
    else return false;  
}  
bool HeadQuarter::ProWolf()  
{  
    if(nElement >= wHP)  
    {  
        nWarrior++;  
        nWolf++;  
        nElement -= wHP;  
        Clock.Disp();  
        cout << " " << strFaction << " wolf "  << nWarrior   
        <<  " born with strength " << wHP << "," << nWolf 
		<< " wolf in " << strFaction << " headquarter" << endl; 
		Wolf tmp(wHP, nWarrior);
		vWolf.push_back(tmp);
        return true;  
    }  
    else return false;  
}  

022:看上去像多态

#include <iostream>
using namespace std;
class B {
private:
	int nBVal;
public:
	void Print()
	{
		cout << "nBVal=" << nBVal << endl;
	}
	void Fun()
	{
		cout << "B::Fun" << endl;
	}
	B(int n) { nBVal = n; }
};
// 在此处补充你的代码
class D:public B
{
private:
	int nDVal;
public:
	D(int nDval_) :nDVal(nDval_),B(3*nDval_){};
	
	void Fun()
	{
		cout << "D::Fun" << endl;
	}
 
	void Print()
	{
		B::Print();
		cout << "nDVal=" << nDVal << endl;
	}
 
};
int main() {
	B * pb; D * pd;
	D d(4); d.Fun();
	pb = new B(2); pd = new D(8);
	pb->Fun(); pd->Fun();
	pb->Print(); pd->Print();
	pb = &d; pb->Fun();
	pb->Print();
	return 0;

023:Fun和Do

#include <iostream> 
using namespace std;
class A {
private:
	int nVal;
public:
	void Fun()
	{
		cout << "A::Fun" << endl;
	};
	void Do()
	{
		cout << "A::Do" << endl;
	}
};
class B :public A {
public:
	virtual void Do()
	{
		cout << "B::Do" << endl;
	}
};
class C :public B {
public:
	void Do()
	{
		cout << "C::Do" << endl;
	}
	void Fun()
	{
		cout << "C::Fun" << endl;
	}
};
void Call(B &p
	// 在此处补充你的代码
) {
	p.Fun(); p.Do();
}
int main() {
	C c;
	Call(c);
	system("pause");
	return 0;
}

024:这是什么鬼delete

#include <iostream> 
using namespace std;
class A 
{ 
public:
	A() { }
	~A(){cout << "destructor A" << endl;} 
}; 
class B:public A { 
	public: 
	~B() { cout << "destructor B" << endl; } 
}; 
int main() 
{
	B * pa;//此处是B类指针,就没有设虚函数的烦恼
	pa = new B; 
	delete pa; 
	return 0;
}

025:怎么又是Fun和Do

#include <iostream>
using namespace std;
class A {
	private:
	int nVal;
	public:
	void Fun()
	{ cout << "A::Fun" << endl; };
	virtual void Do()
	{ cout << "A::Do" << endl; }
};
class B:public A {
	public:
	virtual void Do()
	{ cout << "B::Do" << endl;}
};
class C:public B {
	public:
	void Do( )
	{ cout <<"C::Do"<<endl; }
	void Fun()
	{ cout << "C::Fun" << endl; }
};
void Call(
A *p
) {
	p->Fun(); p->Do();
}
int main() {
	Call( new A());
	Call( new C());
	return 0;
}

026:编程填空:统计动物数量

#include <iostream>
using namespace std;
// 在此处补充你的代码
class Animal{
public:
    static int number;
    Animal() {}
    virtual ~Animal(){
        number--;
    }
};
 
class Dog:public Animal{
public:
    static int number;
    Dog(){
        Animal::number++; //wo need to point out that which "number" is.
        Dog::number++;
    }
     virtual ~Dog(){
        number--;
    }
};
 
class Cat:public Animal{
public:
    static int number;
    Cat(){
        Animal::number++;
        Cat::number++;
    }
    virtual ~Cat(){
        number--;
    }
};
 
//never forget to initiate the variable !!!
int Animal::number = 0;
int Dog::number = 0;
int Cat::number = 0;
 
void print() {
    cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
}
 
int main() {
    print();
    Dog d1, d2; //class Dog
    Cat c1; //class Cat
    print();
    Dog* d3 = new Dog();
    Animal* c2 = new Cat; //class Animal, class Animal is the basic of class Dog and Cat
    Cat* c3 = new Cat; //why is it different from new Dog() ?
    print();
    delete c3;
    delete c2;
    delete d3;
    print();
}

027:简单的SunArray

#include <iostream>
#include <string>
using namespace std;
template <class T>
T SumArray(T* a,T* b){
	T sum = *a;
	for (T* i = a + 1; i < b; ++i) {
		sum += *i;
	}
	return sum;

}
int main() {
	string array[4] = { "Tom","Jack","Mary","John"};
	cout << SumArray(array,array+4) << endl;
	int a[4] = { 1, 2, 3, 4};  //提示:1+2+3+4 = 10
	cout << SumArray(a,a+4) << endl;
	return 0;
}

028:简单的foreach

#include <iostream>
#include <string>
using namespace std;
void MyForeach(T *start,T *end,Pred pt)
{
	for (T* p = start; p < end; p++)
		pt(*p);
} 

void Print(string s)
{
	cout << s;
}
void Inc(int & n)
{
	++ n;
}
string array[100];
int a[100];
int main() {
	int m,n;
	while(cin >> m >> n) {
		for(int i = 0;i < m; ++i)
			cin >> array[i];
		for(int j = 0; j < n; ++j)
			cin >> a[j];
		MyForeach(array,array+m,Print);		 
		cout << endl;
		MyForeach(a,a+n,Inc);		 
		for(int i = 0;i < n; ++i)
			cout << a[i] << ",";
		cout << endl;
	}
	return 0;
}

029:简单的Filter

#include <iostream>
#include <string>
using namespace std;
template <class T1,class T2>
T1  *Filter(T1 *start,T1 *end,T1 *newn,T2 pt)
{
	while(start != end)
	{
		if(pt(*start))
		{
			*newn = *start;
			newn++;
		}
		start++;	
    }
    return newn;
}

bool LargerThan2(int n)
{
	return n > 2;
}
bool LongerThan3(string s) 
{
	return s.length() > 3;
}

string as1[5] = {"Tom","Mike","Jack","Ted","Lucy"};
string as2[5];
int  a1[5] = { 1,2,3,4,5};
int a2[5];
int main() {
	string * p = Filter(as1,as1+5,as2,LongerThan3);
	for(int i = 0;i < p - as2; ++i)
		cout << as2[i];
	cout << endl; 
	int * p2 = Filter(a1,a1+5,a2,LargerThan2);
	for(int i = 0;i < p2-a2; ++i)
		cout << a2[i] << ",";
	return 0;
}

030:你真的搞清楚为啥 while(cin >> n) 能成立了吗

#include <iostream>
using namespace std;
class MyCin
{
// 在此处补充你的代码
bool valid;              //valid成员 
public:
	MyCin():valid(true){};       //构造函数,valid为true 
	
	operator bool(){        //重载bool值 
		return valid;              //while(cin>>需要重载bool类型 
	} 
	
	
MyCin & operator >>(int &n){        //运算符重载函数——重载>>实现cin功能 
	cin>>n;
	if (n==-1) valid=false;     //此为cin对象的bool类型判断条件 
	return *this;        //返回当前对象,继承此时的valid 
}
//实现cin功能——重载>>,执行Cin,再判断输入的是否为-1,返回当前对象——对象为cin 
// 

};
int main()
{
    MyCin m;
    int n1,n2;
    while( m >> n1 >> n2)        //-1时结束 
        cout  << n1 << " " << n2 << endl;
    return 0;
}

031:山寨版istream_iterator

#include <iostream>
#include <string>

using namespace std;
template <class T>
class CMyistream_iterator
{
    bool flag;
    T a;
    istream & in;
public:
    CMyistream_iterator(istream & i):in(i){
        flag = 0;//初始化
    }//获得输入符
    T & operator * (){
        if(flag)//判断是否已有读入
            return a;
        in >> a;
        flag = 1;
        return a;
    }//对*重载
    T & operator ++(int){
        in >> a;
        return a;
    }//对后置++重载需要一个没用的参数int

};

int main()  
{ 
	int t;
	cin >> t;
	while( t -- ) {
		 CMyistream_iterator<int> inputInt(cin);
		 int n1,n2,n3;
		 n1 = * inputInt; //读入 n1
		 int tmp = * inputInt;
		 cout << tmp << endl;
		 inputInt ++;   
		 n2 = * inputInt; //读入 n2
		 inputInt ++;
		 n3 = * inputInt; //读入 n3
		 cout << n1 << " " << n2<< " " << n3 << " ";
		 CMyistream_iterator<string> inputStr(cin);
		 string s1,s2;
		 s1 = * inputStr;
		 inputStr ++;
		 s2 = * inputStr;
		 cout << s1 << " " << s2 << endl;
	}
	 return 0;  
}

032:这个模板并不难

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
template <class T>  
class myclass {
// 在此处补充你的代码
public:
    T *p, *p_temp;
    int size;
    myclass(T* _p, int _size) : size(_size)
    {
        p = new T[size];
        // p_temp = new T[size];
        for(int i=0; i<size; i++)
        {
            p[i] = _p[i];
        }
    }
	~myclass( ) {
		delete [] p;
	}
	void Show()
	{
		for( int i = 0;i < size;i ++ ) {
			cout << p[i] << ",";
		}
		cout << endl;
	}
};
int a[100];
int main() {
	char line[100];
	while( cin >> line ) {
		myclass<char> obj(line,strlen(line));;
		obj.Show();
		int n;
		cin >> n;
		for(int i = 0;i < n; ++i)
			cin >> a[i];
		myclass<int> obj2(a,n);
		obj2.Show();
	}
	return 0;
}

033:排序,又见排序!

#include <iostream>
using namespace std;

bool Greater2(int n1,int n2) 
{
	return n1 > n2;
}
bool Greater1(int n1,int n2) 
{
	return n1 < n2;
}
bool Greater3(double d1,double d2)
{
	return d1 < d2;
}

template <class T1,class T2>
void mysort(
template <class T1,class T2>
void mysort(T1 s, T1 e, T2 op)
{
    int n = e - s;  //我可能是太垃圾了,末减首就是个数了。。。
    int i, j;
    for(i = 0; i < n-1; i++)  //我用的冒泡排序
    {
        for(j = 0; j < n-1-i; j++)
        {
            if(!op(*(s+j), *(s+j+1)))
            {
                swap(*(s+j), *(s+j+1));//这里还有一种是用auto定义一个变量,在c++里用auto必须初始化
                                         auto t = *(s+j); //这里t的类型就根据后面传入的类型来判断,好神奇奥
                                         *(s+j) = *(s+j+1);
                                         *(s+j+1) = t;
            }
        }
    }
}

#define NUM 5
int main()
{
    int an[NUM] = { 8,123,11,10,4 };
    mysort(an,an+NUM,Greater1); //从小到大排序 
    for( int i = 0;i < NUM; i ++ )
       cout << an[i] << ",";
    mysort(an,an+NUM,Greater2); //从大到小排序 
    cout << endl;
    for( int i = 0;i < NUM; i ++ )
        cout << an[i] << ","; 
    cout << endl;
    double d[6] = { 1.4,1.8,3.2,1.2,3.1,2.1};
    mysort(d+1,d+5,Greater3); //将数组从下标1到下标4从小到大排序 
    for( int i = 0;i < 6; i ++ )
         cout << d[i] << ","; 
	return 0;
}

034:goodcopy

#include <iostream>
using namespace std;


template <class T>
struct GoodCopy {
template <class T>
struct GoodCopy {
	operator()(T *a,T *ad,T * b){
		int flag = 0;
		for(T *temp = a;temp < ad;temp++){
			if(temp == b){
				flag = 1;
			}
		}
		while(flag == 0 && a != ad){
			*b = *a;
			b++;
			a++; 
		}
		if(flag == 1){
			for(T *temp = a;temp < ad;temp++,b++);
			--b;
			T * q = ad;
			-- q;
			for(;q != a;q--,b--)
				*b = *q;
			*b = *q;
		}
	} 
};

};

int a[200];
int b[200];
string c[200];
string d[200];

template <class T>
void Print(T s,T e) {
	for(; s != e; ++s)
		cout << * s << ",";
	cout << endl;
}

int main()
{
	int t;
	cin >> t;
	while( t -- ) {
		int m ;
		cin >> m;
		for(int i = 0;i < m; ++i)
			cin >> a[i];
		GoodCopy<int>()(a,a+m,b);
		Print(b,b+m);
		GoodCopy<int>()(a,a+m,a+m/2);
		Print(a+m/2,a+m/2 + m);

		for(int i = 0;i < m; ++i)
			cin >> c[i];
		GoodCopy<string>()(c,c+m,d);
		Print(c,c+m);
		GoodCopy<string>()(c,c+m,c+m/2);
		Print(c+m/2,c+m/2 + m);
	}
	return 0;
}

035:按距离排序

#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
using namespace std;
template <class T1,class T2>
struct Closer {
// 在此处补充你的代码
private:
	T1 n;
	T2 distance;
public:	
	Closer(T1 _n,T2 p){
		n = _n;
		distance = p;
	}
bool operator () (const T1 & v1, const T1 & v2) {
		int d1 = distance(v1,n);
		int d2 = distance(v2,n);
		if(d1 == d2)
			return v1 < v2;
		else if(d1 < d2)
			return true;
		else
			return false;
	}

};

int Distance1(int n1,int n2) {
	return abs(n1-n2);
}
int Distance2(const string & s1, const string & s2)
{
	return abs((int)s1.length()- (int) s2.length());
}
int a[10] = { 0,3,1,4,7,9,20,8,10,15};
string b[6] = {"American","Jack","To","Peking","abcdefghijklmnop","123456789"};
int main()
{
	int n;string s;
	while( cin >> n >> s ) {
		sort(a,a+10,Closer<int ,int (*)(int ,int)> (n,Distance1));
		for(int i = 0;i < 10; ++i)
			cout << a[i] << "," ;
		cout << endl;
		sort(b,b+6,Closer<string,int (*)(const string &,const string &  )> (s,Distance2)); 
		for(int i = 0;i < 6; ++i)
			cout << b[i] << "," ;
		cout << endl;
	}
	return 0;
}

036:很难蒙混过关的CArray3d三维数组模板类

#include <iostream>
#include <iomanip> 
#include <cstring>
using namespace std;
template <class T>
class CArray3D
{
// 在此处补充你的代码
class CArray3D
{
public:
	T* p;
	int f, r, c; //数组共f层,每层r行,每行c列

	class CArray2D {
	public:
		T* fp; // fp是一层的元素的起始地址
		int c; //数组每行c列

		CArray2D(T* p_, int c_) :fp(p_), c(c_) { }
		T* operator[](int r) {
			return fp + r * c; //返回本层的第 r行起始地址		  
		}
		operator T* () {
			return fp; //返回值本层的起始地址		  
		}
	};
	CArray3D(int _f, int _r, int _c) :f(_f), r(_r), c(_c) {
		p = new T[f * r * c];
	}
	CArray2D operator[](int _f) {//第_f层元素的起始地址
		return CArray2D(p + _f * r * c, c);
	}
	~CArray3D() { delete[] p; }
};


};

CArray3D<int> a(3,4,5);
CArray3D<double> b(3,2,2);
void PrintA()
{
	for(int i = 0;i < 3; ++i) {
		cout << "layer " << i << ":" << endl;
		for(int j = 0; j < 4; ++j) {
			for(int k = 0; k < 5; ++k) 
				cout << a[i][j][k] << "," ;
			cout << endl;
		}
	}
}
void PrintB()
{
	for(int i = 0;i < 3; ++i) {
		cout << "layer " << i << ":" << endl;
		for(int j = 0; j < 2; ++j) {
			for(int k = 0; k < 2; ++k) 
				cout << b[i][j][k] << "," ;
			cout << endl;
		}
	}
}

int main()
{

	int No = 0;
	for( int i = 0; i < 3; ++ i ) {
		a[i];
		for( int j = 0; j < 4; ++j ) {
			a[j][i];
			for( int k = 0; k < 5; ++k )
				a[i][j][k] = No ++;
			a[j][i][i];	
		}
	}
	PrintA();
	memset(a[1],-1 ,20*sizeof(int));	
	memset(a[1],-1 ,20*sizeof(int));
	PrintA(); 
	memset(a[1][1],0 ,5*sizeof(int));	
	PrintA();

	for( int i = 0; i < 3; ++ i )
		for( int j = 0; j < 2; ++j )
			for( int k = 0; k < 2; ++k )
				b[i][j][k] = 10.0/(i+j+k+1);
	PrintB();
	int n = a[0][1][2];
	double f = b[0][1][1];
	cout << "****" << endl;
	cout << n << "," << f << endl;
		
	return 0;
}

037:函数对象的过滤器

#include <iostream>
#include <vector>
using namespace std;
 
 
struct A {
	int v;
	A() { }
	A(int n) :v(n) { };
	bool operator<(const A & a) const {
		return v < a.v;
	}
};
// 在此处补充你的代码
 
template <class T>
struct FilterClass {
	T m, n;
	FilterClass(T a, T b):m(a),n(b) {}
	bool operator()(T s) {
		return (m < s) && (s < n);
	}
};
 
template <class T>
void Print(T s, T e)
{
	for (; s != e; ++s)
		cout << *s << ",";
	cout << endl;
}
template <class T1, class T2, class T3>
T2 Filter(T1 s, T1 e, T2 s2, T3 op)
{
	for (; s != e; ++s) {
		if (op(*s)) {
			*s2 = *s;
			++s2;
		}
	}
	return s2;
}
 
ostream & operator <<(ostream & o, A & a)
{
	o << a.v;
	return o;
}
vector<int> ia;
vector<A> aa;
int main()
{
	int m, n;
	while (cin >> m >> n) {
		ia.clear();
		aa.clear();
		int k, tmp;
		cin >> k;
		for (int i = 0; i < k; ++i) {
			cin >> tmp;
			ia.push_back(tmp);
			aa.push_back(tmp);
		}
		vector<int> ib(k);
		vector<A> ab(k);
		vector<int>::iterator p = Filter(ia.begin(), ia.end(), ib.begin(), FilterClass<int>(m, n));
		Print(ib.begin(), p);
		vector<A>::iterator pp = Filter(aa.begin(), aa.end(), ab.begin(), FilterClass<A>(m, n));
		Print(ab.begin(), pp);
 
	}
	return 0;
}

038:白给的list排序

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int main()
{	
	double a[] = {1.2,3.4,9.8,7.3,2.6};
	list<double> lst(a,a+5);
	lst.sort(greater<double>());

);
	
	for(list<double>::iterator i  = lst.begin(); i != lst.end(); ++i) 
		cout << * i << "," ;
    return 0;
}

039:我自己的 ostream_iterator

#include <iostream>
#include <list>
#include <string>
using namespace std;

template <class T1,class T2>
void Copy(T1 s,T1 e, T2 x)  //这里的x从后面看是一个对象,所以要重载* ++ =,还有这里这个++如果他不给的话,没啥用,但是他给了,
                            // 就得重载,把他去了,反而没有warning了。。。
{
	for(; s != e; ++s,++x)
		*x = *s;
}

 
template<class T>
class myostream_iteraotr
{
ostream& o;
    string s;
public:
    myostream_iteraotr(ostream& oo, string ss): o(oo), s(ss) {}
    void operator = (const T& a) //这里的返回值有也可以,没有也可以
    {
        o << a << s;
        //return *this;
    }
    myostream_iteraotr& operator * ()
    {
        return *this;
    }
    myostream_iteraotr& operator ++ () {} //++没啥用,但是就是得写上
};


int main()
{	const int SIZE = 5;
	int a[SIZE] = {5,21,14,2,3};
	double b[SIZE] = { 1.4, 5.56,3.2,98.3,3.3};
	list<int> lst(a,a+SIZE);
	myostream_iteraotr<int> output(cout,",");
	Copy( lst.begin(),lst.end(),output); 
	cout << endl;
	myostream_iteraotr<double> output2(cout,"--");
	Copy(b,b+SIZE,output2);
	return 0;
}

040:List

#include<iostream>
#include<algorithm>
#include<list>
using namespace std;


list<int>lis[10010];
int main() {
	int n; cin >> n;
	while (n--) {
		string str;
		int x1,x2;
		list<int>::iterator it;
		cin >> str;
		switch (str[0]) {
		case 'n':
			cin >> x1;
			break;
		case 'a':
			cin >> x1 >> x2;
			lis[x1].push_back(x2);
			break;
		case 'm':
			cin >> x1 >> x2;
			lis[x1].merge(lis[x2]);
			break;
		case 'u':
			cin >> x1;
			lis[x1].sort();
			lis[x1].unique();
			break;
		case 'o':
			cin >> x1;
			lis[x1].sort();
			for (it = lis[x1].begin(); it != lis[x1].end(); ++it) {
				cout << *it << " ";
			}
			cout << endl;
			break;
		}
	}
}

041:

#include <iostream>
#include <string>
#include <set>
using namespace std;

int main()
{
    int opernumbers,number;
    string func;
    cin>>opernumbers;
    multiset<int> mset;
    multiset<int>::iterator m;
    set<int> tset;
    set<int>::iterator t;
    while(opernumbers--)
    {
        cin>>func;
        if(func == "add")
        {
            cin>>number;
            mset.insert(number);
            tset.insert(number);
            cout<<mset.count(number)<<endl;
        }
        else if(func == "del")
        {
            cin>>number;
            cout<<mset.count(number)<<endl;
            mset.erase(mset.lower_bound(number),mset.upper_bound(number));
        }
        else
        {
            cin>>number;
            t = tset.find(number);
            if(t == tset.end()) cout<<"0 0"<<endl;
            else    cout<<"1 "<<mset.count(number)<<endl;
        }
    }
    return 0;
}

042:热血格斗场

#include<iostream>
#include<map>
#include<string>
#include<iterator>
using namespace std;
struct Ren{
	int zhanli;
	int id;
};
typedef map<int,int> MP;
int main()
{
	int n;
	MP mp;
	scanf("%d",&n);
	Ren ren;
	ren.id = 1;
	ren.zhanli = 1000000000;
	mp.insert(make_pair(ren.zhanli,ren.id));
	while(n--){
		scanf("%d%d",&ren.id,&ren.zhanli);
		MP::iterator di = mp.lower_bound(ren.zhanli);
		MP::iterator gao;
		if(di != mp.begin()){
			if(di != mp.end()){
				gao = di;
				di--;
				if(ren.zhanli - di -> first == gao -> first - ren.zhanli){
					printf("%d %d\n",ren.id,di -> second);
				}
				else if(ren.zhanli - di -> first < gao -> first - ren.zhanli){
					printf("%d %d\n",ren.id,di -> second);
				}
				else{
					printf("%d %d\n",ren.id,gao -> second);
				}
			}
			else{
				di--;
				printf("%d %d\n",ren.id,di -> second);
			}
		}
		else{
			printf("%d %d\n",ren.id,di -> second);
		}
		mp.insert(make_pair(ren.zhanli,ren.id));
	}
	return 0;
}

043:冷血格斗场:

#include<iostream>
#include<map>
#include<cmath>
#include <cstdio>
using namespace std;

multimap<int,int> MEMBER;
multimap<int,int>::iterator i,a1,a2;

int n;
int id;
int power;
//有相同战斗力的,只保留id最小的那个就行了
 
int main(){
	scanf("%d",&n);
	MEMBER.insert(make_pair(1000000000,1));
	while(n--){
		scanf("%d%d",&id,&power);
		if(MEMBER.find(power)!=MEMBER.end()){       //如果有相同值 
			i=MEMBER.find(power);         //找到该值 

			if (id < i->second){        	  //新的id更小 
				printf("%d %d\n",id,i->second);    //输出 
				MEMBER.erase(i->first);                    //擦除老的 
				MEMBER.insert(make_pair(power,id)); //更新新的 

			}
			else 
				printf("%d %d\n",id,i->second);       //新的id更大,则直接输出比赛
		}
		
		//无相同值 
		else{
		i=MEMBER.insert(make_pair(power,id));    //插入 
		if(i==MEMBER.begin()){                    //插入的位置是头 
			printf("%d %d\n",id,(++i)->second);   //输出头的下一个 
		}
		else if(i==(--MEMBER.end())){                     //插入的位置是尾 
			printf("%d %d\n",id,(--i)->second);       //输出尾的上一个 
		}
		else{
			a1=--i;             
			++i;
			a2=++i;                
			if(abs(power-a1->first)<abs(power-a2->first)){  //a1距离更近 
				printf("%d %d\n",id,a1->second); 
			}
			else if(abs(power-a1->first)>abs(power-a2->first)){ //a2距离更近 
				printf("%d %d\n",id,a2->second); 
			}
			else{                        //距离相同 
				if(a1->second<a2->second)           //a1id更小       
					printf("%d %d\n",id,a1->second);
				else
					printf("%d %d\n",id,a2->second);  //a2id更小 
			}
		}
		MEMBER.insert(make_pair(power,id));       //入组 
	}
	}	
}

044:编程填空:数据库内的学生信息

#include <iostream>
#include <string>
#include <map>
#include <iterator>
#include <algorithm>
using namespace std;
// 在此处补充你的代码
template<class Key, class Value, class Pred=greater<Key> >
class MyMultimap{
private:
    multimap<Key, Value, Pred> m;
public:
    typedef typename multimap<Key, Value, Pred>::iterator iterator;
    MyMultimap(){
        m.clear();
    }
    void insert(pair<Key, Value> p){
        m.insert(p);
    }
    void clear(){
        m.clear();
    }
    void Set(Key k, Value v){
        iterator start = m.equal_range(k).first;
        iterator end = m.equal_range(k).second;
        while(start!=end){
            start->second = v;
            start++;
        } 
    }
    iterator begin(){
        return m.begin();
    }
    iterator end(){
        return m.end();
    }
    iterator find(const Key k){
        return m.find(k);
    }
};
template <class Key, class Value>
ostream& operator<< (ostream& os, pair<Key, Value> i){
    os << "(" << i.first << "," << i.second << ")";
    return os;
}
struct Student 
{
	string name;
	int score;
};
template <class T>
void Print(T first,T last) {
	for(;first!= last; ++ first)
		cout << * first << ",";
	cout << endl;
}
int main()
{
	
	Student s[] = { {"Tom",80},{"Jack",70},
					{"Jone",90},{"Tom",70},{"Alice",100} };
	
	MyMultimap<string,int> mp;
	for(int i = 0; i<5; ++ i)
		mp.insert(make_pair(s[i].name,s[i].score));
	Print(mp.begin(),mp.end()); //按姓名从大到小输出

	mp.Set("Tom",78); //把所有名为"Tom"的学生的成绩都设置为78
	Print(mp.begin(),mp.end());
	
	
	
	MyMultimap<int,string,less<int> > mp2;
	for(int i = 0; i<5; ++ i) 
		mp2.insert(make_pair(s[i].score,s[i].name));
	
	Print(mp2.begin(),mp2.end()); //按成绩从小到大输出
	mp2.Set(70,"Error");          //把所有成绩为70的学生,名字都改为"Error"
	Print(mp2.begin(),mp2.end());
	cout << "******" << endl;
	
	mp.clear();
	
	string name;
	string cmd;
	int score;		
	while(cin >> cmd ) {
		if( cmd == "A") {
			cin >> name >> score;
			if(mp.find(name) != mp.end() ) {
				cout << "erroe" << endl;
			}
			mp.insert(make_pair(name,score));
		}
		else if(cmd == "Q") {
			cin >> name;
			MyMultimap<string,int>::iterator p = mp.find(name);
			if( p!= mp.end()) {
				 cout << p->second << endl;
			}
			else {
				cout << "Not Found" << endl; 
			}		
		}
	}
	return 0;
}

045:魔兽世界三(开战)

#pragma warning(disable:4996)
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string weapon[3] = { "sword","bomb","arrow" };
int m, citys, loyalty_d, deadline;//m:生命值
bool r_win = false, b_win = false;
class weapons {
public:
	int weapons_n;//武器的编号
	string name;//武器名称
	int w_atk;//武器的攻击力
	int n;//武器寿命(即所能使用的次数)
	bool w_ok;//武器是否还能用
	weapons(string name,int atk) {
		this->name = name;
		if (name == "sword") {
			this->n = 0xffff;
			this->w_atk = atk * 2/10;
			weapons_n = 0;
		}
		else if (name == "bomb") {
			this->n = 1;
			this->w_atk = atk * 4 / 10;
			weapons_n = 1;
		}
		else if (name == "arrow") {
			this->n = 2;
			this->w_atk = atk * 3 / 10;
			weapons_n = 2;
		}
		w_ok = true;
	}
 
	void update_w() {
		if (this->w_ok==true) {
			if (this->name != "sword") {
				if (this->n>0) this->n--;
				if (this->n <= 0) this->w_ok = false;
			}
		}
 
	}
 
};
struct w_rule_1 {
	bool operator()(const weapons &a, const weapons &b) const {//对象比较
		if (a.weapons_n < b.weapons_n) {
			return true;
		}
		else if (a.weapons_n == b.weapons_n) {//使用过的优先(n--)
			return a.n < b.n;
		}
		else {
			return false;
		}
	}
};
 
struct w_rule_2 {
	bool operator()(const weapons &a, const weapons &b) const {//对象比较
		if (a.weapons_n < b.weapons_n) {
			return true;
		}
		else if (a.weapons_n == b.weapons_n) {//没使用过的优先
			return a.n > b.n;
		}
		else {
			return false;
		}
	}
};
 
class warrior {//武士类
public:
	int n, hp, atk, flag,city_n,elements;//编号,生命值,攻击力,红蓝方标记,所在城市,剩余生命元
	bool alive;
	int loyalty, loyalty_d;
	bool isninja;//默认值是false
	bool isiceman;
	bool isdragon;
	bool islion;
	bool iswolf;
	vector<weapons> arms;
	bool exist;
	bool isescape;
	warrior() {
		exist = false;
	}
	warrior(int n, int hp, int atk, int flag,int elements) {
		this->n = n;
		this->hp = hp;
		this->atk = atk;
		this->flag = flag;
		this->elements = elements;
		alive = true;
		if (flag == 0) city_n = 0;//r初始所在城市编号
		else city_n = citys + 1;//b初始所在城市编号
		exist = true;
	}
	bool isalive() {
		return alive;
	}
	void update_s() {//更新武士存活的状态
		if (hp<=0) {
			alive = false;
		}
	}
	bool weapon_equal(vector<weapons> &v) {
		int cnt = 0;
		for (vector<weapons>::iterator iter = arms.begin(); iter != arms.end(); ++iter) {
			if (iter->n != v[cnt++].n) {//发现状态不一致
				return false;
			}
		}
		return true;
	}
 
	void attack(warrior &w,int id) {//用当前武士手中总体编号为id的武器去攻击武士w
		if (this->isalive()&&w.isalive()) {	
			if (this->hp > 0) {
				if (this->isninja == true && this->arms[id].name == "bomb") ;//ninja使用bomb就不用减自己的生命力
				else if(this->arms[id].name=="bomb") this->hp -= this->arms[id].w_atk/2;//自己减去生命力
				w.hp -= this->arms[id].w_atk;//敌方减去生命力
				this->update_s();//更新武士存活的状态
				w.update_s();
				
				this->arms[id].update_w();//更新武器状态(只需更新攻击者的)
			}
		}
	}
 
	virtual void print() {}
	virtual void goahead(int hours) {}
	virtual string getname() { return string(NULL); }
	virtual void escape(int hours){}
};
 
class dragon :public warrior {
public:
	double morale;//士气
 
	dragon(int n_t, int hp_t, int atk_t, int flag_t, int elements_t) :warrior(n_t, hp_t, atk_t, flag_t,elements_t) {
		morale = double(elements_t) / hp_t;
		arms.push_back(*(new weapons(weapon[n_t % 3],atk_t)));
		isdragon = true;
	}
	virtual void print() {
		if (flag == 0)
			printf("%03d:00 red dragon %d born\n", n - 1, n);
		else
			printf("%03d:00 blue dragon %d born\n", n - 1, n);
 
	}
	virtual void goahead(int hours) {
		if (flag == 0)
			printf("%03d:10 red dragon %d marched to city %d with %d elements and force %d\n", hours, n, city_n,hp,atk);
		else
			printf("%03d:10 blue dragon %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
	}
	virtual string getname() {
		return string("dragon");
	}
};
 
class ninja :public warrior {
public:
 
	ninja(int n_t, int hp_t, int atk_t, int flag_t,int elements_t) :warrior(n_t, hp_t, atk_t, flag_t, elements_t) {
		arms.push_back(*(new weapons(weapon[n_t % 3], atk_t)));
		arms.push_back(*(new weapons(weapon[(n_t+1) % 3], atk_t)));
		isninja = true;
	}
	virtual void print() {
		if (flag == 0)
			printf("%03d:00 red ninja %d born\n", n - 1, n);
		else
			printf("%03d:00 blue ninja %d born\n", n - 1, n);
	}
	virtual void goahead(int hours) {
		if (flag == 0)
			printf("%03d:10 red ninja %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
		else
			printf("%03d:10 blue ninja %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
	}
	virtual string getname() {
		return string("ninja");
	}
};
 
class iceman :public warrior {
public:
 
	iceman(int n_t, int hp_t, int atk_t, int flag_t,int elements_t) :warrior(n_t, hp_t, atk_t, flag_t, elements_t) {
		flag = flag_t;
		arms.push_back(*(new weapons(weapon[n_t % 3], atk_t)));
		isiceman = true;
	}
 
	virtual void print() {
		if (flag == 0)
			printf("%03d:00 red iceman %d born\n", n - 1, n);
		else
			printf("%03d:00 blue iceman %d born\n", n - 1, n);
	}
	virtual void goahead(int hours) {
		hp -=(hp / 10);
		if (flag == 0)
			printf("%03d:10 red iceman %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
		else
			printf("%03d:10 blue iceman %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
	}
	virtual string getname() {
		return string("iceman");
	}
};
 
class lion :public warrior {
public:
 
	lion(int n_t, int hp_t, int atk_t, int flag_t,int loyalty_d,int elements_t) :warrior(n_t, hp_t, atk_t, flag_t, elements_t) {
		loyalty = elements_t;
		arms.push_back(*(new weapons(weapon[n_t % 3], atk_t)));
		islion = true;
		this->loyalty_d = loyalty_d;
	}
	virtual void print() {
		if (flag == 0)
			printf("%03d:00 red lion %d born\n", n - 1, n);
		else
			printf("%03d:00 blue lion %d born\n", n - 1, n);
		cout << "Its loyalty is " << loyalty << endl;
	}
	//lion逃跑05,此时还没前进一步
	virtual void escape(int hours) {
		if (loyalty <= 0) {
			if (flag == 0 && isalive()&& city_n != citys + 1) {//实际上在05时刻,还没前进一步,是不可能占领了司令部的(因为在那之前10时刻的gameover()会检测到并结束对战)
				printf("%03d:05 red lion %d ran away\n", hours, n);//lion逃跑后武器怎么办呢?
				alive = false;
				return;//跑了
			}
			else if (flag == 1 && isalive() && city_n != 0) {
				printf("%03d:05 blue lion %d ran away\n", hours, n);
				alive = false;
				return;//跑了
			}
		}
	}
 
	//10
	virtual void goahead(int hours) {
		loyalty -= loyalty_d;
		if (flag == 0)
			printf("%03d:10 red lion %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
		else
			printf("%03d:10 blue lion %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
	}
	virtual string getname() {
		return string("lion");
	}
};
 
class wolf :public warrior {
public:
 
	wolf(int n_t, int hp_t, int atk_t, int flag_t,int elements_t) :warrior(n_t, hp_t, atk_t, flag_t, elements_t) {
		flag = flag_t;
		iswolf = true;
	}
	virtual void print() {
		if (flag == 0)
			printf("%03d:00 red wolf %d born\n", n - 1, n);
		else
			printf("%03d:00 blue wolf %d born\n", n - 1, n);
	}
	virtual void goahead(int hours) {
		if (flag == 0)
			printf("%03d:10 red wolf %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
		else
			printf("%03d:10 blue wolf %d marched to city %d with %d elements and force %d\n", hours, n, city_n, hp, atk);
	}
	virtual string getname() {
		return string("wolf");
	}
};
 
//10
void gameover(warrior &r, warrior &b, int hours) {
	//抵达,占领司令部10,10之后的事情就不会再发生了
	if (r.exist&&b.exist) {//同时占领
		printf("%03d:10 red %s %d reached blue headquarter with %d elements and force %d\n", hours, r.getname().c_str(), r.n, r.hp, r.atk);
		printf("%03d:10 red headquarter was taken\n", hours);
		printf("%03d:10 blue %s %d reached red headquarter with %d elements and force %d\n", hours, b.getname().c_str(), b.n, b.hp, b.atk);
		printf("%03d:10 red headquarter was taken\n", hours);
		b_win = true;
		r_win = true;
	}else if (r.exist&&!b.exist) {//r占领b
		printf("%03d:10 red %s %d reached blue headquarter with %d elements and force %d\n", hours, r.getname().c_str(), r.n, r.hp, r.atk);
		printf("%03d:10 red headquarter was taken\n", hours);
		r_win = true;
	}else if (b.exist&&!r.exist) {//b占领r
		printf("%03d:10 blue %s %d reached red headquarter with %d elements and force %d\n", hours, b.getname().c_str(), b.n, b.hp, b.atk);
		printf("%03d:10 red headquarter was taken\n", hours);
		b_win = true;
	}
}
 
int get_weapon_atk(int atk, string name) {
	if (name == "sword") return atk * 2 / 10;
	if (name == "bomb") return atk * 4 / 10;
	if (name == "arrow") return atk * 3 / 10;
	return 0;
}
 
//35
void rob(warrior &r, warrior &b, int n, int hours) {
	//wolf的特性 35
	if (r.iswolf&&b.iswolf) return;
	if (r.iswolf && !b.iswolf) {//r抢b的武器
		if (b.arms.empty()) return;
		sort(b.arms.begin(), b.arms.end(), w_rule_2());//(r抢b)的武器排序(2)
		string name_t = b.arms[0].name;//抢的武器名
		int sum = 0;//抢的武器数目
		for (vector<weapons>::iterator iter = b.arms.begin(); iter != b.arms.end(); ++iter) {
			if (r.arms.size() >= 10) break;
			if (name_t != iter->name) break;//确保只抢编号最小的那种武器
			iter->w_atk = get_weapon_atk(r.atk, iter->name);
			r.arms.push_back(*iter);
			++sum;
		}
		//抢完了,汇报
		printf("%03d:35 red wolf %d took %d ", hours, r.n, sum);
		cout << name_t << " from blue " << b.getname();
		printf(" %d in city %d\n", b.n, n);
	}
	else if (!r.iswolf&&b.iswolf) {//b抢r的武器
		if (r.arms.empty()) return;
		sort(r.arms.begin(), r.arms.end(), w_rule_2());//(b抢r)的武器排序(2)
		string name_t = r.arms[0].name;//抢的武器名
		int sum = 0;//抢的武器数目
		for (vector<weapons>::iterator iter = r.arms.begin(); iter != r.arms.end(); ++iter) {
			if (b.arms.size() >= 10) break;
			if (name_t != iter->name) break;//确保只抢编号最小的那种武器
			iter->w_atk = get_weapon_atk(b.atk, iter->name);
			b.arms.push_back(*iter);
			++sum;
		}
		//抢完了,汇报
		printf("%03d:35 blue wolf %d took %d ", hours, b.n, sum);
		cout << name_t << " from red " << r.getname();
		printf(" %d in city %d\n", r.n, n);
	}
}
 
bool weapons_atk_ok(vector<weapons> &v) {//检测是否还有能产生伤害的武器
	for (vector<weapons>::iterator iter = v.begin(); iter != v.end(); ++iter) {
		if (iter->w_atk > 0) return true;
	}
	return false;
}
 
bool weapons_w_ok(vector<weapons> &v) {//检测是否还有武器能用
	for (vector<weapons>::iterator iter = v.begin(); iter != v.end(); ++iter) {
		if (iter->w_ok) return true;
	}
	return false;
}
 
//40
//调用前做好入口检查,当没有遇敌的时候只会发生武士降生,(lion逃跑)武士前进和武士报告情况(没交战也要报告),这种情况应另外考虑
void battle(warrior &r, warrior &b, int n,int hours) {//n:城市编号,hours:整点时刻,要确保r,b都活着才能传入参数
 
	bool flag = false;//平局的标记,false表示非平局
	if (r.arms.size() == 0 && b.arms.size() == 0) {//如果战斗开始时双方武器都没武器,则以平局结束
		flag = true;
	} 
	//if (!weapons_atk_ok(r.arms)  && !weapons_atk_ok(b.arms)) {//双方都没有能产生攻击力的武器了,则平局
	//	flag = true;
	//}
	sort(r.arms.begin(), r.arms.end(), w_rule_1());//武器排序(1)
	sort(b.arms.begin(), b.arms.end(), w_rule_1());
	int r_id = 0, b_id = 0;//红方,蓝方当前使用的武器编号
	while (flag==false&&r.alive && b.alive) {
		int r_hp_t = r.hp, b_hp_t = b.hp;
		vector<weapons> r_arms_t(r.arms), b_arms_t(b.arms);
		r_id %= r.arms.size();//轮换使用武器
		b_id %= b.arms.size();//轮换使用武器
		if (r.arms.size() > 0&& weapons_w_ok(r.arms)) {//不排除只有其中一方没武器
			while (r.arms[r_id].w_ok == false) {
				++r_id;
				r_id %= r.arms.size();//轮换使用武器
			}
		}
		if (b.arms.size() > 0 && weapons_w_ok(b.arms)) {//不排除只有其中一方没武器
			while (b.arms[b_id].w_ok == false) {
				++b_id;
				b_id %= b.arms.size();//轮换使用武器
			}
		}
		if (!weapons_w_ok(r.arms) && !weapons_w_ok(b.arms)) break;
		//if (!weapons_atk_ok(r.arms) && !weapons_atk_ok(b.arms)) break;
		if (n % 2 == 0) {//偶数城市,blue先攻击
			if (b.arms.size() > 0 && b.arms[b_id].w_ok) {
				b.attack(r, b_id);//不排除只有其中一方没武器
				++b_id;
			}
			if (r.arms.size() > 0 && r.arms[r_id].w_ok) {
				r.attack(b, r_id);//不排除只有其中一方没武器
				++r_id;
			}
		}
		else {
			if (r.arms.size() > 0 && r.arms[r_id].w_ok) {
				r.attack(b, r_id);//不排除只有其中一方没武器
				++r_id;
			}
			if (b.arms.size() > 0 && b.arms[b_id].w_ok) {
				b.attack(r, b_id);//不排除只有其中一方没武器
				++b_id;
			}
		}
 
		if (r.hp == r_hp_t && b.hp == b_hp_t) {
			if (r.weapon_equal(r_arms_t) && b.weapon_equal(b_arms_t)) {
				break;//生命值,武器状态不再发生改变了,以平局结束(可能是武器攻击力太低(只剩sword了)或者武器都用完了)
			}
		}
 
	}
 
	if (!r.alive && !b.alive) {//都死了的平局
		printf("%03d:40 both red ", hours);
		cout << r.getname() << " " << r.n << " and blue " << b.getname() << " " << b.n << " died in city " << n << endl;
 
	}
	if(!r.arms.empty())
		for (vector<weapons>::iterator iter = r.arms.begin(); iter != r.arms.end();) {//清理报废的武器
			if (iter->w_ok == false) {
				iter = r.arms.erase(iter);
			}
			else {
				++iter;
			}
		}
	if(!b.arms.empty())
		for (vector<weapons>::iterator iter = b.arms.begin(); iter != b.arms.end();) {//清理报废的武器
			if (iter->w_ok == false) {
				iter = b.arms.erase(iter);
			}
			else {
				++iter;
			}
		}
 
	//打完以后更新武器的状态并报告战斗情况 40
	//都活着的平局(可能是武器攻击力太低或者武器都用完了)
	if (r.alive && b.alive) {
		printf("%03d:40 both red ", hours);
		cout << r.getname() << " " << r.n << " and blue " << b.getname() << " " << b.n << " were alive in city " << n << endl;
	}
 
	//有胜负
	if (r.alive &&!b.alive) {//r赢
		printf("%03d:40 red ", hours);
		cout<<r.getname()<<" "<<r.n<<" killed blue "<<b.getname()<<" "<<b.n<<" in city "<<n<<" remaining "<<r.hp<<" elements"<<endl;
		//r缴获b的武器
		sort(b.arms.begin(), b.arms.end(), w_rule_2());
		for (vector<weapons>::iterator iter = b.arms.begin(); iter != b.arms.end(); ++iter) {
			if (r.arms.size() >= 10) break;
			iter->w_atk = get_weapon_atk(r.atk, iter->name);
			r.arms.push_back(*iter);
		}
 
	}
	if (b.alive &&!r.alive) {//b赢
		printf("%03d:40 blue ", hours);
		cout << b.getname() << " " << b.n << " killed red " << r.getname() << " " << r.n << " in city " << n << " remaining " << b.hp << " elements" << endl;
		//b缴获r的武器
		sort(r.arms.begin(), r.arms.end(), w_rule_2());
		for (vector<weapons>::iterator iter = r.arms.begin(); iter != r.arms.end(); ++iter) {
			if (b.arms.size() >= 10) break;
			iter->w_atk = get_weapon_atk(b.atk, iter->name);
			b.arms.push_back(*iter);
		}
 
	}
 
	//dragon的特性--欢呼 40
	if (r.alive && r.isdragon) {
		printf("%03d:40 red dragon %d yelled in city %d\n", hours, r.n, n);
	}
	if (b.alive && b.isdragon) {
		printf("%03d:40 blue dragon %d yelled in city %d\n", hours, b.n, n);
	}
 
}
 
//50
void showheadquarters(int hours,int r_elements,int b_elements) {
	printf("%03d:50 %d elements in red headquarter\n", hours, r_elements);
	printf("%03d:50 %d elements in blue headquarter\n", hours, b_elements);
}
 
void getweapons(vector<weapons> &v,int *a) {
	a[0] = 0;
	a[1] = 0;
	a[2] = 0;
	for (vector<weapons>::iterator iter = v.begin(); iter != v.end(); ++iter) {
		if (iter->name == "sword") ++a[0];
		if (iter->name == "bomb") ++a[1];
		if (iter->name == "arrow") ++a[2];
	}
 
}
 
//55 调用前做好入口检查
void showwarriors(warrior* r[], warrior* b[],int hours) {
	int a[3];
	for (int i = 1; i <= citys; ++i) {
		if (r[i]!=NULL&&r[i]->isalive()) {//只有存在的且活着的才报告情况
			getweapons(r[i]->arms, a);
			printf("%03d:55 red %s %d has %d sword %d bomb %d arrow and %d elements\n",
				hours, r[i]->getname().c_str(), r[i]->n,a[0],a[1],a[2],r[i]->hp);
		}
		if (b[i]!=NULL&&b[i]->isalive()) {
			getweapons(b[i]->arms, a);
			printf("%03d:55 blue %s %d has %d sword %d bomb %d arrow and %d elements\n",
				hours, b[i]->getname().c_str(), b[i]->n, a[0], a[1], a[2], b[i]->hp);
		}
	}
}
 
int main()
{
	//freopen("C:\\Users\\pc\\Desktop\\openjudge\\in.txt", "r", stdin);
	freopen("C:\\Users\\pc\\Desktop\\openjudge\\out.txt", "w", stdout);
	int N;
	scanf("%d", &N);
	int cnt = 0;//case的编号
	while (N--) {
		scanf("%d %d %d %d", &m, &citys, &loyalty_d, &deadline);
		int hour = deadline / 60;
		int minuter = deadline - hour * 60;
		warrior* battlefield[2][25];//战斗的场所
		for (int i = 0; i < 2; ++i) {//初始化
			for (int j = 0; j < 25; ++j) {
				battlefield[i][j] = NULL;
			}
		}
		int d, n, i, l, w;//武士们的所需生命值
		scanf("%d %d %d %d %d", &d, &n, &i, &l, &w);
		int min_hp = min(d, min(n, min(i, min(l, w))));
		int da, na, ia, la, wa;//武士们的攻击力
		scanf("%d %d %d %d %d", &da, &na, &ia, &la, &wa);
		printf("Case %d:\n", ++cnt);
 
		int r = m, b = m;//双方剩余生命值
		int cnt_r = 1, cnt_b = 1;//武士的编号,-1就是整点时刻
		vector<warrior*> r_army, b_army;
		int r_end = 0, b_end = 0;//等于1时,表示已经无法再生成了
		int r_i_ok = 0, r_l_ok = 0, r_w_ok = 0, r_n_ok = 0, r_d_ok = 0;//轮换生成,表明检测过
		int b_i_ok = 0, b_l_ok = 0, b_w_ok = 0, b_n_ok = 0, b_d_ok = 0;
 
		int r_ok = 0, b_ok = 0;//等于1时,说明已经生成了一个,等于0时说明还没生成,此时才可以生成
		while (1) {//生成武士
			//if (max(cnt_r, cnt_b) == hour + 2) break;//武士编号从1开始(1-hour+1),整点时刻从0开始(0-hour),因为有余数,所以可能要多保留一个状态
			if (r_end == 1 && b_end == 1) break;//只有当无法生成时才跳出循环 
			r_ok = 0;
			b_ok = 0;
			if (r_ok == 0 && r_end == 0) {
				if (r_i_ok == 1 && r_l_ok == 1 && r_w_ok == 1 && r_n_ok == 1 && r_d_ok == 1) {
					r_i_ok = 0;
					r_l_ok = 0;
					r_w_ok = 0;
					r_n_ok = 0;
					r_d_ok = 0;
				}
				if (r >= i && r_ok == 0 && r_i_ok == 0) {//iceman
					r -= i;
					r_army.push_back(new iceman(cnt_r++, i, ia, 0,r));
					r_ok = 1;//红方本轮生成了,本轮下面就不用再生成了
					r_i_ok = 1;
				}
				else if (r_i_ok == 0 && r < i) {//检测到,本该生成,但因为生命元不够而不能生成
					r_end = 1;
					r_ok = 1;//确保本轮下面也不生成了
				}
				if (r >= l && r_ok == 0 && r_l_ok == 0) {//lion
					r -= l;
					r_army.push_back(new lion(cnt_r++, l,la, 0, loyalty_d,r));
					r_ok = 1;
					r_l_ok = 1;
				}
				else if (r_l_ok == 0 && r < l) {
					r_end = 1;
					r_ok = 1;
				}
				if (r >= w && r_ok == 0 && r_w_ok == 0) {//wolf
					r -= w;
					r_army.push_back(new wolf(cnt_r++, w, wa, 0,r));
					r_ok = 1;
					r_w_ok = 1;
				}
				else if (r_w_ok == 0 && r < w) {
					r_end = 1;
					r_ok = 1;
				}
				if (r >= n && r_ok == 0 && r_n_ok == 0) {//ninja
					r -= n;
					r_army.push_back(new ninja(cnt_r++, n, na, 0,r));
					r_ok = 1;
					r_n_ok = 1;
				}
				else if (r_n_ok == 0 && r < n) {
					r_end = 1;
					r_ok = 1;
				}
				if (r >= d && r_ok == 0 && r_d_ok == 0) {//dragon
					r -= d;
					r_army.push_back(new dragon(cnt_r++, d, da, 0, r));
					r_ok = 1;
					r_d_ok = 1;
				}
				else if (r_d_ok == 0 && r < d) {
					r_end = 1;
					r_ok = 1;
				}
			}
 
			if (b_ok == 0 && b_end == 0) {
				//if (r_ok == 0 && r_end == 0) continue;//red一方没有生成,且还有足够的生命元的话,此时blue一方也不能生成,需要下一轮重新遍历
				if (b_i_ok == 1 && b_l_ok == 1 && b_w_ok == 1 && b_n_ok == 1 && b_d_ok == 1) {
					b_i_ok = 0;
					b_l_ok = 0;
					b_w_ok = 0;
					b_n_ok = 0;
					b_d_ok = 0;
				}
				if (b >= l && b_ok == 0 && b_l_ok == 0) {//lion
					b -= l;
					b_army.push_back(new lion(cnt_b++, l,la, 1, loyalty_d,b));
					b_ok = 1;
					b_l_ok = 1;
				}
				else if (b_l_ok == 0 && b < l) {
					b_end = 1;
					b_ok = 1;
				}
				if (b >= d && b_ok == 0 && b_d_ok == 0) {//dragon
					b -= d;
					b_army.push_back(new dragon(cnt_b++, d, da, 1, b));
					b_ok = 1;
					b_d_ok = 1;
				}
				else if (b_d_ok == 0 && b < d) {
					b_end = 1;
					b_ok = 1;
				}
				if (b >= n && b_ok == 0 && b_n_ok == 0) {//ninja
					b -= n;
					b_army.push_back(new ninja(cnt_b++, n, na, 1,b));
					b_ok = 1;
					b_n_ok = 1;
				}
				else if (b_n_ok == 0 && b < n) {
					b_end = 1;
					b_ok = 1;
				}
				if (b >= i && b_ok == 0 && b_i_ok == 0) {//iceman
					b -= i;
					b_army.push_back(new iceman(cnt_b++, i, ia, 1,b));
					b_ok = 1;
					b_i_ok = 1;
				}
				else if (b_i_ok == 0 && b < i) {
					b_end = 1;
					b_ok = 1;
				}
				if (b >= w && b_ok == 0 && b_w_ok == 0) {//wolf
					b -= w;
					b_army.push_back(new wolf(cnt_b++, w, wa, 1,b));
					b_ok = 1;
					b_w_ok = 1;
				}
				else if (b_w_ok == 0 && b < w) {
					b_end = 1;
					b_ok = 1;
				}
			}
 
 
		}
 
		int r_size = r_army.size(), b_size = b_army.size();
		//cout << r_size << " " << b_size <<" "<<hour<<endl;
		bool flag_0 = false, flag_05=false,flag_10 = false, flag_35 = false, flag_40 = false, flag_50 = false,flag_55=false;//余数时间控制
		if (minuter >= 0) flag_0 = true;
		if (minuter >= 5) flag_05 = true;
		if (minuter >= 10) flag_10 = true;
		if (minuter >= 35) flag_35 = true;
		if (minuter >= 40) flag_40 = true;
		if (minuter >= 50) flag_50 = true;
		if (minuter >= 55) flag_55 = true;
		for (int i = 0; i <= hour; ++i) {
			if (i == hour && flag_0 == false) break;
			//降生00
			if (i<r_size) r_army[i]->print();
			if (i<b_size) b_army[i]->print();
 
			//lion 逃跑 05
			if (i == hour && flag_05 == false) break;
			for (int j = 1; j <= citys; ++j) {
				if (battlefield[0][j] != NULL || battlefield[1][j] != NULL) {//战场上有战士																	
					if (battlefield[0][j]!=NULL&&battlefield[0][j]->islion) battlefield[0][j]->escape(i);
					if (battlefield[1][j]!=NULL&&battlefield[1][j]->islion) battlefield[1][j]->escape(i);
				}
			}
 
			//前进一步 10
			if (i == hour && flag_10 == false) break;
			//for (int j = 0; j <= i; ++j) {
			//	if (j<r_size&&r_army[j]->alive) r_army[j]->goahead(i);
			//	if (j<b_size&&b_army[j]->alive) b_army[j]->goahead(i);
			//}
 
			//分配到战场上(10)
			for (int j = 0; j <= i; ++j) {
				if (j<r_size&&r_army[j]->alive) battlefield[0][++r_army[j]->city_n] = r_army[j];//red: 1 ~ citys+1
				if (j<b_size&&b_army[j]->alive) battlefield[1][--b_army[j]->city_n] = b_army[j];//blue: citys ~ 0
			}
 
			//前进一步 10
			for (int j = 1; j <= citys; ++j) {
				if (battlefield[0][j] != NULL && battlefield[0][j]->alive) battlefield[0][j]->goahead(i);
				if (battlefield[1][j] != NULL && battlefield[1][j]->alive) battlefield[1][j]->goahead(i);
			}
 
			//占领司令部(10)
			if (!r_win && !b_win) { //gamover 10
				if (battlefield[1][citys + 1] != NULL || battlefield[0][0] != NULL) {
					if (battlefield[1][citys + 1] == NULL && battlefield[0][0] != NULL) {
						if(battlefield[0][0]->alive) gameover(*(new warrior()), *battlefield[0][0], i);
					}
					else if (battlefield[1][citys + 1] != NULL && battlefield[0][0] == NULL) {
						if(battlefield[1][citys + 1]->alive) gameover(*battlefield[1][citys + 1], *(new warrior()), i);
					}
					else {
						if (battlefield[1][citys + 1]->alive&&battlefield[0][0]->alive)
							gameover(*battlefield[1][citys + 1], *battlefield[0][0], i);//red占领blue(1)的citys+1号,blue占领red(0)的0号
					}
				}
			}
 
			//wolf 35,rob
			if (i == hour && flag_35 == false) break;
			if (r_win || b_win) break;
			for (int j = 1; j <= citys; ++j) {
				if (battlefield[0][j] != NULL && battlefield[1][j] != NULL) {//战场上双方都有战士																	
					if (battlefield[0][j]->alive && battlefield[1][j]->alive) {//且都活着
						if (battlefield[0][j]->iswolf || battlefield[1][j]->iswolf) rob(*battlefield[0][j], *battlefield[1][j], j, i);
					}
				}
			}
 
			//battle 40
			if (i == hour && flag_40 == false) break;
			for (int j = 1; j <= citys; ++j) {
				if (battlefield[0][j] != NULL && battlefield[1][j] != NULL) {//战场上双方都有战士																	
					if (battlefield[0][j]->alive && battlefield[1][j]->alive) {//且都活着
						battle(*battlefield[0][j], *battlefield[1][j], j, i);
					}
 
				}
			}
 
			//50 司令部报告生命元数量
			if (i == hour && flag_50 == false) break;
			showheadquarters(i, r_size == 0 ? m : battlefield[0][1]->elements, b_size == 0 ? m : battlefield[1][citys]->elements);
			//55 武士报告情况
			if (i == hour && flag_55 == false) break;
			showwarriors(battlefield[0], battlefield[1], i);
			
			//for (int i = 0; i < 2; ++i) {//初始化
			//	for (int j = 0; j < 25; ++j) {
			//		battlefield[i][j] = NULL;
			//	}
			//}
		}
	}
 
	//rob(*new iceman(1, 1, 1, 0, 10), *new wolf(2, 3, 4, 1, 10),5,20);
	//system("pause");
	return 0;
}
 

  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值