#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> using namespace std; const int maxn = 1000; const int maxm = 1000000; typedef struct { int from; int to; int w; } node; node edge[maxm]; int head[maxn]; int n , m ; bool cmp(node a , node b) { if(a.from == b.from && a.to == b.to) return a.w < b.w; if(a.from == b.from) return a.to < b.to; return a.from < b.from; } void input() { for(int i = 0; i < m; i ++) { scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].w); } memset(head , -1 , sizeof(head)); sort(edge , edge + m , cmp); head[edge[0].from] = 0; for(int i = 1; i < m; i ++) { if(edge[i].from != edge[i-1].from) { head[edge[i].from] = i; //确定起点为vi的第一条边的位置。 } } } void output() { for(int i = 1; i <= n; i ++) cout << "head["<<i<<"]: "<<head[i]<<endl; cout << "遍历所有的边"<<endl; for(int i = 1; i <= n; i ++) //head[i]的下标i等于vi; { for(int j = head[i]; edge[i].from == i && j < m; j ++) { cout << edge[j].from << " " << edge[j].to << " " << edge[j].w <<endl; } } } int main() { while(scanf("%d%d",&n , &m)!=EOF) { input(); output(); } return 0; } /* 4 5 1 2 2 1 3 4 1 4 6 2 3 3 4 3 5 */
前向星
最新推荐文章于 2022-01-20 19:58:34 发布