//k is the system of numeration longlong words_num, k; cin>>words_num>>k;
while (words_num--){ longlong word; cin>>word; words.push({word, 0}); } //every loop for merge will delete k nodes and add a combined node, //so k-1 nodes decrease in each merge. //the loop will continues until there is only one node. //loop time = (words_num - 1) / (k-1). //if the time is not a integer, just add zero node until it can be a integer. while ((words.size() - 1) % (k - 1) != 0) words.push({0,0});
//the with power length is the new coded book length longlong wpl = 0;
while (words.size() > 1){ longlong combined_node_val = 0; int max_depth = 0; for (int i = 0; i < k; ++i) { //get the min node auto min_node = words.top(); //merge combined_node_val += min_node.first; //save the highest son-tree's depth max_depth = max(max_depth, min_node.second); //delete the node words.pop(); } //add the combined node. words.push({combined_node_val,max_depth + 1}); //the new combined node value is a part of the WPL. wpl += combined_node_val; }
booltopSort(){ //head指向队头,rear指向队列最后一个元素 int head = 0, rear = -1; //因为顶点编号从1开始,所以入度数组从索引1开始遍历 for (int i = 1; i <= n; ++i) { //遍历顶点,如果顶点入度为0,就入队 if (!inDegree[i]){ checkQueue[++rear] = i; } } while (head <= rear){ //取出队头元素 auto top = checkQueue[head++]; //遍历它的邻边,将邻边那头对应点的入度减一 for (auto p = link[top]; p ; p = p->next){ inDegree[p->nodeId]--; //如果没有了前置结点,代表可以入队(即被遍历,或者说该工程任务可以执行了) if (inDegree[p->nodeId] == 0){ checkQueue[++rear] = p->nodeId; } } }
//如果队列中的元素个数刚好等于顶点个数,就代表拓扑排序成立,即不存在闭环。 //因为如果有闭环,闭环上结点的入度始终不为0,无法入队。 return n == rear + 1; }
intmain(){
cin>>n>>m;
while (m--){ int from, to; cin>>from>>to; addLink(from, to); inDegree[to]++; }
//如果拓扑排序无效,则输出-1 if (!topSort()) cout<<"-1"; else for (int i = 0; i < n; ++i) cout<<checkQueue[i]<<' ';