It is a typical greedy algorithm, but you must pay attention to parity, such:
S: 4 6
E: 5 7
What is the answer to this example? The answer is 20.
The numbers 5 and 6 overlap, so we have to finish the operation twice.
It can be seen from the above that when E is an odd number, if the next S = e + 1, it will need to be moved one more time;
Similarly, when E is an even number, if the next S = E-1, also need to move more time;
Code:
#include <stdio.h>
#include <stdlib.h>
#define N 207
struct node
{
int e;
int s;
}num[N];
int cmp(const void * a, const void *b)
{
return (*(struct node*)a).e - (*(struct node *)b).e;
}
int main()
{
//freopen("data.in", "r", stdin);
int t, n, i, j;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d%d", &num[i].s, &num[i].e);
if(num[i].s > num[i].e) //chang
{
num[i].s = num[i].s + num[i].e;
num[i].e = num[i].s - num[i].e;
num[i].s = num[i].s - num[i].e;
}
}
qsort(num, n, sizeof(num[0]), cmp);
int sum = 0;
for(i = 0; i < n; i++)
{
int x = 0;
for(j = i; j < n; j++)
{
if(num[i].e >= num[j].s) x++;
else if(num[i].e % 2 == 0) //"e" is even
{
if(num[j].s == num[i].e - 1)
x++;
}
else if(num[i].e % 2) //"e" is odd
{
if(num[j].s == num[i].e + 1)
x++;
}
else break;
}
if(x > sum) sum = x;
}
printf("%d\n", sum*10);
}
return 0;
}