Codechef Not a Triangle题解
来源:互联网 发布:无人机数据处理软件 编辑:程序博客网 时间:2024/05/15 05:34
找出一个数组中的三个数,三个数不能组成三角形。
三个数不能组成三角形的条件是:a + b < c
两边和小于第三边。
这个问题属于三个数的组合问题了。暴力法可解,但是时间效率就是O(n*n*n)了,很慢。
不过既然是组合问题就必定可以使用排序后处理的方法降低时间效率的。
这里降低时间效率的方法是:
选一个最大的数c,然后选两个小数a和b,其中a < b,如果符合条件,那么两个数中间的数必定都可以作为b符合条件a + b < c
这样可以把时间效率降到O(n*n)。
这个规律也不好找啊。要非常认真观察,然后总结出来。
处理一个数组,要从小到大,从大到小反复观察,寻找其规律。
原题:http://www.codechef.com/problems/NOTATRI/
#include <stdio.h>#include <stdlib.h>#include <algorithm>using std::sort;class NotATriangle{//细心找出其规律进行优化int getNotTris_3(int *A, const int n){sort(A, A+n);int i = 0, j = 1, k = n-1, ans = 0;for ( ; k >= 2; k--){i = 0, j = k-1;while (i < j){if (A[i] + A[j] < A[k]){ans += j - i;i++;}else j--;}}return ans;}public:NotATriangle(){int N = 0;while (scanf("%d", &N) && 0 != N){int *A = (int *) malloc(sizeof(int)* N);for (int i = 0; i < N; i++){scanf("%d", &A[i]);}printf("%d\n", getNotTris_3(A, N));free(A);}}};int notATriangle(){NotATriangle ntir;return 0;}
1 0
- Codechef Not a Triangle题解
- codechef Sums in a Triangle题解
- Codechef A Simple Equation 题解
- CodeChef A
- codechef Turbo Sort 题解
- codechef Ambiguous Permutations 题解
- codechef Prime Palindromes 题解
- Codechef Nuclear Reactors 题解
- codechef Cleaning Up 题解
- codechef Permutation Cycles 题解
- codechef Birthday Candles 题解
- codechef Cutting Recipes题解
- codechef Carvans 题解
- Codechef Racing Horses题解
- codechef Hotel Bytelandia题解
- codechef Top Batsmen题解
- codechef Attic Crossing 题解
- codechef Recipe Reconstruction 题解
- 理财
- 理财
- 《逆袭大学》文摘——9.5 用算法和数学奠定专业基础
- 使用ffserver实现转发实时流媒体(摄像头捕获)
- 20060224- All about pixel colors: Reference information
- Codechef Not a Triangle题解
- JS创建类和对象
- 从细节入手为您的客户创造价值
- 使用ffmpeg捕获USB外部摄像头视频流
- 浅析JAVA设计模式之代理模式(五)
- PHP模板学习--Smarty 内置函数
- 第十一周 项目1—1存储班长信息的学生类(protected)
- 第十一周 项目1-2存储班长信息的学生类(private)
- PHP封装可执行