fatemehkarimi's blog

By fatemehkarimi, history, 4 years ago, In English

Hello my dear friends @codeforces!

my team failed to solve Problem H of Tehran ICPC 2018 during the contest. I tried to solve it with a greedy algorithm after the contest but I failed. I have the test cases, and even when I solve the failed test case with hand, it ends with a wrong answer always greater than the accepted answer. this shows my approach is totally wrong. I thought a lot about the problem, but no other algorithm comes to my mind. can anyone help me to solve it?

problem statements

test case

this is the code that fails.

//TEHRAN SITE
//2018-Problem H

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(void)
{
	int n, smaller, bigger;
	cin >> n >> smaller >> bigger;
	if(bigger < smaller)
		swap(smaller, bigger);

	vector <int> coordinates(n);
	for(int i = 0; i < n; ++i)
		cin >> coordinates[i];

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

	vector <int> anntena(n, smaller);

	for(int i = 0; i < n; ++i){
		int max_dis = max((i - 1 >= 0 ? coordinates[i] - coordinates[i - 1] : 0)
					, i + 1 < n ? coordinates[i + 1] - coordinates[i]: 0);

		if(max_dis > smaller)
			anntena[i] = bigger;
		if(max_dis > bigger){
			cout << -1 << endl;
			return 0;
		}
	}

	long long int result = 0;
	for(auto a : anntena)
		result += a;
	cout << result << endl;
	return 0;
}
  • Vote: I like it
  • +2
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I didn't saw your test cases (can't open from my phone), but I found small test case for your solution:

4 1 10
1 6 7 12

The main issue of your solution is that you take into account only closest antennas. I suggest the following:

  1. Sort antennas as you did.

  2. Calculate antennas radii as minimum distance to neighbors (to be connected with at least one). Print -1 if it is impossible for any. Remind, which antennas were covered by neighbors. Notice that all uncovered antennas are big already.

  3. Find first (leftmost) uncovered antenna.

  4. Find the rightmost antenna that is still in the radius of antenna from step 3. Make it big. If there is no such antenna, take closest from left antenna. Also notice that some other antennas can become covered after this.

  5. Skip antennas that covered by antenna from step 4. Repeat step 3.

Steps 3-5 can be made in one loop over n. We just need to check if next uncovered antenna is farther than right radius bound of last antenna from step 4.