USACO Section2.1 Ordered Fractions 解题报告

    frac1解题报告 —— icedream61 博客园(转载请注明出处)
------------------------------------------------------------------------------------------------------------------------------------------------
【题目】
  给你N,对于所有的既约分数i/j(1<=j<=N,0<=i<=j),升序排列输出(重复则只留j最小的)。
【数据范围】
  1<=N<=160
【输入样例】
  5
【输出样例】
  0/1
  1/5
  1/4
  1/3
  2/5
  1/2
  3/5
  2/3
  3/4
  4/5
  1/1
------------------------------------------------------------------------------------------------------------------------------------------------
【分析】
  双向链表,往里一个一个插就好了。每个分母i,分子从0到i,扫一遍当前队列即可完成插入。因此,复杂度不到O(N²)。
------------------------------------------------------------------------------------------------------------------------------------------------
【总结】
  没啥可说的。

------------------------------------------------------------------------------------------------------------------------------------------------

【代码】

复制代码
 1 /*
 2 ID: icedrea1
 3 PROB: frac1
 4 LANG: C++
 5 */
 6 
 7 #include <iostream>
 8 #include <fstream>
 9 using namespace std;
10 
11 struct Node
12 {
13     int x,y;
14     Node *l,*r;
15     Node() {}
16     Node(int i,int j):x(i),y(j),l(0),r(0) {}
17     friend bool operator==(Node p,Node q) { return p.x*q.y==p.y*q.x; }
18     friend bool operator<(Node p,Node q) { return p.x*q.y<p.y*q.x; }
19     friend bool operator>(Node p,Node q) { return p.x*q.y>p.y*q.x; }
20     friend ostream& operator<<(ostream& out,Node p) { return cout<<p.x<<"/"<<p.y; }
21 }*A,*B;
22 
23 int N;
24 
25 int main()
26 {
27     ifstream in("frac1.in");
28     ofstream out("frac1.out");
29 
30     in>>N;
31     A=new Node(-1,1); B=new Node(2,1); A->r=B; B->l=A;
32 
33     for(int i=1;i<=N;++i) // 分母为i
34     {
35         Node *now=A;
36         for(int j=0;j<=i;++j) // 分子为j
37         {
38             Node *p=new Node(j,i);
39             while(*p>*now) now=now->r;
40             if(*p==*now) continue; else now=now->l;
41             p->r=now->r; p->r->l=p; p->l=now; now->r=p;
42         }
43         //for(Node *p=A->r;p!=B;p=p->r) cout<<p->x<<"/"<<p->y<<endl; cin.get();
44     }
45 
46     for(Node *p=A->r;p!=B;p=p->r) out<<p->x<<"/"<<p->y<<endl;
47 
48     in.close();
49     out.close();
50     return 0;
51 }
复制代码

 

posted on   IceDream61  阅读(167)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示