# 从一个问题的多个算法看算法的优化

297人阅读 评论(0)

#include <cstdio>

const int N = 100 + 10;
const int inf = 1000000000;

int A[N], B[N];
int n;

inline bool in_range(int left, int right, int x)
{
return x >= left && x <= right;
}

bool check(int left, int right, int& d)
{
int tmp, i;
if (left > right)
{
tmp = left;
left = right;
right = tmp;
}
for (i=0; i<n; i++) if (!in_range(left, right, A[i] + B[i]) && !in_range(left, right, A[i] - B[i])) return false;
d = right - left;
return true;
}

int main()
{
int res, t, d, i, j, k;
scanf("%d", &t);
while (t --)
{
scanf("%d", &n);
for (i=0; i<n; i++) scanf("%d", &A[i]);
for (i=0; i<n; i++) scanf("%d", &B[i]);
if (n == 1)
{
printf("0\n");
continue;
}
res = inf;
for (i=0; i<n-1; i++)
for (j=i+1; j<n; j++)
{
if (check(A[i] + B[i], A[j] + B[j], d) && d < res) res = d;
if (check(A[i] + B[i], A[j] - B[j], d) && d < res) res = d;
if (check(A[i] - B[i], A[j] + B[j], d) && d < res) res = d;
if (check(A[i] - B[i], A[j] - B[j], d) && d < res) res = d;
}
printf("%d\n", res);
}
return 0;
}


#include <cstdio>
#include <algorithm>

using namespace std;

const int N = 100 + 10;
const int inf = 1000000000;

int A[N], B[N];
int n;

bool check(int left, int& d)
{
int right, i;
right = left;
for (i=0; i<n; i++)
if (A[i] + B[i] >= left && A[i] - B[i] >= left) right = max(right, min(A[i] + B[i], A[i] - B[i]));
else if (A[i] + B[i] >= left) right = max(right, A[i] + B[i]);
else if (A[i] - B[i] >= left) right = max(right, A[i] - B[i]);
else return false;
d = right - left;
return true;
}

int main()
{
int res, t, d, i, j;
scanf("%d", &t);
while (t --)
{
scanf("%d", &n);
for (i=0; i<n; i++) scanf("%d", &A[i]);
for (i=0; i<n; i++) scanf("%d", &B[i]);
res = inf;
for (i=0; i<n; i++)
{
if (check(A[i] + B[i], d) && d < res) res = d;
if (check(A[i] - B[i], d) && d < res) res = d;
}
printf("%d\n", res);
}
return 0;
} 

#include <cstdio>
#include <algorithm>

using namespace std;

const int N = 100 + 10;
const int inf = 1000000000;

struct ITEM
{
int val, id;
ITEM(int val=0, int id=0):val(val), id(id){}
};

int A[N], B[N], cnt[N];
ITEM C[2*N];
int n;

bool operator < (const ITEM& a, const ITEM& b)
{
return a.val < b.val;
}

int main()
{
int res, t, s, i, j;
scanf("%d", &t);
while (t --)
{
scanf("%d", &n);
for (i=0; i<n; i++) scanf("%d", &A[i]);
for (i=0; i<n; i++) scanf("%d", &B[i]);
for (i=0; i<n; i++)
{
C[i*2] = ITEM(A[i] + B[i], i);
C[i*2+1] = ITEM(A[i] - B[i], i);
cnt[i] = 0;
}
sort(C, C + 2 * n);
s = 0;
for (i=0; i<2*n; i++)
{
cnt[C[i].id] ++;
if (cnt[C[i].id] == 1) s ++;
if (s == n) break;
}
j = 0;
for (; cnt[C[j].id]==2; j++) cnt[C[j].id] --;
res = C[i].val - C[j].val;
for (i++; i<2*n; i++)
{
cnt[C[i].id] ++;
for (; cnt[C[j].id]==2; j++) cnt[C[j].id] --;
res = min(res, C[i].val - C[j].val);
}
printf("%d\n", res);
}
return 0;
} 

2
0

个人资料
• 访问：302次
• 积分：42
• 等级：
• 排名：千里之外
• 原创：1篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档