数据结构中的无向图,用C语言实现的过程中的思路???

数据结构中的无向图,用C语言实现的过程中的思路???

问题描述:

roblem Description
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:

There is an undirected graph with n vertices and m edges. Then Yuta does q operations on this graph. Each operation is described by two integers L,R (1≤L≤R≤n) and can be split into three steps:

  1. Delete all the edges which have at least one vertice outside the range [L,R].

  2. Yuta wants you to tell him the number of connected component of the graph.

  3. Restore the graph.

This task is too hard for Rikka to solve. Can you help her?

Input
There are at most 100 testcases and there are at least 97 testcases with n,m,q≤1000.

For each testcase, the first line contains three numbers n,m,q (n,q≤105,m≤2×105).

Then m lines follow. Each line contains two numbers ui,vi (1≤ui,vi≤105) which describe an edge of the graph.

Then q lines follows. Each line contains two numbers Li,Ri (1≤L≤R≤n) which describe an operation.

Output
For each operation you need print a single line with a single number - the answer of this operation.

Sample Input
3 3 2
1 2
1 3
2 3
1 2
1 3

Sample Output
2
1

图有一种邻接表储存结构,这里以无向图为例,输入图的参数,构造并输出图的邻接表。

#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTEX_NUM 100
typedef struct ArcNode{
    int adjvex;//该边的另一个顶点的位置 
    struct ArcNode *nextarc; //指向下一条边 
}ArcNode;
typedef struct VNode{
    int data;//顶点的值 
    ArcNode *firstarc;//指向第一条依附该顶点的边的指针 
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct{
    AdjList vertices;//顶点数组 
    int vexnum,arcnum;
}ALGraph;
int LocateVex(ALGraph G,int v){//定位函数 
    for(int i=0;i<G.vexnum;i++){
        if(v==G.vertices[i].data)return i;
    } 
}
void CreateUDG(ALGraph &G){
    ArcNode *p,*q;
    int i,j,k,v1,v2;
    printf("分别输入顶点个数和边的数目:\n");
    scanf("%d%d",&G.vexnum,&G.arcnum);
    printf("分别输入各个顶点值:\n");
    for(i=0;i<G.vexnum;i++){
    scanf("%d",&G.vertices[i].data);
    G.vertices[i].firstarc=NULL;//初始化 
    } 
    printf("分别输入各条边的两个顶点:\n");
    for(k=0;k<G.arcnum;k++){
        scanf("%d%d",&v1,&v2);
        i=LocateVex(G,v1);j=LocateVex(G,v2);//定位 
        p=(ArcNode*)malloc(sizeof(ArcNode));//申请一个结点 
        p->adjvex=j;p->nextarc=NULL;//赋值 
        p->nextarc=G.vertices[i].firstarc;//连接结点 
        G.vertices[i].firstarc=p;//连接结点 
        q=(ArcNode*)malloc(sizeof(ArcNode));
        q->adjvex=i;q->nextarc=NULL;
        q->nextarc=G.vertices[j].firstarc;
        G.vertices[j].firstarc=q;
    }
}
void PrintUDG(ALGraph G){//输出邻接表 
    int i,j;
    for(i=0;i<G.vexnum;i++){
        printf("%d:",i);
        ArcNode *p;
        p=G.vertices[i].firstarc;
        while(p!=NULL){
            printf("->%d",p->adjvex);
            p=p->nextarc;
        }
        printf("\n");
    }
}
int main(){
    ALGraph G;
    CreateUDG(G);
    PrintUDG(G);
    return 0;
}