POJ 2996 Help Me with the Game

实现思路:

用到的数据结构:

struct Piece{int x,y,v};

vector<vector<Piece> > pieces(12);

Piece主要用于存点的信息,行号,列号,还有字符值(int(char))。

根据输出的要求知道必须按字符顺序输出,从K开始,这样每个字符用于数组(即vector)的下标,根据每个pieces[i]可以给基于同样字符的点排序。输出时转换注意数字,大写字母,小写字母的ASCII码是逐渐变大的,比如字符为v(为小写),要输出对应的大写字母,则可以char(v-'a'+'A')就可以满足要求。

注意比较函数是按第一个参数与第二个参数的return的逻辑顺序排序的。

我做题太慢了,太浪费时间了,赶快让我的功力上来吧。

View Code
  1 #include<iostream>
2 #include<vector>
3 #include<cstring>
4 #include<cstdio>
5 #include<algorithm>
6
7 #define ONLINE
8
9 void online()
10 {
11 #ifdef ONLINE
12 #else
13 freopen("D:\\t1.txt","r",stdin);
14 freopen("D:\\t2.txt","w",stdout);
15 #endif
16
17 }
18
19 using namespace std;
20
21 const int maxn=8;
22
23 struct Piece{
24 int x,y,v;//x代表行号,y代表列号,v代表字符
25 Piece()
26 {
27 }
28 Piece(int xx,int yy,char vv):x(xx),y(yy),v(vv)
29 {
30 }
31 };
32
33 vector<vector<Piece> > pieces(12);
34
35 int getid[128];
36
37
38
39 void init()
40 {
41 memset(getid,-1,sizeof(getid));
42
43 getid[int('K')]=0; //数组不能在函数外初始化
44 getid[int('Q')]=1;
45 getid[int('R')]=2;
46 getid[int('B')]=3;
47 getid[int('N')]=4;
48 getid[int('P')]=5;
49 getid[int('k')]=6;
50 getid[int('q')]=7;
51 getid[int('r')]=8;
52 getid[int('b')]=9;
53 getid[int('n')]=10;
54 getid[int('p')]=11;
55 string str;
56
57 for(int i=1;i<=maxn;i++)
58 {
59 getline(cin,str);
60 for(int j=1;j<=maxn;j++)
61 {
62 getchar();
63 getchar();
64 char ch;
65 cin>>ch; //getchar返回值一般设置为int类型,因为getchar返回值必须够大。。。
66 if(getid[int(ch)]!=-1)
67 pieces[getid[int(ch)]].push_back(Piece(i,j,ch));
68 getchar();
69 }
70 // getchar(); 去掉这一行,加上47行,因为每行结尾不止一个字符。。。
71 getline(cin,str);
72 }
73 }
74
75
76 void output()
77 {
78 cout<<"White: ";
79 bool first=true;
80 for(int i=0;i<=5;i++)
81 {
82 for(vector<Piece>::iterator iter=pieces[i].begin();iter!=pieces[i].end();iter++)
83 {
84 if(!first)
85 {
86 cout<<",";
87 }
88 first=false;
89
90 char second=iter->y+'a'-1;
91 int three=9-iter->x;
92 if(iter->v!='P')
93 cout<<char(iter->v);
94 cout<<second<<three;
95 }
96 }
97 cout<<endl;
98 cout<<"Black: ";
99 first=true;
100 for(int i=6;i<=11;i++)
101 {
102 for(vector<Piece>::iterator iter=pieces[i].begin();iter!=pieces[i].end();iter++)
103 {
104 if(!first)
105 {
106 cout<<",";
107 }
108 first=false;
109 char second=iter->y+'a'-1;
110 int three=9-iter->x;
111 if(iter->v!='p')
112 cout<<char(iter->v-'k'+'K');
113 cout<<second<<three;
114 }
115 }
116
117 }
118
119 bool cmpWhite(const Piece& a,const Piece& b)
120 {
121 if(a.x==b.x)
122 return a.y<b.y;
123 return a.x>b.x;
124 }
125
126 bool cmpBlack(const Piece& a,const Piece& b)
127 {
128 if(a.x==b.x)
129 return a.y<b.y;
130 return a.x<b.x;
131 }
132
133 void outsort()
134 {
135 for(int i=0;i<=5;i++)
136 sort(pieces[i].begin(),pieces[i].end(),cmpWhite);
137 for(int i=6;i<=11;i++)
138 sort(pieces[i].begin(),pieces[i].end(),cmpBlack);
139 }
140
141 int main()
142 {
143 online();
144 init();
145 outsort();
146 output();
147 return 0;
148 }

原文地址:https://www.cnblogs.com/YipWingTim/p/2218012.html