http://codeforces.com/contest/1141/problem/F2
题意:给出n个数,要求找到数量最大的不相交的下标区间 [l,r] ,并且每个区间的数字和相同。
这道题自己想的时候没想出来,想了个n4的暴力算法,wa掉了。但通过看题解发现一些很nb的 STL用法!!!长见识了
思路:首先建立一个map<int,vector<pair<int,int>>>
用来保存sum对应的区间,然后对于每一个sum贪心的取区间r最小的,(建立vector时就是以r从小到大建立,所以只需要判断下一个l是否大于前一个r) 然后循环取到最大的。
这里发现一个细节:如果我把 vector tmp定义在循环外面需要每一次清空该数组,如果定义时就在循环会自动清空。
总结:
1.map可以映射vector等其他容器来灵活运用
2.vector数组可以直接用 = 来复制
3.vector定义在内部可以直接清空
#include<bits/stdc++.h>
#define fi first
#define se second
#define log2(a) log(n)/log(2)
#define show(a) cout<<a<<endl;
#define show2(a,b) cout<<a<<" "<<b<<endl;
#define show3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<P, int> LP;
const ll inf = 1e17 + 10;
const int N = 1e6 + 10;
const ll mod = 1e9+7;
const int base=131;
const double pi=acos(-1);
map<string, int>ml;
map<ll,ll> mp;
map<int,int> vi;
ll b[N], num2[N],vis2[N], vis[N],num[N],a[N] ,n, m, k,x,y;
ll ex, ey, t,cnt, cnt2,ans, sum, flag;
ll nex[N];
vector<int> fac[N],A,B,C,D;
map<int,int> dp[N];
set<ll> fi,se;
string s,ss;
vector<int> v[N],v2[N];
map<int,vector<P>> p;
int main( )
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int r=1;r<=n;r++)
{
sum=0;
for(int l=r;l>=1;l--)
{
sum+=a[l];
p[sum].push_back({l,r});
}
}
vector<P> res;
vector<P> tmp;
for(auto x:p)
{
vector<P> pp=x.second;
sum=0;
int r=-1;
for(auto to:pp)
{
if(to.fi>r)
{
sum++;
tmp.push_back(to);
r=to.se;
}
}
if(sum>ans)
{
ans=sum;
res=tmp;
}
tmp.clear();
}
cout<<ans<<endl;
for(auto x:res) show2(x.fi,x.se)
}