Hdu_1050 & poj_1083 move tables (Greedy)

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.