Wednesday 28 January 2015

UNION FIND FOR CODECHEF QUESTION http://www.codechef.com/ALMA2015/problems/ALMA03/


chota bheem and gcd (https://www.codechef.com/problems/ALMA03 )

  1. #include <bits/stdc++.h>
  2. using namespace std;

  3. #define MAXN 205
  4. #define MOD 1000000007
  5. int parent[MAXN],A[MAXN];
  6. void init()
  7. {
  8. for(int i=0;i<MAXN;++i)
  9. parent[i] = -1;
  10. }
  11. int find(int i)
  12. {
  13. if(parent[i]==-1)
  14. return i;
  15. else
  16. return parent[i] = find(parent[i]);
  17. }
  18. void merge(int x,int y)
  19. {
  20. x = find(x);
  21. y = find(y);
  22. if(x!=y)
  23. {
  24. if(A[x]>A[y])
  25. parent[y] = x; /// whose rank is greater will become parent (here Rank work is done by Cost itself)
  26. else
  27. parent[x] = y;
  28. }
  29. }
  30. int main()
  31. {
  32. int t,n;
  33. scanf("%d",&t);
  34. while(t--)
  35. {
  36. init();
  37. scanf("%d",&n);
  38. for(int i=0;i<n;++i
  39. { scanf("%d",A+i); }
  40. for(int i=0;i<n;++i)
  41. for(int j=i+1;j<n;++j)
  42. if(__gcd(A[i],A[j])>1)
  43. merge(i,j);

  44. long long result = 1;
  45. for(int i=0;i<n;++i)
  46. if(parent[i]==-1)
  47. {
  48. result *= A[i];
  49. result %= MOD;
  50. }
  51. printf("%lld\n",result);
  52. }
  53. }

No comments:

Post a Comment

Uploading and Running Lambda function in AWS

Main.go package main import ( "fmt" "encoding/json" "log" "github.com/aws/aws-lambda-g...