SPOJ - Sort 1

0

http://pl.spoj.com/problems/PP0506A/

#include <iostream>
#include <list>
#include <cmath>

using namespace std;

class Punkt
{
public:
    Punkt(string n,int px,int py):nazwa(n),x(px),y(py),modul(sqrt(x*x+y*y)){}
    string nazwa;
    int x;
    int y;
    int modul;
};

bool operator<(Punkt & P1, Punkt & P2)
{
    return P1.modul<P2.modul;
}

ostream & operator<< (ostream & os, Punkt & a)
{
    os << a.nazwa << " " << a.x << " " << a.y << endl;
    return os;
}

int main()
{
    list <Punkt> Lista;
    list <Punkt>::iterator itr;
    itr=Lista.begin();

    int t; cin>>t;
    for(int i=1;i<=t;i++)
    {
        int n; cin>>n;
        for(int j=1;j<=n;j++)
        {
            string nazwa; cin>>nazwa;
            int x; cin>>x;
            int y; cin>>y;
            Punkt MojPunkt(nazwa,x,y);
            Lista.push_back(MojPunkt);
        }
        Lista.sort();
        for(itr=Lista.begin();itr!=Lista.end();++itr)
            cout << *itr;
        Lista.clear();
        cout << endl;
    }
    return 0;
}
 

Napisałem tu program. SPOJ pokazuje, że błędna odpowiedź a output się zgadza. Nie wiem co tu może być źle. Może uda się komuś wymyślić taki input, że program będzie dawał złe wyniki?

1

Odległość punktu od środka układu współrzędnych trzymasz w int-cie (a już przy punkcje B wyjdzie ci ułamek, który po skonwertowaniu na int-a może zafałszować wynik) daj modul jako double i będzie dobrze

2

Wywal <cmath> i sqrt()

1
class Punkt
{
public:
    Punkt(string n,int px,int py) 
        : nazwa(n)
        , r2(x*x+y*y)
    {}
    string nazwa;
    int r2;
};
bool operator<(const Punt& a, const Punt& b)
{
     return a.r2<b.r2;
}
1

Swoją drogą ciekawy jestem czy zadanie w zestawach danych uwzględnia takie przypadki:

2
4
A 1 1
B -1- 1
C -1 1
D 1 1
4
A 1 1
B -1- 3
C -1 1
D 1 1

bo może należy użyć stable_sort.

1
#include <algorithm>
#include <iterator>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
 
class Point
  {
   public:
   bool operator<(const Point &p)const { return order<p.order; }
   friend ostream &operator<<(ostream &s,const Point &p) { return s<<p.show; }
   friend istream &operator>>(istream &s,Point &p) 
     {
      getline(s>>ws,p.show);
      istringstream ss(p.show);
      int x,y;
      string name;
      ss>>name>>x>>y;
      p.order=x*x+y*y;
      p.show+='\n';
      return s; 
     }
   private:
   string show;
   int order;
  };
  
int main()
  {
   size_t test,count;
   for(cin>>test;test--;cout<<'\n')
     {
      cin>>count;
      vector<Point> tb(count);
      for(vector<Point>::iterator i=tb.begin();i!=tb.end();++i) cin>>*i;
      //copy_n(istream_iterator<Point>(cin),count,tb.begin());
      sort(tb.begin(),tb.end());
      copy(tb.begin(),tb.end(),ostream_iterator<Point>(cout));
     }
   return 0;
  }

1 użytkowników online, w tym zalogowanych: 0, gości: 1