Created
November 29, 2016 06:45
-
-
Save jianminchen/bcee26d0f395cd6dee04b3d53184c2a4 to your computer and use it in GitHub Desktop.
HackerRank - ACM ICPC Practice Contest 2016 - New year present - first submission, a lot of issues, pass test case 1, 5, failed 0. Just rush in before completion of coding.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace NewYearPresent | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int n = Convert.ToInt32(Console.ReadLine()); | |
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); | |
Console.WriteLine(calculate(n, arr)); | |
} | |
/* | |
* test c(6, 3) = 6 *5 *4/(3*2*1) | |
*/ | |
private static long calCombination(int n, int k) | |
{ | |
long res = 1; | |
for (int i = n; i >= (n - k + 1); i--) | |
res *= i; | |
for (int i = 1; i <= k; i++) | |
{ | |
res /= i; | |
} | |
return res; | |
} | |
private static long calculate(int n, int[] arr) | |
{ | |
int SIZE = 10000001; | |
int[] buckets = new int[SIZE]; | |
for(int i = 0;i < n; i++) | |
{ | |
buckets[arr[i]]++; | |
} | |
long count = 0; | |
for(int i=2; i< SIZE; i++) | |
{ | |
int n2 = buckets[i]; | |
int sum = i; | |
// Try 2 - for example, n2 = 5, 1 4 1 4 5 5 | |
if (n2 >= 2) | |
{ | |
long m = calCombination(n2, 2); | |
int foundTwo = 1; | |
bool foundFirst = false; | |
bool foundSecond = false; | |
int start = 1; | |
while (foundTwo < 3) | |
{ | |
for (int j = start; j < n2; j++) | |
{ | |
int v1 = buckets[i]; | |
if (v1 == 0 || v1 >= n2) | |
continue; | |
for (int k = j + 1; k < n2; k++) | |
{ | |
int v2 = buckets[k]; | |
if (v2 == 0 || Math.Abs(v1 + v2 - sum) > 0) | |
continue; | |
if (foundTwo == 1) | |
{ | |
foundFirst = true; | |
start = j; | |
} | |
else if (foundTwo == 2) | |
foundSecond = true; | |
} | |
} | |
foundTwo++; | |
} | |
if(foundFirst && foundSecond) | |
count += m; | |
} | |
// Try 3 - for example, n2 =5, 1 2 2 5 5 5 | |
if(n2>=3) | |
{ | |
long m = calCombination(n2, 3); | |
for (int j = 1; j < n2; j++) | |
{ | |
int v1 = buckets[i]; | |
if (v1 == 0 || v1>= n2) | |
continue; | |
for (int k = j+1; k < n2; k++) | |
{ | |
int v2 = buckets[k]; | |
if (v2 == 0 || (v1+v2) >= n2) | |
continue; | |
for (int l = k + 1; l < n2; l++) | |
{ | |
int v3 = buckets[l]; | |
if (buckets[l] == 0 || Math.Abs(v1+v2+v3-sum) > 0) | |
continue; | |
count += m; | |
} | |
} | |
} | |
} | |
} | |
return count; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment