vector创建图
目录
一、vector 简介及基本操作:
1、vector是c++中stl库中封装好的容器,常用定义不定长数组来构建无向图或有向图.
2、基本操作:
(1)头文件#include<vector>.
(2)创建vector对象,vector<int> vec;
(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();
vector的元素不仅仅可以使int,double,string,还可以是结构体,但是要注意:结构体要定义为全局的,否则会出错。
如下例:struct node {int s, t , v ; };
vector <node>G[ ];
二、构建图:
(1) 定义不定长数组 vector <int> map[100010] ;
(2) 建边
for(i=1; i < = n ; i + +)
{
scanf("%d %d",&s,&t);map[s].push_back(t);
map[t].push_back(s); //有向图时,此步省略。
}
(3)遍历
for (i=0; i< = map[s].size(); i++)
{
printf("%d\n",map[s][i]);}
三、vector创建图与邻接表创建图的区别
邻接表插入元素时是在表头插入,而vector是在表尾插入
例如:增加三条有向边(1,2)(1,3)(1,4)
vector:1->2->3->4
邻接表:1->4->3->2
vector建图
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 200010;
int n, m;
vector<int> g[N];
int q[N], p[N], top;
int sz[N];
void dfs(int u)
{
sz[u] = 1;
q[top] = u, p[u] = top;
top ++ ;
for (auto v: g[u])
{
dfs(v);
sz[u] += sz[v];
}
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 2; i <= n; i ++ )
{
int t;
scanf("%d", &t);
g[t].push_back(i);
}
dfs(1);
while (m -- )
{
int u, k;
scanf("%d%d", &u, &k);
if (k > sz[u]) puts("-1");
else printf("%d\n", q[p[u] + k - 1]);
}
return 0;
}
邻接表建图
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int N = 200010, M = 200010;
int h[N], e[M], ne[M], idx;
int n, query;
int g[N], cnt;
int pos[N], num[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int dfs(int u)
{
int sum = 1;
g[cnt ++ ] = u;
priority_queue<int, vector<int>, greater<int> > q;
for(int i = h[u]; i != -1; i = ne[i]) q.push(e[i]);
while(q.size())
{
auto t = q.top();
q.pop();
sum += dfs(t);
}
num[u] = sum;
return sum;
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> query;
for(int i = 2; i <= n; i ++ )
{
int x; cin >> x;
add(x, i);
}
dfs(1);
for(int i = 0; i < cnt; i ++ ) pos[g[i]] = i;
// cout << "dfs: ";
// for(int i = 0; i < cnt; i ++ ) cout << g[i] << " ";
// cout << endl << "cnt: ";
// for(int i = 0; i < n; i ++ ) cout << num[i] << " ";
// cout << endl;
while(query -- )
{
int u, k;
cin >> u >> k;
int start = pos[u];
if(start + k - 1 >= cnt || k > num[u]) cout << -1 << endl;
else cout << g[start + k - 1] << endl;
}
return 0;
}