在c++中,vector是一个十分有用的容器,下面对这个容器做一下总结。
1 基本操作
(1)头文件#include<vector>.
(2)创建vector对象,vector<int> 数组名[MAX];
(3)尾部插入数字:vec.push_back(a);
(4)使用下标访问元素,cout<<vec[0]<<endl;记住下标是从0开始的。
(5)使用迭代器访问元素.
vector<int>::iterator it; for(it=vec.begin();it!=vec.end();it++) cout<<*it<<endl;
(6)插入元素: vec.insert(vec.begin()+i,a);在第i+1个元素前面插入a;
(7)删除元素: vec.erase(vec.begin()+2);删除第3个元素
vec.erase(vec.begin()+i,vec.end()+j);删除区间[i,j-1];区间从0开始
(8)向量大小:vec.size();
(9)清空:vec.clear();//无外于初始化
Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4673 Accepted Submission(s): 1427
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a's reward should more than b's.Dandelion's unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work's reward will be at least 888 , because it's a lucky number.
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
2 1 1 2 2 2 1 2 2 1
1777 -1
解题分析:
刚刚开始的想法是邻接矩阵来存储的,单听队友说,邻接矩阵内存占用过大。想我推荐了VECTOR 之不定长数组来定义邻接表。初次见到这个c++函数,还有点不会用,
百度了一下,直接上代码,但中间一直WR,一开始我以为不用初始化呢,后来发现就是因为少了q.clear();才导致的一直提交不正确!
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int p[11000];
int du[11000];
vector<int> dp[11000];
int main()
{
int n,m;
int i,j;
int a,b;
int mark;
int sum;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=0;i<11000;i++)
dp[i].clear();
mark=1;
queue <int> q;
memset(du,0,sizeof(du));
memset(p,0,sizeof(p));
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
dp[b].push_back(a);
du[a]++;
}
for(i=1;i<=n;i++)
{
if(du[i]==0)
{
q.push(i);
}
}
if(q.empty())
{
printf("-1\n");
continue;
}
while(!q.empty())
{
int t=q.front();
q.pop();
for(i=0;i<dp[t].size();i++)
{
p[dp[t][i]]=max(p[dp[t][i]],p[t]+1);//特别注意此处,防止取小了@下有图解
du[dp[t][i]]--;
if(du[dp[t][i]]==0)
{
q.push(dp[t][i]);
}
}
}
for(i=1;i<=n;i++)
{
if(du[i])
{
mark=0;
break;
}
}
if(mark==0)
{
printf("-1\n");
continue;
}
sum=0;
for(i=1;i<=n;i++)
sum+=p[i];
printf("%d\n",sum+888*n);
}
return 0;
}
图解:
比如此图中的4要大于2和5,但是2已经为1了,而5还是0,要保证满足题意,故要实现4大于两者最大的一个