4226. Japan

 

Japan plans to welcome the ACM ICPC World Finals and a lot of roads must be built for the venue. Japan is tall island with n cities on the East coast and m cities on the West coast (m ≤ 1000, n ≤ 1000). k superhighways will be build. Cities on each coast are numbered 1, 2, ... from North to South. Each superhighway is straight line and connects city on the East coast with city of the West coast.

 The funding for the construction is guaranteed by ACM. A major portion of the sum is determined by the number of crossings between superhighways. At most two superhighways cross at one location. Write a program that calculates the number of the crossings between superhighways.

 

Input. The input file starts with t – the number of test cases. Each test case starts with three numbers – n, m, k. Each of the next k lines contains two numbers – the numbers of cities connected by the superhighway. The first one is the number of the city on the East coast and second one is the number of the city of the West coast.

 

Output. For each test case write one line on the standard output:

Test case "case number": "number of crossings"

 

Sample Input

1

3 4 4

1 4

2 3

3 2

3 1

 

Sample Output

Test case 1: 5

 

 

РЕШЕНИЕ

структуры данных – дерево Фенвика

 

Анализ алгоритма

Пусть a1, a2, …, an – города на восточном побережье, b1, b2, …, bm  - на западном. Отсортируем заданные пары автострад (ai, bj) по возрастанию первой компоненты.

Пусть m = (0, 0, …, 0) – массив, изначально заполненный нулями длины 1000. Его обработку моделируем деревом Фенвика. Просматриваем автострады с конца, по убыванию первой компоненты. Пусть (ai, bj) – текущая автострада. Увеличим m[bj] на 1. Количество автострад, которое она пересекает, равно m[1] + m[2] + … + m[bj – 1].

 

Пример

Для примера, заданного в условии, имеется 5 точек пересечения.

 

 

Реализация алгоритма

 

#include <cstdio>

#include <vector>

#include <algorithm>

#define MAX 1001

using namespace std;

 

vector<int> Fenwick;

vector<pair<int, int> > cross;

int cs, i, n, m, k, tests, a, b;

long long res;

 

// Fenwick[0] + Fenwick[1] + ... + Fenwick[i]

long long Summma0_i(int i)

{

  long long result = 0;

  for (; i >= 0; i = (i & (i + 1)) - 1)

    result += Fenwick[i];

  return result;

}

 

// Fenwick[i] = Fenwick[i] + 1

void IncElement(int i, int delta)

{

  for (; i < MAX; i = (i | (i+1)))

    Fenwick[i] += delta;

}

 

int main (void)

{

  scanf("%d",&tests);

  for(cs = 1; cs <= tests; cs++)

  {

    scanf("%d %d %d",&n,&m,&k);

    Fenwick.assign(MAX,0);

    cross.clear();

    for(res = i = 0; i < k; i++)

    {

      scanf("%d %d",&a,&b);

      cross.push_back(make_pair(a,b));

    }

    sort(cross.begin(),cross.end());

 

    for(i = cross.size() - 1; i >= 0; i--)

    {

      res += Summma0_i(cross[i].second - 1);

      IncElement(cross[i].second,1);

    }

    printf("Test case %d: %lld\n",cs,res);

  }

  return 0;

}