跳到正文

个人记录

12-12 总结

Wonderful_Anser约 5 分钟
原文

这是 2025年12月14日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年12月14日
收录
2025年12月14日
更新
2026年11月20日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

比赛链接

比赛情况

P1094 纪念品分组B3928 田忌赛马P1638 逛画展P3029 Cow Lineup SP1102 A-B 数对总分
100pts100pts100pts100pts100pts100pts16pts16pts100pts100pts416pts416pts

题目

P3029 [USACO11NOV] Cow Lineup S

错误代码

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 50005;
struct node
{
	int x, id, cnt;
} a[N];
int vis[N], cnt[N];
bool cmp(node x, node y)
{
	return x.x < y.x;
}
int main() 
{
    int n;
	cin >> n;
	int cnt2 = 0;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i].x >> a[i].id;
		if (vis[a[i].id] == 0)
			cnt2++, vis[a[i].id]++;
		a[i].cnt = cnt2;
	}
	sort(a + 1, a + 1 + n, cmp);
	int r = 1;
    long long ans = LLONG_MAX;
    for (int l = 1; l <= n; l++)
    {
        while (r <= n)
		{
			if (a[r].cnt - a[l - 1].cnt == cnt2)
			{
				ans = min(ans, 1ll * abs(a[r].x - a[l].x));	
				break;
			}
			r++;
		}
    }
	cout << ans - 1;
    return 0;
}

错误原因如下:

  • 错误的预处理逻辑

    C++
    for (int i = 1; i <= n; i++)
    {
        cin >> a[i].x >> a[i].id;
        if (vis[a[i].id] == 0)
            cnt2++, vis[a[i].id]++;
        a[i].cnt = cnt2;  // 问题在这里!
    }

    看出错误代码的错误原因来了吧,a[i].cnt 存储的是”到第i个点时,已经出现过的不同id种类数”,但这是基于输入顺序的,排序后会混乱。

  • 排序后逻辑错误

    C++
    sort(a + 1, a + 1 + n, cmp);  // 按x从大到小排序

    排序后,a[i].cnt 的意义完全失效,因为 cnt 是按输入顺序计算的,排序后不再对应正确的统计。

  • 错误的滑动窗口逻辑

    C++
    while (r <= n)
    {
        if (a[r].cnt - a[l - 1].cnt == cnt2)  // 错误的判断条件
        {
            ans = min(ans, 1ll * abs(a[r].x - a[l].x));	
            break;
        }
        r++;
    }
    • a[R].cnt - a[L - 1].cnt 没有实际意义
    • 只考虑了 R 向右移动,没有 L 的滑动窗口机制
    • 使用了 a[L - 1] 可能导致数组越界(当 L = 1 时)

好像整个代码都错了。。。

正确代码

C++
#include <bits/stdc++.h>
using namespace std;
struct node 
{
	int x, id;
} a[50005];
map <int, int> cnt;
bool cmp(node x, node y) 
{
	return x.x < y.x;
}
int main() 
{
	int n;
	cin >> n;
    int tot = 0;
	for (int i = 1; i <= n; i++) 
    {
        cin >> a[i].x >> a[i].id;
        if (cnt[a[i].id] == 0) 
        {
			cnt[a[i].id]++;
			tot++;
		}
    }
	sort(a + 1, a + 1 + n, cmp);
	cnt.clear();
	int l = 1, r = 0, sum = 0, ans = INT_MAX;
	while (r < n) 
    {
		while (sum < tot && r < n) 
        {
			r++;
			cnt[a[r].id]++;
			if (cnt[a[r].id] == 1)
				sum++;
		}
		while (sum == tot) 
        {
			ans = min(a[r].x - a[l].x, ans);
			cnt[a[l].id]--;
			if (cnt[a[l].id] == 0)
				sum--;
			l++;
		}
	}
	cout << ans;
	return 0;
}

正确代码时间复杂度:O(n log n)(主要开销在排序)