最近ACM学习了一些堆的操作和简单的图论算法,以及自己做了一些题,接下来总结一下近期所学。
往堆中加入一个元素的算法(put)
void put(int d) //heap[1]为堆顶
{
int now, next;
heap[++heap_size] = d;
now = heap_size;
while(now > 1)
{
next = now >> 1;
if(heap[now] >= heap[next]) break;
swap(heap[now], heap[next]);
now = next;
}
}
从堆中取出并删除一个元素的算法(get)
int get() //heap[1]为堆顶
{
int now=1, next, res= heap[1];
heap[1] = heap[heap_size--];
while(now * 2 <= heap_size)
{
next = now * 2;
if (next < heap_size && heap[next + 1] < heap[next]) next++;
if (heap[now] <= heap[next]) break;
swap(heap[now], heap[next]);
now = next;
}
return res;
}
完全图:
一个n 阶的完全无向图含有n*(n-1)/2 条边;一个n 阶的完全有向图含有n*(n-1)条边;
数组模拟邻接表存储:
#include <iostream>
using namespace std;
const int maxn=1001,maxm=100001;
struct Edge
{
int next; //下一条边的编号
int to; //这条边到达的点
int dis; //这条边的长度
}edge[maxm];
int head[maxn],num_edge,n,m,u,v,d;
void add_edge(int from,int to,int dis) //加入一条从from到to距离为dis的单向边
{
edge[++num_edge].next=head[from];
edge[num_edge].to=to;
edge[num_edge].dis=dis;
head[from]=num_edge;
}
int main()
{
num_edge=0;
scanf("%d %d",&n,&m); //读入点数和边数
for(int i=1;i<=m;i++)
{
scanf("%d %d %d",&u,&v,&d); //u、v之间有一条长度为d的边
add_edge(u,v,d);
}
for(int i=head[1];i!=0;i=edge[i].next) //遍历从点1开始的所有边
{
//...
}
//...
return 0;
}
闲碎知识点总结:
1. ios::sync_with_stdio(false); //优化。打消iostream的输入输出缓存,使得cin cout 时间和printf scanf 相差无几
2. C++中substr的用法:
substr用法: s.substr(i,j)表示从下标为i的位置开始截取j位。
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s("12345asdf");
string a=s.substr(0,5);
cout<<a<<endl;
}
//上述代码获得字符串a为从第0位开始的长度为5的字符串
输出结果为: 12345