Frac1 Problem Solving report--icedream61 Blog Park (reproduced please specify the source)
--------------------------------------------------------------------------------------------------------------- ---------------------------------
Topic
Give you N, for all the i/j (1<=j<=n,0<=i<=j), sort the output in ascending order (repetition only leaves J minimum).
"Data Range"
1<=n<=160
"Input Sample"
5
"Output Example"
0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1
--------------------------------------------------------------------------------------------------------------- ---------------------------------
Analysis
Two-way linked list, one by one plug in the good. Each denominator I, a molecule from 0 to I, sweeps through the current queue to complete the insertion. Therefore, the complexity is less than O (N²).
--------------------------------------------------------------------------------------------------------------- ---------------------------------
Summary
There's nothing to say.
--------------------------------------------------------------------------------------------------------------- ---------------------------------
Code
1 /*2 id:icedrea13 Prob:frac14 lang:c++5 */6 7#include <iostream>8#include <fstream>9 using namespacestd;Ten One structNode A { - intx, y; -Node *l,*R; the Node () {} -Node (intIintj): X (i), Y (j), L (0), R (0) {} -FriendBOOL operator= = (Node p,node q) {returnp.x*q.y==p.y*q.x;} -FriendBOOL operator< (Node P,node q) {returnp.x*q.y<p.y*q.x;} +FriendBOOL operator> (Node p,node q) {returnp.x*q.y>p.y*q.x;} -Friend ostream&operator<< (ostream& out, Node p) {returncout<<p.x<<"/"<<p.y;} +}*a,*B; A at intN; - - intMain () - { -Ifstreaminch("frac1.in"); -Ofstream out("Frac1.out"); in - inch>>N; toA=NewNode (-1,1); b=NewNode (2,1); a->r=b; B->l=A; + - for(intI=1; i<=n;++i)//Denominator is I the { *Node *now=A; $ for(intj=0; j<=i;++j)//molecule is JPanax Notoginseng { -Node *p=NewNode (j,i); the while(*p>*now) now=now->R; + if(*p==*now)Continue;ElseNow=now->l; Ap->r=now->r; p->r->l=p; p->l=now; Now->r=p; the } + //For (Node *p=a->r;p!=b;p=p->r) cout<<p->x<< "/" <<p->y<<endl; cin.get (); - } $ $ for(Node *p=a->r;p!=b;p=p->r) out<<p->x<<"/"<<p->y<<Endl; - - inch. Close (); the out. Close (); - return 0;Wuyi}
Usaco Section2.1 Ordered Fractions Problem Solving report