TLE in Foe Pairs(教育规范第10轮)

时间:2016-03-29 05:23:09

标签: optimization runtime time-complexity dynamic-programming

Foe Pairs问题实现O(N + M)复杂度代码 http://codeforces.com/contest/652/problem/C,我在测试案例12中获得了TLE。

约束:(1≤N,M≤3·105)

我没有得到,为什么这个约束O(N + M)正在获得TLE。

这里是代码

#include<iostream>
#include<vector>

using namespace std;
int main()
{
    int n,m;
    cin>>n>>m;
    std::vector<int> v(n+1);
    for (int i = 0; i < n; ++i)
    {
        int x;
        cin>>x;
        v[x] = i;
    }
    std::vector<int> dp(n,0);
    for (int i = 0; i < m; ++i)
    {
        int a,b;
        cin>>a>>b;
        if(v[a]>v[b])
            swap(a,b);
        dp[v[b]] = max(dp[v[b]], v[a]+1);
    }
    for (int i = 1; i < n; ++i)
    {
        dp[i] = max(dp[i], dp[i-1]);
    }
    long long s = 0;

    for (int i = 0; i < n; ++i)
    {
        s+=(i+1-dp[i]);
    }
    cout<<s;
}

有什么,我想念?

1 个答案:

答案 0 :(得分:1)

我将所有cin更改为scanf,它通过了所有测试用例:http://codeforces.com/contest/652/submission/17014495

#include<cstdio>
#include<iostream>
#include<vector>

using namespace std;
int main()
{
    int n,m;
    scanf("%d%d", &n, &m);
    //cin>>n>>m;
    std::vector<int> v(n+1);
    for (int i = 0; i < n; ++i)
    {
        int x;
        //cin>>x;
        scanf("%d", &x);
        v[x] = i;
    }
    std::vector<int> dp(n,0);
    for (int i = 0; i < m; ++i)
    {
        int a,b;
        //cin>>a>>b;
        scanf("%d%d", &a, &b);
        if(v[a]>v[b])
            swap(a,b);
        dp[v[b]] = max(dp[v[b]], v[a]+1);
    }
    for (int i = 1; i < n; ++i)
    {
        dp[i] = max(dp[i], dp[i-1]);
    }
    long long s = 0;

    for (int i = 0; i < n; ++i)
    {
        s+=(i+1-dp[i]);
    }
    cout<<s;
    return 0;
}

当输入量较大时,你应该总是尝试使用scanf。

您可以在此处详细了解scanf更快:Using scanf() in C++ programs is faster than using cin?