Codeforces Round #486 (Div. 3) ---- C. Equal Sums (map的应用)

题目链接:http://codeforces.com/contest/988/problem/C

题意: 给你k个序列,让你从中选两个序列,分别从两个序列中删除一个元素使得两个序列的和相等。输出删除的两个元素分别在第几个序列的第几个

思路: 一开始写了一个极复杂的容器混合QAQ(不说了)
然后发现map的count可以很好地处理这个题。
来源:
map和set两种容器的底层结构都是红黑树,所以容器中不会出现相同的元素(指key),因此count()的结果只能为0和1,可以以此来判断键值元素是否存在(当然也可以使用find()方法判断键值是否存在)。

拿map< key,value>举例,find()方法返回值是一个迭代器,成功返回迭代器指向要查找的元素,失败返回的迭代器指向end。count()方法返回值是一个整数,1表示有这个元素,0表示没有这个元素。

AC代码:

#include <bits/stdc++.h>
#define rep(i,s,e) for(int i=s;i<=e;i++)
#define rev(i,s,e) for(int i=e;i>=s;i--)
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int maxn = 2e5+5;
map<LL,PII> m;
LL sum;
int a[maxn];
int k,n;
int main()
{
    #ifdef LOCAL_FILE
    freopen("in.txt", "r", stdin);
    #endif
    ios_base::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int flag = 0;
    cin>>k;
    for(int i=1;i<=k;i++)
    {
        cin>>n;
        sum = 0;
        for(int j=1;j<=n;j++)
        {
            cin>>a[j];
            sum+=a[j];
        }
        for(int j=1;j<=n;j++)
        {
            if(m.count(sum-a[j]))
            {
                cout<<"YES"<<endl;
                cout<<m[sum-a[j]].first<<" "<<m[sum-a[j]].second<<endl;
                cout<<i<<" "<<j<<endl;
                flag = 1;
                break;
            }
        }
        if(flag) break;
        for(int j=1;j<=n;j++)
        {
            m[sum-a[j]]={i,j};
        }
    }
    if(!flag) cout<<"NO"<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37624640/article/details/80699467