12-12 总结

· · 个人记录

比赛链接

比赛情况

P1094 纪念品分组 B3928 田忌赛马 P1638 逛画展 P3029 Cow Lineup S P1102 A-B 数对 总分
100pts 100pts 100pts 16pts 100pts 416pts

题目

P3029 [USACO11NOV] Cow Lineup S

错误代码

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

错误原因如下:

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

正确代码

#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)(主要开销在排序)