题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1224
方法:根据输入数据建立好的图(图中每个顶点会纪录当前累计获取的有趣度和自己本身的有趣度)是不会有回路的有向图,所以可以是用拓扑排序,由于题目输入数据就定下了第一个定点是起点,所以代码中直接从第一个顶点开始扫描的顺序就是拓扑排序的顺序,程序中不需要在进行拓扑排序。按该顺序每访问一个点,就松弛其所有的边,并设置其在最长(短)路径中的前驱。
感想:通过聚集分析,时间复杂度是o(v+e).
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<algorithm> #include<queue> #include<stack> using namespace std; int const MAX =0x3f3f3f3f; //int const MAX = 10005; int cityCount=0; int straughtFlightCount=0; struct straughtFlight { int destination; straughtFlight* nextFlight; int source; }; struct cityNode { int intrestingPoint; straughtFlight* firstFlight; bool visisted; int currentInstPont; cityNode* pre; int index; }; cityNode* cites[102]; void createStraightFlight(int x,int y) { straughtFlight* flight = (straughtFlight*)malloc(sizeof(straughtFlight)); flight->destination=y; if(cites[x]->firstFlight == NULL) flight->nextFlight = NULL; else flight->nextFlight = cites[x]->firstFlight; cites[x]->firstFlight = flight; } struct cmp { bool operator()(cityNode* x,cityNode* y) { if(x->currentInstPont<y->currentInstPont) return true; return false; } }; int getTheMax(int startPos = 1) { straughtFlight* t_flight; for(int i=startPos;i<=cityCount;i++) { t_flight = cites[i]->firstFlight; while(t_flight!=NULL) { if(cites[t_flight->destination]->intrestingPoint + cites[i]->currentInstPont > cites[t_flight->destination]->currentInstPont) { cites[t_flight->destination]->currentInstPont = cites[t_flight->destination]->intrestingPoint + cites[i]->currentInstPont; cites[t_flight->destination]->pre = cites[i]; } t_flight=t_flight->nextFlight; } } return cites[cityCount+1]->currentInstPont; } int main() { int tc=0,t; scanf("%d",&t); while(tc<t) { scanf("%d",&cityCount); for(int i=1;i<=cityCount;i++) { cites[i] = (cityNode*)malloc(sizeof(cityNode)); scanf("%d",&cites[i]->intrestingPoint); cites[i]->visisted=false; cites[i]->currentInstPont = -MAX; cites[i]->firstFlight = NULL; cites[i]->pre=NULL; cites[i]->index = i; } cites[1]->currentInstPont = 0; cites[cityCount+1] = (cityNode*)malloc(sizeof(cityNode)); cites[cityCount+1]->currentInstPont =-MAX; cites[cityCount+1]->intrestingPoint = 0; cites[cityCount+1]->firstFlight=NULL; cites[cityCount+1]->visisted = false; cites[cityCount+1]->pre=NULL; cites[cityCount+1]->index = 1; scanf("%d",&straughtFlightCount); int a,b; for(int i =0;i<straughtFlightCount;i++) { scanf("%d %d",&a,&b); if(a>b) { int t = a; a = b; b = t; } createStraightFlight(a , b ); } int re = getTheMax( 1); cityNode* t_n = cites[cityCount+1]; stack<cityNode*> stk; while(t_n!=NULL) { stk.push(t_n); t_n = t_n->pre; } cout<<"CASE "<<tc+1<<"#"<<endl; cout<<"points : "<< (re<0 ? 0 :re) <<endl; cout<<"circuit : "; bool first = true; while(!stk.empty()) { if(first) { first=false; } else { cout<<"->"; } cout<<stk.top()->index; stk.pop(); } cout<<endl; if(tc<t-1) cout<<endl; tc++; } return 0; }