21

Re: Facebook Hacker Cup

Я не про те, я про те як можна дужки групувати. Тобто якщо дивитись

( :( )

, то в середині смайл. А якщо дивитись

(: ()

, то йде дужка, двокрапка і потім збалансований вираз. Тобто немає однозначності

22

Re: Facebook Hacker Cup

Хтось може пояснити цей алгоритм: http://stackoverflow.com/questions/1453 … rge-inputs

import os, sys

f = open(sys.argv[1], 'r')

T = int(f.readline())

def next(ary, start):
    j = start
    l = len(ary)
    ret = start - 1
    while j < l and ary[j]:
        ret = j
        j += 1
    return ret

for t in range(T):
    n, k = map(int, f.readline().strip().split(' '))
    a, b, c, r = map(int, f.readline().strip().split(' '))

    m = [0] * (4 * k)
    s = [0] * (k+1)
    m[0] = a
    if m[0] <= k:
        s[m[0]] = 1
    for i in xrange(1, k):
        m[i] = (b * m[i-1] + c) % r
        if m[i] < k+1:
            s[m[i]] += 1

    p = next(s, 0)
    m[k] = p + 1
    p = next(s, p+2)

    for i in xrange(k+1, n):
        if m[i-k-1] > p or s[m[i-k-1]] > 1:
            m[i] = p + 1
            if m[i-k-1] <= k:
                s[m[i-k-1]] -= 1
            s[m[i]] += 1
            p = next(s, p+2)
        else:
            m[i] = m[i-k-1]
        if p == k:
            break

    if p != k:
        print 'Case #%d: %d' % (t+1, m[n-1])
    else:
        print 'Case #%d: %d' % (t+1, m[i-k + (n-i+k+k) % (k+1)])

23 Востаннє редагувалося ADR (01.02.2013 22:05:01)

Re: Facebook Hacker Cup

Рішення перших трьох задач:
http://s7.postimage.org/ucuceied7/scrin.png
Скачати Кваліфікація.7z з LoadingBox.net

unit MainUnit;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
  System.Generics.Collections, Vcl.ComCtrls;

type
  TMainForm = class(TForm)
    SourceMemo: TMemo;
    DisplayMemo: TMemo;
    Splitter1: TSplitter;
    BottomPanel: TPanel;
    Quest1Button: TButton;
    Quest2Button: TButton;
    Quest3Button: TButton;
    InsertSourceButton: TButton;
    CopyResultButton: TButton;
    ProgressBar1: TProgressBar;
    Label1: TLabel;
    TimeLabel: TLabel;
    procedure Quest2ButtonClick(Sender: TObject);
    procedure InsertSourceButtonClick(Sender: TObject);
    procedure CopyResultButtonClick(Sender: TObject);
    procedure Quest1ButtonClick(Sender: TObject);
    procedure Quest3ButtonClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    StartTime: Integer;

    procedure InitCalc;
    procedure FinalizeCalc;

    procedure EnabledControl(AEnable: Boolean);
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MainForm: TMainForm;

implementation

{$R *.dfm}

resourcestring
  StrFormat = 'Case #%d: %s';

const
  BoolLabel: array [Boolean] of string = ('NO', 'YES');

function ParseInt(S: string): TArray<Integer>;
var
  P, P2: PChar;
begin
  P := PChar(S);
  SetLength(Result, 0);

  while P^ <> #0 do
  begin
    while not CharInSet(P^, ['0'..'9'])  do
      Inc(P);
      
    P2 := P;
    while CharInSet(P^, ['0'..'9']) do
      Inc(P);

    if Integer(P2) < Integer(P) then
    begin    
      SetLength(Result, Length(Result) + 1);
      Result[High(Result)] := StrToInt(Copy(P2, 0, P - P2));
    end;
  end;
end;

procedure TMainForm.CopyResultButtonClick(Sender: TObject);
begin
  DisplayMemo.SelectAll;
  DisplayMemo.CopyToClipboard;
end;

procedure TMainForm.InsertSourceButtonClick(Sender: TObject);
begin
  SourceMemo.Clear;
  SourceMemo.PasteFromClipboard;
end;

procedure TMainForm.EnabledControl(AEnable: Boolean);
begin
  Quest1Button.Enabled := AEnable;
  Quest2Button.Enabled := AEnable;
  Quest3Button.Enabled := AEnable;
  InsertSourceButton.Enabled := AEnable;
  CopyResultButton.Enabled := AEnable;
end;

procedure TMainForm.FinalizeCalc;
begin
  DisplayMemo.Lines.EndUpdate;
  EnabledControl(True);
  TimeLabel.Caption := IntToStr(GetTickCount - StartTime);
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  {$IFDEF DEBUG} MainForm.Caption := MainForm.Caption + ' (DEBUG)'; {$ENDIF}
end;

procedure TMainForm.InitCalc;
begin
  DisplayMemo.Lines.Clear;
  DisplayMemo.Lines.BeginUpdate;
  ProgressBar1.Max := StrToInt(SourceMemo.Lines[0]);
  StartTime := GetTickCount;
  EnabledControl(False);
end;

procedure TMainForm.Quest1ButtonClick(Sender: TObject);

  function NiceOfStr(S: string): Integer;
  var
    C: Char;
    CharsCount: array [1..26] of Integer;
    I: Integer;
  begin
    S := AnsiLowerCase(S);
    Result := 0;
    for I := 1 to 26 do CharsCount[i] := 0;      
    for C in S do
      if CharInSet(C, ['a'..'z']) then
        Inc(CharsCount[Ord(C) - Ord('a') + 1]);

    TArray.Sort<Integer>(CharsCount);
    for I := 1 to 26 do
      Inc(Result, CharsCount[i] * I);
  end;

var
  I: Integer;
begin
  InitCalc;
  with SourceMemo do
  try
    for I := 1 to Lines.Count - 1 do
    begin
      DisplayMemo.Lines.Add(Format(StrFormat,
        [I, IntToStr(NiceOfStr(Lines[i]))]));
      ProgressBar1.Position := I;
      Application.ProcessMessages;
    end;
  finally
    FinalizeCalc;
  end;
end;

procedure TMainForm.Quest2ButtonClick(Sender: TObject);

  function IsBalanc(PText: PChar; Opened: Integer = 0): Boolean;
  begin
    while PText^ <> #0 do
    begin
      if (PText[0] = ':') and (CharInSet(PText[1], ['(', ')'])) then
        Exit(IsBalanc(PChar(PText + 1), Opened)           // це дужка
        or IsBalanc(PChar(PText + 2), Opened));         // це смайлик

      case PText^ of
      '(' : Inc(Opened);
      ')' : Dec(Opened);
      else end;
      if Opened < 0 then Exit(False);
      Inc(PText);
    end;
    Result := Opened = 0;
  end;

var
  I: Integer;
begin
  InitCalc;
  with SourceMemo do
  try
    for I := 1 to Lines.Count - 1 do
    begin
      DisplayMemo.Lines.Add(Format(StrFormat,
        [I, BoolLabel[IsBalanc(PChar(Lines[i]))]]));
      ProgressBar1.Position := I;
      Application.ProcessMessages;
    end;
  finally
    FinalizeCalc;
  end;
end;

procedure TMainForm.Quest3ButtonClick(Sender: TObject);

  function GetItem(n, k, a, b, c, r: Int64): Int64;

    function InitM(Ak: Int64): TArray<Int64>;
    var
      I: Integer;
    begin
      SetLength(Result, Ak);
      Result[0] := a;
      for I := 1 to Ak -1 do
        Result[i] := (b * Result[I -1] + c) mod r;
    end;

    function GetFreeNumbers(Arr: TArray<Int64>): TArray<Boolean>;
    var
      I: Integer;
    begin
      SetLength(Result, Length(Arr) + 1);  //k + 1;
      for I := 0 to High(Result) do
        Result[i] := True;

      for I := High(Arr) downto 0 do    // ігноруємо дублі
        if Arr[i] <= High(Result) then
          if Result[Arr[i]] then
            Result[Arr[i]] := False
          else
            Arr[i] := MaxInt;
    end;

    function NextFree(Arr: TArray<Boolean>; var Start: Integer; Use: Boolean): Integer;
    var
      I: Integer;
    begin
      for I := Start to High(Arr) do
        if Arr[i] then
        begin
          if Use then
          begin
            Arr[i] := False;
            Start := I + 1;
          end
          else
            Start := I;
          Exit(I);
        end;
      Result := MaxInt;
    end;

  var
    m, X: TArray<Int64>;
    I: Integer;
    FreeNumbers: TArray<Boolean>;
    Start: Integer;
  begin
    m := InitM(k);
    FreeNumbers := GetFreeNumbers(m);
    SetLength(m, 2 * k + 1);

    Start := 0;
    m[k] := NextFree(FreeNumbers, Start, True);
    for I := k + 1 to High(m) do
      if m[I - k - 1] < Start then
        m[i] := m[I - k - 1]
      else
      begin
        if m[I - k - 1] <= k then
          FreeNumbers[m[I - k - 1]] := True;

        if m[I - k - 1] < NextFree(FreeNumbers, Start, False) then
          m[i] := m[I - k - 1]
        else
          m[i] := NextFree(FreeNumbers, Start, True);
      end;


    X := Copy(m, k, k + 1);
    Result := X[(n) mod (k + 1)];
  end;

var
  I: Integer;
begin
  InitCalc;
  with SourceMemo do
  try
    for I := 1 to (Lines.Count - 1) div 2 do
    begin
      DisplayMemo.Lines.Add(Format(StrFormat,
        [I, IntToStr(GetItem( ParseInt(Lines[I * 2 - 1])[0],
                              ParseInt(Lines[I * 2 - 1])[1],
                              ParseInt(Lines[I * 2])[0],
                              ParseInt(Lines[I * 2])[1],
                              ParseInt(Lines[I * 2])[2],
                              ParseInt(Lines[I * 2])[3]))]));
      ProgressBar1.Position := I;
      Application.ProcessMessages;
    end;
  finally
    FinalizeCalc;
  end;
end;

end.

ПС в архіві старіша версія ніж цей код. Декілька рядків дали прискорення 2-3 порядки =)

24

Re: Facebook Hacker Cup

Перший раунд почнеться завтра (субота, 02.02.13) о 20:00 за київськім часом (10:00 для США).

Топ-500 попадуть у другий раунд.

Оригінал:

Прихований текст

Congratulations!

You have advanced to Round 1 of the 2013 Facebook Hacker Cup!

Online Round 1 will last 24 hours and start February 2, 2013 at 10:00 AM PT. Start time in different time zones around the world: Round 1 start time

The top 500 competitors will advance to Round 2.

Best of luck and happy hacking,
The Hacker Cup Team

25

Re: Facebook Hacker Cup

Card Game (20 points)
John is playing a game with his friends. The game's rules are as follows: There is deck of N cards from which each person is dealt a hand of K cards. Each card has an integer value representing its strength. A hand's strength is determined by the value of the highest card in the hand. The person with the strongest hand wins the round. Bets are placed before each player reveals the strength of their hand.

John needs your help to decide when to bet. He decides he wants to bet when the strength of his hand is higher than the average hand strength. Hence John wants to calculate the average strength of ALL possible sets of hands. John is very good at division, but he needs your help in calculating the sum of the strengths of all possible hands.

Problem
You are given an array a with N ≤ 10 000 different integer numbers and a number, K, where 1 ≤ K ≤ N. For all possible subsets of a of size K find the sum of their maximal elements modulo 1 000 000 007.

Input
The first line contains the number of test cases T, where 1 ≤ T ≤ 25

Each case begins with a line containing integers N and K. The next line contains N space-separated numbers 0 ≤ a [і] ≤ 2 000 000 000, which describe the array a.

Output
For test case i, numbered from 1 to T, output "Case #i: ", followed by a single integer, the sum of maximal elements for all subsets of size K modulo 1 000 000 007.

Example
For a = [3, 6, 2, 8] and N = 4 and K = 3, the maximal numbers among all triples are 6, 8, 8, 8 and the sum is 30.

Example input

5
4 3
3 6 2 8 
5 2
10 20 30 40 50 
6 4
0 1 2 3 5 8 
2 2
1069 1122 
10 5
10386 10257 10432 10087 10381 10035 10167 10206 10347 10088

Example output

Case #1: 30
Case #2: 400
Case #3: 103
Case #4: 1122
Case #5: 2621483
Подякували: Vo_Vik1

26 Востаннє редагувалося Voron (03.02.2013 18:00:46)

Re: Facebook Hacker Cup

Security 35 points

You are designing a new encryption system that works in the following way:

For server-client communication you need a key k, composed of m sections, each of length l, and the key consists only of lowercase characters in the set {a, b, c, d, e, f}. The server has a key k1 and the client has a key k2 where:

k1 = f(k). f is a function that receives a key and replace some random letters by ? indicating that those characters can be any lowercase letter of the set described before.
k2 = f(g(k)). g is a function that takes a key and produces a random permutation of its m sections. And f is the function defined above.
For example: let m = 3, l = 2

f('abacbc') = '?ba??c'
g('abacbc') = 'acbcab' (each section was moved one place to the left).
Your task is given k1 and k2, find key k. If there are several solutions, print the lexicographically smallest key. And if there is no solution at all, print "IMPOSSIBLE" (without the quotes).

Input description:
The first line has a single integer T, which corresponds to the number of test cases. T test cases follows: the first line of the test case corresponds to the integer m, the second line contains the string k1 and the third line contains the string k2.

Constraints:
T <= 20
0 < |k1| <= 100
0 < m <= 50
|k2| = |k1|
It is guaranteed that m is always a divisor of |k1|
k1 and k2 consist of {a, b, c, d, e, f, ?}

Output description:
For test case i, numbered from 1 to T, output "Case #i: ", followed by the lexicographically smallest key or "IMPOSSIBLE".

Example input

5
2
abcd
c?ab
3
ab?c?c
ac?c??
3
ab?c?c
aabbdd
2
aa
bb
2
abcd
cdab

Example output

Case #1: abcd
Case #2: abacac
Case #3: IMPOSSIBLE
Case #4: IMPOSSIBLE
Case #5: abcd

27

Re: Facebook Hacker Cup

Dead Pixels 45 points

John's friend Peter purchases a new high resolution monitor with dimension W * H where W is the number of pixels in each row (i.e. width) and H is the number of pixels in each column (i.e. height).

However, there are N dead pixels on the monitor. The i-th dead pixel is located at (x[і], y[і]). (0, 0) is the top-left pixel and (W - 1, H - 1) is the bottom-right pixel. The locations of the dead pixels could be generated by 6 given integers X, Y, a, b, c and d by the following rules. If 2 pixels are at the same location, they are considered the same. It is possible that there are less than N distinct dead pixels.

x[0] = X
y[0] = Y
x[і] = (x[i - 1] * a + y[i - 1] * b + 1) % W (for 0 < i < N)
y[і] = (x[i - 1] * c + y[i - 1] * d + 1) % H (for 0 < i < N)
Peter connects his monitor to his computer and opens an image with dimension P (width) * Q (height). How many unique positions can the image be placed so that it can be displayed perfectly (i.e. all pixels of the picture are shown on the monitor)? The image cannot be rotated.

Input
The first line contains an integer T, which is the number of test cases. Then T test cases follow. Each test case contains 11 integers W, H, P, Q, N, X, Y, a, b, c, d.

Output
For each of the test cases numbered in order from 1 to T, output "Case #", followed by the case number (with 1 being the first test case), followed by ": ", followed by an integer which is the number of different possible positions for the poster.

Constraints
1 ≤ T ≤ 20
1 ≤ W, H ≤ 40 000
1 ≤ P ≤ W
1 ≤ Q ≤ H
1 ≤ N ≤ min(1 000 000, W * H)
1 ≤ a, b, c, d ≤ 100
0 ≤ X < W
0 ≤ Y < H


Example input

5
4 4 2 2 1 0 2 1 2 3 4
4 4 1 1 3 1 1 2 2 2 2
6 10 3 2 2 0 0 5 4 3 2
16 18 5 1 5 10 8 21 27 29 87
14 15 12 4 4 3 5 84 74 53 68

Example output

Case #1: 7
Case #2: 15
Case #3: 32
Case #4: 197
Case #5: 16

28

Re: Facebook Hacker Cup

Ну першу задачу друго туру я би вирішував так.
Впорядковуємо масив від меншого до більшого.

10 20 30 40 50

далі починаючи з елементу i=k рахуємо суму
sum+= a{i}*(i-1)!/(k-1)!/(i-k-1)!
причому факторіали можна рекурсивно прахувати для всіх 1<i<N і занести в масив.
для n=5, k=2 , будемо мати
20+30*2+40*3+50*4=400 - що і маємо в прикладі.

29 Востаннє редагувалося Vo_Vik (07.02.2013 21:18:56)

Re: Facebook Hacker Cup

Другу теж в голові склав, але треба написати)
1) Розбиваємо на кусочки довжиною l і пхаємо в 2 масиви
2) рекурсивна фунція, яка приймає 2 масиви. Повертає масив можливих розв’язків.
Працює так. Бере перший елемент з друго масиву, якщо він співпадає(включаючи ?) з будьяким елементом першого масиву, то викликаємо рекурсію виключивши ці 2 елементи.
Десь так. Реалізацію зробля як буду мати час)
Прохід по другому прикладу:

Прихований текст

ab?c?c
ac?c??

(ab)(?c)(?c)
(ac)(?c)(??)
перший крок рекурсії (ac)=(?c)
(ab)(?c)
(?c)(??)
2 крок рекурсії (?c)=(?c)
(ab)
(??)
(ab)=(??)
Маємо - (ab)(?c)(ac) з ішого відгалуження рекурсії одержимо (ab)(ac)(?c) - найменшим з них буде (ab)(ac)(ac)

30

Re: Facebook Hacker Cup

Vo_Vik написав:

Ну першу задачу друго туру я би вирішував так.
Впорядковуємо масив від меншого до більшого.

10 20 30 40 50

далі починаючи з елементу i=k рахуємо суму
sum+= a{i}*(i-1)!/(k-1)!/(i-k-1)!
причому факторіали можна рекурсивно прахувати для всіх 1<i<N і занести в масив.
для n=5, k=2 , будемо мати
20+30*2+40*3+50*4=400 - що і маємо в прикладі.

Я теж так думав... але факторіал від 7000 трооошки завеликий виходить


тут є рішення http://www.facebook.com/notes/facebook- … 9202663318

31 Востаннє редагувалося Vo_Vik (09.02.2013 01:58:02)

Re: Facebook Hacker Cup

Там дано що суму треба знайти по модулю числа 1 000 000 007, оскільки при множенні модуль по числу зберігається, то факторіал можна теж шукати по модулю 1 000 000 007
Вони щось роблять в оцьому куску коду, хоча ще треба розібратись що)

Прихований текст
 bin [0][0] = 1;

  for (n = 1; n < MAXN; n++) {

    bin [n][0] = 1;

    bin [n][n] = 1;

    for (k = 1; k < n; k++) {

      bin [n][k] = bin [n - 1][k] + bin [n - 1][k - 1];

      if (bin [n][k] >= MOD) {

        bin [n][k] -= MOD;

      }

    }

  }

32 Востаннє редагувалося Vo_Vik (09.02.2013 01:57:25)

Re: Facebook Hacker Cup

Дубль.

33

Re: Facebook Hacker Cup

У першій задачі наскільки зрозумів потрібно рахувати через трикутник Паскаля - http://uk.wikipedia.org/wiki/Трикутник_Паскаля