🔙 Back to Top

Sat Aug 22 17:34:54 JST 2015

問題

No.267 トランプソート - yukicoder

解答

http://yukicoder.me/submissions/45138

トランプカードの入出力クラス

自前クラスの入出力と、compare< を定義するだけの実装ゲー

#include <bits/stdc++.h>
using namespace std;

#define rep(i,n) for(int i=0;i<(n);++i)
#define trace(var) cerr<<">>> "<<#var<<" = "<<var<<endl;

template<class T> inline
ostream& operator<<(ostream&os, vector<T> v) {
  if (v.size() == 0) { return os << "(empty)"; }
  os << v[0];
  for (int i=1, len=v.size(); i<len; ++i) os << ' ' << v[i];
  return os;
}

template<class T> inline
istream& operator>>(istream&is, vector<T>&v) {
  rep (i, v.size()) is >> v[i];
  return is;
}

enum Suit { D, C, H, S };
struct Card {
  Suit s;
  int n;
  Card() {};
  Card(Suit _s, int _n) : s(_s), n(_n) {};
};

ostream& operator<<(ostream&os, Suit&s) {
  if (s == D) os << 'D';
  else if (s == H) os << 'H';
  else if (s == C) os << 'C';
  else if (s == S) os << 'S';
  else cerr << "Suit show Error" << endl;
  return os;
}

ostream& operator<<(ostream&os, Card&c) {
  os << c.s;
  if (c.n == 1) os << 'A';
  else if (c.n == 10) os << 'T';
  else if (c.n == 11) os << 'J';
  else if (c.n == 12) os << 'Q';
  else if (c.n == 13) os << 'K';
  else os << c.n;
  return os;
}

istream& operator>>(istream&is, Suit&s) {
  char c; is >> c;
  if (c == 'D') s = D;
  else if (c == 'H') s = H;
  else if (c == 'C') s = C;
  else if (c == 'S') s = S;
  else cerr << "Suit read Error" << endl;
  return is;
}

istream& operator>>(istream&is, Card&c) {
  Suit s; is >> s;
  char n; is >> n;
  c.s = s;
  if (n == 'A') c.n = 1;
  else if (n == 'T') c.n = 10;
  else if (n == 'J') c.n = 11;
  else if (n == 'Q') c.n = 12;
  else if (n == 'K') c.n = 13;
  else c.n = n - '0';
  return is;
}

bool operator<(const Card& lh, const Card& rh) {
  if (lh.s != rh.s) return lh.s < rh.s;
  return lh.n < rh.n;
}

int main() {

  int n; cin >> n;
  vector<Card> cs(n); cin >> cs;
  sort(begin(cs), end(cs));
  cout << cs << endl;

  return 0;
}

vector<T> の入出力はテンプレに入れてるが、重宝している. 特に入力はしょっちゅう使うし、 出力は問題に依存するが、yukicoderでは私の定義の形でそのまま使えることが多い気がする.